repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
ding327/MobileSafe
src/com/ding/mobilesafe/domain/BlackNumberInfo.java
409
package com.ding.mobilesafe.domain; /** * 黑名单号码的业务bean * @author Administrator * */ public class BlackNumberInfo { private String number; private String mode; public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public String getMode() { return mode; } public void setMode(String mode) { this.mode = mode; } }
apache-2.0
CloudSlang/score-actions
cs-nutanix-prism/src/main/java/io/cloudslang/content/nutanix/prism/entities/NutanixCommonInputs.java
12806
/* * (c) Copyright 2020 Micro Focus, L.P. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Apache License v2.0 which accompany this distribution. * * The Apache License is available at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.cloudslang.content.nutanix.prism.entities; import org.jetbrains.annotations.NotNull; import static org.apache.commons.lang3.StringUtils.EMPTY; public class NutanixCommonInputs { private final String hostname; private final String port; private final String username; private final String password; private final String apiVersion; private final String requestBody; private final String proxyHost; private final String proxyPort; private final String proxyUsername; private final String proxyPassword; private final String trustAllRoots; private final String x509HostnameVerifier; private final String trustKeystore; private final String trustPassword; private final String keystore; private final String keystorePassword; private final String connectTimeout; private final String socketTimeout; private final String keepAlive; private final String responseCharacterSet; private final String connectionsMaxPerRoot; private final String connectionsMaxTotal; private final String preemptiveAuth; @java.beans.ConstructorProperties({"hostname", "port", "username", "password", "apiVersion", "requestBody", "proxyHost", "proxyPort", "proxyUsername", "proxyPassword", "trustAllRoots", "x509HostnameVerifier", "trustKeystore", "trustPassword", "keystore", "keystorePassword", "connectTimeout", "socketTimeout", "keepAlive", "responseCharacterSet", "connectionsMaxPerRoot", "connectionsMaxTotal", "preemptiveAuth"}) private NutanixCommonInputs(String hostname, String port, String username, String password, String apiVersion, String requestBody, String proxyHost, String proxyPort, String proxyUsername, String proxyPassword, String trustAllRoots, String x509HostnameVerifier, String trustKeystore, String trustPassword, String keystore, String keystorePassword, String connectTimeout, String socketTimeout, String keepAlive, String responseCharacterSet, String connectionsMaxPerRoot, String connectionsMaxTotal, String preemptiveAuth) { this.hostname = hostname; this.port = port; this.username = username; this.password = password; this.apiVersion = apiVersion; this.requestBody = requestBody; this.proxyHost = proxyHost; this.proxyPort = proxyPort; this.proxyUsername = proxyUsername; this.proxyPassword = proxyPassword; this.trustAllRoots = trustAllRoots; this.x509HostnameVerifier = x509HostnameVerifier; this.trustKeystore = trustKeystore; this.trustPassword = trustPassword; this.keystore = keystore; this.keystorePassword = keystorePassword; this.connectTimeout = connectTimeout; this.socketTimeout = socketTimeout; this.keepAlive = keepAlive; this.responseCharacterSet = responseCharacterSet; this.connectionsMaxPerRoot = connectionsMaxPerRoot; this.connectionsMaxTotal = connectionsMaxTotal; this.preemptiveAuth = preemptiveAuth; } @NotNull public static NutanixCommonInputs.NutanixCommonInputsBuilder builder() { return new NutanixCommonInputs.NutanixCommonInputsBuilder(); } @NotNull public String getConnectionsMaxPerRoot() { return connectionsMaxPerRoot; } @NotNull public String getConnectionsMaxTotal() { return connectionsMaxTotal; } @NotNull public String getRequestBody() { return requestBody; } @NotNull public String getAPIVersion() { return apiVersion; } @NotNull public String getUsername() { return this.username; } @NotNull public String getPort() { return this.port; } @NotNull public String getPassword() { return this.password; } @NotNull public String getHostname() { return this.hostname; } @NotNull public String getProxyHost() { return this.proxyHost; } @NotNull public String getProxyPort() { return this.proxyPort; } @NotNull public String getProxyUsername() { return this.proxyUsername; } @NotNull public String getProxyPassword() { return this.proxyPassword; } @NotNull public String getTrustAllRoots() { return this.trustAllRoots; } @NotNull public String getX509HostnameVerifier() { return this.x509HostnameVerifier; } @NotNull public String getTrustKeystore() { return this.trustKeystore; } @NotNull public String getTrustPassword() { return this.trustPassword; } @NotNull public String getKeystore() { return this.keystore; } @NotNull public String getKeystorePassword() { return this.keystorePassword; } @NotNull public String getConnectTimeout() { return this.connectTimeout; } @NotNull public String getSocketTimeout() { return this.socketTimeout; } @NotNull public String getKeepAlive() { return this.keepAlive; } @NotNull public String getResponseCharacterSet() { return this.responseCharacterSet; } @NotNull public String getPreemptiveAuth() { return this.preemptiveAuth; } public static class NutanixCommonInputsBuilder { private String hostname = EMPTY; private String port = EMPTY; private String username = EMPTY; private String password = EMPTY; private String apiVersion = EMPTY; private String requestBody = EMPTY; private String proxyHost = EMPTY; private String proxyPort = EMPTY; private String proxyUsername = EMPTY; private String proxyPassword = EMPTY; private String trustAllRoots = EMPTY; private String x509HostnameVerifier = EMPTY; private String trustKeystore = EMPTY; private String trustPassword = EMPTY; private String keystore = EMPTY; private String keystorePassword = EMPTY; private String connectTimeout = EMPTY; private String socketTimeout = EMPTY; private String keepAlive = EMPTY; private String responseCharacterSet = EMPTY; private String connectionsMaxPerRoot = EMPTY; private String connectionsMaxTotal = EMPTY; private String preemptiveAuth = EMPTY; NutanixCommonInputsBuilder() { } @NotNull public NutanixCommonInputs.NutanixCommonInputsBuilder hostname(@NotNull final String hostname) { this.hostname = hostname; return this; } @NotNull public NutanixCommonInputs.NutanixCommonInputsBuilder port(@NotNull final String port) { this.port = port; return this; } @NotNull public NutanixCommonInputs.NutanixCommonInputsBuilder username(@NotNull final String username) { this.username = username; return this; } @NotNull public NutanixCommonInputs.NutanixCommonInputsBuilder password(@NotNull final String password) { this.password = password; return this; } @NotNull public NutanixCommonInputs.NutanixCommonInputsBuilder apiVersion(@NotNull final String apiVersion) { this.apiVersion = apiVersion; return this; } @NotNull public NutanixCommonInputs.NutanixCommonInputsBuilder requestBody(@NotNull final String requestBody) { this.requestBody = requestBody; return this; } @NotNull public NutanixCommonInputs.NutanixCommonInputsBuilder trustAllRoots(@NotNull final String trustAllRoots) { this.trustAllRoots = trustAllRoots; return this; } @NotNull public NutanixCommonInputs.NutanixCommonInputsBuilder x509HostnameVerifier (@NotNull final String x509HostnameVerifier) { this.x509HostnameVerifier = x509HostnameVerifier; return this; } @NotNull public NutanixCommonInputs.NutanixCommonInputsBuilder trustKeystore(@NotNull final String trustKeystore) { this.trustKeystore = trustKeystore; return this; } @NotNull public NutanixCommonInputs.NutanixCommonInputsBuilder trustPassword(@NotNull final String trustPassword) { this.trustPassword = trustPassword; return this; } @NotNull public NutanixCommonInputs.NutanixCommonInputsBuilder keystore(@NotNull final String keystore) { this.keystore = keystore; return this; } @NotNull public NutanixCommonInputs.NutanixCommonInputsBuilder keystorePassword(@NotNull final String keystorePassword) { this.keystorePassword = keystorePassword; return this; } @NotNull public NutanixCommonInputs.NutanixCommonInputsBuilder proxyHost(@NotNull final String proxyHost) { this.proxyHost = proxyHost; return this; } @NotNull public NutanixCommonInputs.NutanixCommonInputsBuilder proxyPort(final String proxyPort) { this.proxyPort = proxyPort; return this; } @NotNull public NutanixCommonInputs.NutanixCommonInputsBuilder proxyUsername(@NotNull final String proxyUsername) { this.proxyUsername = proxyUsername; return this; } @NotNull public NutanixCommonInputs.NutanixCommonInputsBuilder proxyPassword(@NotNull final String proxyPassword) { this.proxyPassword = proxyPassword; return this; } @NotNull public NutanixCommonInputs.NutanixCommonInputsBuilder connectTimeout(@NotNull final String connectTimeout) { this.connectTimeout = connectTimeout; return this; } @NotNull public NutanixCommonInputs.NutanixCommonInputsBuilder socketTimeout(@NotNull final String socketTimeout) { this.socketTimeout = socketTimeout; return this; } @NotNull public NutanixCommonInputs.NutanixCommonInputsBuilder keepAlive(@NotNull final String keepAlive) { this.keepAlive = keepAlive; return this; } @NotNull public NutanixCommonInputs.NutanixCommonInputsBuilder responseCharacterSet (@NotNull final String responseCharacterSet) { this.responseCharacterSet = responseCharacterSet; return this; } @NotNull public NutanixCommonInputs.NutanixCommonInputsBuilder connectionsMaxPerRoot (@NotNull final String connectionsMaxPerRoot) { this.connectionsMaxPerRoot = connectionsMaxPerRoot; return this; } @NotNull public NutanixCommonInputs.NutanixCommonInputsBuilder connectionsMaxTotal (@NotNull final String connectionsMaxTotal) { this.connectionsMaxTotal = connectionsMaxTotal; return this; } @NotNull public NutanixCommonInputs.NutanixCommonInputsBuilder preemptiveAuth(@NotNull final String preemptiveAuth) { this.preemptiveAuth = preemptiveAuth; return this; } public NutanixCommonInputs build() { return new NutanixCommonInputs(hostname, port, username, password, apiVersion, requestBody, proxyHost, proxyPort, proxyUsername, proxyPassword, trustAllRoots, x509HostnameVerifier, trustKeystore, trustPassword, keystore, keystorePassword, connectTimeout, socketTimeout, keepAlive, responseCharacterSet, connectionsMaxPerRoot, connectionsMaxTotal, preemptiveAuth); } } }
apache-2.0
siddimania/AlarmPro-X
src/com/alarmpro_x/MainActivity.java
5518
/* siddhartha dimania */ package com.alarmpro_x; import java.text.DateFormat; import java.util.Calendar; import java.util.Date; import android.app.Activity; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.graphics.Typeface; import android.os.Bundle; import android.os.CountDownTimer; import android.util.Log; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageButton; import android.widget.TextView; import android.widget.Toast; import android.widget.ToggleButton; public class MainActivity extends Activity { Calendar cal = Calendar.getInstance(); int minute = cal.get(Calendar.MINUTE); int hour = cal.get(Calendar.HOUR); TextView text2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); DbHelper dbHelper = new DbHelper(getApplicationContext()); SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentValues values= new ContentValues(); values.put(DbHelper._ID2, 23); values.put(DbHelper.TOGGLE_ON_OFF,7); db.close(); dbHelper.close(); setContentView(R.layout.activity_main); TextView text = (TextView) findViewById(R.id.textView1); Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/RobotoSlab-Light.ttf"); text.setTypeface(tf); text2 = (TextView) findViewById(R.id.textView2); TextView text3 = (TextView) findViewById(R.id.textView3); TextView text4 = (TextView) findViewById(R.id.textView4); int year = cal.get(Calendar.YEAR); int am_pm = cal.get(Calendar.AM_PM); int dayofweek = cal.get(Calendar.DAY_OF_WEEK); int day = cal.getFirstDayOfWeek(); int month = cal.get(Calendar.MONTH); int date = cal.get(Calendar.DATE); String monthofyear = null; String weekday = null; String Am_Pm = null; switch (month) { case 0: monthofyear = "January"; break; case 1: monthofyear = "Faburary"; break; case 2: monthofyear = "March"; break; case 3: monthofyear = "April"; break; case 4: monthofyear = "May"; break; case 5: monthofyear = "June"; break; case 6: monthofyear = "July"; break; case 7: monthofyear = "August"; break; case 8: monthofyear = "September"; break; case 9: monthofyear = "October"; break; case 10: monthofyear = "November"; break; case 11: monthofyear = "December"; break; default: break; } switch (dayofweek) { case 1: weekday = "Sunday"; break; case 2: weekday = "Monday"; break; case 3: weekday = "Tuesday"; break; case 4: weekday = "Wednesday"; break; case 5: weekday = "Thursday"; break; case 6: weekday = "Friday"; break; case 7: weekday = "Saturday"; break; default: break; } switch (am_pm) { case 0: Am_Pm = "AM"; break; case 1: Am_Pm = "PM"; break; } if (hour == 0) hour = 12; if(minute<10) text2.setText(hour + ":0" + minute); else text2.setText(hour + ":" + minute); Typeface tf2 = Typeface.createFromAsset(getAssets(), "fonts/Roboto-Thin.ttf"); text2.setTypeface(tf2); text3.setText(Am_Pm); text3.setTypeface(tf); text4.setText(weekday + ", " + date + " " + monthofyear + " " + year); text4.setTypeface(tf); // text2.setText(new SimpleDateFormat("h:mm a dd,MMMM yy").format(new // Date())); // text2.setText(DateFormat.getDateTimeInstance().format(new // Date(1000))); // text2.setText(new Date().toString()); addListenerOnAddAlarm(); andListenerOnPlus(); addListenerOnSettings(); addListenerOnBack(); addListenerOnList(); } private void addListenerOnList() { ImageButton addButton = (ImageButton) findViewById(R.id.imageButton4); addButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent intent = new Intent(v.getContext(), alarm_list.class); startActivityForResult(intent, 0); } }); } private void addListenerOnBack() { ImageButton addButton = (ImageButton) findViewById(R.id.imageButton2); addButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { finish(); } }); } private void addListenerOnSettings() { ImageButton addButton = (ImageButton) findViewById(R.id.imageButton5); addButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent intent = new Intent(v.getContext(), settings.class); startActivityForResult(intent, 0); // finish(); } }); } private void addListenerOnAddAlarm() { Button addButton = (Button) findViewById(R.id.button1); addButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent intent = new Intent(v.getContext(), add_alarm.class); startActivityForResult(intent, 0); // finish(); } }); } private void andListenerOnPlus() { ImageButton addButton = (ImageButton) findViewById(R.id.imageButton1); addButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent intent = new Intent(v.getContext(), add_alarm.class); startActivityForResult(intent, 0); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
apache-2.0
MironovVadim/vmironov
chapter_001/src/main/java/ru/job4j/calculator/operations/SubstractOperation.java
410
package ru.job4j.calculator.operations; /** * Substract operation. */ public class SubstractOperation implements SingleOperation { /** * String key of substract operation. */ private final String key = "-"; @Override public String key() { return key; } @Override public double doOperation(double first, double second) { return first - second; } }
apache-2.0
Frank-Zhu/FZBaseLib
appbaselibrary/src/main/java/com/frankzhu/appbaselibrary/base/FZBasePullRefreshFragment.java
2283
package com.frankzhu.appbaselibrary.base; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.widget.SwipeRefreshLayout; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.frankzhu.appbaselibrary.R; /** * Author: ZhuWenWu * Version V1.0 * Date: 16/1/26 下午4:12. * Description: 下拉刷新View Fragment * Modification History: * Date Author Version Description * ----------------------------------------------------------------------------------- * 16/1/26 ZhuWenWu 1.0 1.0 * Why & What is modified: */ public abstract class FZBasePullRefreshFragment extends FZBaseViewPagerFragment implements SwipeRefreshLayout.OnRefreshListener { protected SwipeRefreshLayout mSwipeRefreshLayout; protected abstract View getFragmentContentView(LayoutInflater inflater, ViewGroup container); protected abstract void setUpViewComponent(View rootView); @Override protected int getFragmentLayoutRes() { return R.layout.fragment_base_pull_refresh; } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View rootView = super.onCreateView(inflater, container, savedInstanceState); setUpSwipeRefreshLayout(rootView, inflater, container); return rootView; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); setUpViewComponent(view); } private void setUpSwipeRefreshLayout(View rootView, LayoutInflater inflater, ViewGroup container) { if (rootView != null) { mSwipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_refresh_layout); mSwipeRefreshLayout.addView(getFragmentContentView(inflater, container)); mSwipeRefreshLayout.setOnRefreshListener(this); mSwipeRefreshLayout.setColorSchemeResources(R.color.holo_blue_light, R.color.holo_green_light, R.color.holo_orange_light, R.color.holo_red_light); } } }
apache-2.0
hortonworks/cloudbreak
client-cm/src/main/java/com/sequenceiq/cloudbreak/cm/client/transaction/CmApiCallInTransactionException.java
519
package com.sequenceiq.cloudbreak.cm.client.transaction; import com.sequenceiq.cloudbreak.common.exception.CloudbreakServiceException; public class CmApiCallInTransactionException extends CloudbreakServiceException { public CmApiCallInTransactionException(String message) { super(message); } public CmApiCallInTransactionException(String message, Throwable cause) { super(message, cause); } public CmApiCallInTransactionException(Throwable cause) { super(cause); } }
apache-2.0
ako/OracleConnector
javasource/oracleconnector/interfaces/ConnectionManager.java
254
package oracleconnector.interfaces; import java.sql.Connection; import java.sql.SQLException; public interface ConnectionManager { Connection getConnection(final String jdbcUrl, final String userName, final String password) throws SQLException; }
apache-2.0
jroper/netty
codec/src/test/java/io/netty/handler/codec/marshalling/RiverCompatibleMarshallingDecoderTest.java
1352
/* * Copyright 2012 The Netty Project * * The Netty Project 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 io.netty.handler.codec.marshalling; import org.jboss.marshalling.MarshallerFactory; import org.jboss.marshalling.Marshalling; import org.jboss.marshalling.MarshallingConfiguration; public class RiverCompatibleMarshallingDecoderTest extends AbstractCompatibleMarshallingDecoderTest { @Override protected MarshallerFactory createMarshallerFactory() { return Marshalling.getProvidedMarshallerFactory("river"); } @Override protected MarshallingConfiguration createMarshallingConfig() { // Create a configuration final MarshallingConfiguration configuration = new MarshallingConfiguration(); configuration.setVersion(3); return configuration; } }
apache-2.0
Hartorn/mysql2postgresql
XmlToSql/src/main/java/com/github/hartorn/mysql2pgsql/Xml2SqlDataEventHandler.java
5518
package com.github.hartorn.mysql2pgsql; import java.io.IOException; import java.io.Writer; import java.text.MessageFormat; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * Class used to convert data Row in XML to SQL String. Class extending a DefaultHandler for a SaxParser, to use to * render a string to add this row (data row) to a SQL database. * * @author Bazire * */ public class Xml2SqlDataEventHandler extends DefaultHandler { private static final Logger LOG = LogManager.getLogger(Xml2SqlDataEventHandler.class); private static final String SQL_TEMPLATE = "INSERT INTO {0} ({1}) VALUES ({2});\n"; private final Writer writer; private final Map<String, TableStruct> dbProperties; private final Map<String, String> attributesMap = new HashMap<>(); private TableStruct currentTable = null; private String fieldName = null; private long nbElts; public Xml2SqlDataEventHandler(final Writer writer, final Map<String, TableStruct> tableMap) { this.writer = writer; this.dbProperties = tableMap; } /** * {@inheritDoc}. */ @Override public void characters(final char[] ch, final int start, final int length) throws SAXException { if (this.fieldName != null) { this.attributesMap.put(this.fieldName, String.copyValueOf(ch, start, length)); } } /** * {@inheritDoc}. */ @Override public void endDocument() throws SAXException { try { endSql(); } catch (final IOException e) { throw new SAXException(e); } } /** * {@inheritDoc}. */ @Override public void endElement(final String uri, final String localName, final String otherName) throws SAXException { switch (localName) { case "table_data": Xml2SqlDataEventHandler.LOG.info("Finished SQL for table :\"{}\" Nb lines : {}", this.currentTable.getTableName(), this.nbElts); this.currentTable = null; this.nbElts = 0; break; case "row": try { writeSql(); } catch (final IOException e) { throw new SAXException(e); } this.attributesMap.clear(); break; case "field": this.fieldName = null; break; default: break; } } private void endSql() throws IOException { this.writer.write("\n\ncommit;"); } private String prepareStringValueForSql(final String attrName, final String value) throws SAXException { final DbTypesMapping dbType = this.currentTable.getDbType(attrName.toLowerCase().trim()); return dbType.formatForSql(value); } /** * {@inheritDoc}. */ @Override public void startDocument() throws SAXException { try { startSql(); } catch (final IOException e) { throw new SAXException(e); } } /** * {@inheritDoc}. */ @Override public void startElement(final String uri, final String localName, final String otherName, final Attributes attributes) throws SAXException { switch (localName) { case "row": this.nbElts++; break; case "table_data": this.currentTable = this.dbProperties.get(attributes.getValue(attributes.getIndex("name")).toLowerCase().trim()); this.nbElts = 0; Xml2SqlDataEventHandler.LOG.info("Writing SQL for table :\"{}\"", this.currentTable.getTableName()); break; case "field": this.fieldName = attributes.getValue(attributes.getIndex("name")); if (this.fieldName != null) { this.attributesMap.put(this.fieldName, this.currentTable.getDbType(this.fieldName.toLowerCase().trim()).nullValueForSql()); } break; default: break; } } private void startSql() throws IOException { this.writer.write("SET CLIENT_ENCODING TO '" + XmlToSql.CHARSET + "';\n\n"); this.writer.write("start transaction;\n\n"); } private void writeSql() throws IOException, SAXException { final StringBuilder attrNames = new StringBuilder(); final StringBuilder attrValues = new StringBuilder(); final Set<Entry<String, String>> row = this.attributesMap.entrySet(); for (final Entry<String, String> entry : row) { attrNames.append(entry.getKey()).append(','); } if (attrNames.length() > 0) { attrNames.setLength(attrNames.length() - 1); } for (final Entry<String, String> entry : row) { attrValues.append(prepareStringValueForSql(entry.getKey(), entry.getValue())).append(','); } if (attrValues.length() > 0) { attrValues.setLength(attrValues.length() - 1); } this.writer.write(MessageFormat.format(Xml2SqlDataEventHandler.SQL_TEMPLATE, this.currentTable.getTableName(), attrNames.toString(), attrValues.toString())); } }
apache-2.0
gibri/kelvin
kelvin/src/main/java/org/apache/solr/kelvin/SingletonConditionRegistry.java
1930
/* Copyright 2013 Giovanni Bricconi Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.apache.solr.kelvin; import java.util.Map; import java.util.TreeMap; import org.apache.solr.kelvin.testcases.DateRangeCondition; import org.apache.solr.kelvin.testcases.SimpleCondition; import org.apache.solr.kelvin.testcases.ValueListCondition; import com.fasterxml.jackson.databind.JsonNode; public class SingletonConditionRegistry { private static SimpleClassRegistry<ICondition> registry= new SimpleClassRegistry<ICondition>(ICondition.class); public static void configure(JsonNode config) throws Exception { registry.configure(config); //default built in conditions Map<String,Class<?>> defaults = new TreeMap<String,Class<?>>(); //defaults.put(null, SimpleCondition.class); defaults.put("", SimpleCondition.class); defaults.put("default", SimpleCondition.class); defaults.put("valueList", ValueListCondition.class); defaults.put("dateRange", DateRangeCondition.class); defaults.put("slug", ValueListCondition.class); //legacy registry.addMappingsFromClasses(defaults); } public static ICondition instantiate(JsonNode conf) throws Exception { String type=""; if (conf.has("type")) type = conf.get("type").asText(); //legacy if (conf.has("mode")) type = conf.get("mode").asText(); ICondition ret = registry.instantiate(type); ret.configure(conf); return ret; } }
apache-2.0
FulanoD3Tal/Thetvdb_api_v2
src/com/fulanodetalcompany/gson/models/main.java
788
/* * Copyright 2017 Roberto Alonso De la Garza Mendoza. * * 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.fulanodetalcompany.gson.models; /** * @version 0.0.1 * @author Roberto Alonso De la Garza Mendoza */ public class main { }
apache-2.0
las1991/spring-data-dynamodb-demo
src/main/java/com/sengled/rest/data/dynamodb/test/UserRepositoryIntegrationTest.java
1714
package com.sengled.rest.data.dynamodb.test; import com.sengled.rest.data.dynamodb.domain.User; import org.junit.Test; import org.junit.runner.RunWith; import com.sengled.rest.data.dynamodb.repository.UserRepository; import com.sengled.rest.data.dynamodb.util.JsonUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.List; /** * @version 1.0 * @Description * @Author:andy * @CreateDate:2016/5/17 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = SpringDataDynamoDemoConfig.class) public class UserRepositoryIntegrationTest { @Autowired UserRepository userRepository; @Test public void sampleTestCase() { List<User> result = userRepository.findByAccount("test1@sengled.com"); System.out.println(result.get(0)); } @Test public void sampleTest1Case() { List<User> result = userRepository.queryById(1); System.out.println(result.get(0)); } @Test public void save(){ String s="{\n" + " \"id\" : 101,\n" + " \"account\" : \"test101@sengled.com\",\n" + " \"properties\" : {\n" + " \"sex\" : \"m\",\n" + " \"password\" : \"1010101\",\n" + " \"telphone\" : \"644453071\"\n" + " },\n" + " \"friends\" : [ \"3\", \"2\", \"1\", \"0\", \"7\", \"6\", \"5\", \"4\" ]\n" + "}"; User user= JsonUtil.getInstance().fromJson(s,User.class); userRepository.save(user); } }
apache-2.0
DirkBrand/Pokemaps
src/com/pokemaps/pokemaps/Utilities.java
10452
package com.pokemaps.pokemaps; import java.util.Random; import com.google.android.gms.maps.model.LatLng; import com.pokemaps.pokemaps.data.Item; import com.pokemaps.pokemaps.data.Pokemon; import com.pokemaps.pokemaps.data.Pokemon.PokemonRarity; import com.pokemaps.pokemaps.data.Pokemon.PokemonType; import com.pokemaps.pokemaps.data.User; import com.pokemaps.pokemaps.data.Zone.ZoneType; public class Utilities { public static final int IMAGES[] = { R.drawable.bulbasaur, R.drawable.ivysaur, R.drawable.venusaur, R.drawable.charmander, R.drawable.charmeleon, R.drawable.charizard, R.drawable.squirtle, R.drawable.wartortle, R.drawable.blastoise, R.drawable.caterpie, R.drawable.metapod, R.drawable.butterfree, R.drawable.weedle, R.drawable.kakuna, R.drawable.beedrill, R.drawable.pidgey, R.drawable.pidgeotto, R.drawable.pidgeot, R.drawable.rattata, R.drawable.raticate, R.drawable.spearow, R.drawable.fearow, R.drawable.ekans, R.drawable.arbok, R.drawable.pikachu, R.drawable.raichu, R.drawable.sandshrew, R.drawable.sandslash, R.drawable.nidoranf, R.drawable.nidorina, R.drawable.nidoqueen, R.drawable.nidoranm, R.drawable.nidorino, R.drawable.nidoking, R.drawable.clefairy, R.drawable.clefable, R.drawable.vulpix, R.drawable.ninetails, R.drawable.jigglypuff, R.drawable.wigglytuff, R.drawable.zubat, R.drawable.golbat, R.drawable.oddish, R.drawable.gloom, R.drawable.vileplume, R.drawable.paras, R.drawable.parasect, R.drawable.venonat, R.drawable.venomoth, R.drawable.diglett, R.drawable.dugtrio, R.drawable.meowth, R.drawable.persian, R.drawable.psyduck, R.drawable.golduck, R.drawable.mankey, R.drawable.primeape, R.drawable.growlithe, R.drawable.arcanine, R.drawable.poliwag, R.drawable.poliwhirl, R.drawable.poliwrath, R.drawable.abra, R.drawable.kadabra, R.drawable.alakazam, R.drawable.machop, R.drawable.machoke, R.drawable.bellsprout, R.drawable.weepinbell, R.drawable.victreebel, R.drawable.tentacool, R.drawable.tentacruel, R.drawable.geodude, R.drawable.graveler, R.drawable.golem, R.drawable.ponyta, R.drawable.rapidash, R.drawable.slowpoke, R.drawable.slowbro, R.drawable.magnemite, R.drawable.magneton, R.drawable.farfetchd, R.drawable.doduo, R.drawable.dodrio, R.drawable.seel, R.drawable.dewgong, R.drawable.grimer, R.drawable.muk, R.drawable.shellder, R.drawable.cloyster, R.drawable.gastly, R.drawable.haunter, R.drawable.gengar, R.drawable.onix, R.drawable.drowzee, R.drawable.hypno, R.drawable.krabby, R.drawable.kingler, R.drawable.voltorb, R.drawable.electrode, R.drawable.exeggcute, R.drawable.exeggutor, R.drawable.cubone, R.drawable.marowak, R.drawable.hitmonlee, R.drawable.hitmonchan, R.drawable.lickitung, R.drawable.koffing, R.drawable.weezing, R.drawable.rhyhorn, R.drawable.rhydon, R.drawable.chansey, R.drawable.tangela, R.drawable.kangaskhan, R.drawable.horsea, R.drawable.seadra, R.drawable.goldeen, R.drawable.seaking, R.drawable.staryu, R.drawable.staryu, R.drawable.mr_mime, R.drawable.scyther, R.drawable.jynx, R.drawable.electabuzz, R.drawable.magmar, R.drawable.pinsir, R.drawable.tauros, R.drawable.magikarp, R.drawable.gyarados, R.drawable.lapras, R.drawable.ditto, R.drawable.eevee, R.drawable.vaporean, R.drawable.jolteon, R.drawable.flareon, R.drawable.porygon, R.drawable.omanyte, R.drawable.omastar, R.drawable.kabuto, R.drawable.kabutops, R.drawable.aerodactyl, R.drawable.snorlax, R.drawable.articuno, R.drawable.zapdos, R.drawable.moltres, R.drawable.dratini, R.drawable.dragonair, R.drawable.dragonite, R.drawable.mewtwo, R.drawable.mew }; public static final int GREY_IMAGES[] = { R.drawable.bulbasaur_grey, R.drawable.ivysaur_grey, R.drawable.venusaur_grey, R.drawable.charmander_grey, R.drawable.charmeleon_grey, R.drawable.charizard_grey, R.drawable.squirtle_grey, R.drawable.wartortle_grey, R.drawable.blastoise_grey, R.drawable.caterpie_grey, R.drawable.metapod_grey, R.drawable.butterfree_grey, R.drawable.weedle_grey, R.drawable.kakuna_grey, R.drawable.beedrill_grey, R.drawable.pidgey_grey, R.drawable.pidgeotto_grey, R.drawable.pidgeot_grey, R.drawable.rattata_grey, R.drawable.raticate_grey, R.drawable.spearow_grey, R.drawable.fearow_grey, R.drawable.ekans_grey, R.drawable.arbok_grey, R.drawable.pikachu_grey, R.drawable.raichu_grey, R.drawable.sandshrew_grey, R.drawable.sandslash_grey, R.drawable.nidoranf_grey, R.drawable.nidorina_grey, R.drawable.nidoqueen_grey, R.drawable.nidoranm_grey, R.drawable.nidorino_grey, R.drawable.nidoking_grey, R.drawable.clefairy_grey, R.drawable.clefable_grey, R.drawable.vulpix_grey, R.drawable.ninetails_grey, R.drawable.jigglypuff_grey, R.drawable.wigglytuff_grey, R.drawable.zubat_grey, R.drawable.golbat_grey, R.drawable.oddish_grey, R.drawable.gloom_grey, R.drawable.vileplume_grey, R.drawable.paras_grey, R.drawable.parasect_grey, R.drawable.venonat_grey, R.drawable.venomoth_grey, R.drawable.diglett_grey, R.drawable.dugtrio_grey, R.drawable.meowth_grey, R.drawable.persian_grey, R.drawable.psyduck_grey, R.drawable.golduck_grey, R.drawable.mankey_grey, R.drawable.primeape_grey, R.drawable.growlithe_grey, R.drawable.arcanine_grey, R.drawable.poliwag_grey, R.drawable.poliwhirl_grey, R.drawable.poliwrath_grey, R.drawable.abra_grey, R.drawable.kadabra_grey, R.drawable.alakazam_grey, R.drawable.machop_grey, R.drawable.machoke_grey, R.drawable.bellsprout_grey, R.drawable.weepinbell, R.drawable.victreebel_grey, R.drawable.tentacool_grey, R.drawable.tentacruel_grey, R.drawable.geodude_grey, R.drawable.graveler_grey, R.drawable.golem_grey, R.drawable.ponyta_grey, R.drawable.rapidash_grey, R.drawable.slowpoke_grey, R.drawable.slowbro_grey, R.drawable.magnemite_grey, R.drawable.magneton_grey, R.drawable.farfetchd_grey, R.drawable.doduo_grey, R.drawable.dodrio_grey, R.drawable.seel_grey, R.drawable.dewgong_grey, R.drawable.grimer_grey, R.drawable.muk_grey, R.drawable.shellder_grey, R.drawable.cloyster_grey, R.drawable.gastly_grey, R.drawable.haunter_grey, R.drawable.gengar_grey, R.drawable.onix_grey, R.drawable.drowzee_grey, R.drawable.hypno_grey, R.drawable.krabby_grey, R.drawable.kingler_grey, R.drawable.voltorb_grey, R.drawable.electrode_grey, R.drawable.exeggcute_grey, R.drawable.exeggutor_grey, R.drawable.cubone_grey, R.drawable.marowak_grey, R.drawable.hitmonlee_grey, R.drawable.hitmonchan_grey, R.drawable.lickitung_grey, R.drawable.koffing_grey, R.drawable.weezing_grey, R.drawable.rhyhorn_grey, R.drawable.rhydon_grey, R.drawable.chansey_grey, R.drawable.tangela_grey, R.drawable.kangaskhan_grey, R.drawable.horsea_grey, R.drawable.seadra_grey, R.drawable.goldeen_grey, R.drawable.seaking_grey, R.drawable.staryu_grey, R.drawable.staryu_grey, R.drawable.mr_mime_grey, R.drawable.scyther_grey, R.drawable.jynx_grey, R.drawable.electabuzz_grey, R.drawable.magmar_grey, R.drawable.pinsir_grey, R.drawable.tauros_grey, R.drawable.magikarp_grey, R.drawable.gyarados_grey, R.drawable.lapras_grey, R.drawable.ditto_grey, R.drawable.eevee_grey, R.drawable.vaporean_grey, R.drawable.jolteon_grey, R.drawable.flareon_grey, R.drawable.porygon_grey, R.drawable.omanyte_grey, R.drawable.omastar_grey, R.drawable.kabuto_grey, R.drawable.kabutops_grey, R.drawable.aerodactyl_grey, R.drawable.snorlax_grey, R.drawable.articuno_grey, R.drawable.zapdos_grey, R.drawable.moltres_grey, R.drawable.dratini_grey, R.drawable.dragonair_grey, R.drawable.dragonite_grey, R.drawable.mewtwo_grey, R.drawable.mew_grey }; public static double CalculationByDistance(LatLng StartP, LatLng EndP) { double lat1 = StartP.latitude; double lat2 = EndP.latitude; double lon1 = StartP.longitude; double lon2 = EndP.longitude; double dLat = Math.toRadians(lat2 - lat1); double dLon = Math.toRadians(lon2 - lon1); double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2); double c = 2 * Math.asin(Math.sqrt(a)); return 6366000 * c; } public static ZoneType textToZoneType(String text) { if (text.equals("GRASSLAND")) { return ZoneType.GRASSLAND; } if (text.equals("WATER")) { return ZoneType.WATER; } if (text.equals("MOUNTAIN")) { return ZoneType.MOUNTAIN; } if (text.equals("SEA")) { return ZoneType.SEA; } if (text.equals("ROUGH")) { return ZoneType.ROUGH; } if (text.equals("URBAN")) { return ZoneType.URBAN; } if (text.equals("CAVE")) { return ZoneType.CAVE; } if (text.equals("FOREST")) { return ZoneType.FOREST; } return null; } public static PokemonType textToPokemonType(String text) { if (text.equals("GRASS")) { return PokemonType.GRASS; } if (text.equals("POISON")) { return PokemonType.POISON; } if (text.equals("FIRE")) { return PokemonType.FIRE; } if (text.equals("WATER")) { return PokemonType.WATER; } if (text.equals("BUG")) { return PokemonType.BUG; } if (text.equals("FLYING")) { return PokemonType.FLYING; } if (text.equals("NORMAL")) { return PokemonType.NORMAL; } if (text.equals("ELECTRIC")) { return PokemonType.ELECTRIC; } if (text.equals("GROUND")) { return PokemonType.GROUND; } if (text.equals("PSYCIC")) { return PokemonType.PSYCIC; } if (text.equals("FIGHTING")) { return PokemonType.FIGHTING; } if (text.equals("STEEL")) { return PokemonType.STEEL; } if (text.equals("GHOST")) { return PokemonType.GHOST; } if (text.equals("ICE")) { return PokemonType.ICE; } if (text.equals("DRAGON")) { return PokemonType.DRAGON; } return null; } public static PokemonRarity textToRarity(String text) { if (text.equals("VERYCOMMON")) { return PokemonRarity.VERYCOMMON; } if (text.equals("COMMON")) { return PokemonRarity.COMMON; } if (text.equals("UNCOMMON")) { return PokemonRarity.UNCOMMON; } if (text.equals("RARE")) { return PokemonRarity.RARE; } if (text.equals("VERYRARE")) { return PokemonRarity.VERYRARE; } return null; } public static boolean calculate_catch(User currentUser, Pokemon pokemon, Item pokeball) { Random rand = new Random(); // Assume pokeball int N = rand.nextInt(pokeball.getExtraValue()); if (N > pokemon.getCatchRate()) { // Breaks free! return false; } else { return true; } } }
apache-2.0
kpavlov/json-service-starter
src/main/java/kpavlov/jsonweb/Application.java
230
package kpavlov.jsonweb; import org.springframework.boot.SpringApplication; public class Application { public static void main(String[] args) throws Exception { SpringApplication.run(AppConfig.class, args); } }
apache-2.0
ryandcarter/hybris-connector
src/main/java/org/mule/modules/hybris/model/CelumPicturesIntegrationJobsDTO.java
2433
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // 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: 2013.11.29 at 12:35:53 PM GMT // package org.mule.modules.hybris.model; 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.XmlType; /** * <p>Java class for celumPicturesIntegrationJobsDTO complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="celumPicturesIntegrationJobsDTO"> * &lt;complexContent> * &lt;extension base="{}abstractCollectionDTO"> * &lt;sequence> * &lt;element ref="{}celumpicturesintegrationjob" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "celumPicturesIntegrationJobsDTO", propOrder = { "celumpicturesintegrationjob" }) public class CelumPicturesIntegrationJobsDTO extends AbstractCollectionDTO { protected List<CelumPicturesIntegrationJobDTO> celumpicturesintegrationjob; /** * Gets the value of the celumpicturesintegrationjob 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 celumpicturesintegrationjob property. * * <p> * For example, to add a new item, do as follows: * <pre> * getCelumpicturesintegrationjob().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link CelumPicturesIntegrationJobDTO } * * */ public List<CelumPicturesIntegrationJobDTO> getCelumpicturesintegrationjob() { if (celumpicturesintegrationjob == null) { celumpicturesintegrationjob = new ArrayList<CelumPicturesIntegrationJobDTO>(); } return this.celumpicturesintegrationjob; } }
apache-2.0
XClouded/t4f-core
plugin/osgi/eclipse/src/examples/org.eclipse.swt.snippets/src/org/eclipse/swt/snippets/Snippet347.java
1798
/******************************************************************************* * Copyright (c) 2000, 2010 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.swt.snippets; /* * Display snippet: use the AppMenuBar when available. * * For a list of all SWT example snippets see * http://www.eclipse.org/swt/snippets/ * * @since 3.7 */ import org.eclipse.swt.*; import org.eclipse.swt.events.*; import org.eclipse.swt.layout.*; import org.eclipse.swt.widgets.*; public class Snippet347 { public static void main(String[] args) { final Display display = new Display(); Shell shell = new Shell(display); shell.setLayout(new GridLayout(1, false)); Menu appMenuBar = display.getMenuBar(); if (appMenuBar == null) { appMenuBar = new Menu(shell, SWT.BAR); shell.setMenuBar(appMenuBar); } MenuItem file = new MenuItem(appMenuBar, SWT.CASCADE); file.setText("File"); Menu dropdown = new Menu(appMenuBar); file.setMenu(dropdown); MenuItem exit = new MenuItem(dropdown, SWT.PUSH); exit.setText("Exit"); exit.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { display.dispose(); } }); Button b = new Button(shell, SWT.PUSH); b.setText("Test"); shell.pack(); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); } }
apache-2.0
tingley/tm3
src/main/java/com/globalsight/ling/tm3/core/TM3LeverageResults.java
4509
package com.globalsight.ling.tm3.core; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; /** * A set of results for a single leverage operation. */ public class TM3LeverageResults<T extends TM3Data> { private T source; private Map<TM3Attribute, Object> attributes; private SortedSet<TM3LeverageMatch<T>> matches = new TreeSet<TM3LeverageMatch<T>>(COMPARATOR); public TM3LeverageResults(T source, Map<TM3Attribute, Object> attributes) { this.source = source; this.attributes = attributes; } /** * Return the match key that was used to search the TM. */ public T getSource() { return source; } /** * Return the attributes, if any, that were specified on the search. * @return attribute map, possibly empty (if no attributes were specified) */ public Map<TM3Attribute, Object> getSourceAttributes() { return attributes; } /** * Drop all but the lowest 'max' results in this result set. * @param max */ void keepHighest(int max) { if (matches.size() < max) { return; } int count = 0; // Note that SortedSet.headSet() is backed by itself, so // it will hold a reference to the results we don't need // any more. Hence, the copy. SortedSet<TM3LeverageMatch<T>> newMatches = new TreeSet<TM3LeverageMatch<T>>(COMPARATOR); for (TM3LeverageMatch<T> match : matches) { if (++count > max) { break; } newMatches.add(match); } matches = newMatches; } /** * Returns matches in descending order of match score. * * @return set of {@link TM3LeverageMatch}, possibly empty if no * matches were found */ public SortedSet<TM3LeverageMatch<T>> getMatches() { return matches; } void addExactMatch(TM3Tu<T> segment, TM3Tuv<T> tuv) { matches.add(new ExactMatch(segment, tuv)); } void addFuzzyMatch(TM3Tu<T> segment, TM3Tuv<T> tuv, int score) { matches.add(new FuzzyMatch(segment, tuv, score)); } class ExactMatch extends TM3LeverageMatch<T> { ExactMatch(TM3Tu<T> segment, TM3Tuv<T> tuv) { super(segment, tuv); } @Override public int getScore() { return 100; } @Override public boolean isExact() { return true; } @Override public String toString() { return "[" + getTuv() + ", exact]"; } } class FuzzyMatch extends TM3LeverageMatch<T> { private int score; FuzzyMatch(TM3Tu<T> segment, TM3Tuv<T> tuv, int score) { super(segment, tuv); this.score = score; } @Override public int getScore() { return score; } @Override public boolean isExact() { return false; } @Override public String toString() { return "[" + getTuv() + ", fuzzy score " + getScore() + "]"; } } static final MatchComparator COMPARATOR = new MatchComparator(); static class MatchComparator implements Comparator<TM3LeverageMatch<?>> { @Override public int compare(TM3LeverageMatch<?> o1, TM3LeverageMatch<?> o2) { int v = (o2.getScore() - o1.getScore()); if (v == 0) { // Needed to make this consistent with equals if (o1.getTuv().equals(o2.getTuv())) { return 0; } // Use fingerprints as a surrogate ordering that is stable but // not tied to database order v = ltoi(o1.getTuv().getFingerprint() - o2.getTuv().getFingerprint()); if (v == 0) { // Fall back on DB ordering in the (unlikely) case of fingerprint collision v = ltoi(o1.getTu().getId() - o2.getTu().getId()); } } return v; } } // Safely convert a long into a value we can return from a comparator. // (Casting may overflow the integer.) private static int ltoi(long l) { return (l < 0) ? -1 : (l == 0) ? 0 : 1; } }
apache-2.0
dagnir/aws-sdk-java
aws-java-sdk-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/transform/DescribeDocumentRequestMarshaller.java
2380
/* * Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.simplesystemsmanagement.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.simplesystemsmanagement.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * DescribeDocumentRequestMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class DescribeDocumentRequestMarshaller { private static final MarshallingInfo<String> NAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("Name").build(); private static final MarshallingInfo<String> DOCUMENTVERSION_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("DocumentVersion").build(); private static final DescribeDocumentRequestMarshaller instance = new DescribeDocumentRequestMarshaller(); public static DescribeDocumentRequestMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(DescribeDocumentRequest describeDocumentRequest, ProtocolMarshaller protocolMarshaller) { if (describeDocumentRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(describeDocumentRequest.getName(), NAME_BINDING); protocolMarshaller.marshall(describeDocumentRequest.getDocumentVersion(), DOCUMENTVERSION_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
apache-2.0
macaroons-io/macaroons-io.github.io
jmacaroons2js/src/main/resources/com/googlecode/cryptogwt/provider/Padding.java
458
package com.googlecode.cryptogwt.provider; import javax.crypto.BadPaddingException; import javax.crypto.IllegalBlockSizeException; public interface Padding { public int pad(byte[] input, int offset, int len, byte[] output, int outputOffset, int blockSize) throws IllegalBlockSizeException; public int depad(byte[] input, int offset, int len, byte[] output, int outputOffset, int blockSize) throws BadPaddingException; }
apache-2.0
kwakeroni/BusinessParameters
parameters-backend/parameters-backend-inmemory/src/main/java/be/kwakeroni/evelyn/model/ParseException.java
1413
package be.kwakeroni.evelyn.model; import java.util.Optional; import java.util.OptionalInt; public class ParseException extends Exception { private String source = null; private Integer line = null; private Integer position = null; public ParseException(String message) { super(message); } @Override public String getMessage() { String message = super.getMessage(); if (line != null) { if (position != null) { message += " at position " + line + ":" + position; } else { message += " at line " + line; } } if (source != null) { message += " in source " + source; } return message; } public ParseException atLine(int line) { this.line = line; return this; } public ParseException atPosition(int pos) { this.position = pos; return this; } public ParseException inSource(String source) { this.source = source; return this; } public OptionalInt getLine() { return (line == null) ? OptionalInt.empty() : OptionalInt.of(line); } public OptionalInt getPosition() { return (position == null) ? OptionalInt.empty() : OptionalInt.of(position); } public Optional<String> getSource() { return Optional.ofNullable(source); } }
apache-2.0
hexonxons/LepraWatch
LepraWatch/src/com/hexonxons/leprawatch/view/PostElementView.java
1678
package com.hexonxons.leprawatch.view; import com.hexonxons.leprawatch.R; import android.content.Context; import android.util.AttributeSet; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; public class PostElementView extends RelativeLayout { // Post text. public LinearLayout messageWrapper = null; // Author name. public TextView author = null; // Post info group. public ViewGroup infoWrapper = null; // Comments icon. public ImageView commentsIcon = null; // Comments count. public TextView commentsCount = null; // Post rating. public TextView rating = null; public PostElementView(Context context) { super(context); } public PostElementView(Context context, AttributeSet attrs) { super(context, attrs); } public PostElementView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onFinishInflate() { super.onFinishInflate(); messageWrapper = (LinearLayout) findViewById(R.id.post_message); author = (TextView) findViewById(R.id.post_author); infoWrapper = (ViewGroup) findViewById(R.id.post_info_wrapper); commentsCount = (TextView) findViewById(R.id.post_info_comments_count); commentsIcon = (ImageView) findViewById(R.id.post_info_comments_icon); rating = (TextView) findViewById(R.id.post_info_rating); } }
apache-2.0
t4gedieb/ews-client
src/main/java/ews/client/config/JacksonConfiguration.java
998
package ews.client.config; import org.joda.time.DateTime; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.format.datetime.joda.DateTimeFormatterFactory; import com.fasterxml.jackson.datatype.joda.JodaModule; import com.fasterxml.jackson.datatype.joda.cfg.JacksonJodaDateFormat; import com.fasterxml.jackson.datatype.joda.ser.DateTimeSerializer; @Configuration public class JacksonConfiguration { @Bean public JodaModule jacksonJodaModule() { JodaModule module = new JodaModule(); DateTimeFormatterFactory formatterFactory = new DateTimeFormatterFactory(); formatterFactory.setIso(DateTimeFormat.ISO.DATE); module.addSerializer(DateTime.class, new DateTimeSerializer(new JacksonJodaDateFormat(formatterFactory .createDateTimeFormatter().withZoneUTC()))); return module; } }
apache-2.0
ConsecroMUD/ConsecroMUD
com/suscipio_solutions/consecro_mud/Abilities/Prayers/Prayer_SenseLife.java
4481
package com.suscipio_solutions.consecro_mud.Abilities.Prayers; import java.util.Vector; import com.suscipio_solutions.consecro_mud.Abilities.interfaces.Ability; import com.suscipio_solutions.consecro_mud.Common.interfaces.CMMsg; import com.suscipio_solutions.consecro_mud.Exits.interfaces.Exit; import com.suscipio_solutions.consecro_mud.Locales.interfaces.Room; import com.suscipio_solutions.consecro_mud.MOBS.interfaces.MOB; import com.suscipio_solutions.consecro_mud.core.CMClass; import com.suscipio_solutions.consecro_mud.core.CMLib; import com.suscipio_solutions.consecro_mud.core.Directions; import com.suscipio_solutions.consecro_mud.core.interfaces.Physical; import com.suscipio_solutions.consecro_mud.core.interfaces.Tickable; @SuppressWarnings("rawtypes") public class Prayer_SenseLife extends Prayer { @Override public String ID() { return "Prayer_SenseLife"; } private final static String localizedName = CMLib.lang().L("Sense Life"); @Override public String name() { return localizedName; } private final static String localizedStaticDisplay = CMLib.lang().L("(Sense Life)"); @Override public String displayText() { return localizedStaticDisplay; } @Override public int classificationCode(){return Ability.ACODE_PRAYER|Ability.DOMAIN_COMMUNING;} @Override protected int canAffectCode(){return CAN_MOBS;} @Override protected int canTargetCode(){return CAN_MOBS;} @Override public int enchantQuality(){return Ability.QUALITY_BENEFICIAL_SELF;} @Override public int abstractQuality(){ return Ability.QUALITY_OK_SELF;} @Override public long flags(){return Ability.FLAG_HOLY|Ability.FLAG_UNHOLY;} protected Room lastRoom=null; @Override public void unInvoke() { // undo the affects of this spell if(!(affected instanceof MOB)) return; final MOB mob=(MOB)affected; super.unInvoke(); if(canBeUninvoked()) { lastRoom=null; mob.tell(L("Your life sensations fade.")); } } public boolean inhabitated(MOB mob, Room R) { if(R==null) return false; for(int i=0;i<R.numInhabitants();i++) { final MOB M=R.fetchInhabitant(i); if((M!=null) &&(!CMLib.flags().isGolem(M)) &&(M.charStats().getMyRace().canBreedWith(M.charStats().getMyRace())) &&(M!=mob)) return true; } return false; } public void messageTo(MOB mob) { String last=""; String dirs=""; for(int d=Directions.NUM_DIRECTIONS()-1;d>=0;d--) { final Room R=mob.location().getRoomInDir(d); final Exit E=mob.location().getExitInDir(d); if((R!=null)&&(E!=null)&&(inhabitated(mob,R))) { if(last.length()>0) dirs+=", "+last; last=Directions.getFromDirectionName(d); } } if(inhabitated(mob,mob.location())) { if(last.length()>0) dirs+=", "+last; last="here"; } if((dirs.length()==0)&&(last.length()==0)) mob.tell(L("You do not sense any life beyond your own.")); else if(dirs.length()==0) mob.tell(L("You sense a life force coming from @x1.",last)); else mob.tell(L("You sense a life force coming from @x1, and @x2.",dirs.substring(2),last)); } @Override public boolean tick(Tickable ticking, int tickID) { if(!super.tick(ticking,tickID)) return false; if((tickID==Tickable.TICKID_MOB) &&(affected!=null) &&(affected instanceof MOB) &&(((MOB)affected).location()!=null) &&((lastRoom==null)||(((MOB)affected).location()!=lastRoom))) { lastRoom=((MOB)affected).location(); messageTo((MOB)affected); } return true; } @Override public boolean invoke(MOB mob, Vector commands, Physical givenTarget, boolean auto, int asLevel) { if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; Physical target=mob; if((auto)&&(givenTarget!=null)) target=givenTarget; final boolean success=proficiencyCheck(mob,0,auto); if(success) { // it worked, so build a copy of this ability, // and add it to the affects list of the // affected MOB. Then tell everyone else // what happened. final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?L("<T-NAME> attain(s) life-like senses!"):L("^S<S-NAME> listen(s) for a message from @x1.^?",hisHerDiety(mob))); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); beneficialAffect(mob,target,asLevel,0); } } else return beneficialWordsFizzle(mob,null,L("<S-NAME> listen(s) to @x1 for a message, but there is no answer.",hisHerDiety(mob))); // return whether it worked return success; } }
apache-2.0
chat-sdk/chat-sdk-android
chat-sdk-core/src/main/java/sdk/chat/core/dao/UserDao.java
5306
package sdk.chat.core.dao; import android.database.Cursor; import android.database.sqlite.SQLiteStatement; import org.greenrobot.greendao.AbstractDao; import org.greenrobot.greendao.Property; import org.greenrobot.greendao.internal.DaoConfig; import org.greenrobot.greendao.database.Database; import org.greenrobot.greendao.database.DatabaseStatement; // THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. /** * DAO for table "USER". */ public class UserDao extends AbstractDao<User, Long> { public static final String TABLENAME = "USER"; /** * Properties of entity User.<br/> * Can be used for QueryBuilder and for referencing column names. */ public static class Properties { public final static Property Id = new Property(0, Long.class, "id", true, "_id"); public final static Property EntityID = new Property(1, String.class, "entityID", false, "ENTITY_ID"); public final static Property LastOnline = new Property(2, java.util.Date.class, "lastOnline", false, "LAST_ONLINE"); public final static Property IsOnline = new Property(3, Boolean.class, "isOnline", false, "IS_ONLINE"); } private DaoSession daoSession; public UserDao(DaoConfig config) { super(config); } public UserDao(DaoConfig config, DaoSession daoSession) { super(config, daoSession); this.daoSession = daoSession; } /** Creates the underlying database table. */ public static void createTable(Database db, boolean ifNotExists) { String constraint = ifNotExists? "IF NOT EXISTS ": ""; db.execSQL("CREATE TABLE " + constraint + "\"USER\" (" + // "\"_id\" INTEGER PRIMARY KEY ," + // 0: id "\"ENTITY_ID\" TEXT UNIQUE ," + // 1: entityID "\"LAST_ONLINE\" INTEGER," + // 2: lastOnline "\"IS_ONLINE\" INTEGER);"); // 3: isOnline } /** Drops the underlying database table. */ public static void dropTable(Database db, boolean ifExists) { String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "\"USER\""; db.execSQL(sql); } @Override protected final void bindValues(DatabaseStatement stmt, User entity) { stmt.clearBindings(); Long id = entity.getId(); if (id != null) { stmt.bindLong(1, id); } String entityID = entity.getEntityID(); if (entityID != null) { stmt.bindString(2, entityID); } java.util.Date lastOnline = entity.getLastOnline(); if (lastOnline != null) { stmt.bindLong(3, lastOnline.getTime()); } Boolean isOnline = entity.getIsOnline(); if (isOnline != null) { stmt.bindLong(4, isOnline ? 1L: 0L); } } @Override protected final void bindValues(SQLiteStatement stmt, User entity) { stmt.clearBindings(); Long id = entity.getId(); if (id != null) { stmt.bindLong(1, id); } String entityID = entity.getEntityID(); if (entityID != null) { stmt.bindString(2, entityID); } java.util.Date lastOnline = entity.getLastOnline(); if (lastOnline != null) { stmt.bindLong(3, lastOnline.getTime()); } Boolean isOnline = entity.getIsOnline(); if (isOnline != null) { stmt.bindLong(4, isOnline ? 1L: 0L); } } @Override protected final void attachEntity(User entity) { super.attachEntity(entity); entity.__setDaoSession(daoSession); } @Override public Long readKey(Cursor cursor, int offset) { return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0); } @Override public User readEntity(Cursor cursor, int offset) { User entity = new User( // cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1), // entityID cursor.isNull(offset + 2) ? null : new java.util.Date(cursor.getLong(offset + 2)), // lastOnline cursor.isNull(offset + 3) ? null : cursor.getShort(offset + 3) != 0 // isOnline ); return entity; } @Override public void readEntity(Cursor cursor, User entity, int offset) { entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0)); entity.setEntityID(cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1)); entity.setLastOnline(cursor.isNull(offset + 2) ? null : new java.util.Date(cursor.getLong(offset + 2))); entity.setIsOnline(cursor.isNull(offset + 3) ? null : cursor.getShort(offset + 3) != 0); } @Override protected final Long updateKeyAfterInsert(User entity, long rowId) { entity.setId(rowId); return rowId; } @Override public Long getKey(User entity) { if(entity != null) { return entity.getId(); } else { return null; } } @Override public boolean hasKey(User entity) { return entity.getId() != null; } @Override protected final boolean isEntityUpdateable() { return true; } }
apache-2.0
jacarrichan/eoffice
src/main/java/com/palmelf/eoffice/model/admin/ConfSummary.java
3683
package com.palmelf.eoffice.model.admin; import java.util.Date; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import com.palmelf.core.model.BaseModel; import com.palmelf.eoffice.model.system.FileAttach; @Entity @Table(name = "conf_summary") public class ConfSummary extends BaseModel { /** * */ private static final long serialVersionUID = 4802924035069500594L; private Conference confId; private Long sumId; private Date createtime; private String creator; private String sumContent; private Short status; private Set<FileAttach> attachFiles = new HashSet<FileAttach>(); @Id @GeneratedValue @Column(name = "sumId", unique = true, nullable = false) public Long getSumId() { return this.sumId; } public void setSumId(Long sumId) { this.sumId = sumId; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "confId") public Conference getConfId() { return this.confId; } public void setConfId(Conference conference) { this.confId = conference; } @Column(name = "createtime", nullable = false, length = 19) public Date getCreatetime() { return this.createtime; } public void setCreatetime(Date createtime) { this.createtime = createtime; } @Column(name = "creator", nullable = false, length = 32) public String getCreator() { return this.creator; } public void setCreator(String creator) { this.creator = creator; } @Column(name = "sumContent", nullable = false) public String getSumContent() { return this.sumContent; } public void setSumContent(String sumContent) { this.sumContent = sumContent; } @Column(name = "status") public Short getStatus() { return this.status; } public void setStatus(Short status) { this.status = status; } @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JoinTable(name = "conf_sum_attach", joinColumns = { @JoinColumn(name = "sumId", nullable = false, updatable = false) }, inverseJoinColumns = { @JoinColumn(name = "fileId", nullable = false, updatable = false) }) public Set<FileAttach> getAttachFiles() { return this.attachFiles; } public void setAttachFiles(Set<FileAttach> fileAttachs) { this.attachFiles = fileAttachs; } @Override public boolean equals(Object object) { if (!(object instanceof ConfSummary)) { return false; } ConfSummary rhs = (ConfSummary) object; return new EqualsBuilder().append(this.sumId, rhs.sumId).append(this.confId, rhs.confId) .append(this.createtime, rhs.createtime).append(this.creator, rhs.creator) .append(this.sumContent, rhs.sumContent).append(this.status, rhs.status).isEquals(); } @Override public int hashCode() { return new HashCodeBuilder(-82280557, -700257973).append(this.sumId).append(this.confId) .append(this.createtime).append(this.creator).append(this.sumContent).append(this.status).toHashCode(); } @Override public String toString() { return new ToStringBuilder(this).append("sumId", this.sumId).append("confId", this.confId) .append("createtime", this.createtime).append("creator", this.creator) .append("sumContent", this.sumContent).append("status", this.status).toString(); } }
apache-2.0
mcaprari/smack
test-unit/org/jivesoftware/smack/TestUtils.java
2145
/** * $RCSfile$ * $Revision$ * $Date$ * * Copyright 2013 Robin Collier * * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jivesoftware.smack; import java.io.IOException; import java.io.StringReader; import org.xmlpull.mxp1.MXParser; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; final public class TestUtils { private TestUtils() { } public static XmlPullParser getIQParser(String stanza) { return getParser(stanza, "iq"); } public static XmlPullParser getMessageParser(String stanza) { return getParser(stanza, "message"); } public static XmlPullParser getPresenceParser(String stanza) { return getParser(stanza, "presence"); } public static XmlPullParser getParser(String stanza, String startTag) { XmlPullParser parser = new MXParser(); try { parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true); parser.setInput(new StringReader(stanza)); boolean found = false; while (!found) { if ((parser.next() == XmlPullParser.START_TAG) && parser.getName().equals(startTag)) found = true; } if (!found) throw new IllegalArgumentException("Cannot parse start tag [" + startTag + "] from stanza [" + stanza + "]"); } catch (XmlPullParserException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } return parser; } }
apache-2.0
FuckBoilerplate/base_app_android
app/src/main/java/app/data/foundation/net/mock/Seeder.java
1419
/* * Copyright 2016 FuckBoilerplate * * 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 app.data.foundation.net.mock; import java.util.ArrayList; import java.util.List; import app.data.foundation.Repository; import app.domain.user_demo.User; public class Seeder { public User getUserByName(String name) { User user = new User(1); user.setLogin(name); user.setAvatar_url("https://assets-cdn.github.com/images/modules/logos_page/GitHub-Mark.png"); return user; } public List<User> getUsers() { List<User> users = new ArrayList<>(); for (int i = 1; i < Repository.PER_PAGE; i++) { User user = new User(i); user.setLogin("Name " + i); user.setAvatar_url("https://assets-cdn.github.com/images/modules/logos_page/GitHub-Mark.png"); users.add(user); } return users; } }
apache-2.0
StepicOrg/stepik-android
app/src/main/java/org/stepic/droid/core/ScreenManager.java
7366
package org.stepic.droid.core; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.net.Uri; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentActivity; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.stepic.droid.model.CertificateListItem; import org.stepic.droid.social.SocialMedia; import org.stepik.android.domain.auth.model.SocialAuthType; import org.stepik.android.domain.course.analytic.CourseViewSource; import org.stepik.android.domain.course_list.model.CourseListQuery; import org.stepik.android.domain.course_payments.model.DeeplinkPromoCode; import org.stepik.android.domain.feedback.model.SupportEmailData; import org.stepik.android.domain.last_step.model.LastStep; import org.stepik.android.domain.lesson.model.LessonData; import org.stepik.android.model.Course; import org.stepik.android.model.Lesson; import org.stepik.android.model.Section; import org.stepik.android.model.Step; import org.stepik.android.model.Unit; import org.stepik.android.model.comments.DiscussionThread; import org.stepik.android.model.user.Profile; import org.stepik.android.view.auth.model.AutoAuth; import org.stepik.android.view.course.routing.CourseScreenTab; import org.stepik.android.view.routing.deeplink.BranchRoute; import org.stepik.android.view.video_player.model.VideoPlayerMediaData; public interface ScreenManager { void showLaunchFromSplash(Activity activity); void showLaunchScreen(Context context); void showLaunchScreenAfterLogout(Context context); void showLaunchScreen(Context context, boolean fromMainFeed, int indexInMenu); void showRegistration(Activity sourceActivity, @Nullable Course course); void showLogin(Activity sourceActivity, @Nullable String email, @Nullable String password, AutoAuth autoAuth, @Nullable Course course); void showMainFeedAfterLogin(Activity sourceActivity, @Nullable Course course); void showMainFeedFromSplash(Activity sourceActivity); void showMainFeed(Context sourceActivity, int indexOfMenu); void showPdfInBrowserByGoogleDocs(Activity activity, String fullPath); void openComments(Activity context, @NonNull DiscussionThread discussionThread, @NonNull Step step, @Nullable Long discussionId, boolean needOpenForm, boolean isTeacher); void showSteps(Activity sourceActivity, @NotNull Unit unit, @NotNull Lesson lesson, @NotNull Section section); void showSteps(Activity sourceActivity, @NotNull Unit unit, @NotNull Lesson lesson, @NotNull Section section, boolean backAnimation, boolean isAutoplayEnabled); void showTrialLesson(Activity sourceActivity, Long lessonId, Long unitId); void openStepInWeb(Context context, Step step); void openRemindPassword(AppCompatActivity context); void showCourseDescription(Context context, long courseId, @NotNull CourseViewSource viewSource); void showCourseDescription(Context context, @NotNull Course course, @NotNull CourseViewSource viewSource); void showCourseDescription(Context context, @NotNull Course course, @NotNull CourseViewSource viewSource, boolean autoEnroll); void showCourseModules(Context context, @NotNull Course course, @NotNull CourseViewSource viewSource); void showCourseScreen(Context context, @NotNull Course course, @NotNull CourseViewSource viewSource, boolean autoEnroll, CourseScreenTab tab); void showStoreWithApp(Activity sourceActivity); void showDownloads(Context context); void showCatalog(Context context); Intent getCatalogIntent(Context context); void showVideo(@NotNull Fragment sourceFragment, @NotNull VideoPlayerMediaData videoPlayerMediaData, @Nullable LessonData lessonMovementBundle); void showSettings(Activity sourceActivity); void showNotificationSettings(Activity sourceActivity); void showStorageManagement(Activity activity); void openInWeb(Activity context, String path); void addCertificateToLinkedIn(CertificateListItem.Data certificateListItem); void showCertificates(Context context); void showCertificates(Context context, long userId, boolean isCurrentUser); Intent getCertificateIntent(); Intent getOpenInWebIntent(String path); /** * Redirects to external web browser in case if app intercepts wrong deeplink (if uri contains `from_mobile_app=true` query param) * @param context - activity context * @param uri - Intent::data */ void redirectToWebBrowserIfNeeded(@NotNull Context context, @NotNull Uri uri); void openLinkInWebBrowser(@NotNull Context context, @NotNull Uri uri); void openProfile(@NonNull Context context, long userId); void openFeedbackActivity(Activity activity); Intent getMyCoursesIntent(@NotNull Context context); Intent getProfileIntent(@NotNull Context context); Intent getMyProfileIntent(@NotNull Context context); void openSplash(Context context); void openAboutActivity(Activity activity); void openPrivacyPolicyWeb(Activity activity); void openTermsOfServiceWeb(Activity activity); void continueAdaptiveCourse(Activity activity, Course course); void continueCourse(Activity activity, long courseId, @NotNull CourseViewSource viewSource, @NotNull LastStep lastStep); void continueCourse(Activity activity, @NotNull LastStep lastStep); void showLaunchScreen(FragmentActivity activity, @NotNull Course course); void openImage(Context context, String path); void showAdaptiveStats(Context context, long courseId); void showOnboarding(@NotNull Activity activity); void showAchievementsList(Context context, long userId, boolean isMyProfile); void openDeepLink(Context context, BranchRoute route); void showProfileEdit(Context context); void showProfileEditInfo(Activity activity, Profile profile); void showProfileEditPassword(Activity activity, long profileId); void openTextFeedBack(Context context, SupportEmailData supportEmailData); void openSocialMediaLink(Context context, String link); void openSocialMediaLink(Context context, SocialMedia socialLink); void loginWithSocial(FragmentActivity activity, SocialAuthType type); void showCachedAttempts(@NotNull Context context, long courseId); void showCoursesByQuery(Context context, String courseListTitle, CourseListQuery courseListQuery); void showCoursesCollection(Context context, long courseCollectionId); void showUserCourses(Context context); void showVisitedCourses(Context context); void showPersonalizedOnboarding(Context context); void showCourseFromNavigationDialog(Context context, long courseId, CourseViewSource courseViewSource, CourseScreenTab courseScreenTab); void showCoursePurchaseFromLessonDemoDialog(Context context, long courseId, CourseViewSource courseViewSource, CourseScreenTab courseScreenTab, DeeplinkPromoCode deeplinkPromoCode); void showWishlist(Context context); void showCourseRevenue(Context context, long courseId, @Nullable String courseTitle); void showUserReviews(Context context); void showCourseAfterPurchase(Context context, Course course, CourseViewSource courseViewSource, CourseScreenTab courseScreenTab); }
apache-2.0
crate/crate
server/src/test/java/org/elasticsearch/cluster/coordination/FollowersCheckerTests.java
30646
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.cluster.coordination; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.Version; import org.elasticsearch.cluster.ClusterName; import org.elasticsearch.cluster.coordination.Coordinator.Mode; import org.elasticsearch.cluster.coordination.FollowersChecker.FollowerCheckRequest; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.node.DiscoveryNodeRole; import org.elasticsearch.cluster.node.DiscoveryNodes; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings.Builder; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.EqualsHashCodeTestUtils; import org.elasticsearch.test.EqualsHashCodeTestUtils.CopyFunction; import org.elasticsearch.test.transport.CapturingTransport; import org.elasticsearch.test.transport.MockTransport; import org.elasticsearch.threadpool.ThreadPool.Names; import org.elasticsearch.transport.AbstractSimpleTransportTestCase; import org.elasticsearch.transport.ConnectTransportException; import org.elasticsearch.transport.TransportException; import org.elasticsearch.transport.TransportRequest; import org.elasticsearch.transport.TransportResponse; import org.elasticsearch.transport.TransportResponse.Empty; import org.elasticsearch.transport.TransportResponseHandler; import org.elasticsearch.transport.TransportService; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.elasticsearch.cluster.coordination.FollowersChecker.FOLLOWER_CHECK_ACTION_NAME; import static org.elasticsearch.cluster.coordination.FollowersChecker.FOLLOWER_CHECK_INTERVAL_SETTING; import static org.elasticsearch.cluster.coordination.FollowersChecker.FOLLOWER_CHECK_RETRY_COUNT_SETTING; import static org.elasticsearch.cluster.coordination.FollowersChecker.FOLLOWER_CHECK_TIMEOUT_SETTING; import static org.elasticsearch.node.Node.NODE_NAME_SETTING; import static org.elasticsearch.transport.TransportService.HANDSHAKE_ACTION_NAME; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.core.IsInstanceOf.instanceOf; public class FollowersCheckerTests extends ESTestCase { public void testChecksExpectedNodes() { final DiscoveryNode localNode = new DiscoveryNode("local-node", buildNewFakeTransportAddress(), Version.CURRENT); final Settings settings = Settings.builder().put(NODE_NAME_SETTING.getKey(), localNode.getName()).build(); final DiscoveryNodes[] discoveryNodesHolder = new DiscoveryNodes[]{DiscoveryNodes.builder().add(localNode).localNodeId(localNode.getId()).build()}; final DeterministicTaskQueue deterministicTaskQueue = new DeterministicTaskQueue(settings, random()); final Set<DiscoveryNode> checkedNodes = new HashSet<>(); final AtomicInteger checkCount = new AtomicInteger(); final MockTransport mockTransport = new MockTransport() { @Override protected void onSendRequest(long requestId, String action, TransportRequest request, DiscoveryNode node) { assertThat(action, equalTo(FOLLOWER_CHECK_ACTION_NAME)); assertThat(request, instanceOf(FollowerCheckRequest.class)); assertTrue(discoveryNodesHolder[0].nodeExists(node)); assertThat(node, not(equalTo(localNode))); checkedNodes.add(node); checkCount.incrementAndGet(); handleResponse(requestId, Empty.INSTANCE); } }; final TransportService transportService = mockTransport.createTransportService( settings, deterministicTaskQueue.getThreadPool(), boundTransportAddress -> localNode, null ); transportService.start(); transportService.acceptIncomingRequests(); final FollowersChecker followersChecker = new FollowersChecker(settings, transportService, fcr -> { assert false : fcr; }, (node, reason) -> { assert false : node; }); followersChecker.setCurrentNodes(discoveryNodesHolder[0]); deterministicTaskQueue.runAllTasks(); assertThat(checkedNodes, empty()); assertThat(followersChecker.getFaultyNodes(), empty()); final DiscoveryNode otherNode1 = new DiscoveryNode("other-node-1", buildNewFakeTransportAddress(), Version.CURRENT); followersChecker.setCurrentNodes(discoveryNodesHolder[0] = DiscoveryNodes.builder(discoveryNodesHolder[0]).add(otherNode1).build()); while (checkCount.get() < 10) { if (deterministicTaskQueue.hasRunnableTasks()) { deterministicTaskQueue.runRandomTask(); } else { deterministicTaskQueue.advanceTime(); } } assertThat(checkedNodes, contains(otherNode1)); assertThat(followersChecker.getFaultyNodes(), empty()); checkedNodes.clear(); checkCount.set(0); final DiscoveryNode otherNode2 = new DiscoveryNode("other-node-2", buildNewFakeTransportAddress(), Version.CURRENT); followersChecker.setCurrentNodes(discoveryNodesHolder[0] = DiscoveryNodes.builder(discoveryNodesHolder[0]).add(otherNode2).build()); while (checkCount.get() < 10) { if (deterministicTaskQueue.hasRunnableTasks()) { deterministicTaskQueue.runRandomTask(); } else { deterministicTaskQueue.advanceTime(); } } assertThat(checkedNodes, containsInAnyOrder(otherNode1, otherNode2)); assertThat(followersChecker.getFaultyNodes(), empty()); checkedNodes.clear(); checkCount.set(0); followersChecker.setCurrentNodes(discoveryNodesHolder[0] = DiscoveryNodes.builder(discoveryNodesHolder[0]).remove(otherNode1).build()); while (checkCount.get() < 10) { if (deterministicTaskQueue.hasRunnableTasks()) { deterministicTaskQueue.runRandomTask(); } else { deterministicTaskQueue.advanceTime(); } } assertThat(checkedNodes, contains(otherNode2)); assertThat(followersChecker.getFaultyNodes(), empty()); checkedNodes.clear(); followersChecker.clearCurrentNodes(); deterministicTaskQueue.runAllTasks(); assertThat(checkedNodes, empty()); } public void testFailsNodeThatDoesNotRespond() { final Builder settingsBuilder = Settings.builder(); if (randomBoolean()) { settingsBuilder.put(FOLLOWER_CHECK_RETRY_COUNT_SETTING.getKey(), randomIntBetween(1, 10)); } if (randomBoolean()) { settingsBuilder.put(FOLLOWER_CHECK_INTERVAL_SETTING.getKey(), randomIntBetween(100, 100000) + "ms"); } if (randomBoolean()) { settingsBuilder.put(FOLLOWER_CHECK_TIMEOUT_SETTING.getKey(), randomIntBetween(1, 100000) + "ms"); } final Settings settings = settingsBuilder.build(); testBehaviourOfFailingNode(settings, () -> null, "followers check retry count exceeded", (FOLLOWER_CHECK_RETRY_COUNT_SETTING.get(settings) - 1) * FOLLOWER_CHECK_INTERVAL_SETTING.get(settings).millis() + FOLLOWER_CHECK_RETRY_COUNT_SETTING.get(settings) * FOLLOWER_CHECK_TIMEOUT_SETTING.get(settings).millis()); } public void testFailsNodeThatRejectsCheck() { final Builder settingsBuilder = Settings.builder(); if (randomBoolean()) { settingsBuilder.put(FOLLOWER_CHECK_RETRY_COUNT_SETTING.getKey(), randomIntBetween(1, 10)); } if (randomBoolean()) { settingsBuilder.put(FOLLOWER_CHECK_INTERVAL_SETTING.getKey(), randomIntBetween(100, 100000) + "ms"); } final Settings settings = settingsBuilder.build(); testBehaviourOfFailingNode(settings, () -> { throw new ElasticsearchException("simulated exception"); }, "followers check retry count exceeded", (FOLLOWER_CHECK_RETRY_COUNT_SETTING.get(settings) - 1) * FOLLOWER_CHECK_INTERVAL_SETTING.get(settings).millis()); } public void testFailureCounterResetsOnSuccess() { final Builder settingsBuilder = Settings.builder(); if (randomBoolean()) { settingsBuilder.put(FOLLOWER_CHECK_RETRY_COUNT_SETTING.getKey(), randomIntBetween(2, 10)); } if (randomBoolean()) { settingsBuilder.put(FOLLOWER_CHECK_INTERVAL_SETTING.getKey(), randomIntBetween(100, 100000) + "ms"); } final Settings settings = settingsBuilder.build(); final int retryCount = FOLLOWER_CHECK_RETRY_COUNT_SETTING.get(settings); final int maxRecoveries = randomIntBetween(3, 10); // passes just enough checks to keep it alive, up to maxRecoveries, and then fails completely testBehaviourOfFailingNode(settings, new Supplier<Empty>() { private int checkIndex; private int recoveries; @Override public Empty get() { checkIndex++; if (checkIndex % retryCount == 0 && recoveries < maxRecoveries) { recoveries++; return Empty.INSTANCE; } throw new ElasticsearchException("simulated exception"); } }, "followers check retry count exceeded", (FOLLOWER_CHECK_RETRY_COUNT_SETTING.get(settings) * (maxRecoveries + 1) - 1) * FOLLOWER_CHECK_INTERVAL_SETTING.get(settings).millis()); } public void testFailsNodeThatIsDisconnected() { testBehaviourOfFailingNode(Settings.EMPTY, () -> { throw new ConnectTransportException(null, "simulated exception"); }, "disconnected", 0); } public void testFailsNodeThatDisconnects() { final DiscoveryNode localNode = new DiscoveryNode("local-node", buildNewFakeTransportAddress(), Version.CURRENT); final DiscoveryNode otherNode = new DiscoveryNode("other-node", buildNewFakeTransportAddress(), Version.CURRENT); final Settings settings = Settings.builder().put(NODE_NAME_SETTING.getKey(), localNode.getName()).build(); final DeterministicTaskQueue deterministicTaskQueue = new DeterministicTaskQueue(settings, random()); final MockTransport mockTransport = new MockTransport() { @Override protected void onSendRequest(long requestId, String action, TransportRequest request, DiscoveryNode node) { assertFalse(node.equals(localNode)); if (action.equals(HANDSHAKE_ACTION_NAME)) { handleResponse(requestId, new TransportService.HandshakeResponse(node, ClusterName.DEFAULT, Version.CURRENT)); return; } deterministicTaskQueue.scheduleNow(new Runnable() { @Override public void run() { handleResponse(requestId, Empty.INSTANCE); } @Override public String toString() { return "sending response to [" + action + "][" + requestId + "] from " + node; } }); } }; final TransportService transportService = mockTransport.createTransportService( settings, deterministicTaskQueue.getThreadPool(), boundTransportAddress -> localNode, null ); transportService.start(); transportService.acceptIncomingRequests(); final AtomicBoolean nodeFailed = new AtomicBoolean(); final FollowersChecker followersChecker = new FollowersChecker(settings, transportService, fcr -> { assert false : fcr; }, (node, reason) -> { assertTrue(nodeFailed.compareAndSet(false, true)); assertThat(reason, equalTo("disconnected")); }); DiscoveryNodes discoveryNodes = DiscoveryNodes.builder().add(localNode).add(otherNode).localNodeId(localNode.getId()).build(); followersChecker.setCurrentNodes(discoveryNodes); AbstractSimpleTransportTestCase.connectToNode(transportService, otherNode); transportService.disconnectFromNode(otherNode); deterministicTaskQueue.runAllRunnableTasks(); assertTrue(nodeFailed.get()); assertThat(followersChecker.getFaultyNodes(), contains(otherNode)); } private void testBehaviourOfFailingNode(Settings testSettings, Supplier<TransportResponse.Empty> responder, String failureReason, long expectedFailureTime) { final DiscoveryNode localNode = new DiscoveryNode("local-node", buildNewFakeTransportAddress(), Version.CURRENT); final DiscoveryNode otherNode = new DiscoveryNode("other-node", buildNewFakeTransportAddress(), Version.CURRENT); final Settings settings = Settings.builder().put(NODE_NAME_SETTING.getKey(), localNode.getName()).put(testSettings).build(); final DeterministicTaskQueue deterministicTaskQueue = new DeterministicTaskQueue(settings, random()); final MockTransport mockTransport = new MockTransport() { @Override protected void onSendRequest(long requestId, String action, TransportRequest request, DiscoveryNode node) { assertFalse(node.equals(localNode)); deterministicTaskQueue.scheduleNow(new Runnable() { @Override public void run() { if (node.equals(otherNode) == false) { // other nodes are ok handleResponse(requestId, Empty.INSTANCE); return; } try { final Empty response = responder.get(); if (response != null) { handleResponse(requestId, response); } } catch (Exception e) { handleRemoteError(requestId, e); } } @Override public String toString() { return "sending response to [" + action + "][" + requestId + "] from " + node; } }); } }; final TransportService transportService = mockTransport.createTransportService( settings, deterministicTaskQueue.getThreadPool(), boundTransportAddress -> localNode, null ); transportService.start(); transportService.acceptIncomingRequests(); final AtomicBoolean nodeFailed = new AtomicBoolean(); final FollowersChecker followersChecker = new FollowersChecker(settings, transportService, fcr -> { assert false : fcr; }, (node, reason) -> { assertTrue(nodeFailed.compareAndSet(false, true)); assertThat(reason, equalTo(failureReason)); }); DiscoveryNodes discoveryNodes = DiscoveryNodes.builder().add(localNode).add(otherNode).localNodeId(localNode.getId()).build(); followersChecker.setCurrentNodes(discoveryNodes); while (nodeFailed.get() == false) { if (deterministicTaskQueue.hasRunnableTasks() == false) { deterministicTaskQueue.advanceTime(); } deterministicTaskQueue.runAllRunnableTasks(); } assertThat(deterministicTaskQueue.getCurrentTimeMillis(), equalTo(expectedFailureTime)); assertThat(followersChecker.getFaultyNodes(), contains(otherNode)); deterministicTaskQueue.runAllTasks(); // add another node and see that it schedules checks for this new node but keeps on considering the old one faulty final DiscoveryNode otherNode2 = new DiscoveryNode("other-node-2", buildNewFakeTransportAddress(), Version.CURRENT); discoveryNodes = DiscoveryNodes.builder(discoveryNodes).add(otherNode2).build(); followersChecker.setCurrentNodes(discoveryNodes); deterministicTaskQueue.runAllRunnableTasks(); deterministicTaskQueue.advanceTime(); deterministicTaskQueue.runAllRunnableTasks(); assertThat(followersChecker.getFaultyNodes(), contains(otherNode)); // remove the faulty node and see that it is removed discoveryNodes = DiscoveryNodes.builder(discoveryNodes).remove(otherNode).build(); followersChecker.setCurrentNodes(discoveryNodes); assertThat(followersChecker.getFaultyNodes(), empty()); deterministicTaskQueue.runAllRunnableTasks(); deterministicTaskQueue.advanceTime(); deterministicTaskQueue.runAllRunnableTasks(); // remove the working node and see that everything eventually stops discoveryNodes = DiscoveryNodes.builder(discoveryNodes).remove(otherNode2).build(); followersChecker.setCurrentNodes(discoveryNodes); deterministicTaskQueue.runAllTasks(); // add back the faulty node afresh and see that it fails again discoveryNodes = DiscoveryNodes.builder(discoveryNodes).add(otherNode).build(); followersChecker.setCurrentNodes(discoveryNodes); nodeFailed.set(false); assertThat(followersChecker.getFaultyNodes(), empty()); deterministicTaskQueue.runAllTasksInTimeOrder(); assertTrue(nodeFailed.get()); assertThat(followersChecker.getFaultyNodes(), contains(otherNode)); } public void testFollowerCheckRequestEqualsHashCodeSerialization() { // Note: the explicit cast of the CopyFunction is needed for some IDE (specifically Eclipse 4.8.0) to infer the right type EqualsHashCodeTestUtils.checkEqualsAndHashCode(new FollowerCheckRequest(randomNonNegativeLong(), new DiscoveryNode(randomAlphaOfLength(10), buildNewFakeTransportAddress(), Version.CURRENT)), (CopyFunction<FollowerCheckRequest>) rq -> copyWriteable(rq, writableRegistry(), FollowerCheckRequest::new), rq -> { if (randomBoolean()) { return new FollowerCheckRequest(rq.getTerm(), new DiscoveryNode(randomAlphaOfLength(10), buildNewFakeTransportAddress(), Version.CURRENT)); } else { return new FollowerCheckRequest(randomNonNegativeLong(), rq.getSender()); } }); } public void testResponder() { final DiscoveryNode leader = new DiscoveryNode("leader", buildNewFakeTransportAddress(), Version.CURRENT); final DiscoveryNode follower = new DiscoveryNode("follower", buildNewFakeTransportAddress(), Version.CURRENT); final Settings settings = Settings.builder().put(NODE_NAME_SETTING.getKey(), follower.getName()).build(); final DeterministicTaskQueue deterministicTaskQueue = new DeterministicTaskQueue(settings, random()); final MockTransport mockTransport = new MockTransport() { @Override protected void onSendRequest(long requestId, String action, TransportRequest request, DiscoveryNode node) { throw new AssertionError("no requests expected"); } }; final TransportService transportService = mockTransport.createTransportService( settings, deterministicTaskQueue.getThreadPool(), boundTransportAddress -> follower, null ); transportService.start(); transportService.acceptIncomingRequests(); final AtomicBoolean calledCoordinator = new AtomicBoolean(); final AtomicReference<RuntimeException> coordinatorException = new AtomicReference<>(); final FollowersChecker followersChecker = new FollowersChecker(settings, transportService, fcr -> { assertTrue(calledCoordinator.compareAndSet(false, true)); final RuntimeException exception = coordinatorException.get(); if (exception != null) { throw exception; } }, (node, reason) -> { assert false : node; }); { // Does not call into the coordinator in the normal case final long term = randomNonNegativeLong(); followersChecker.updateFastResponseState(term, Mode.FOLLOWER); final ExpectsSuccess expectsSuccess = new ExpectsSuccess(); transportService.sendRequest(follower, FOLLOWER_CHECK_ACTION_NAME, new FollowerCheckRequest(term, leader), expectsSuccess); deterministicTaskQueue.runAllTasks(); assertTrue(expectsSuccess.succeeded()); assertFalse(calledCoordinator.get()); } { // Does not call into the coordinator for a term that's too low, just rejects immediately final long leaderTerm = randomLongBetween(1, Long.MAX_VALUE - 1); final long followerTerm = randomLongBetween(leaderTerm + 1, Long.MAX_VALUE); followersChecker.updateFastResponseState(followerTerm, Mode.FOLLOWER); final AtomicReference<TransportException> receivedException = new AtomicReference<>(); transportService.sendRequest(follower, FOLLOWER_CHECK_ACTION_NAME, new FollowerCheckRequest(leaderTerm, leader), new TransportResponseHandler<TransportResponse.Empty>() { @Override public TransportResponse.Empty read(StreamInput in) { return TransportResponse.Empty.INSTANCE; } @Override public void handleResponse(TransportResponse.Empty response) { fail("unexpected success"); } @Override public void handleException(TransportException exp) { assertThat(exp, not(nullValue())); assertTrue(receivedException.compareAndSet(null, exp)); } @Override public String executor() { return Names.SAME; } }); deterministicTaskQueue.runAllTasks(); assertFalse(calledCoordinator.get()); assertThat(receivedException.get(), not(nullValue())); } { // Calls into the coordinator if the term needs bumping final long leaderTerm = randomLongBetween(2, Long.MAX_VALUE); final long followerTerm = randomLongBetween(1, leaderTerm - 1); followersChecker.updateFastResponseState(followerTerm, Mode.FOLLOWER); final ExpectsSuccess expectsSuccess = new ExpectsSuccess(); transportService.sendRequest(follower, FOLLOWER_CHECK_ACTION_NAME, new FollowerCheckRequest(leaderTerm, leader), expectsSuccess); deterministicTaskQueue.runAllTasks(); assertTrue(expectsSuccess.succeeded()); assertTrue(calledCoordinator.get()); calledCoordinator.set(false); } { // Calls into the coordinator if not a follower final long term = randomNonNegativeLong(); followersChecker.updateFastResponseState(term, randomFrom(Mode.LEADER, Mode.CANDIDATE)); final ExpectsSuccess expectsSuccess = new ExpectsSuccess(); transportService.sendRequest(follower, FOLLOWER_CHECK_ACTION_NAME, new FollowerCheckRequest(term, leader), expectsSuccess); deterministicTaskQueue.runAllTasks(); assertTrue(expectsSuccess.succeeded()); assertTrue(calledCoordinator.get()); calledCoordinator.set(false); } { // If it calls into the coordinator and the coordinator throws an exception then it's passed back to the caller final long term = randomNonNegativeLong(); followersChecker.updateFastResponseState(term, randomFrom(Mode.LEADER, Mode.CANDIDATE)); final String exceptionMessage = "test simulated exception " + randomNonNegativeLong(); coordinatorException.set(new ElasticsearchException(exceptionMessage)); final AtomicReference<TransportException> receivedException = new AtomicReference<>(); transportService.sendRequest(follower, FOLLOWER_CHECK_ACTION_NAME, new FollowerCheckRequest(term, leader), new TransportResponseHandler<TransportResponse.Empty>() { @Override public TransportResponse.Empty read(StreamInput in) { return TransportResponse.Empty.INSTANCE; } @Override public void handleResponse(TransportResponse.Empty response) { fail("unexpected success"); } @Override public void handleException(TransportException exp) { assertThat(exp, not(nullValue())); assertTrue(receivedException.compareAndSet(null, exp)); } @Override public String executor() { return Names.SAME; } }); deterministicTaskQueue.runAllTasks(); assertTrue(calledCoordinator.get()); assertThat(receivedException.get(), not(nullValue())); assertThat(receivedException.get().getRootCause().getMessage(), equalTo(exceptionMessage)); } } public void testPreferMasterNodes() { List<DiscoveryNode> nodes = randomNodes(10); DiscoveryNodes.Builder discoNodesBuilder = DiscoveryNodes.builder(); nodes.forEach(dn -> discoNodesBuilder.add(dn)); DiscoveryNodes discoveryNodes = discoNodesBuilder.localNodeId(nodes.get(0).getId()).build(); CapturingTransport capturingTransport = new CapturingTransport(); final Settings settings = Settings.builder().put(NODE_NAME_SETTING.getKey(), nodes.get(0).getName()).build(); final DeterministicTaskQueue deterministicTaskQueue = new DeterministicTaskQueue(settings, random()); TransportService transportService = capturingTransport.createTransportService( Settings.EMPTY, deterministicTaskQueue.getThreadPool(), x -> nodes.get(0), null ); final FollowersChecker followersChecker = new FollowersChecker(Settings.EMPTY, transportService, fcr -> { assert false : fcr; }, (node, reason) -> { assert false : node; }); followersChecker.setCurrentNodes(discoveryNodes); List<DiscoveryNode> followerTargets = Stream.of(capturingTransport.getCapturedRequestsAndClear()) .map(cr -> cr.node).collect(Collectors.toList()); List<DiscoveryNode> sortedFollowerTargets = new ArrayList<>(followerTargets); Collections.sort(sortedFollowerTargets, Comparator.comparing(n -> n.isMasterEligibleNode() == false)); assertEquals(sortedFollowerTargets, followerTargets); } private static List<DiscoveryNode> randomNodes(final int numNodes) { List<DiscoveryNode> nodesList = new ArrayList<>(); for (int i = 0; i < numNodes; i++) { Map<String, String> attributes = new HashMap<>(); if (frequently()) { attributes.put("custom", randomBoolean() ? "match" : randomAlphaOfLengthBetween(3, 5)); } final DiscoveryNode node = newNode(i, attributes, new HashSet<>(randomSubsetOf(DiscoveryNodeRole.BUILT_IN_ROLES))); nodesList.add(node); } return nodesList; } private static DiscoveryNode newNode(int nodeId, Map<String, String> attributes, Set<DiscoveryNodeRole> roles) { return new DiscoveryNode("name_" + nodeId, "node_" + nodeId, buildNewFakeTransportAddress(), attributes, roles, Version.CURRENT); } private static class ExpectsSuccess implements TransportResponseHandler<Empty> { private final AtomicBoolean responseReceived = new AtomicBoolean(); @Override public void handleResponse(Empty response) { assertTrue(responseReceived.compareAndSet(false, true)); } @Override public void handleException(TransportException exp) { throw new AssertionError("unexpected", exp); } @Override public String executor() { return Names.SAME; } public boolean succeeded() { return responseReceived.get(); } @Override public TransportResponse.Empty read(StreamInput in) { return TransportResponse.Empty.INSTANCE; } } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-inspector/src/main/java/com/amazonaws/services/inspector/model/SecurityGroup.java
5448
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.inspector.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * Contains information about a security group associated with a network interface. This data type is used as one of the * elements of the <a>NetworkInterface</a> data type. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/inspector-2016-02-16/SecurityGroup" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class SecurityGroup implements Serializable, Cloneable, StructuredPojo { /** * <p> * The name of the security group. * </p> */ private String groupName; /** * <p> * The ID of the security group. * </p> */ private String groupId; /** * <p> * The name of the security group. * </p> * * @param groupName * The name of the security group. */ public void setGroupName(String groupName) { this.groupName = groupName; } /** * <p> * The name of the security group. * </p> * * @return The name of the security group. */ public String getGroupName() { return this.groupName; } /** * <p> * The name of the security group. * </p> * * @param groupName * The name of the security group. * @return Returns a reference to this object so that method calls can be chained together. */ public SecurityGroup withGroupName(String groupName) { setGroupName(groupName); return this; } /** * <p> * The ID of the security group. * </p> * * @param groupId * The ID of the security group. */ public void setGroupId(String groupId) { this.groupId = groupId; } /** * <p> * The ID of the security group. * </p> * * @return The ID of the security group. */ public String getGroupId() { return this.groupId; } /** * <p> * The ID of the security group. * </p> * * @param groupId * The ID of the security group. * @return Returns a reference to this object so that method calls can be chained together. */ public SecurityGroup withGroupId(String groupId) { setGroupId(groupId); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getGroupName() != null) sb.append("GroupName: ").append(getGroupName()).append(","); if (getGroupId() != null) sb.append("GroupId: ").append(getGroupId()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof SecurityGroup == false) return false; SecurityGroup other = (SecurityGroup) obj; if (other.getGroupName() == null ^ this.getGroupName() == null) return false; if (other.getGroupName() != null && other.getGroupName().equals(this.getGroupName()) == false) return false; if (other.getGroupId() == null ^ this.getGroupId() == null) return false; if (other.getGroupId() != null && other.getGroupId().equals(this.getGroupId()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getGroupName() == null) ? 0 : getGroupName().hashCode()); hashCode = prime * hashCode + ((getGroupId() == null) ? 0 : getGroupId().hashCode()); return hashCode; } @Override public SecurityGroup clone() { try { return (SecurityGroup) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.inspector.model.transform.SecurityGroupMarshaller.getInstance().marshall(this, protocolMarshaller); } }
apache-2.0
Cloudyle/hapi-fhir
hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/dao/dstu3/BaseJpaDstu3Test.java
11670
package ca.uhn.fhir.jpa.dao.dstu3; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import java.io.IOException; import java.io.InputStream; import javax.persistence.EntityManager; import org.apache.commons.io.IOUtils; import org.hibernate.search.jpa.FullTextEntityManager; import org.hibernate.search.jpa.Search; import org.hl7.fhir.dstu3.hapi.validation.IValidationSupport; import org.hl7.fhir.dstu3.model.Bundle; import org.hl7.fhir.dstu3.model.CodeableConcept; import org.hl7.fhir.dstu3.model.Coding; import org.hl7.fhir.dstu3.model.ConceptMap; import org.hl7.fhir.dstu3.model.Device; import org.hl7.fhir.dstu3.model.DiagnosticOrder; import org.hl7.fhir.dstu3.model.DiagnosticReport; import org.hl7.fhir.dstu3.model.Encounter; import org.hl7.fhir.dstu3.model.Immunization; import org.hl7.fhir.dstu3.model.Location; import org.hl7.fhir.dstu3.model.Media; import org.hl7.fhir.dstu3.model.Medication; import org.hl7.fhir.dstu3.model.MedicationOrder; import org.hl7.fhir.dstu3.model.Meta; import org.hl7.fhir.dstu3.model.NamingSystem; import org.hl7.fhir.dstu3.model.Observation; import org.hl7.fhir.dstu3.model.Organization; import org.hl7.fhir.dstu3.model.Patient; import org.hl7.fhir.dstu3.model.Practitioner; import org.hl7.fhir.dstu3.model.Questionnaire; import org.hl7.fhir.dstu3.model.QuestionnaireResponse; import org.hl7.fhir.dstu3.model.StructureDefinition; import org.hl7.fhir.dstu3.model.Subscription; import org.hl7.fhir.dstu3.model.Substance; import org.hl7.fhir.dstu3.model.ValueSet; import org.hl7.fhir.instance.model.api.IBaseResource; import org.junit.Before; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.ApplicationContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.jpa.config.TestDstu3Config; import ca.uhn.fhir.jpa.dao.BaseJpaTest; import ca.uhn.fhir.jpa.dao.DaoConfig; import ca.uhn.fhir.jpa.dao.IFhirResourceDao; import ca.uhn.fhir.jpa.dao.IFhirResourceDaoPatient; import ca.uhn.fhir.jpa.dao.IFhirResourceDaoSubscription; import ca.uhn.fhir.jpa.dao.IFhirResourceDaoValueSet; import ca.uhn.fhir.jpa.dao.IFhirSystemDao; import ca.uhn.fhir.jpa.dao.ISearchDao; import ca.uhn.fhir.jpa.dao.dstu2.FhirResourceDaoDstu2SearchNoFtTest; import ca.uhn.fhir.jpa.entity.ForcedId; import ca.uhn.fhir.jpa.entity.ResourceHistoryTable; import ca.uhn.fhir.jpa.entity.ResourceHistoryTag; import ca.uhn.fhir.jpa.entity.ResourceIndexedSearchParamCoords; import ca.uhn.fhir.jpa.entity.ResourceIndexedSearchParamDate; import ca.uhn.fhir.jpa.entity.ResourceIndexedSearchParamNumber; import ca.uhn.fhir.jpa.entity.ResourceIndexedSearchParamQuantity; import ca.uhn.fhir.jpa.entity.ResourceIndexedSearchParamString; import ca.uhn.fhir.jpa.entity.ResourceIndexedSearchParamToken; import ca.uhn.fhir.jpa.entity.ResourceIndexedSearchParamUri; import ca.uhn.fhir.jpa.entity.ResourceLink; import ca.uhn.fhir.jpa.entity.ResourceTable; import ca.uhn.fhir.jpa.entity.ResourceTag; import ca.uhn.fhir.jpa.entity.SubscriptionFlaggedResource; import ca.uhn.fhir.jpa.entity.SubscriptionTable; import ca.uhn.fhir.jpa.entity.TagDefinition; import ca.uhn.fhir.jpa.provider.dstu3.JpaSystemProviderDstu3; import ca.uhn.fhir.parser.IParser; import ca.uhn.fhir.rest.method.MethodUtil; import ca.uhn.fhir.rest.server.interceptor.IServerInterceptor; //@formatter:off @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes= {TestDstu3Config.class}) //@formatter:on public abstract class BaseJpaDstu3Test extends BaseJpaTest { @Autowired @Qualifier("myJpaValidationSupportChainDstu3") protected IValidationSupport myValidationSupport; @Autowired protected ApplicationContext myAppCtx; @Autowired protected ISearchDao mySearchDao; @Autowired @Qualifier("myConceptMapDaoDstu3") protected IFhirResourceDao<ConceptMap> myConceptMapDao; @Autowired @Qualifier("myMedicationDaoDstu3") protected IFhirResourceDao<Medication> myMedicationDao; @Autowired @Qualifier("myMedicationOrderDaoDstu3") protected IFhirResourceDao<MedicationOrder> myMedicationOrderDao; @Autowired protected DaoConfig myDaoConfig; @Autowired @Qualifier("myDeviceDaoDstu3") protected IFhirResourceDao<Device> myDeviceDao; @Autowired @Qualifier("myDiagnosticOrderDaoDstu3") protected IFhirResourceDao<DiagnosticOrder> myDiagnosticOrderDao; @Autowired @Qualifier("myDiagnosticReportDaoDstu3") protected IFhirResourceDao<DiagnosticReport> myDiagnosticReportDao; @Autowired @Qualifier("myEncounterDaoDstu3") protected IFhirResourceDao<Encounter> myEncounterDao; // @PersistenceContext() @Autowired protected EntityManager myEntityManager; @Autowired @Qualifier("myFhirContextDstu3") protected FhirContext myFhirCtx; @Autowired @Qualifier("myImmunizationDaoDstu3") protected IFhirResourceDao<Immunization> myImmunizationDao; protected IServerInterceptor myInterceptor; @Autowired @Qualifier("myLocationDaoDstu3") protected IFhirResourceDao<Location> myLocationDao; @Autowired @Qualifier("myObservationDaoDstu3") protected IFhirResourceDao<Observation> myObservationDao; @Autowired @Qualifier("myOrganizationDaoDstu3") protected IFhirResourceDao<Organization> myOrganizationDao; @Autowired @Qualifier("myPatientDaoDstu3") protected IFhirResourceDaoPatient<Patient> myPatientDao; @Autowired @Qualifier("myNamingSystemDaoDstu3") protected IFhirResourceDao<NamingSystem> myNamingSystemDao; @Autowired @Qualifier("myMediaDaoDstu3") protected IFhirResourceDao<Media> myMediaDao; @Autowired @Qualifier("myPractitionerDaoDstu3") protected IFhirResourceDao<Practitioner> myPractitionerDao; @Autowired @Qualifier("myQuestionnaireDaoDstu3") protected IFhirResourceDao<Questionnaire> myQuestionnaireDao; @Autowired @Qualifier("myQuestionnaireResponseDaoDstu3") protected IFhirResourceDao<QuestionnaireResponse> myQuestionnaireResponseDao; @Autowired @Qualifier("myResourceProvidersDstu3") protected Object myResourceProviders; @Autowired @Qualifier("myStructureDefinitionDaoDstu3") protected IFhirResourceDao<StructureDefinition> myStructureDefinitionDao; @Autowired @Qualifier("mySubscriptionDaoDstu3") protected IFhirResourceDaoSubscription<Subscription> mySubscriptionDao; @Autowired @Qualifier("mySubstanceDaoDstu3") protected IFhirResourceDao<Substance> mySubstanceDao; @Autowired @Qualifier("mySystemDaoDstu3") protected IFhirSystemDao<Bundle, Meta> mySystemDao; @Autowired @Qualifier("mySystemProviderDstu3") protected JpaSystemProviderDstu3 mySystemProvider; @Autowired protected PlatformTransactionManager myTxManager; @Autowired @Qualifier("myValueSetDaoDstu3") protected IFhirResourceDaoValueSet<ValueSet, Coding, CodeableConcept> myValueSetDao; @Before public void beforeCreateInterceptor() { myInterceptor = mock(IServerInterceptor.class); myDaoConfig.setInterceptors(myInterceptor); } @Before @Transactional public void beforeFlushFT() { FullTextEntityManager ftem = Search.getFullTextEntityManager(myEntityManager); ftem.purgeAll(ResourceTable.class); ftem.purgeAll(ResourceIndexedSearchParamString.class); ftem.flushToIndexes(); myDaoConfig.setSchedulingDisabled(true); } @Before public void beforeResetConfig() { myDaoConfig.setHardSearchLimit(1000); myDaoConfig.setHardTagListLimit(1000); myDaoConfig.setIncludeLimit(2000); } @Before @Transactional() public void beforePurgeDatabase() { final EntityManager entityManager = this.myEntityManager; purgeDatabase(entityManager, myTxManager); } protected <T extends IBaseResource> T loadResourceFromClasspath(Class<T> type, String resourceName) throws IOException { InputStream stream = FhirResourceDaoDstu2SearchNoFtTest.class.getResourceAsStream(resourceName); if (stream == null) { fail("Unable to load resource: " + resourceName); } String string = IOUtils.toString(stream, "UTF-8"); IParser newJsonParser = MethodUtil.detectEncodingNoDefault(string).newParser(myFhirCtx); return newJsonParser.parseResource(type, string); } public TransactionTemplate newTxTemplate() { TransactionTemplate retVal = new TransactionTemplate(myTxManager); retVal.setPropagationBehavior(TransactionTemplate.PROPAGATION_REQUIRES_NEW); retVal.afterPropertiesSet(); return retVal; } public static void purgeDatabase(final EntityManager entityManager, PlatformTransactionManager theTxManager) { TransactionTemplate txTemplate = new TransactionTemplate(theTxManager); txTemplate.setPropagationBehavior(TransactionTemplate.PROPAGATION_REQUIRED); txTemplate.execute(new TransactionCallback<Void>() { @Override public Void doInTransaction(TransactionStatus theStatus) { entityManager.createQuery("UPDATE " + ResourceHistoryTable.class.getSimpleName() + " d SET d.myForcedId = null").executeUpdate(); entityManager.createQuery("UPDATE " + ResourceTable.class.getSimpleName() + " d SET d.myForcedId = null").executeUpdate(); return null; } }); txTemplate.execute(new TransactionCallback<Void>() { @Override public Void doInTransaction(TransactionStatus theStatus) { entityManager.createQuery("DELETE from " + SubscriptionFlaggedResource.class.getSimpleName() + " d").executeUpdate(); entityManager.createQuery("DELETE from " + ForcedId.class.getSimpleName() + " d").executeUpdate(); entityManager.createQuery("DELETE from " + ResourceIndexedSearchParamDate.class.getSimpleName() + " d").executeUpdate(); entityManager.createQuery("DELETE from " + ResourceIndexedSearchParamNumber.class.getSimpleName() + " d").executeUpdate(); entityManager.createQuery("DELETE from " + ResourceIndexedSearchParamQuantity.class.getSimpleName() + " d").executeUpdate(); entityManager.createQuery("DELETE from " + ResourceIndexedSearchParamString.class.getSimpleName() + " d").executeUpdate(); entityManager.createQuery("DELETE from " + ResourceIndexedSearchParamToken.class.getSimpleName() + " d").executeUpdate(); entityManager.createQuery("DELETE from " + ResourceIndexedSearchParamUri.class.getSimpleName() + " d").executeUpdate(); entityManager.createQuery("DELETE from " + ResourceIndexedSearchParamCoords.class.getSimpleName() + " d").executeUpdate(); entityManager.createQuery("DELETE from " + ResourceLink.class.getSimpleName() + " d").executeUpdate(); return null; } }); txTemplate.execute(new TransactionCallback<Void>() { @Override public Void doInTransaction(TransactionStatus theStatus) { entityManager.createQuery("DELETE from " + SubscriptionTable.class.getSimpleName() + " d").executeUpdate(); entityManager.createQuery("DELETE from " + ResourceHistoryTag.class.getSimpleName() + " d").executeUpdate(); entityManager.createQuery("DELETE from " + ResourceTag.class.getSimpleName() + " d").executeUpdate(); entityManager.createQuery("DELETE from " + TagDefinition.class.getSimpleName() + " d").executeUpdate(); entityManager.createQuery("DELETE from " + ResourceHistoryTable.class.getSimpleName() + " d").executeUpdate(); entityManager.createQuery("DELETE from " + ResourceTable.class.getSimpleName() + " d").executeUpdate(); return null; } }); } }
apache-2.0
eliogrin/CISEN
project-java/cisen-jenkins/src/main/java/com/epam/cisen/jenkins/JenkinsConnector.java
1181
package com.epam.cisen.jenkins; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Service; import org.osgi.service.component.ComponentContext; import com.epam.cisen.core.api.AbstractConnector; import com.epam.cisen.core.api.Connector; import com.epam.cisen.core.api.dto.CiReport; @Component @Service(Connector.class) public class JenkinsConnector extends AbstractConnector<JenkinsConfig> { private static final JenkinsConfig CONFIG = new JenkinsConfig(); static { CONFIG.setBaseURL("URL"); CONFIG.setJobName("Job name"); CONFIG.setLogin("Login"); CONFIG.setPass("Password"); } private final JenkinsWorker worker = new JenkinsWorker(); @Override public JenkinsConfig getPluginTemplateConfig() { return CONFIG; } @Override protected void activatePlugin(ComponentContext componentContext) { } @Override protected CiReport check(JenkinsConfig config) { return worker.checkStatus(config); } @Override protected String getBuildKey(JenkinsConfig config) { return config.getBaseURL() + "|" + config.getJobName(); } }
apache-2.0
simplelifetian/GomeOnline
jrj-TouGu/src/com/gome/haoyuangong/views/photoview/PreGingerScroller.java
1807
/******************************************************************************* * Copyright 2011, 2012 Chris Banes. * * 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.gome.haoyuangong.views.photoview; import android.content.Context; import android.widget.Scroller; public class PreGingerScroller extends ScrollerProxy { private final Scroller mScroller; public PreGingerScroller(Context context) { mScroller = new Scroller(context); } @Override public boolean computeScrollOffset() { return mScroller.computeScrollOffset(); } @Override public void fling(int startX, int startY, int velocityX, int velocityY, int minX, int maxX, int minY, int maxY, int overX, int overY) { mScroller.fling(startX, startY, velocityX, velocityY, minX, maxX, minY, maxY); } @Override public void forceFinished(boolean finished) { mScroller.forceFinished(finished); } public boolean isFinished() { return mScroller.isFinished(); } @Override public int getCurrX() { return mScroller.getCurrX(); } @Override public int getCurrY() { return mScroller.getCurrY(); } }
apache-2.0
consulo/consulo-xml
xml-impl/src/main/java/com/intellij/xml/util/AnchorReferenceImpl.java
7994
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.xml.util; import com.intellij.codeInsight.daemon.EmptyResolveMessageProvider; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.codeInsight.lookup.LookupElementBuilder; import com.intellij.openapi.util.TextRange; import com.intellij.psi.ElementManipulators; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiReference; import com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReference; import com.intellij.psi.search.PsiElementProcessor; import com.intellij.psi.util.CachedValue; import com.intellij.psi.util.CachedValueProvider; import com.intellij.psi.util.CachedValuesManager; import com.intellij.psi.xml.*; import com.intellij.util.ArrayUtil; import com.intellij.util.IncorrectOperationException; import com.intellij.xml.XmlBundle; import com.intellij.xml.XmlExtension; import consulo.util.dataholder.Key; import org.jetbrains.annotations.NonNls; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.HashMap; import java.util.Map; /** * @author Maxim.Mossienko */ public class AnchorReferenceImpl implements PsiReference, EmptyResolveMessageProvider, AnchorReference { private final String myAnchor; private final FileReference myFileReference; private final PsiElement myElement; private final int myOffset; private final boolean mySoft; @NonNls private static final String ANCHOR_ELEMENT_NAME = "a"; private static final String MAP_ELEMENT_NAME = "map"; private static final Key<CachedValue<Map<String, XmlTag>>> ourCachedIdsKey = Key.create("cached.ids"); AnchorReferenceImpl(final String anchor, @Nullable final FileReference psiReference, final PsiElement element, final int offset, final boolean soft) { myAnchor = anchor; myFileReference = psiReference; myElement = element; myOffset = offset; mySoft = soft; } public PsiElement getElement() { return myElement; } public TextRange getRangeInElement() { return new TextRange(myOffset, myOffset + myAnchor.length()); } public PsiElement resolve() { if(myAnchor.length() == 0) { return myElement; } Map<String, XmlTag> map = getIdMap(); final XmlTag tag = map != null ? map.get(myAnchor) : null; if(tag != null) { XmlAttribute attribute = tag.getAttribute("id"); if(attribute == null) { attribute = tag.getAttribute("name"); } if(attribute == null && MAP_ELEMENT_NAME.equalsIgnoreCase(tag.getName())) { attribute = tag.getAttribute("usemap"); } assert attribute != null : tag.getText(); return attribute.getValueElement(); } return null; } private static boolean processXmlElements(XmlTag element, PsiElementProcessor<XmlTag> processor) { if(!_processXmlElements(element, processor)) { return false; } for(PsiElement next = element.getNextSibling(); next != null; next = next.getNextSibling()) { if(next instanceof XmlTag) { if(!_processXmlElements((XmlTag) next, processor)) { return false; } } } return true; } static boolean _processXmlElements(XmlTag element, PsiElementProcessor<XmlTag> processor) { if(!processor.execute(element)) { return false; } final XmlTag[] subTags = element.getSubTags(); for(XmlTag subTag : subTags) { if(!_processXmlElements(subTag, processor)) { return false; } } return true; } @Nullable private Map<String, XmlTag> getIdMap() { final XmlFile file = getFile(); if(file != null) { CachedValue<Map<String, XmlTag>> value = file.getUserData(ourCachedIdsKey); if(value == null) { value = CachedValuesManager.getManager(file.getProject()).createCachedValue(new MapCachedValueProvider(file), false); file.putUserData(ourCachedIdsKey, value); } return value.getValue(); } return null; } @Nullable private static String getAnchorValue(final XmlTag xmlTag) { final String attributeValue = xmlTag.getAttributeValue("id"); if(attributeValue != null) { return attributeValue; } if(ANCHOR_ELEMENT_NAME.equalsIgnoreCase(xmlTag.getName())) { final String attributeValue2 = xmlTag.getAttributeValue("name"); if(attributeValue2 != null) { return attributeValue2; } } if(MAP_ELEMENT_NAME.equalsIgnoreCase(xmlTag.getName())) { final String map_anchor = xmlTag.getAttributeValue("name"); if(map_anchor != null) { return map_anchor; } } return null; } @Nonnull public String getCanonicalText() { return myAnchor; } public PsiElement handleElementRename(String newElementName) throws IncorrectOperationException { return ElementManipulators.getManipulator(myElement).handleContentChange(myElement, getRangeInElement(), newElementName); } @Nullable public PsiElement bindToElement(@Nonnull PsiElement element) throws IncorrectOperationException { return null; } public boolean isReferenceTo(PsiElement element) { if(!(element instanceof XmlAttributeValue)) { return false; } return myElement.getManager().areElementsEquivalent(element, resolve()); } @Nonnull public Object[] getVariants() { final Map<String, XmlTag> idMap = getIdMap(); if(idMap == null) { return ArrayUtil.EMPTY_OBJECT_ARRAY; } String[] variants = idMap.keySet().toArray(new String[idMap.size()]); LookupElement[] elements = new LookupElement[variants.length]; for(int i = 0, variantsLength = variants.length; i < variantsLength; i++) { elements[i] = LookupElementBuilder.create(variants[i]).withCaseSensitivity(true); } return elements; } @Nullable private XmlFile getFile() { if(myFileReference != null) { final PsiElement psiElement = myFileReference.resolve(); return psiElement instanceof XmlFile ? (XmlFile) psiElement : null; } final PsiFile containingFile = myElement.getContainingFile(); if(containingFile instanceof XmlFile) { return (XmlFile) containingFile; } else { final XmlExtension extension = XmlExtension.getExtensionByElement(myElement); return extension == null ? null : extension.getContainingFile(myElement); } } public boolean isSoft() { return mySoft; } @Nonnull public String getUnresolvedMessagePattern() { final XmlFile xmlFile = getFile(); return xmlFile == null ? XmlBundle.message("cannot.resolve.anchor", myAnchor) : XmlBundle.message("cannot.resolve.anchor.in.file", myAnchor, xmlFile.getName()); } // separate static class to avoid memory leak via this$0 private static class MapCachedValueProvider implements CachedValueProvider<Map<String, XmlTag>> { private final XmlFile myFile; public MapCachedValueProvider(XmlFile file) { myFile = file; } public Result<Map<String, XmlTag>> compute() { final Map<String, XmlTag> resultMap = new HashMap<String, XmlTag>(); XmlDocument document = HtmlUtil.getRealXmlDocument(myFile.getDocument()); final XmlTag rootTag = document != null ? document.getRootTag() : null; if(rootTag != null) { processXmlElements(rootTag, new PsiElementProcessor<XmlTag>() { public boolean execute(@Nonnull final XmlTag element) { final String anchorValue = getAnchorValue(element); if(anchorValue != null) { resultMap.put(anchorValue, element); } return true; } }); } return new Result<Map<String, XmlTag>>(resultMap, myFile); } } }
apache-2.0
mlhartme/metadata
src/main/java/net/oneandone/sushi/metadata/Item.java
5220
/* * Copyright 1&1 Internet AG, https://github.com/1and1/ * * 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 net.oneandone.sushi.metadata; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** An item in a complex type. TODO: rename to field? */ public abstract class Item<T> { protected static Method lookup(Class type, String name) { Method[] methods; int i; Method found; Method tmp; methods = type.getMethods(); found = null; for (i = 0; i < methods.length; i++) { tmp = methods[i]; if (tmp.getName().equalsIgnoreCase(name)) { if (found != null) { throw new IllegalArgumentException("ambiguous: " + name); } found = tmp; } } if (found == null) { throw new IllegalArgumentException("not found: " + name); } return found; } protected static void checkSetter(Class type, Method setter) { if (setter.getParameterTypes().length != 1) { fail(setter); } if (!setter.getParameterTypes()[0].equals(type)) { fail(setter); } if (!setter.getReturnType().equals(Void.TYPE)) { fail(setter); } check(setter); } protected static void checkGetter(Class type, Method getter) { if (getter.getParameterTypes().length != 0) { fail(getter); } if (!getter.getReturnType().equals(type)) { fail(getter); } check(getter); } protected static void check(Method method) { int modifier; modifier = method.getModifiers(); if (Modifier.isAbstract(modifier)) { fail(method); } if (Modifier.isStatic(modifier)) { fail(method); } if (!Modifier.isPublic(modifier)) { fail(method); } } protected static void fail(Method method) { throw new IllegalArgumentException(method.toString()); } /* throws ItemException */ protected static Object invoke(Method method, Object dest, Object ... args) { try { return method.invoke(dest, args); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new ItemException("cannot invoke " + method.getName(), e.getTargetException()); } } //-- /** name in singular. E.g. "package", not "packages" */ private final String name; private final Cardinality cardinality; private final Type type; public Item(String name, Cardinality cardinality, Type type) { this.name = name; this.cardinality = cardinality; this.type = type; } public String getName() { return name; } public String getXmlName() { return xmlName(name); } public Cardinality getCardinality() { return cardinality; } public Type getType() { return type; } public abstract Collection<T> get(Object src); public abstract void set(Object dest, Collection<T> values); public Collection<Instance<T>> getInstances(Object src) { Collection<T> objects; ArrayList<Instance<T>> result; objects = get(src); result = new ArrayList<>(objects.size()); for (Object obj : objects) { result.add(new Instance<>(type, (T) obj)); } return result; } public T getOne(Object src) { Collection<T> all; all = get(src); if (all.size() != 1) { throw new IllegalStateException(all.toString()); } return all.iterator().next(); } public void setOne(Object dest, T value) { List<T> lst; lst = new ArrayList<T>(); lst.add(value); set(dest, lst); } //-- public static String xmlName(String name) { StringBuilder builder; char c; builder = new StringBuilder(); for (int i = 0, max = name.length(); i < max; i++) { c = name.charAt(i); if (i > 0 && Character.isUpperCase(c)) { builder.append('-'); builder.append(Character.toLowerCase(c)); } else { builder.append(c); } } return builder.toString(); } }
apache-2.0
fmarot/idealsphere
modules-interface/src/main/java/com/teamtter/sphere/ISphereModule.java
213
package com.teamtter.sphere; import java.awt.Component; import java.util.List; public interface ISphereModule { public String getName(); public Component getMainPage(); public List<Component> getPages(); }
apache-2.0
prive/prive-android
src/info/guardianproject/otr/OtrDataHandler.java
25171
package info.guardianproject.otr; import info.guardianproject.otr.app.im.IDataListener; import info.guardianproject.otr.app.im.app.ImApp; import info.guardianproject.otr.app.im.engine.Address; import info.guardianproject.otr.app.im.engine.ChatSession; import info.guardianproject.otr.app.im.engine.DataHandler; import info.guardianproject.otr.app.im.engine.Message; import info.guardianproject.util.Debug; import info.guardianproject.util.LogCleaner; import info.guardianproject.util.SystemServices; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.UUID; import org.apache.http.HttpException; import org.apache.http.HttpMessage; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestFactory; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseFactory; import org.apache.http.MethodNotSupportedException; import org.apache.http.ProtocolVersion; import org.apache.http.RequestLine; import org.apache.http.impl.DefaultHttpResponseFactory; import org.apache.http.impl.io.AbstractSessionInputBuffer; import org.apache.http.impl.io.AbstractSessionOutputBuffer; import org.apache.http.impl.io.HttpRequestParser; import org.apache.http.impl.io.HttpRequestWriter; import org.apache.http.impl.io.HttpResponseParser; import org.apache.http.impl.io.HttpResponseWriter; import org.apache.http.io.HttpMessageWriter; import org.apache.http.io.SessionInputBuffer; import org.apache.http.message.BasicHttpRequest; import org.apache.http.message.BasicHttpResponse; import org.apache.http.message.BasicLineFormatter; import org.apache.http.message.BasicLineParser; import org.apache.http.message.BasicStatusLine; import org.apache.http.message.LineFormatter; import org.apache.http.message.LineParser; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpParams; import android.os.Environment; import android.os.RemoteException; import android.util.Log; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.collect.Maps; import com.google.common.collect.Sets; public class OtrDataHandler implements DataHandler { public static final String URI_PREFIX_OTR_IN_BAND = "otr-in-band:/storage/"; private static final int MAX_OUTSTANDING = 3; private static final int MAX_CHUNK_LENGTH = 32768; private static final int MAX_TRANSFER_LENGTH = 1024*1024*64; private static final byte[] EMPTY_BODY = new byte[0]; private static final String TAG = "GB.OtrDataHandler"; private static final ProtocolVersion PROTOCOL_VERSION = new ProtocolVersion("HTTP", 1, 1); private static HttpParams params = new BasicHttpParams(); private static HttpRequestFactory requestFactory = new MyHttpRequestFactory(); private static HttpResponseFactory responseFactory = new DefaultHttpResponseFactory(); private LineParser lineParser = new BasicLineParser(PROTOCOL_VERSION); private LineFormatter lineFormatter = new BasicLineFormatter(); private ChatSession mChatSession; private IDataListener mDataListener; public OtrDataHandler(ChatSession chatSession) { this.mChatSession = chatSession; } public void setDataListener (IDataListener dataListener) { mDataListener = dataListener; } public static class MyHttpRequestFactory implements HttpRequestFactory { public MyHttpRequestFactory() { super(); } public HttpRequest newHttpRequest(final RequestLine requestline) throws MethodNotSupportedException { if (requestline == null) { throw new IllegalArgumentException("Request line may not be null"); } //String method = requestline.getMethod(); return new BasicHttpRequest(requestline); } public HttpRequest newHttpRequest(final String method, final String uri) throws MethodNotSupportedException { return new BasicHttpRequest(method, uri); } } static class MemorySessionInputBuffer extends AbstractSessionInputBuffer { public MemorySessionInputBuffer(byte[] value) { init(new ByteArrayInputStream(value), 1000, params); } @Override public boolean isDataAvailable(int timeout) throws IOException { throw new UnsupportedOperationException(); } } static class MemorySessionOutputBuffer extends AbstractSessionOutputBuffer { ByteArrayOutputStream outputStream; public MemorySessionOutputBuffer() { outputStream = new ByteArrayOutputStream(1000); init(outputStream, 1000, params); } public byte[] getOutput() { return outputStream.toByteArray(); } } public void onIncomingRequest(Address requestThem, Address requestUs, byte[] value) { SessionInputBuffer inBuf = new MemorySessionInputBuffer(value); HttpRequestParser parser = new HttpRequestParser(inBuf, lineParser, requestFactory, params); HttpRequest req; try { req = (HttpRequest)parser.parse(); } catch (IOException e) { throw new RuntimeException(e); } catch (HttpException e) { e.printStackTrace(); return; } String requestMethod = req.getRequestLine().getMethod(); String uid = req.getFirstHeader("Request-Id").getValue(); String url = req.getRequestLine().getUri(); if (requestMethod.equals("OFFER")) { debug("incoming OFFER " + url); if (!url.startsWith(URI_PREFIX_OTR_IN_BAND)) { debug("Unknown url scheme " + url); sendResponse(requestUs, 400, "Unknown scheme", uid, EMPTY_BODY); return; } sendResponse(requestUs, 200, "OK", uid, EMPTY_BODY); if (!req.containsHeader("File-Length")) { sendResponse(requestUs, 400, "File-Length must be supplied", uid, EMPTY_BODY); return; } int length = Integer.parseInt(req.getFirstHeader("File-Length").getValue()); if (!req.containsHeader("File-Hash-SHA1")) { sendResponse(requestUs, 400, "File-Hash-SHA1 must be supplied", uid, EMPTY_BODY); return; } String sum = req.getFirstHeader("File-Hash-SHA1").getValue(); String type = null; if (req.containsHeader("Mime-Type")) { type = req.getFirstHeader("Mime-Type").getValue(); } debug("Incoming sha1sum " + sum); Transfer transfer = new Transfer(url, type, length, requestUs, sum); transferCache.put(url, transfer); // Handle offer // TODO ask user to confirm we want this boolean accept = false; if (mDataListener != null) { try { accept = mDataListener.onTransferRequested(requestThem.getAddress(),requestUs.getAddress(),transfer.url); if (accept) transfer.perform(); } catch (RemoteException e) { LogCleaner.error(ImApp.LOG_TAG, "error approving OTRDATA transfer request", e); } } } else if (requestMethod.equals("GET") && url.startsWith(URI_PREFIX_OTR_IN_BAND)) { debug("incoming GET " + url); ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream(); int reqEnd; try { Offer offer = offerCache.getIfPresent(url); if (offer == null) { sendResponse(requestUs, 400, "No such offer made", uid, EMPTY_BODY); return; } if (!req.containsHeader("Range")) { sendResponse(requestUs, 400, "Range must start with bytes=", uid, EMPTY_BODY); return; } String rangeHeader = req.getFirstHeader("Range").getValue(); String[] spec = rangeHeader.split("="); if (spec.length != 2 || !spec[0].equals("bytes")) { sendResponse(requestUs, 400, "Range must start with bytes=", uid, EMPTY_BODY); return; } String[] startEnd = spec[1].split("-"); if (startEnd.length != 2) { sendResponse(requestUs, 400, "Range must be START-END", uid, EMPTY_BODY); return; } int start = Integer.parseInt(startEnd[0]); int end = Integer.parseInt(startEnd[1]); if (end - start + 1 > MAX_CHUNK_LENGTH) { sendResponse(requestUs, 400, "Range must be at most " + MAX_CHUNK_LENGTH, uid, EMPTY_BODY); return; } File fileGet = new File(offer.getUri()); FileInputStream is = new FileInputStream(fileGet); readIntoByteBuffer(byteBuffer, is, start, end); if (mDataListener != null) { float percent = ((float)end) / ((float)fileGet.length()); if (percent < .98f) { mDataListener.onTransferProgress(requestThem.getAddress(), offer.getUri(), percent); } else { String mimeType = null; if (req.getFirstHeader("Mime-Type") != null) mimeType = req.getFirstHeader("Mime-Type").getValue(); mDataListener.onTransferComplete(requestThem.getAddress(), offer.getUri(), mimeType, offer.getUri()); } } } catch (UnsupportedEncodingException e) { // throw new RuntimeException(e); sendResponse(requestUs, 400, "Unsupported encoding", uid, EMPTY_BODY); return; } catch (IOException e) { //throw new RuntimeException(e); sendResponse(requestUs, 400, "IOException", uid, EMPTY_BODY); return; } catch (NumberFormatException e) { sendResponse(requestUs, 400, "Range is not numeric", uid, EMPTY_BODY); return; } catch (Exception e) { sendResponse(requestUs, 500, "Unknown error", uid, EMPTY_BODY); return; } byte[] body = byteBuffer.toByteArray(); debug("Sent sha1 is " + sha1sum(body)); sendResponse(requestUs, 200, "OK", uid, body); } else { debug("Unknown method / url " + requestMethod + " " + url); sendResponse(requestUs, 400, "OK", uid, EMPTY_BODY); } } private void readIntoByteBuffer(ByteArrayOutputStream byteBuffer, FileInputStream is, int start, int end) throws IOException { if (start != is.skip(start)) { return; } int size = end - start + 1; int buffersize = 1024; byte[] buffer = new byte[buffersize]; int len = 0; while((len = is.read(buffer)) != -1){ if (len > size) { len = size; } byteBuffer.write(buffer, 0, len); size -= len; } } private void readIntoByteBuffer(ByteArrayOutputStream byteBuffer, SessionInputBuffer sib) throws IOException { int buffersize = 1024; byte[] buffer = new byte[buffersize]; int len = 0; while((len = sib.read(buffer)) != -1){ byteBuffer.write(buffer, 0, len); } } private void sendResponse(Address us, int code, String statusString, String uid, byte[] body) { MemorySessionOutputBuffer outBuf = new MemorySessionOutputBuffer(); HttpMessageWriter writer = new HttpResponseWriter(outBuf, lineFormatter, params); HttpMessage response = new BasicHttpResponse(new BasicStatusLine(PROTOCOL_VERSION, code, statusString)); response.addHeader("Request-Id", uid); try { writer.write(response); outBuf.write(body); outBuf.flush(); } catch (IOException e) { throw new RuntimeException(e); } catch (HttpException e) { throw new RuntimeException(e); } byte[] data = outBuf.getOutput(); Message message = new Message(""); message.setFrom(us); debug("send response"); mChatSession.sendDataAsync(message, true, data); } public void onIncomingResponse(Address from, Address to, byte[] value) { SessionInputBuffer buffer = new MemorySessionInputBuffer(value); HttpResponseParser parser = new HttpResponseParser(buffer, lineParser, responseFactory, params); HttpResponse res; try { res = (HttpResponse) parser.parse(); } catch (IOException e) { throw new RuntimeException(e); } catch (HttpException e) { e.printStackTrace(); return; } String uid = res.getFirstHeader("Request-Id").getValue(); Request request = requestCache.getIfPresent(uid); if (request == null) { debug("Unknown request ID " + uid); return; } if (request.isSeen()) { debug("Already seen request ID " + uid); return; } request.seen(); int statusCode = res.getStatusLine().getStatusCode(); if (statusCode != 200) { debug("got status " + statusCode + ": " + res.getStatusLine().getReasonPhrase()); // TODO handle error return; } // TODO handle success try { ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream(); readIntoByteBuffer(byteBuffer, buffer); debug("Received sha1 @" + request.start + " is " + sha1sum(byteBuffer.toByteArray())); if (request.method.equals("GET")) { Transfer transfer = transferCache.getIfPresent(request.url); if (transfer == null) { debug("Transfer expired for url " + request.url); return; } transfer.chunkReceived(request, byteBuffer.toByteArray()); if (transfer.isDone()) { byte[] data = transfer.getData(); debug("Transfer complete for " + request.url); if (transfer.checkSum()) { debug("Received file len=" + data.length + " sha1=" + sha1sum(data)); File fileShare = writeDataToStorage(transfer.url, data); if (mDataListener != null) mDataListener.onTransferComplete( mChatSession.getParticipant().getAddress().getAddress(), transfer.url, transfer.type, fileShare.getCanonicalPath()); } else { if (mDataListener != null) mDataListener.onTransferFailed( mChatSession.getParticipant().getAddress().getAddress(), transfer.url, "checksum"); Log.e(TAG, "Wrong checksum for file len= " + data.length + " sha1=" + sha1sum(data)); } } else { if (mDataListener != null) mDataListener.onTransferProgress(mChatSession.getParticipant().getAddress().getAddress(), transfer.url, ((float)transfer.chunksReceived) / transfer.chunks); transfer.perform(); debug("Progress " + transfer.chunksReceived + " / " + transfer.chunks); } } } catch (IOException e) { debug("Could not read line from response"); } catch (RemoteException e) { debug("Could not read remote exception"); } } private File writeDataToStorage (String url, byte[] data) { //String nickname = getNickName(username); File sdCard = Environment.getExternalStorageDirectory(); String[] path = url.split("/"); //String sanitizedPeer = SystemServices.sanitize(username); String sanitizedPath = SystemServices.sanitize(path[path.length - 1]); File fileDownloadsDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); fileDownloadsDir.mkdirs(); File file = new File(fileDownloadsDir, sanitizedPath); try { OutputStream output = (new FileOutputStream(file)); output.write(data); output.close(); return file; } catch (IOException e) { OtrDebugLogger.log("error writing file", e); return null; } } /** * @param headers may be null */ @Override public void offerData(Address us, String localUri, Map<String, String> headers) { // TODO stash localUri and intended recipient long length = new File(localUri).length(); if (length > MAX_TRANSFER_LENGTH) { throw new RuntimeException("Length too large " + length); } if (headers == null) headers = Maps.newHashMap(); headers.put("File-Length", String.valueOf(length)); ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream(); try { FileInputStream is = new FileInputStream(localUri); readIntoByteBuffer(byteBuffer, is, 0, (int)(length - 1)); } catch (IOException e) { throw new RuntimeException(e); } headers.put("File-Hash-SHA1", sha1sum(byteBuffer.toByteArray())); String[] paths = localUri.split("/"); String url = URI_PREFIX_OTR_IN_BAND + SystemServices.sanitize(paths[paths.length - 1]); Request request = new Request("OFFER", url); offerCache.put(url, new Offer(localUri)); sendRequest(us, "OFFER", url, headers, EMPTY_BODY, request); } public Request performGetData(Address us, String url, Map<String, String> headers, int start, int end) { String rangeSpec = "bytes=" + start + "-" + end; debug("Getting range " + rangeSpec); headers.put("Range", rangeSpec); Request requestMemo = new Request("GET", url, start, end); sendRequest(us, "GET", url, headers, EMPTY_BODY, requestMemo); return requestMemo; } static class Offer { private String mUri; public Offer(String uri) { this.mUri = uri; } public String getUri() { return mUri; } } static class Request { public Request(String method, String url, int start, int end) { this.method = method; this.url = url; this.start = start; this.end = end; } public Request(String method, String url) { this(method, url, -1, -1); } public String method; public String url; public int start; public int end; public byte[] data; public boolean seen = false; public boolean isSeen() { return seen; } public void seen() { seen = true; } } public class Transfer { public String url; public String type; public int chunks = 0; public int chunksReceived = 0; private int length = 0; private int current = 0; private Address us; private Set<Request> outstanding; private byte[] buffer; private String sum; public Transfer(String url, String type, int length, Address us, String sum) { this.url = url; this.type = type; this.length = length; this.us = us; this.sum = sum; if (length > MAX_TRANSFER_LENGTH || length <= 0) { throw new RuntimeException("Invalid transfer size " + length); } chunks = ((length - 1) / MAX_CHUNK_LENGTH) + 1; buffer = new byte[length]; outstanding = Sets.newHashSet(); } public boolean checkSum() { return sum.equals(sha1sum(buffer)); } public boolean perform() { // TODO global throttle rather than this local hack while (outstanding.size() < MAX_OUTSTANDING) { if (current >= length) return false; int end = current + MAX_CHUNK_LENGTH - 1; if (end >= length) { end = length - 1; } Map<String, String> headers = Maps.newHashMap(); Request request= performGetData(us, url, headers, current, end); outstanding.add(request); current = end + 1; } return true; } public byte[] getData() { // TODO Auto-generated method stub return buffer; } public boolean isDone() { return chunksReceived == chunks; } public void chunkReceived(Request request, byte[] bs) { chunksReceived++; System.arraycopy(bs, 0, buffer, request.start, bs.length); outstanding.remove(request); } public String getSum() { return sum; } } Cache<String, Offer> offerCache = CacheBuilder.newBuilder().maximumSize(100).build(); Cache<String, Request> requestCache = CacheBuilder.newBuilder().maximumSize(100).build(); Cache<String, Transfer> transferCache = CacheBuilder.newBuilder().maximumSize(100).build(); private void sendRequest(Address us, String method, String url, Map<String, String> headers, byte[] body, Request requestMemo) { MemorySessionOutputBuffer outBuf = new MemorySessionOutputBuffer(); HttpMessageWriter writer = new HttpRequestWriter(outBuf, lineFormatter, params); HttpMessage req = new BasicHttpRequest(method, url, PROTOCOL_VERSION); String uid = UUID.randomUUID().toString(); req.addHeader("Request-Id", uid); if (headers != null) { for (Entry<String, String> entry : headers.entrySet()) { req.addHeader(entry.getKey(), entry.getValue()); } } try { writer.write(req); outBuf.write(body); outBuf.flush(); } catch (IOException e) { throw new RuntimeException(e); } catch (HttpException e) { throw new RuntimeException(e); } byte[] data = outBuf.getOutput(); Message message = new Message(""); message.setFrom(us); debug("send request " + method + " " + url); requestCache.put(uid, requestMemo); mChatSession.sendDataAsync(message, false, data); } private static String hexChr(int b) { return Integer.toHexString(b & 0xF); } private static String toHex(int b) { return hexChr((b & 0xF0) >> 4) + hexChr(b & 0x0F); } private String sha1sum(byte[] bytes) { MessageDigest digest; try { digest = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } digest.update(bytes, 0, bytes.length); byte[] sha1sum = digest.digest(); String display = ""; for(byte b : sha1sum) display += toHex(b); return display; } private void debug (String msg) { if (Debug.DEBUG_ENABLED) Log.d(ImApp.LOG_TAG,msg); } }
apache-2.0
quarkusio/quarkus
devtools/project-core-extension-codestarts/src/main/resources/codestarts/quarkus/examples/google-cloud-functions-http-example/java/src/main/java/org/acme/googlecloudfunctions/GreetingServlet.java
988
package org.acme.googlecloudfunctionshttp; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet(name = "ServletGreeting", urlPatterns = "/servlet/hello") public class GreetingServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setStatus(200); resp.addHeader("Content-Type", "text/plain"); resp.getWriter().write("hello"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String name = req.getReader().readLine(); resp.setStatus(200); resp.addHeader("Content-Type", "text/plain"); resp.getWriter().write("hello " + name); } }
apache-2.0
dbracewell/apollo
src/main/java/com/davidbracewell/apollo/linear/sparse/SparseFloatNDArray.java
1674
package com.davidbracewell.apollo.linear.sparse; import com.davidbracewell.apollo.linear.NDArray; import com.davidbracewell.apollo.linear.NDArrayFactory; import org.apache.mahout.math.function.IntDoubleProcedure; import org.apache.mahout.math.list.IntArrayList; import org.apache.mahout.math.map.OpenIntFloatHashMap; /** * @author David B. Bracewell */ public class SparseFloatNDArray extends SparseNDArray { private static final long serialVersionUID = 1L; private final OpenIntFloatHashMap storage = new OpenIntFloatHashMap(); public SparseFloatNDArray(int nRows, int nCols) { super(nRows, nCols); } @Override protected double adjustOrPutValue(int index, double amount) { return storage.adjustOrPutValue(index, (float) amount, (float) amount); } @Override public NDArray compress() { storage.trimToSize(); return this; } @Override protected void forEachPair(IntDoubleProcedure procedure) { storage.forEachPair((index, value) -> { procedure.apply(index, value); return true; }); } @Override public double get(int index) { return storage.get(index); } @Override public NDArrayFactory getFactory() { return NDArrayFactory.SPARSE_FLOAT; } @Override protected IntArrayList nonZeroIndexes() { return storage.keys(); } @Override protected void removeIndex(int index) { storage.removeKey(index); } @Override protected void setValue(int index, double value) { storage.put(index, (float) value); } @Override public int size() { return storage.size(); } }//END OF SparseFloatNDArray
apache-2.0
riengcs/zk-tutorial
src/main/java/com/zk/tutorial/component/extend/AlphaNumeric.java
285
package com.zk.tutorial.component.extend; import org.zkoss.zul.Textbox; /** * @author csrieng * */ public class AlphaNumeric extends Textbox{ private static final long serialVersionUID = 1L; public AlphaNumeric(){ setWidgetListener("onBind", "jq(this).mask('******');"); } }
apache-2.0
inoio/solrs
src/test/java/io/ino/solrs/JavaAPIFunTest.java
12586
package io.ino.solrs; import static java.util.Arrays.asList; import static java.util.concurrent.TimeUnit.SECONDS; import static java.util.stream.Collectors.toList; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.*; import java.io.IOException; import java.util.Objects; import java.util.Optional; import java.util.concurrent.ExecutionException; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.beans.Field; import org.apache.solr.client.solrj.impl.HttpSolrClient; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import org.apache.solr.common.SolrInputDocument; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.scalatestplus.junit.JUnitSuite; public class JavaAPIFunTest extends JUnitSuite { private static final long serialVersionUID = 1; private static SolrRunner solrRunner; private static SolrClient solr; private static JavaAsyncSolrClient solrs; @BeforeClass public static void beforeClass() { solrRunner = SolrRunner.startOnce(8888).awaitReady(10, SECONDS); String url = "http://localhost:" + solrRunner.port() + "/solr/collection1"; solr = new HttpSolrClient.Builder(url).build(); solrs = JavaAsyncSolrClient.create(url); } @Before public void before() throws IOException, SolrServerException { solr.deleteByQuery("*:*"); } @AfterClass public static void afterClass() throws IOException { solr.close(); solrs.shutdown(); } @Test public void testAddDocsAsCollection() throws ExecutionException, InterruptedException, IOException, SolrServerException { SolrInputDocument doc1 = newInputDoc("id1", "doc1", "cat1", 10); SolrInputDocument doc2 = newInputDoc("id2", "doc2", "cat1", 20); solrs.addDocs(asList(doc1, doc2)).toCompletableFuture().get(); solr.commit(); SolrDocumentList docs = solr.query(new SolrQuery("*:*")).getResults(); assertThat(docs.getNumFound(), equalTo(2L)); assertThat(docs.stream().map(this::getPrice).collect(toList()), containsInAnyOrder(10f, 20f)); } @Test public void testAddDocsAsIterator() throws ExecutionException, InterruptedException, IOException, SolrServerException { SolrInputDocument doc1 = newInputDoc("id1", "doc1", "cat1", 10); SolrInputDocument doc2 = newInputDoc("id2", "doc2", "cat1", 20); solrs.addDocs(asList(doc1, doc2).iterator()).toCompletableFuture().get(); solr.commit(); SolrDocumentList docs = solr.query(new SolrQuery("*:*")).getResults(); assertThat(docs.getNumFound(), equalTo(2L)); assertThat(docs.stream().map(this::getPrice).collect(toList()), containsInAnyOrder(10f, 20f)); } @Test public void testAddDoc() throws ExecutionException, InterruptedException, IOException, SolrServerException { solrs.addDoc(newInputDoc("id1", "doc1", "cat1", 10)).toCompletableFuture().get(); solr.commit(); SolrDocumentList docs = solr.query(new SolrQuery("*:*")).getResults(); assertThat(docs.getNumFound(), equalTo(1L)); assertThat(docs.stream().map(this::getPrice).collect(toList()), containsInAnyOrder(10f)); } @Test public void testAddBean() throws ExecutionException, InterruptedException, IOException, SolrServerException { TestBean bean = new TestBean("id1", "doc1", "cat1", 10); solrs.addBean(bean).toCompletableFuture().get(); solr.commit(); QueryResponse response = solr.query(new SolrQuery("*:*")); assertThat(response.getResults().getNumFound(), equalTo(1L)); assertThat(response.getBeans(TestBean.class), containsInAnyOrder(bean)); } @Test public void testAddBeansAsIterable() throws ExecutionException, InterruptedException, IOException, SolrServerException { TestBean bean1 = new TestBean("id1", "doc1", "cat1", 10); TestBean bean2 = new TestBean("id2", "doc2", "cat1", 20); solrs.addBeans(asList(bean1, bean2)).toCompletableFuture().get(); solr.commit(); QueryResponse response = solr.query(new SolrQuery("*:*")); assertThat(response.getResults().getNumFound(), equalTo(2L)); assertThat(response.getBeans(TestBean.class), containsInAnyOrder(bean1, bean2)); } @Test public void testAddBeansAsIterator() throws ExecutionException, InterruptedException, IOException, SolrServerException { TestBean bean1 = new TestBean("id1", "doc1", "cat1", 10); TestBean bean2 = new TestBean("id2", "doc2", "cat1", 20); solrs.addBeans(asList(bean1, bean2).iterator()).toCompletableFuture().get(); solr.commit(); QueryResponse response = solr.query(new SolrQuery("*:*")); assertThat(response.getResults().getNumFound(), equalTo(2L)); assertThat(response.getBeans(TestBean.class), containsInAnyOrder(bean1, bean2)); } @Test public void testCommit() throws ExecutionException, InterruptedException, IOException, SolrServerException { solr.add(newInputDoc("id1", "doc1", "cat1", 10)); solrs.commit(); SolrDocumentList docs = solr.query(new SolrQuery("*:*")).getResults(); assertThat(docs.getNumFound(), equalTo(1L)); assertThat(docs.stream().map(this::getPrice).collect(toList()), containsInAnyOrder(10f)); } @Test public void testDeleteById() throws ExecutionException, InterruptedException, IOException, SolrServerException { SolrInputDocument doc1 = newInputDoc("id1", "doc1", "cat1", 10); SolrInputDocument doc2 = newInputDoc("id2", "doc2", "cat1", 20); solr.add(asList(doc1, doc2)); solr.commit(); solrs.deleteById("id1").toCompletableFuture().get(); solr.commit(); SolrDocumentList docs = solr.query(new SolrQuery("*:*")).getResults(); assertThat(docs.getNumFound(), equalTo(1L)); assertThat(docs.stream().map(this::getPrice).collect(toList()), containsInAnyOrder(20f)); } @Test public void testDeleteByIds() throws ExecutionException, InterruptedException, IOException, SolrServerException { SolrInputDocument doc1 = newInputDoc("id1", "doc1", "cat1", 10); SolrInputDocument doc2 = newInputDoc("id2", "doc2", "cat1", 20); SolrInputDocument doc3 = newInputDoc("id3", "doc3", "cat2", 30); solr.add(asList(doc1, doc2, doc3)); solr.commit(); solrs.deleteByIds(asList("id1", "id2")).toCompletableFuture().get(); solr.commit(); SolrDocumentList docs = solr.query(new SolrQuery("*:*")).getResults(); assertThat(docs.getNumFound(), equalTo(1L)); assertThat(docs.stream().map(this::getPrice).collect(toList()), containsInAnyOrder(30f)); } @Test public void testDeleteByQuery() throws ExecutionException, InterruptedException, IOException, SolrServerException { SolrInputDocument doc1 = newInputDoc("id1", "doc1", "cat1", 10); SolrInputDocument doc2 = newInputDoc("id2", "doc2", "cat1", 20); SolrInputDocument doc3 = newInputDoc("id3", "doc3", "cat2", 30); solr.add(asList(doc1, doc2, doc3)); solr.commit(); solrs.deleteByQuery("cat:cat1").toCompletableFuture().get(); solr.commit(); SolrDocumentList docs = solr.query(new SolrQuery("*:*")).getResults(); assertThat(docs.getNumFound(), equalTo(1L)); assertThat(docs.stream().map(this::getPrice).collect(toList()), containsInAnyOrder(30f)); } @Test public void testQuery() throws ExecutionException, InterruptedException, IOException, SolrServerException { SolrInputDocument doc1 = newInputDoc("id1", "doc1", "cat1", 10); SolrInputDocument doc2 = newInputDoc("id2", "doc2", "cat1", 20); SolrInputDocument doc3 = newInputDoc("id3", "doc3", "cat2", 30); solr.add(asList(doc1, doc2, doc3)); solr.commit(); SolrDocumentList docs = solrs.query(new SolrQuery("cat:cat1")).toCompletableFuture().get().getResults(); assertThat(docs.getNumFound(), equalTo(2L)); assertThat(docs.stream().map(this::getPrice).collect(toList()), containsInAnyOrder(10f, 20f)); } @Test public void testGetById() throws ExecutionException, InterruptedException, IOException, SolrServerException { SolrInputDocument doc1 = newInputDoc("id1", "doc1", "cat1", 10); SolrInputDocument doc2 = newInputDoc("id2", "doc2", "cat1", 20); solr.add(asList(doc1, doc2)); solr.commit(); assertThat(solrs.getById("id1").toCompletableFuture().get().map(this::getPrice), equalTo(Optional.of(10f))); } @Test public void testGetByIdAbsent() throws ExecutionException, InterruptedException, IOException, SolrServerException { solr.add(newInputDoc("id1", "doc1", "cat1", 10)); solr.commit(); assertFalse(solrs.getById("id2").toCompletableFuture().get().isPresent()); } @Test public void testGetByIds() throws ExecutionException, InterruptedException, IOException, SolrServerException { SolrInputDocument doc1 = newInputDoc("id1", "doc1", "cat1", 10); SolrInputDocument doc2 = newInputDoc("id2", "doc2", "cat1", 20); SolrInputDocument doc3 = newInputDoc("id3", "doc3", "cat2", 30); solr.add(asList(doc1, doc2, doc3)); solr.commit(); SolrDocumentList docs = solrs.getByIds(asList("id1", "id2")).toCompletableFuture().get(); assertThat(docs.getNumFound(), equalTo(2L)); assertThat(docs.stream().map(this::getPrice).collect(toList()), containsInAnyOrder(10f, 20f)); } @Test public void testGetByIdsAbsent() throws ExecutionException, InterruptedException, IOException, SolrServerException { solr.add(newInputDoc("id1", "doc1", "cat1", 10)); solr.commit(); SolrDocumentList docs = solrs.getByIds(asList("id2", "id3")).toCompletableFuture().get(); assertThat(docs.getNumFound(), equalTo(0L)); assertTrue(docs.isEmpty()); } private SolrInputDocument newInputDoc(String id, String name, String category, float price) { SolrInputDocument doc = new SolrInputDocument(); doc.addField("id", id); doc.addField("name", name); doc.addField("cat", category); doc.addField("price", price); return doc; } private Object getPrice(SolrDocument doc) { return doc.getFieldValue("price"); } public static class TestBean { @Field private String id; @Field private String name; @Field private String category; @Field private float price; public TestBean() { } TestBean(String id, String name, String category, float price) { this.id = id; this.name = name; this.category = category; this.price = price; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TestBean testBean = (TestBean) o; return Float.compare(testBean.price, price) == 0 && Objects.equals(id, testBean.id) && Objects.equals(name, testBean.name) && Objects.equals(category, testBean.category); } @Override public int hashCode() { return Objects.hash(id, name, category, price); } } }
apache-2.0
ttoth/time-tracking-system
src/java/hu/bme/aait/tt/entity/Task.java
3033
/* * 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 hu.bme.aait.tt.entity; import java.io.Serializable; import java.util.Collection; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlTransient; /** * * @author ttoth */ @Entity @Table(name = "task") @XmlAccessorType(XmlAccessType.FIELD) public class Task implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue private Integer id; @Basic(optional = false) @NotNull @Size(min = 1, max = 255) @Column(name = "name") private String name; @ManyToOne @JoinColumn(name = "project_id") private Project project; @OneToMany(mappedBy = "task", cascade = CascadeType.ALL) @XmlTransient private Collection<Unit> units; public Task(String name, Project project) { this.name = name; this.project = project; } public Task() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Project getProject() { return project; } public void setProject(Project project) { this.project = project; } public Collection<Unit> getUnits() { return units; } public void setUnits(Collection<Unit> units) { this.units = units; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Task)) { return false; } Task other = (Task) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "hu.bme.aait.tt.entity.Task[ id=" + id + " ]"; } public void addUnit(Unit unit) { unit.setTask(this); this.getUnits().add(unit); } }
apache-2.0
google/android-uiconductor
backend/core/utils/Circular.java
2650
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.uicd.backend.core.utils; import com.fasterxml.jackson.annotation.JsonIgnore; /** The circular shape of selected region on the UI for comparison */ public class Circular extends Region { private int centerX; private int centerY; private int radius; public Circular() {} public Circular(int centerX, int centerY, int radius) { this.centerX = centerX; this.centerY = centerY; this.radius = radius; } public int getCenterX() { return centerX; } public void setCenterX(int centerX) { this.centerX = centerX; } public int getCenterY() { return centerY; } public void setCenterY(int centerY) { this.centerY = centerY; } public int getRadius() { return radius; } public void setRadius(int radius) { this.radius = radius; } @Override public boolean checkIfWithinBounds(int x, int y) { return Math.hypot(x - centerX, y - centerY) < radius; } @JsonIgnore @Override public Rectangular getBoundingBox() { return new Rectangular(centerX - radius, centerY - radius, radius * 2, radius * 2); } @JsonIgnore @Override public Region getOffsetRemovedRegion() { return new Circular(radius, radius, radius); } @JsonIgnore @Override public Region copy() { return new Circular(centerX, centerY, radius); } @JsonIgnore @Override public Region addOffset(int x, int y) { return new Circular(centerX + x, centerY + y, radius); } @JsonIgnore @Override public Region getScaledRegion( int hostScrnWidth, int hostScrnHeight, int devPhyWidth, int devPhyHeight) { int radiusEndX = centerX + radius; int scaledRadiusEndX = ImageUtil.scaleToTargetPx(radiusEndX, hostScrnWidth, devPhyWidth); int scaledCenterX = ImageUtil.scaleToTargetPx(centerX, hostScrnWidth, devPhyWidth); int scaledRadius = Math.abs(scaledRadiusEndX - scaledCenterX); int scaledCenterY = ImageUtil.scaleToTargetPx(centerY, hostScrnHeight, devPhyHeight); return new Circular(scaledCenterX, scaledCenterY, scaledRadius); } }
apache-2.0
jaschenk/Your-Microservice
your-microservice-core/src/main/java/your/microservice/core/rest/RestIdPClientAccessor.java
4840
package your.microservice.core.rest; /** * RestIdPClientAccessor * * Provides Interface for RESTful Client Accessor. * * @author jeff.a.schenk@gmail.com */ public interface RestIdPClientAccessor { /** * Your Microservice IdP Default Token Authentication Resource Path */ String YOUR_MICROSERVICE_IDP_TOKEN_REQUEST_RESOURCE_PATH = "/api/auth"; String YOUR_MICROSERVICE_IDP_TOKEN_LOGOUT_RESOURCE_PATH = "/api/auth/logout"; /** * Required Headers */ String AUTHORIZATION_HEADER_NAME = "Authorization"; String AUTHORIZATION_HEADER_BEARER_VALUE = "Bearer "; String CONTENT_TYPE_HEADER_NAME = "Content-Type"; String ACCEPT_HEADER_NAME = "Accept"; String ACCEPT_HEADER_JSON_HEADER_DEFAULT_VALUE = "application/json;charset=UTF-8"; String CONTENT_TYPE_JSON = "application/json"; String UTF8 = "UTF-8"; String ORIGIN_HEADER_NAME = "Origin"; /** * Parameter Name Constants */ String USERNAME_PNAME = "username"; String PASSWORD_PNAME = "password"; /** * getAccessToken * * Provides initial Method to gain Access to a Protected Resource, which is * to obtain an Access Token for the Protected Resource. * * @param url Enterprise Eco-System * @param principal User Email Address or UserId to be validated against a IdP Account Store. * @param credentials User Credentials or Password to be validated against a IdP Account Store. * @return RestIdPClientAccessObject which contains the Access Token, Token Type and * Token Expiration in Milliseconds. */ RestIdPClientAccessObject getAccessToken(String url, String principal, String credentials); /** * getAccessToken * * Provides subsequent Method to gain Access to a Protected Resource, which is * to use a Refresh Token to obtain a new Access Token for the Protected Resource. * * @param url Enterprise Eco-System * @param RestIdPClientAccessObject Access Object, which contains Refresh Token. * @return RestIdPClientAccessObject which contains the new Access Token, Refresh Token, Token Type and * Token Expiration in Milliseconds. */ RestIdPClientAccessObject getAccessToken(String url, RestIdPClientAccessObject RestIdPClientAccessObject); /** * get * * Perform RESTful 'GET' Method using specified URL. * * @param url Enterprise Eco-System * @param RestIdPClientAccessObject Access Object, which contains Access Token. * @return Object Response */ Object get(String url, RestIdPClientAccessObject RestIdPClientAccessObject); /** * post * * Perform RESTful 'POST' Method using specified URL. * * @param url Enterprise Eco-System * @param RestIdPClientAccessObject Access Object, which contains Access Token. * @return Object Response */ Object post(String url, RestIdPClientAccessObject RestIdPClientAccessObject); /** * post * * Perform RESTful 'POST' Method using specified URL. * * @param url Enterprise Eco-System * @param payload DTO Payload to be sent with Resource. * @param RestIdPClientAccessObject Access Object, which contains Access Token. * @return Object Response */ Object post(String url, Object payload, RestIdPClientAccessObject RestIdPClientAccessObject); /** * put * * Perform RESTful 'PUT' Method using specified URL. * * @param url Enterprise Eco-System * @param RestIdPClientAccessObject Access Object, which contains Access Token. * @return Object Response */ Object put(String url, RestIdPClientAccessObject RestIdPClientAccessObject); /** * put * * Perform RESTful 'PUT' Method using specified URL. * * @param url Enterprise Eco-System * @param payload DTO Payload to be sent with Resource. * @param RestIdPClientAccessObject Access Object, which contains Access Token. * @return Object Response */ Object put(String url, Object payload, RestIdPClientAccessObject RestIdPClientAccessObject); /** * delete * * Perform RESTful 'DELETE' Method using specified URL. * * @param url Enterprise Eco-System * @param RestIdPClientAccessObject Access Object, which contains Access Token. * @return Object Response */ Object delete(String url, RestIdPClientAccessObject RestIdPClientAccessObject); /** * logout * * Perform Logout to expire supplied Refresh Token. * * @param url Enterprise Eco-System * @param RestIdPClientAccessObject Access Object, which contains Access Token. * @return int Logout HTTPs Return Code. */ int logout(String url, RestIdPClientAccessObject RestIdPClientAccessObject); }
apache-2.0
dacofr/wro4j
wro4j-core/src/test/java/ro/isdc/wro/http/support/TestContentTypeResolver.java
2004
package ro.isdc.wro.http.support; import static org.junit.Assert.assertEquals; import org.junit.Test; public class TestContentTypeResolver { @Test public void shouldResolveCSSExtenstion() { assertEquals("text/css", ContentTypeResolver.get("somefile.css")); } @Test public void shouldResolveJPGExtenstion() { assertEquals("image/jpeg", ContentTypeResolver.get("s/bvews/omefile.jpg")); } @Test public void shouldResolveJPGExtenstionWithoutCharset() { assertEquals("image/jpeg", ContentTypeResolver.get("s/bvews/omefile.jpg", "UTF-8")); } @Test public void shouldResolveHTMLExtenstion() { assertEquals("text/html", ContentTypeResolver.get("mefile.html")); } @Test public void shouldResolveHTMLExtenstionWitCharset() { assertEquals("text/html; charset=UTF-8", ContentTypeResolver.get("mefile.html", "UTF-8")); } @Test public void shouldResolveJSExtenstion() { assertEquals("application/javascript", ContentTypeResolver.get("/ad/df/mefile.js")); } @Test public void shouldResolveUnknownExtenstion() { assertEquals("application/octet-stream", ContentTypeResolver.get("/ad/df/mefile.unknown")); } @Test public void shouldOnlyUseLastDot() { assertEquals("image/png", ContentTypeResolver.get("somefile.js.png")); } @Test public void shouldResolveHTMLUpperCaseExtenstion() { assertEquals("text/css", ContentTypeResolver.get("mefile.CSS")); } @Test public void shouldResolveFontExtensionEot() { assertEquals("application/vnd.ms-fontobject", ContentTypeResolver.get("font.eot")); } @Test public void shouldResolveFontExtensionOtf() { assertEquals("application/x-font-opentype", ContentTypeResolver.get("font.otf")); } @Test public void shouldResolveFontExtensionTtf() { assertEquals("application/octet-stream", ContentTypeResolver.get("font.ttf")); } @Test public void shouldResolveSvg() { assertEquals("image/svg+xml", ContentTypeResolver.get("graphic.svg")); } }
apache-2.0
anninpavel/VTUZ_SE_Store
app/src/main/java/ru/annin/store/presentation/ui/viewholder/DetailStoreViewHolder.java
2903
/* * Copyright 2016, Pavel Annin * * 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 ru.annin.store.presentation.ui.viewholder; import android.support.annotation.NonNull; import android.support.design.widget.TextInputLayout; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.EditText; import ru.annin.store.R; import ru.annin.store.presentation.common.BaseViewHolder; /** * <p>ViewHolder экрана "Склад".</p> * * @author Pavel Annin. */ public class DetailStoreViewHolder extends BaseViewHolder { // View's private final Toolbar toolbar; private final TextInputLayout tilName; private final EditText edtName; // Listener's private OnClickListener listener; public DetailStoreViewHolder(@NonNull View view) { super(view); toolbar = (Toolbar) vRoot.findViewById(R.id.toolbar); tilName = (TextInputLayout) vRoot.findViewById(R.id.til_name); edtName = (EditText) vRoot.findViewById(R.id.edt_name); // Setup toolbar.setNavigationOnClickListener(onNavigationClickListener); toolbar.inflateMenu(R.menu.menu_store_detail); toolbar.setOnMenuItemClickListener(onMenuItemClickListener); } public DetailStoreViewHolder errorName(String text) { tilName.setErrorEnabled(text != null); tilName.setError(text); return this; } public DetailStoreViewHolder showName(String text) { edtName.setText(text); return this; } public void setOnClickListener(OnClickListener listener) { this.listener = listener; } private final View.OnClickListener onNavigationClickListener = v -> { if (listener != null) { listener.onNavigationBackClick(); } }; private String getName() { return edtName.getText().toString(); } private final Toolbar.OnMenuItemClickListener onMenuItemClickListener = item -> { if (listener != null) { switch (item.getItemId()) { case R.id.action_save: listener.onSaveClick(getName()); return true; default: break; } } return false; }; public interface OnClickListener { void onNavigationBackClick(); void onSaveClick(String name); } }
apache-2.0
StrategyObject/fop
src/java/org/apache/fop/layoutmgr/AbstractLayoutManager.java
17941
/* * 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. */ /* $Id$ */ package org.apache.fop.layoutmgr; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.xmlgraphics.util.QName; import org.apache.fop.area.Area; import org.apache.fop.area.AreaTreeObject; import org.apache.fop.area.PageViewport; import org.apache.fop.fo.Constants; import org.apache.fop.fo.FONode; import org.apache.fop.fo.FObj; import org.apache.fop.fo.flow.Marker; import org.apache.fop.fo.flow.RetrieveMarker; /** * The base class for most LayoutManagers. */ public abstract class AbstractLayoutManager extends AbstractBaseLayoutManager implements Constants { /** logging instance */ private static Log log = LogFactory.getLog(AbstractLayoutManager.class); /** Parent LayoutManager for this LayoutManager */ protected LayoutManager parentLayoutManager; /** List of child LayoutManagers */ protected List<LayoutManager> childLMs; /** Iterator for child LayoutManagers */ protected ListIterator fobjIter; /** Marker map for markers related to this LayoutManager */ private Map<String, Marker> markers; /** True if this LayoutManager has handled all of its content. */ private boolean isFinished; /** child LM during getNextKnuthElement phase */ protected LayoutManager curChildLM; /** child LM iterator during getNextKnuthElement phase */ protected ListIterator<LayoutManager> childLMiter; private int lastGeneratedPosition = -1; private int smallestPosNumberChecked = Integer.MAX_VALUE; private boolean preserveChildrenAtEndOfLayout; /** * Abstract layout manager. */ public AbstractLayoutManager() { } /** * Abstract layout manager. * * @param fo the formatting object for this layout manager */ public AbstractLayoutManager(FObj fo) { super(fo); markers = fo.getMarkers(); fobjIter = fo.getChildNodes(); childLMiter = new LMiter(this); } /** {@inheritDoc} */ public void setParent(LayoutManager lm) { this.parentLayoutManager = lm; } /** {@inheritDoc} */ public LayoutManager getParent() { return this.parentLayoutManager; } /** {@inheritDoc} */ public void initialize() { // Empty } /** * Return currently active child LayoutManager or null if * all children have finished layout. * Note: child must implement LayoutManager! If it doesn't, skip it * and print a warning. * @return the current child LayoutManager */ protected LayoutManager getChildLM() { if (curChildLM != null && !curChildLM.isFinished()) { return curChildLM; } if (childLMiter.hasNext()) { curChildLM = childLMiter.next(); curChildLM.initialize(); return curChildLM; } return null; } /** * Set currently active child layout manager. * @param childLM the child layout manager */ protected void setCurrentChildLM(LayoutManager childLM) { curChildLM = childLM; childLMiter = new LMiter(this); do { curChildLM = childLMiter.next(); } while (curChildLM != childLM); } /** * Return indication if getChildLM will return another LM. * @return true if another child LM is still available */ protected boolean hasNextChildLM() { return childLMiter.hasNext(); } /** * Tell whether this LayoutManager has handled all of its content. * @return True if there are no more break possibilities, * ie. the last one returned represents the end of the content. */ public boolean isFinished() { return isFinished; } /** * Set the flag indicating the LayoutManager has handled all of its content. * @param fin the flag value to be set */ public void setFinished(boolean fin) { isFinished = fin; } /** {@inheritDoc} */ public void addAreas(PositionIterator posIter, LayoutContext context) { } /** {@inheritDoc} */ public List getNextKnuthElements(LayoutContext context, int alignment) { log.warn("null implementation of getNextKnuthElements() called!"); setFinished(true); return null; } /** {@inheritDoc} */ public List getChangedKnuthElements(List oldList, int alignment) { log.warn("null implementation of getChangeKnuthElement() called!"); return null; } /** * Return an Area which can contain the passed childArea. The childArea * may not yet have any content, but it has essential traits set. * In general, if the LayoutManager already has an Area it simply returns * it. Otherwise, it makes a new Area of the appropriate class. * It gets a parent area for its area by calling its parent LM. * Finally, based on the dimensions of the parent area, it initializes * its own area. This includes setting the content IPD and the maximum * BPD. * @param childArea the child area for which the parent area is wanted * @return the parent area for the given child */ public Area getParentArea(Area childArea) { return null; } /** * Add a child area to the current area. If this causes the maximum * dimension of the current area to be exceeded, the parent LM is called * to add it. * @param childArea the child area to be added */ public void addChildArea(Area childArea) { } /** * Create the LM instances for the children of the * formatting object being handled by this LM. * @param size the requested number of child LMs * @return the list with the preloaded child LMs */ protected List<LayoutManager> createChildLMs(int size) { if (fobjIter == null) { return null; } List<LayoutManager> newLMs = new ArrayList<LayoutManager>(size); while (fobjIter.hasNext() && newLMs.size() < size) { Object theobj = fobjIter.next(); if (theobj instanceof FONode) { FONode foNode = (FONode) theobj; if (foNode instanceof RetrieveMarker) { foNode = getPSLM().resolveRetrieveMarker( (RetrieveMarker) foNode); } if (foNode != null) { getPSLM().getLayoutManagerMaker() .makeLayoutManagers(foNode, newLMs); } } } return newLMs; } /** {@inheritDoc} */ public PageSequenceLayoutManager getPSLM() { return parentLayoutManager.getPSLM(); } /** * @see PageSequenceLayoutManager#getCurrentPage() * @return the {@link Page} instance corresponding to the current page */ public Page getCurrentPage() { return getPSLM().getCurrentPage(); } /** @return the current page viewport */ public PageViewport getCurrentPV() { return getPSLM().getCurrentPage().getPageViewport(); } /** {@inheritDoc} */ public boolean createNextChildLMs(int pos) { List<LayoutManager> newLMs = createChildLMs(pos + 1 - childLMs.size()); addChildLMs(newLMs); return pos < childLMs.size(); } /** {@inheritDoc} */ public List<LayoutManager> getChildLMs() { if (childLMs == null) { childLMs = new java.util.ArrayList<LayoutManager>(10); } return childLMs; } /** {@inheritDoc} */ public void addChildLM(LayoutManager lm) { if (lm == null) { return; } lm.setParent(this); if (childLMs == null) { childLMs = new java.util.ArrayList<LayoutManager>(10); } childLMs.add(lm); if (log.isTraceEnabled()) { log.trace(this.getClass().getName() + ": Adding child LM " + lm.getClass().getName()); } } /** {@inheritDoc} */ public void addChildLMs(List newLMs) { if (newLMs == null || newLMs.size() == 0) { return; } ListIterator<LayoutManager> iter = newLMs.listIterator(); while (iter.hasNext()) { addChildLM(iter.next()); } } /** * Adds a Position to the Position participating in the first|last determination by assigning * it a unique position index. * @param pos the Position * @return the same Position but with a position index */ public Position notifyPos(Position pos) { if (pos.getIndex() >= 0) { throw new IllegalStateException("Position already got its index"); } pos.setIndex(++lastGeneratedPosition); return pos; } private void verifyNonNullPosition(Position pos) { if (pos == null || pos.getIndex() < 0) { throw new IllegalArgumentException( "Only non-null Positions with an index can be checked"); } } /** * Indicates whether the given Position is the first area-generating Position of this LM. * @param pos the Position (must be one with a position index) * @return True if it is the first Position */ public boolean isFirst(Position pos) { //log.trace("isFirst() smallestPosNumberChecked=" + smallestPosNumberChecked + " " + pos); verifyNonNullPosition(pos); if (pos.getIndex() == this.smallestPosNumberChecked) { return true; } else if (pos.getIndex() < this.smallestPosNumberChecked) { this.smallestPosNumberChecked = pos.getIndex(); return true; } else { return false; } } /** * Indicates whether the given Position is the last area-generating Position of this LM. * @param pos the Position (must be one with a position index) * @return True if it is the last Position */ public boolean isLast(Position pos) { verifyNonNullPosition(pos); return (pos.getIndex() == this.lastGeneratedPosition && isFinished()); } public boolean hasLineAreaDescendant() { if (childLMs == null || childLMs.isEmpty()) { return false; } else { for (LayoutManager childLM : childLMs) { if (childLM.hasLineAreaDescendant()) { return true; } } } return false; } public int getBaselineOffset() { if (childLMs != null) { for (LayoutManager childLM : childLMs) { if (childLM.hasLineAreaDescendant()) { return childLM.getBaselineOffset(); } } } throw newNoLineAreaDescendantException(); } protected IllegalStateException newNoLineAreaDescendantException() { return new IllegalStateException("getBaselineOffset called on an object that has no line-area descendant"); } /** * Transfers foreign attributes from the formatting object to the area. * @param targetArea the area to set the attributes on */ protected void transferForeignAttributes(AreaTreeObject targetArea) { Map<QName, String> atts = fobj.getForeignAttributes(); targetArea.setForeignAttributes(atts); } /** * Transfers extension attachments from the formatting object to the area. * @param targetArea the area to set the extensions on */ protected void transferExtensionAttachments(AreaTreeObject targetArea) { if (fobj.hasExtensionAttachments()) { targetArea.setExtensionAttachments(fobj.getExtensionAttachments()); } } /** * Transfers extensions (foreign attributes and extension attachments) from * the formatting object to the area. * @param targetArea the area to set the extensions on */ protected void transferExtensions(AreaTreeObject targetArea) { transferForeignAttributes(targetArea); transferExtensionAttachments(targetArea); } /** * Registers the FO's markers on the current PageViewport, and if applicable on the parent TableLM. * * @param isStarting boolean indicating whether the markers qualify as 'starting' * @param isFirst boolean indicating whether the markers qualify as 'first' * @param isLast boolean indicating whether the markers qualify as 'last' */ protected void registerMarkers(boolean isStarting, boolean isFirst, boolean isLast) { if (this.markers != null) { getCurrentPV().registerMarkers( this.markers, isStarting, isFirst, isLast); possiblyRegisterMarkersForTables(markers, isStarting, isFirst, isLast); } } /** * Registers the FO's id on the current PageViewport */ protected void addId() { if (fobj != null) { getPSLM().addIDToPage(fobj.getId()); } } /** * Notifies the {@link PageSequenceLayoutManager} that layout * for this LM has ended. */ protected void notifyEndOfLayout() { if (fobj != null) { getPSLM().notifyEndOfLayout(fobj.getId()); } } /** * Checks to see if the incoming {@link Position} * is the last one for this LM, and if so, calls * {@link #notifyEndOfLayout()} and cleans up. * * @param pos the {@link Position} to check */ protected void checkEndOfLayout(Position pos) { if (pos != null && pos.getLM() == this && this.isLast(pos)) { notifyEndOfLayout(); if (!preserveChildrenAtEndOfLayout) { // References to the child LMs are no longer needed childLMs = null; curChildLM = null; childLMiter = null; } /* markers that qualify have been transferred to the page */ markers = null; /* References to the FO's children can be released if the * LM is a descendant of the FlowLM. For static-content * the FO may still be needed on following pages. */ LayoutManager lm = this.parentLayoutManager; while (!(lm instanceof FlowLayoutManager || lm instanceof PageSequenceLayoutManager)) { lm = lm.getParent(); } if (lm instanceof FlowLayoutManager && !preserveChildrenAtEndOfLayout) { fobj.clearChildNodes(); fobjIter = null; } } } /* * Preserves the children LMs at the end of layout. This is necessary if the layout is expected to be * repeated, as when using retrieve-table-markers. */ public void preserveChildrenAtEndOfLayout() { preserveChildrenAtEndOfLayout = true; } /** {@inheritDoc} */ @Override public String toString() { return (super.toString() + (fobj != null ? "{fobj = " + fobj.toString() + "}" : "")); } /** {@inheritDoc} */ @Override public void reset() { isFinished = false; curChildLM = null; childLMiter = new LMiter(this); /* Reset all the children LM that have been created so far. */ for (LayoutManager childLM : getChildLMs()) { childLM.reset(); } if (fobj != null) { markers = fobj.getMarkers(); } lastGeneratedPosition = -1; } public void recreateChildrenLMs() { childLMs = new ArrayList(); isFinished = false; if (fobj == null) { return; } fobjIter = fobj.getChildNodes(); int position = 0; while (createNextChildLMs(position++)) { // } childLMiter = new LMiter(this); for (LMiter iter = new LMiter(this); iter.hasNext();) { AbstractBaseLayoutManager alm = (AbstractBaseLayoutManager) iter.next(); alm.initialize(); alm.recreateChildrenLMs(); alm.preserveChildrenAtEndOfLayout(); } curChildLM = getChildLM(); } protected void possiblyRegisterMarkersForTables(Map<String, Marker> markers, boolean isStarting, boolean isFirst, boolean isLast) { LayoutManager lm = this.parentLayoutManager; if (lm instanceof FlowLayoutManager || lm instanceof PageSequenceLayoutManager || !(lm instanceof AbstractLayoutManager)) { return; } ((AbstractLayoutManager) lm).possiblyRegisterMarkersForTables(markers, isStarting, isFirst, isLast); } public boolean handlingFloat() { if (parentLayoutManager != null && parentLayoutManager instanceof AbstractLayoutManager) { return ((AbstractLayoutManager) parentLayoutManager).handlingFloat(); } return false; } }
apache-2.0
NASA-Tournament-Lab/CoECI-OPM-Service-Credit-Redeposit-Deposit-Application
Code/SCRD_BRE/src/java/ejb/gov/opm/scrd/services/impl/reporting/DeductionRatesReportService.java
17452
/* * Copyright (C) 2014 TopCoder Inc., All Rights Reserved. */ package gov.opm.scrd.services.impl.reporting; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfWriter; import com.lowagie.text.Table; import com.lowagie.text.rtf.RtfWriter2; import gov.opm.scrd.LoggingHelper; import gov.opm.scrd.entities.application.DeductionRate; import gov.opm.scrd.entities.common.Helper; import gov.opm.scrd.services.ExportType; import gov.opm.scrd.services.ReportGenerationException; import gov.opm.scrd.services.ReportService; import gov.opm.scrd.services.impl.BaseReportService; import org.jboss.logging.Logger; import javax.ejb.LocalBean; import javax.ejb.Stateless; import javax.persistence.PersistenceException; import java.io.ByteArrayOutputStream; import java.text.DateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; /** * This class is the implementation of the ReportService which generates deduction rates report. It uses local data for * generating report and iText/iText RTF for generating reports. <p> <strong>Thread-safety:</strong> This class is * effectively thread - safe after configuration, the configuration is done in a thread - safe manner. </p> * * @author AleaActaEst, RaitoShum * @version 1.0 */ @Stateless @LocalBean public class DeductionRatesReportService extends BaseReportService implements ReportService<DeductionRatesReportRequest, DeductionRatesReportResponse> { /** * <p> Represents the class name. </p> */ private static final String CLASS_NAME = DeductionRatesReportService.class .getName(); /** * Creates a new instance of the {@link DeductionRatesReportService} class. */ public DeductionRatesReportService() { super(); } /** * Creates the report for the given request. * * @param request * the request data to generate report. * @return ReportResponse instance containing the report data, can not be null. * @throws IllegalArgumentException * if the request is null. * @throws ReportGenerationException * if there is any problem when generating response. */ public DeductionRatesReportResponse getReport( DeductionRatesReportRequest request) throws ReportGenerationException { String signature = CLASS_NAME + "#getReport(DeductionRatesReportRequest request)"; Logger logger = getLogger(); LoggingHelper.logEntrance(logger, signature, new String[]{ "request" }, new Object[]{ request }); Helper.checkNull(logger, signature, request, "request"); try { DeductionRatesReportResponse response = new DeductionRatesReportResponse(); response.setReportName(getReportName()); response.setReportGenerationDate(new Date()); List<DeductionRate> rates = getEntityManager().createQuery( "SELECT d FROM DeductionRate d", DeductionRate.class) .getResultList(); Map<String, List<DeductionRatesReportResponseItem>> items = new HashMap<String, List<DeductionRatesReportResponseItem>>(); for (DeductionRate rate : rates) { if (items.get(rate.getServiceType()) == null) { items.put(rate.getServiceType(), new ArrayList<DeductionRatesReportResponseItem>()); } DeductionRatesReportResponseItem item = new DeductionRatesReportResponseItem(); item.setRetirementType(rate.getRetirementType().getName()); item.setStartDate(rate.getStartDate()); item.setDays(rate.getDaysInPeriod()); item.setRate(rate.getRate()); item.setEndDate(rate.getEndDate()); items.get(rate.getServiceType()).add(item); } response.setItems(items); LoggingHelper.logExit(logger, signature, new Object[]{ response }); return response; } catch (IllegalStateException e) { throw LoggingHelper.logException(logger, signature, new ReportGenerationException( "The entity manager has been closed.", e)); } catch (PersistenceException e) { throw LoggingHelper .logException( logger, signature, new ReportGenerationException( "An error has occurred when accessing persistence.", e)); } } /** * Exports the report for the given request. * * @param response * the request data to generate report. * @param exportType * the type of the report data to generate. * @return The byte array of contents of the exported report, can not be null. * @throws IllegalArgumentException * if the request/exportType is null. * @throws ReportGenerationException * if there is any problem when generating response. */ public byte[] exportReport(DeductionRatesReportResponse response, ExportType exportType) throws ReportGenerationException { String signature = CLASS_NAME + "#exportReport(DeductionRatesReportResponse response)"; Logger logger = getLogger(); LoggingHelper.logEntrance(logger, signature, new String[]{ "response" }, new Object[]{ response }); Helper.checkNull(logger, signature, response, "response"); try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); if (exportType == ExportType.DOC || exportType == ExportType.RTF) { com.lowagie.text.Document document = new com.lowagie.text.Document(); RtfWriter2.getInstance(document, outputStream); document.open(); ReportServiceHelper.addReportDate(document, response.getReportGenerationDate(), ReportServiceHelper.REPORT_DATE_FORMAT, ReportServiceHelper.RTF_ALIGN_LEFT); ReportServiceHelper.addReportTitle(document, response.getReportName()); if (response.getItems() != null) { int[] alignments = new int[]{ ReportServiceHelper.RTF_ALIGN_LEFT, ReportServiceHelper.RTF_ALIGN_LEFT, ReportServiceHelper.RTF_ALIGN_RIGHT, ReportServiceHelper.RTF_ALIGN_RIGHT }; int[] cellWidths = new int[]{ 30, 20, 20, 15, 15 }; DateFormat dateFormat = DateFormat .getDateInstance(DateFormat.LONG); int j = 1; for (String jobName : response.getItems().keySet()) { Table table = new Table(5); table.setSpacing(1); table.setWidths(cellWidths); table.addCell(ReportServiceHelper.createTableCell( "FERS", ReportServiceHelper.RTF_REPORT_HEADER_FONT, null, ReportServiceHelper.RTF_ALIGN_LEFT, null, 1)); for (int i = 0; i < response.getItems().get(jobName) .size(); i++) { if (i == 0) { table.addCell(ReportServiceHelper .createTableCell( jobName, ReportServiceHelper.RTF_REPORT_HEADER_FONT, null, ReportServiceHelper.RTF_ALIGN_LEFT, null, 4)); table.addCell(ReportServiceHelper .createEmptyCell( 1, ReportServiceHelper.RTF_NO_BORDER)); ReportServiceHelper .addReportTableRow( table, new String[]{ "Start Date", "End Date", "Days", "Rate" }, ReportServiceHelper.RTF_REPORT_CONTENT_FONT, null, alignments, ReportServiceHelper.RTF_BORDER_BOTTOM); } DeductionRatesReportResponseItem item = response .getItems().get(jobName).get(i); table.addCell(ReportServiceHelper.createEmptyCell( 1, ReportServiceHelper.RTF_NO_BORDER)); String startDate = item.getStartDate() == null ? null : dateFormat.format(item.getStartDate()); String endDate = item.getEndDate() == null ? null : dateFormat.format(item.getEndDate()); ReportServiceHelper .addReportTableRow( table, new Object[]{ startDate, endDate, item.getDays(), item.getRate() == null ? null : item.getRate() + "%" }, ReportServiceHelper.RTF_REPORT_CONTENT_FONT, null, alignments, ReportServiceHelper.RTF_NO_BORDER); } if (j == response.getItems().keySet().size()) { table.setBorder(ReportServiceHelper.RTF_BORDER_BOTTOM); table.setBorderWidth(2); } else { table.setBorder(ReportServiceHelper.RTF_NO_BORDER); } document.add(table); j++; } } document.close(); } else { com.itextpdf.text.Document document = new com.itextpdf.text.Document(); PdfWriter.getInstance(document, outputStream); document.open(); ReportServiceHelper.addReportDate(document, response.getReportGenerationDate(), ReportServiceHelper.REPORT_DATE_FORMAT, ReportServiceHelper.PDF_ALIGN_LEFT); ReportServiceHelper.addReportTitle(document, response.getReportName()); if (response.getItems() != null) { int[] alignments = new int[]{ ReportServiceHelper.PDF_ALIGN_LEFT, ReportServiceHelper.PDF_ALIGN_LEFT, ReportServiceHelper.PDF_ALIGN_RIGHT, ReportServiceHelper.PDF_ALIGN_RIGHT }; int[] cellWidths = new int[]{ 30, 20, 20, 15, 15 }; DateFormat dateFormat = DateFormat .getDateInstance(DateFormat.LONG); int j = 1; for (String jobName : response.getItems().keySet()) { PdfPTable table = new PdfPTable(5); table.setWidths(cellWidths); table.setSpacingBefore(20); table.addCell(ReportServiceHelper.createTableCell( "FERS", ReportServiceHelper.PDF_REPORT_HEADER_FONT, null, ReportServiceHelper.PDF_ALIGN_LEFT, null, 1)); for (int i = 0; i < response.getItems().get(jobName) .size(); i++) { if (i == 0) { table.addCell(ReportServiceHelper .createTableCell( jobName, ReportServiceHelper.PDF_REPORT_HEADER_FONT, null, ReportServiceHelper.PDF_ALIGN_LEFT, null, 4)); table.addCell(ReportServiceHelper .createEmptyPdfCell( 1, ReportServiceHelper.PDF_NO_BORDER)); ReportServiceHelper .addReportTableRow( table, new String[]{ "Start Date", "End Date", "Days", "Rate" }, ReportServiceHelper.PDF_REPORT_CONTENT_FONT, null, alignments, ReportServiceHelper.PDF_BORDER_BOTTOM); } DeductionRatesReportResponseItem item = response .getItems().get(jobName).get(i); int border = j == response.getItems().keySet() .size() && i == response.getItems().get(jobName) .size() - 1 ? ReportServiceHelper.PDF_BORDER_BOTTOM : ReportServiceHelper.PDF_NO_BORDER; table.addCell(ReportServiceHelper .createEmptyPdfCell(1, border)); String startDate = item.getStartDate() == null ? null : dateFormat.format(item.getStartDate()); String endDate = item.getEndDate() == null ? null : dateFormat.format(item.getEndDate()); ReportServiceHelper .addReportTableRow( table, new Object[]{ startDate, endDate, item.getDays(), item.getRate() == null ? null : item.getRate() + "%" }, ReportServiceHelper.PDF_REPORT_CONTENT_FONT, null, alignments, border); } document.add(table); j++; } } document.close(); } LoggingHelper.logExit(getLogger(), signature, null); return outputStream.toByteArray(); } catch (com.lowagie.text.DocumentException ex) { throw LoggingHelper.logException(getLogger(), signature, new ReportGenerationException( "Error occurred while exporting the report.", ex)); } catch (com.itextpdf.text.DocumentException ex) { throw LoggingHelper.logException(getLogger(), signature, new ReportGenerationException( "Error occurred while exporting the report.", ex)); } } /** * Renders the chart image. * * @param response the service response for rendering. * @return the byte array of the image. * @throws ReportGenerationException if there are any error. */ @Override public byte[] renderChart(DeductionRatesReportResponse response) throws ReportGenerationException { return null; } }
apache-2.0
codechix/CodeChix-Public-Repo
pytheas-solardata/src/main/java/com/codechix/explorers/solardata/installation/InstallationBuilder.java
1689
package com.codechix.explorers.solardata.installation; public class InstallationBuilder { private SolarInstallation installation; public InstallationBuilder() { installation = new SolarInstallation(); } public SolarInstallation build() { return installation; } public InstallationBuilder withApplicationNumber(String applicationNumber) { installation.setApplicationNumber(applicationNumber); return this; } public InstallationBuilder withId(String applicationNumber) { installation.setApplicationNumber(applicationNumber); return this; } public InstallationBuilder withIncentive(String incentive) { installation.setIncentiveAmount(incentive); return this; } public InstallationBuilder withTotalCost(String totalCost) { installation.setTotalCost(totalCost); return this; } public InstallationBuilder withZipCode(String zipCode) { installation.setZipCode(zipCode); return this; } public SolarInstallation buildWithStats(String[] stats) { for (int i = 0; i < stats.length; i++) { switch (i) { case 0: installation.setApplicationNumber(stats[i]); break; case 1: installation.setIncentiveAmount(stats[i]); break; case 2: installation.setTotalCost(stats[i]); break; case 3: installation.setZipCode(stats[i]); break; } } return installation; } }
apache-2.0
dump247/aws-sdk-java
aws-java-sdk-machinelearning/src/main/java/com/amazonaws/services/machinelearning/model/transform/S3DataSpecJsonUnmarshaller.java
3572
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights * Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.machinelearning.model.transform; import java.util.Map; import java.util.Map.Entry; import com.amazonaws.services.machinelearning.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * S3DataSpec JSON Unmarshaller */ public class S3DataSpecJsonUnmarshaller implements Unmarshaller<S3DataSpec, JsonUnmarshallerContext> { public S3DataSpec unmarshall(JsonUnmarshallerContext context) throws Exception { S3DataSpec s3DataSpec = new S3DataSpec(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) return null; while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("DataLocationS3", targetDepth)) { context.nextToken(); s3DataSpec.setDataLocationS3(StringJsonUnmarshaller .getInstance().unmarshall(context)); } if (context.testExpression("DataRearrangement", targetDepth)) { context.nextToken(); s3DataSpec.setDataRearrangement(StringJsonUnmarshaller .getInstance().unmarshall(context)); } if (context.testExpression("DataSchema", targetDepth)) { context.nextToken(); s3DataSpec.setDataSchema(StringJsonUnmarshaller .getInstance().unmarshall(context)); } if (context.testExpression("DataSchemaLocationS3", targetDepth)) { context.nextToken(); s3DataSpec.setDataSchemaLocationS3(StringJsonUnmarshaller .getInstance().unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals( currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return s3DataSpec; } private static S3DataSpecJsonUnmarshaller instance; public static S3DataSpecJsonUnmarshaller getInstance() { if (instance == null) instance = new S3DataSpecJsonUnmarshaller(); return instance; } }
apache-2.0
jt120/algorithm
new-alg/src/main/java/std/algs/UF.java
7659
package std.algs; import std.libs.*; /**************************************************************************** * Compilation: javac UF.java * Execution: java UF < input.txt * Dependencies: StdIn.java StdOut.java * Data files: http://algs4.cs.princeton.edu/15uf/tinyUF.txt * http://algs4.cs.princeton.edu/15uf/mediumUF.txt * http://algs4.cs.princeton.edu/15uf/largeUF.txt * * Weighted quick-union by rank with path compression by halving. * * % java UF < tinyUF.txt * 4 3 * 3 8 * 6 5 * 9 4 * 2 1 * 5 0 * 7 2 * 6 1 * 2 components * ****************************************************************************/ /** * The <tt>UF</tt> class represents a <em>union-find data type</em> * (also known as the <em>disjoint-sets data type</em>). * It supports the <em>union</em> and <em>find</em> operations, * along with a <em>connected</em> operation for determinig whether * two sites in the same component and a <em>count</em> operation that * returns the total number of components. * <p> * The union-find data type models connectivity among a set of <em>N</em> * sites, named 0 through <em>N</em> &ndash; 1. * The <em>is-connected-to</em> relation must be an * <em>equivalence relation</em>: * <ul> * <p><li> <em>Reflexive</em>: <em>p</em> is connected to <em>p</em>. * <p><li> <em>Symmetric</em>: If <em>p</em> is connected to <em>q</em>, * <em>q</em> is connected to <em>p</em>. * <p><li> <em>Transitive</em>: If <em>p</em> is connected to <em>q</em> * and <em>q</em> is connected to <em>r</em>, then * <em>p</em> is connected to <em>r</em>. * </ul> * An equivalence relation partitions the sites into * <em>equivalence classes</em> (or <em>components</em>). In this case, * two sites are in the same component if and only if they are connected. * Both sites and components are identified with integers between 0 and * <em>N</em> &ndash; 1. * Initially, there are <em>N</em> components, with each site in its * own component. The <em>component identifier</em> of a component * (also known as the <em>root</em>, <em>canonical element</em>, <em>leader</em>, * or <em>set representative</em>) is one of the sites in the component: * two sites have the same component identifier if and only if they are * in the same component. * <ul> * <p><li><em>union</em>(<em>p</em>, <em>q</em>) adds a * connection between the two sites <em>p</em> and <em>q</em>. * If <em>p</em> and <em>q</em> are in different components, * then it replaces * these two components with a new component that is the union of * the two. * <p><li><em>find</em>(<em>p</em>) returns the component * identifier of the component containing <em>p</em>. * <p><li><em>connected</em>(<em>p</em>, <em>q</em>) * returns true if both <em>p</em> and <em>q</em> * are in the same component, and false otherwise. * <p><li><em>count</em>() returns the number of components. * </ul> * The component identifier of a component can change * only when the component itself changes during a call to * <em>union</em>&mdash;it cannot change during a call * to <em>find</em>, <em>connected</em>, or <em>count</em>. * <p> * This implementation uses weighted quick union by rank with path compression * by halving. * Initializing a data structure with <em>N</em> sites takes linear time. * Afterwards, the <em>union</em>, <em>find</em>, and <em>connected</em> * operations take logarithmic time (in the worst case) and the * <em>count</em> operation takes constant time. * Moreover, the amortized time per <em>union</em>, <em>find</em>, * and <em>connected</em> operation has inverse Ackermann complexity. * For alternate implementations of the same API, see * {@link std.algs.QuickUnionUF}, {@link std.algs.QuickFindUF}, and {@link WeightedQuickUnionUF}. * * <p> * For additional documentation, see <a href="http://algs4.cs.princeton.edu/15uf">Section 1.5</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne */ public class UF { private int[] id; // id[i] = parent of i private byte[] rank; // rank[i] = rank of subtree rooted at i (cannot be more than 31) private int count; // number of components /** * Initializes an empty union-find data structure with <tt>N</tt> * isolated components <tt>0</tt> through <tt>N-1</tt> * @throws IllegalArgumentException if <tt>N &lt; 0</tt> * @param N the number of sites */ public UF(int N) { if (N < 0) throw new IllegalArgumentException(); count = N; id = new int[N]; rank = new byte[N]; for (int i = 0; i < N; i++) { id[i] = i; rank[i] = 0; } } /** * Returns the component identifier for the component containing site <tt>p</tt>. * @param p the integer representing one object * @return the component identifier for the component containing site <tt>p</tt> * @throws IndexOutOfBoundsException unless <tt>0 &le; p &lt; N</tt> */ public int find(int p) { if (p < 0 || p >= id.length) throw new IndexOutOfBoundsException(); while (p != id[p]) { id[p] = id[id[p]]; // path compression by halving p = id[p]; } return p; } /** * Returns the number of components. * @return the number of components (between <tt>1</tt> and <tt>N</tt>) */ public int count() { return count; } /** * Are the two sites <tt>p</tt> and <tt>q</tt> in the same component? * @param p the integer representing one site * @param q the integer representing the other site * @return true if the two sites <tt>p</tt> and <tt>q</tt> are in the same component; false otherwise * @throws IndexOutOfBoundsException unless * both <tt>0 &le; p &lt; N</tt> and <tt>0 &le; q &lt; N</tt> */ public boolean connected(int p, int q) { return find(p) == find(q); } /** * Merges the component containing site <tt>p</tt> with the * the component containing site <tt>q</tt>. * @param p the integer representing one site * @param q the integer representing the other site * @throws IndexOutOfBoundsException unless * both <tt>0 &le; p &lt; N</tt> and <tt>0 &le; q &lt; N</tt> */ public void union(int p, int q) { int i = find(p); int j = find(q); if (i == j) return; // make root of smaller rank point to root of larger rank if (rank[i] < rank[j]) id[i] = j; else if (rank[i] > rank[j]) id[j] = i; else { id[j] = i; rank[i]++; } count--; } /** * Reads in a an integer <tt>N</tt> and a sequence of pairs of integers * (between <tt>0</tt> and <tt>N-1</tt>) from standard input, where each integer * in the pair represents some site; * if the sites are in different components, merge the two components * and print the pair to standard output. */ public static void main(String[] args) { int N = StdIn.readInt(); UF uf = new UF(N); while (!StdIn.isEmpty()) { int p = StdIn.readInt(); int q = StdIn.readInt(); if (uf.connected(p, q)) continue; uf.union(p, q); StdOut.println(p + " " + q); } StdOut.println(uf.count() + " components"); } }
apache-2.0
JeffLi1993/springdream
spring/springdream-ioc/src/main/java/org/spring/bean/pojo/Car.java
253
package org.spring.bean.pojo; /** * Created by BYSocket on 2015/12/10. */ public class Car { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
apache-2.0
primeval-io/saga
saga-thymeleaf/src/main/java/io/primeval/saga/thymeleaf/internal/SagaTemplateResolver.java
1024
package io.primeval.saga.thymeleaf.internal; import java.util.Map; import org.thymeleaf.IEngineConfiguration; import org.thymeleaf.templateresolver.AbstractConfigurableTemplateResolver; import org.thymeleaf.templateresource.ClassLoaderTemplateResource; import org.thymeleaf.templateresource.ITemplateResource; public final class SagaTemplateResolver extends AbstractConfigurableTemplateResolver { public SagaTemplateResolver() { setPrefix("templates/"); setSuffix(".thl.html"); } @Override protected ITemplateResource computeTemplateResource(IEngineConfiguration configuration, String ownerTemplate, String template, String resourceName, String characterEncoding, Map<String, Object> templateResolutionAttributes) { ClassLoader classloader = (ClassLoader) templateResolutionAttributes .get(ThymeleafTemplateEngineImpl.CLASSLOADER_VAR); return new ClassLoaderTemplateResource(classloader, resourceName, characterEncoding); } }
apache-2.0
alancnet/artifactory
backend/core/src/main/java/org/artifactory/repo/db/DbStoringRepoMixin.java
36688
/* * Artifactory is a binaries repository manager. * Copyright (C) 2012 JFrog Ltd. * * Artifactory is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Artifactory is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Artifactory. If not, see <http://www.gnu.org/licenses/>. */ package org.artifactory.repo.db; import com.google.common.collect.Lists; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpStatus; import org.apache.maven.artifact.repository.metadata.Metadata; import org.apache.maven.artifact.repository.metadata.SnapshotVersion; import org.apache.maven.artifact.repository.metadata.Versioning; import org.artifactory.addon.AddonsManager; import org.artifactory.addon.filteredresources.FilteredResourcesAddon; import org.artifactory.addon.HaAddon; import org.artifactory.addon.PropertiesAddon; import org.artifactory.addon.RestCoreAddon; import org.artifactory.api.common.BasicStatusHolder; import org.artifactory.api.context.ArtifactoryContext; import org.artifactory.api.context.ContextHelper; import org.artifactory.api.maven.MavenMetadataService; import org.artifactory.api.properties.PropertiesService; import org.artifactory.api.repo.exception.FileExpectedException; import org.artifactory.api.repo.exception.ItemNotFoundRuntimeException; import org.artifactory.api.repo.exception.RepoRejectException; import org.artifactory.api.security.AuthorizationService; import org.artifactory.binstore.BinaryInfo; import org.artifactory.checksum.ChecksumInfo; import org.artifactory.checksum.ChecksumType; import org.artifactory.checksum.ChecksumsInfo; import org.artifactory.common.ConstantValues; import org.artifactory.common.StatusHolder; import org.artifactory.descriptor.property.PropertySet; import org.artifactory.descriptor.repo.LocalCacheRepoDescriptor; import org.artifactory.descriptor.repo.RemoteRepoDescriptor; import org.artifactory.descriptor.repo.RepoBaseDescriptor; import org.artifactory.exception.CancelException; import org.artifactory.fs.FileInfo; import org.artifactory.fs.ItemInfo; import org.artifactory.fs.RepoResource; import org.artifactory.fs.ZipEntryRepoResource; import org.artifactory.io.SimpleResourceStreamHandle; import org.artifactory.io.checksum.policy.ChecksumPolicy; import org.artifactory.io.checksum.policy.ChecksumPolicyException; import org.artifactory.maven.MavenModelUtils; import org.artifactory.md.Properties; import org.artifactory.mime.MavenNaming; import org.artifactory.mime.NamingUtils; import org.artifactory.model.common.RepoPathImpl; import org.artifactory.model.xstream.fs.PropertiesImpl; import org.artifactory.model.xstream.fs.StatsImpl; import org.artifactory.repo.InternalRepoPathFactory; import org.artifactory.repo.LocalCacheRepo; import org.artifactory.repo.LocalRepo; import org.artifactory.repo.RepoPath; import org.artifactory.repo.SaveResourceContext; import org.artifactory.repo.cache.expirable.CacheExpiry; import org.artifactory.repo.interceptor.StorageInterceptors; import org.artifactory.repo.local.LocalNonCacheOverridable; import org.artifactory.repo.local.PathDeletionContext; import org.artifactory.repo.service.InternalRepositoryService; import org.artifactory.request.InternalRequestContext; import org.artifactory.request.RepoRequests; import org.artifactory.request.Request; import org.artifactory.request.RequestContext; import org.artifactory.resource.FileResource; import org.artifactory.resource.MutableRepoResourceInfo; import org.artifactory.resource.ResolvedResource; import org.artifactory.resource.ResourceStreamHandle; import org.artifactory.resource.UnfoundRepoResource; import org.artifactory.resource.UnfoundRepoResourceReason; import org.artifactory.sapi.fs.MutableVfsFile; import org.artifactory.sapi.fs.MutableVfsFolder; import org.artifactory.sapi.fs.MutableVfsItem; import org.artifactory.sapi.fs.VfsFile; import org.artifactory.sapi.fs.VfsFolder; import org.artifactory.sapi.fs.VfsItem; import org.artifactory.security.AccessLogger; import org.artifactory.storage.StorageException; import org.artifactory.storage.fs.VfsFileProvider; import org.artifactory.storage.fs.VfsFolderProvider; import org.artifactory.storage.fs.VfsItemProvider; import org.artifactory.storage.fs.VfsItemProviderFactory; import org.artifactory.storage.fs.lock.FsItemsVault; import org.artifactory.storage.fs.lock.LockEntryId; import org.artifactory.storage.fs.lock.LockingHelper; import org.artifactory.storage.fs.repo.StoringRepo; import org.artifactory.storage.fs.service.FileService; import org.artifactory.storage.fs.service.StatsService; import org.artifactory.storage.fs.session.StorageSession; import org.artifactory.storage.fs.session.StorageSessionHolder; import org.artifactory.storage.service.StatsServiceImpl; import org.artifactory.util.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.transaction.interceptor.TransactionAspectSupport; import javax.annotation.Nullable; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Set; import java.util.jar.JarEntry; import java.util.jar.JarInputStream; public class DbStoringRepoMixin<T extends RepoBaseDescriptor> /*implements StoringRepo<T> */ implements StoringRepo { private static final Logger log = LoggerFactory.getLogger(DbStoringRepoMixin.class); private static final String CONTENT_TYPE_PROP_KEY = PropertySet.ARTIFACTORY_RESERVED_PROP_SET + "." + PropertiesService.CONTENT_TYPE_PROPERTY_NAME; private final T descriptor; private AuthorizationService authorizationService; private StorageInterceptors interceptors; private AddonsManager addonsManager; private FileService fileService; private StatsService statsService; private DbStoringRepoMixin oldStoringRepo; private FsItemsVault fsItemsVault; private InternalRepositoryService repositoryService; private MavenMetadataService mavenMetadataService; private VfsItemProviderFactory vfsItemProviderFactory; public DbStoringRepoMixin(T descriptor, DbStoringRepoMixin oldStoringRepo) { this.descriptor = descriptor; this.oldStoringRepo = oldStoringRepo; } public void init() throws StorageException { ArtifactoryContext context = ContextHelper.get(); authorizationService = context.beanForType(AuthorizationService.class); interceptors = context.beanForType(StorageInterceptors.class); addonsManager = context.beanForType(AddonsManager.class); fileService = context.beanForType(FileService.class); statsService = context.beanForType(StatsServiceImpl.class); repositoryService = context.beanForType(InternalRepositoryService.class); vfsItemProviderFactory = context.beanForType(VfsItemProviderFactory.class); mavenMetadataService = context.beanForType(MavenMetadataService.class); if (oldStoringRepo != null) { fsItemsVault = oldStoringRepo.fsItemsVault; } else { fsItemsVault = addonsManager.addonByType(HaAddon.class).getFsItemVault(); } // Throw away after usage oldStoringRepo = null; //Create the repo node if it doesn't exist RepoPath rootRP = InternalRepoPathFactory.create(getKey(), ""); if (!fileService.exists(rootRP)) { createOrGetFolder(rootRP); } } /** * Create the resource in the local repository */ @SuppressWarnings("unchecked") public RepoResource saveResource(SaveResourceContext context) throws IOException, RepoRejectException { RepoResource res = context.getRepoResource(); RepoPath repoPath = InternalRepoPathFactory.create(getKey(), res.getRepoPath().getPath()); MutableVfsFile mutableFile = null; try { //Create the parent folder if it does not exist RepoPath parentPath = repoPath.getParent(); if (parentPath == null) { throw new StorageException("Cannot save resource, no parent repo path exists"); } // get or create the file. also creates any ancestors on the path to this item mutableFile = createOrGetFile(repoPath); invokeBeforeCreateInterceptors(mutableFile); setClientChecksums(res, mutableFile); /** * If the file isn't a non-unique snapshot and it already exists, create a defensive of the checksums * info for later comparison */ boolean isNonUniqueSnapshot = MavenNaming.isNonUniqueSnapshot(repoPath.getId()); String overriddenFileSha1 = null; if (!isNonUniqueSnapshot && !mutableFile.isNew()) { overriddenFileSha1 = mutableFile.getSha1(); log.debug("Overriding {} with sha1: {}", mutableFile.getRepoPath(), overriddenFileSha1); } fillBinaryData(context, mutableFile); verifyChecksum(mutableFile); if (jarValidationRequired(repoPath)) { validateArtifactIfRequired(mutableFile, repoPath); } long lastModified = res.getInfo().getLastModified(); mutableFile.setModified(lastModified); mutableFile.setUpdated(lastModified); String userId = authorizationService.currentUsername(); mutableFile.setModifiedBy(userId); if (mutableFile.isNew()) { mutableFile.setCreatedBy(userId); } // allow admin override of selected file details (i.e., override when replicating) overrideFileDetailsFromRequest(context, mutableFile); updateResourceWithActualBinaryData(res, mutableFile); clearOldFileData(mutableFile, isNonUniqueSnapshot, overriddenFileSha1); Properties properties = context.getProperties(); if (properties != null) { saveProperties(context, mutableFile); } invokeAfterCreateInterceptors(mutableFile); AccessLogger.deployed(repoPath); return res; } catch (Exception e) { TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); if (mutableFile != null) { mutableFile.markError(); } // throw back any CancelException if (e instanceof CancelException) { if (mutableFile != null) { LockingHelper.removeLockEntry(mutableFile.getRepoPath()); } RepoRejectException repoRejectException = new RepoRejectException(e); context.setException(repoRejectException); throw repoRejectException; } // throw back any RepoRejectException (ChecksumPolicyException etc) Throwable rejectException = ExceptionUtils.getCauseOfTypes(e, RepoRejectException.class); if (rejectException != null) { context.setException(rejectException); throw (RepoRejectException) rejectException; } //Unwrap any IOException and throw it Throwable ioCause = ExceptionUtils.getCauseOfTypes(e, IOException.class); if (ioCause != null) { log.error("IO error while trying to save resource {}'': {}: {}", res.getRepoPath(), ioCause.getClass().getName(), ioCause.getMessage()); log.debug("IO error while trying to save resource {}'': {}", res.getRepoPath(), ioCause.getMessage(), ioCause); context.setException(ioCause); throw (IOException) ioCause; } // Throw any RuntimeException instances if (e instanceof RuntimeException) { context.setException(e); throw e; } context.setException(e); throw new RuntimeException("Failed to save resource '" + res.getRepoPath() + "'.", e); } } private void fillBinaryData(SaveResourceContext context, MutableVfsFile mutableFile) { BinaryInfo binaryInfo = context.getBinaryInfo(); boolean usedExistingBinary = false; if (binaryInfo != null) { usedExistingBinary = mutableFile.tryUsingExistingBinary( binaryInfo.getSha1(), binaryInfo.getMd5(), binaryInfo.getLength()); if (!usedExistingBinary) { log.debug("Tried to save with existing binary info but failed: '{}': {}", mutableFile.getRepoPath().toPath(), binaryInfo); } } if (!usedExistingBinary) { InputStream in = context.getInputStream(); mutableFile.fillBinaryData(in); } else { log.trace("Using existing binary info for '{}': {}", mutableFile.getRepoPath().toPath(), binaryInfo); } } private boolean jarValidationRequired(RepoPath repoPath) { if (!NamingUtils.isJarVariant(repoPath.getPath())) { return false; } RemoteRepoDescriptor remoteRepoDescriptor; T repoDescriptor = getDescriptor(); if (repoDescriptor instanceof RemoteRepoDescriptor) { remoteRepoDescriptor = ((RemoteRepoDescriptor) repoDescriptor); } else if (repoDescriptor instanceof LocalCacheRepoDescriptor) { remoteRepoDescriptor = ((LocalCacheRepoDescriptor) repoDescriptor).getRemoteRepo(); } else { return false; } if (!remoteRepoDescriptor.isRejectInvalidJars()) { return false; } return true; } private void validateArtifactIfRequired(MutableVfsFile mutableFile, RepoPath repoPath) throws RepoRejectException { String pathId = repoPath.getId(); InputStream jarStream = mutableFile.getStream(); try { log.info("Validating the content of '{}'.", pathId); JarInputStream jarInputStream = new JarInputStream(jarStream, true); JarEntry entry = jarInputStream.getNextJarEntry(); if (entry == null) { if (jarInputStream.getManifest() != null) { log.trace("Found manifest validating the content of '{}'.", pathId); return; } throw new IllegalStateException("Could not find entries within the archive."); } do { log.trace("Found the entry '{}' validating the content of '{}'.", entry.getName(), pathId); } while ((jarInputStream.available() == 1) && (entry = jarInputStream.getNextJarEntry()) != null); log.info("Finished validating the content of '{}'.", pathId); } catch (Exception e) { String message = String.format("Failed to validate the content of '%s': %s", pathId, e.getMessage()); if (log.isDebugEnabled()) { log.debug(message, e); } else { log.error(message); } throw new RepoRejectException(message, HttpStatus.SC_CONFLICT); } finally { IOUtils.closeQuietly(jarStream); } } private void saveProperties(SaveResourceContext context, MutableVfsFile mutableFile) throws RepoRejectException { Properties properties = context.getProperties(); if ((properties != null) && !properties.isEmpty()) { BasicStatusHolder statusHolder = new BasicStatusHolder(); for (String key : properties.keys()) { Set<String> values = properties.get(key); String[] vals = (values != null) ? values.toArray(new String[values.size()]) : new String[]{}; interceptors.beforePropertyCreate(mutableFile, statusHolder, key, vals); } checkForCancelException(statusHolder); mutableFile.setProperties(properties); for (String key : properties.keys()) { Set<String> values = properties.get(key); String[] vals = (values != null) ? values.toArray(new String[values.size()]) : new String[]{}; interceptors.afterPropertyCreate(mutableFile, statusHolder, key, vals); } } } private void verifyChecksum(MutableVfsFile mutableFile) throws ChecksumPolicyException { ChecksumPolicy policy = getOwningRepo().getChecksumPolicy(); ChecksumsInfo checksumsInfo = mutableFile.getInfo().getChecksumsInfo(); boolean passes = policy.verify(checksumsInfo.getChecksums()); if (!passes) { throw new ChecksumPolicyException(policy, checksumsInfo, mutableFile.getRepoPath()); } } private void invokeBeforeCreateInterceptors(MutableVfsFile mutableFile) throws RepoRejectException { if (mutableFile.getInfo().getRepoPath().isRoot()) { return; } BasicStatusHolder statusHolder = new BasicStatusHolder(); StorageInterceptors interceptors = ContextHelper.get().beanForType(StorageInterceptors.class); interceptors.beforeCreate(mutableFile, statusHolder); checkForCancelException(statusHolder); } private void invokeAfterCreateInterceptors(MutableVfsFile mutableFile) throws RepoRejectException { //TODO: [by YS] leave it here until we decide how to implement events if (mutableFile.isNew()) { StorageSession storageSession = StorageSessionHolder.getSession(); if (storageSession != null) { storageSession.save(); } } BasicStatusHolder statusHolder = new BasicStatusHolder(); interceptors.afterCreate(mutableFile, statusHolder); checkForCancelException(statusHolder); } private void checkForCancelException(StatusHolder status) throws RepoRejectException { if (status.getCancelException() != null) { throw status.getCancelException(); } } /** * Return <b>locally</b> stored file resource. Unfound resource will be returned if the requested resource doesn't * exist locally. */ public RepoResource getInfo(InternalRequestContext context) throws FileExpectedException { RestCoreAddon restCoreAddon = addonsManager.addonByType(RestCoreAddon.class); org.artifactory.repo.StoringRepo storingRepo = getOwningRepo(); context = restCoreAddon.getDynamicVersionContext(storingRepo, context, false); String path = context.getResourcePath(); RepoPath repoPath = InternalRepoPathFactory.create(getKey(), path); if (!itemExists(path)) { RepoRequests.logToContext("Unable to find resource in %s", repoPath); return new UnfoundRepoResource(repoPath, "File not found."); } PropertiesAddon propertiesAddon = addonsManager.addonByType(PropertiesAddon.class); if (MavenNaming.isMavenMetadata(path)) { RepoResource mdResource = propertiesAddon.assembleDynamicMetadata(context, repoPath); if ((mdResource instanceof FileResource) && MavenNaming.isSnapshotMavenMetadata(path)) { mdResource = resolveMavenMetadataForCompatibility(((FileResource) mdResource), context); } return mdResource; } //Handle query-aware get Properties properties = repositoryService.getProperties(repoPath); Properties queryProperties = context.getProperties(); boolean exactMatch = true; if (!queryProperties.isEmpty()) { RepoRequests.logToContext("Request includes query properties"); Properties.MatchResult matchResult; if (properties != null) { matchResult = properties.matchQuery(queryProperties); } else { matchResult = Properties.MatchResult.NO_MATCH; } if (matchResult == Properties.MatchResult.NO_MATCH) { exactMatch = false; RepoRequests.logToContext("Request query properties don't match those that annotate the artifact"); } else if (matchResult == Properties.MatchResult.CONFLICT) { RepoRequests.logToContext("Request query properties conflict with those that annotate the " + "artifact - returning unfound resource"); return new UnfoundRepoResource(repoPath, "File '" + repoPath + "' was found, but mandatory properties do not match.", UnfoundRepoResourceReason.Reason.PROPERTY_MISMATCH); } } RepoResource localResource = getFilteredOrFileResource(repoPath, context, properties, exactMatch); setMimeType(localResource, properties); return localResource; } private void setMimeType(RepoResource localResource, Properties properties) { if (!localResource.isFound() || !(localResource instanceof FileResource) || (properties == null)) { return; } String customMimeType = properties.getFirst(CONTENT_TYPE_PROP_KEY); if (StringUtils.isNotBlank(customMimeType)) { ((FileResource) localResource).setMimeType(customMimeType); } } private org.artifactory.repo.StoringRepo getOwningRepo() { return repositoryService.storingRepositoryByKey(descriptor.getKey()); } private RepoResource resolveMavenMetadataForCompatibility(FileResource metadataResource, InternalRequestContext context) { if (ConstantValues.mvnMetadataVersion3Enabled.getBoolean() && !context.clientSupportsM3SnapshotVersions()) { RepoRequests.logToContext("Use of v3 Maven metadata is enabled, but the requesting client doesn't " + "support it - checking if the response should be modified for compatibility"); FileInfo info = metadataResource.getInfo(); try { Metadata metadata = MavenModelUtils.toMavenMetadata(repositoryService.getStringContent(info)); Versioning versioning = metadata.getVersioning(); if (versioning != null) { List<SnapshotVersion> snapshotVersions = versioning.getSnapshotVersions(); if ((snapshotVersions != null) && !snapshotVersions.isEmpty()) { RepoRequests.logToContext("Found snapshot versions - modifying the response for compatibility"); versioning.setSnapshotVersions(null); return new ResolvedResource(metadataResource, MavenModelUtils.mavenMetadataToString(metadata)); } } } catch (IOException e) { RepoPath repoPath = info.getRepoPath(); log.error("An error occurred while filtering Maven metadata '{}' for compatibility: " + "{}\nReturning original content.", repoPath, e.getMessage()); RepoRequests.logToContext("An error occurred while filtering for compatibility. Returning the " + "original content: %s", e.getMessage()); } } //In case none of the above apply, or if we encountered an error, return the original resource return metadataResource; } @Override public boolean hasChildren(VfsFolder vfsFolder) { return fileService.hasChildren(vfsFolder.getRepoPath()); } @Override public List<VfsItem> getImmutableChildren(VfsFolder folder) { List<ItemInfo> childrenInfo = fileService.loadChildren(folder.getRepoPath()); List<VfsItem> mutableChildren = Lists.newArrayListWithCapacity(childrenInfo.size()); for (ItemInfo childInfo : childrenInfo) { mutableChildren.add(getImmutableItem(childInfo.getRepoPath())); } return mutableChildren; } @Override public List<MutableVfsItem> getMutableChildren(MutableVfsFolder folder) { List<ItemInfo> childrenInfo = fileService.loadChildren(folder.getRepoPath()); List<MutableVfsItem> mutableChildren = Lists.newArrayListWithCapacity(childrenInfo.size()); for (ItemInfo childInfo : childrenInfo) { MutableVfsItem mutableItem = getMutableItem(childInfo.getRepoPath()); if (mutableItem != null) { mutableChildren.add(mutableItem); } else { log.debug("Item deleted between first item loading and write lock: {}", childInfo.getRepoPath()); } } return mutableChildren; } @Override public boolean itemExists(String relativePath) { return fileService.exists(new RepoPathImpl(getKey(), relativePath)); } private RepoResource getFilteredOrFileResource(RepoPath repoPath, RequestContext context, Properties properties, boolean exactMatch) { VfsFile vfsFile = getImmutableFile(repoPath); if (vfsFile == null) { return new UnfoundRepoResource(repoPath, "File " + repoPath + " was deleting during download!"); } Request request = context.getRequest(); if (request != null && descriptor.isReal()) { FilteredResourcesAddon filteredResourcesAddon = addonsManager.addonByType(FilteredResourcesAddon.class); if (filteredResourcesAddon.isFilteredResourceFile(repoPath, properties)) { RepoRequests.logToContext("Resource is marked as filtered - sending it through the engine"); InputStream stream = vfsFile.getStream(); try { return filteredResourcesAddon.getFilteredResource(request, vfsFile.getInfo(), stream); } finally { IOUtils.closeQuietly(stream); } } } if (request != null && request.isZipResourceRequest()) { RepoRequests.logToContext("Resource is contained within an archiving - retrieving"); InputStream stream = vfsFile.getStream(); try { return addonsManager.addonByType(FilteredResourcesAddon.class).getZipResource( request, vfsFile.getInfo(), stream); } finally { IOUtils.closeQuietly(stream); } } return new FileResource(vfsFile.getInfo(), exactMatch); } public T getDescriptor() { return descriptor; } private void overrideFileDetailsFromRequest(SaveResourceContext context, MutableVfsFile mutableFile) { // Only administrators can override the core attributed of a file. This is mainly used during replication // This is not open to non-admin to prevent faked data (e.g., createdBy) if (!authorizationService.isAdmin()) { return; } if (context.getCreated() > 0) { mutableFile.setCreated(context.getCreated()); } if (StringUtils.isNotBlank(context.getCreateBy())) { mutableFile.setCreatedBy(context.getCreateBy()); } if (StringUtils.isNotBlank(context.getModifiedBy())) { mutableFile.setModifiedBy(context.getModifiedBy()); } } private void setClientChecksums(RepoResource res, MutableVfsFile mutableFile) { // set the file extension checksums (only needed if the file is currently being downloaded) ChecksumsInfo resourceChecksums = res.getInfo().getChecksumsInfo(); ChecksumInfo sha1Info = resourceChecksums.getChecksumInfo(ChecksumType.sha1); mutableFile.setClientSha1(sha1Info != null ? sha1Info.getOriginalOrNoOrig() : null); ChecksumInfo md5Info = resourceChecksums.getChecksumInfo(ChecksumType.md5); mutableFile.setClientMd5(md5Info != null ? md5Info.getOriginalOrNoOrig() : null); } private void updateResourceWithActualBinaryData(RepoResource res, VfsFile vfsFile) { // update the resource with actual checksums and size (calculated in fillBinaryData) - RTFACT-3112 if (res.getInfo() instanceof MutableRepoResourceInfo) { ChecksumsInfo newlyCalculatedChecksums = vfsFile.getInfo().getChecksumsInfo(); MutableRepoResourceInfo info = (MutableRepoResourceInfo) res.getInfo(); info.setChecksums(newlyCalculatedChecksums.getChecksums()); info.setSize(vfsFile.length()); } } private void clearOldFileData(MutableVfsFile mutableFile, boolean isNonUniqueSnapshot, String oldFileSha1) { // If the artifact is not a non-unique snapshot and already exists but with a different checksum, remove // all the existing metadata if (!isNonUniqueSnapshot && oldFileSha1 != null) { if (!oldFileSha1.equals(mutableFile.getSha1())) { mutableFile.setStats(new StatsImpl()); mutableFile.setProperties(new PropertiesImpl()); } } } MutableVfsItem getMutableItem(RepoPath repoPath) { VfsItemProvider provider = vfsItemProviderFactory.createItemProvider(this, repoPath, fsItemsVault); return provider.getMutableFsItem(); } VfsItem getImmutableItem(RepoPath repoPath) { VfsItemProvider provider = vfsItemProviderFactory.createItemProvider(this, repoPath, fsItemsVault); return provider.getImmutableFsItem(); } public VfsFile getImmutableFile(RepoPath repoPath) { VfsFileProvider provider = vfsItemProviderFactory.createFileProvider(this, repoPath, fsItemsVault); return provider.getImmutableFile(); } public MutableVfsFile getMutableFile(RepoPath repoPath) { VfsFileProvider provider = vfsItemProviderFactory.createFileProvider(this, repoPath, fsItemsVault); return provider.getMutableFile(); } public MutableVfsFile createOrGetFile(RepoPath repoPath) { VfsFileProvider provider = vfsItemProviderFactory.createFileProvider(this, repoPath, fsItemsVault); return provider.getOrCreMutableFile(); } @Override public VfsFolder getImmutableFolder(RepoPath repoPath) { VfsFolderProvider provider = vfsItemProviderFactory.createFolderProvider(this, repoPath, fsItemsVault); return provider.getImmutableFolder(); } public MutableVfsFolder getMutableFolder(RepoPath repoPath) { VfsFolderProvider provider = vfsItemProviderFactory.createFolderProvider(this, repoPath, fsItemsVault); return provider.getMutableFolder(); } public MutableVfsFolder createOrGetFolder(RepoPath repoPath) { VfsFolderProvider provider = vfsItemProviderFactory.createFolderProvider(this, repoPath, fsItemsVault); return provider.getOrCreMutableFolder(); } @Override public String getKey() { return descriptor.getKey(); } @Override public boolean isWriteLocked(RepoPath repoPath) { // TODO: [by FSI] Invalid argument if not me repo key LockEntryId lock = fsItemsVault.getLock(repoPath); return lock.getLock().isLocked(); } public void undeploy(RepoPath repoPath, boolean calcMavenMetadata) { MutableVfsItem item = getMutableItem(repoPath); if (item == null || item.isMarkedForDeletion()) { return; } item.delete(); //TODO: [by YS] why don't we use the interceptor?? the async here is a big waste if (calcMavenMetadata) { // calculate maven metadata on the parent path RepoPath folderForMetadataCalculation = repoPath.getParent(); if (folderForMetadataCalculation != null && !folderForMetadataCalculation.isRoot()) { if (item.isFile()) { // calculate maven metadata on the artifactId node folderForMetadataCalculation = folderForMetadataCalculation.getParent(); } mavenMetadataService.calculateMavenMetadataAsync(folderForMetadataCalculation, true); } } } public ResourceStreamHandle getResourceStreamHandle(RequestContext requestContext, RepoResource res) throws IOException { RepoPathImpl repoPath = new RepoPathImpl(getKey(), res.getRepoPath().getPath()); RepoRequests.logToContext("Creating a resource handle from '%s'", repoPath); VfsFile file = getImmutableFile(repoPath); // If resource does not exist throw an IOException if (file == null) { RepoRequests.logToContext("Unable to find the resource - throwing exception"); throw new FileNotFoundException( "Could not get resource stream. Path '" + repoPath.getPath() + "' not found in " + this); } RepoRequests.logToContext("Identified requested resource as a file"); ResourceStreamHandle handle; Request request = requestContext.getRequest(); if (request != null && request.isZipResourceRequest() && (res instanceof ZipEntryRepoResource)) { RepoRequests.logToContext("Requested resource is contained within an archive - " + "using specialized handle"); handle = addonsManager.addonByType(FilteredResourcesAddon.class).getZipResourceHandle(res, file.getStream()); } else { RepoRequests.logToContext("Requested resource is an ordinary artifact - " + "using normal content handle with length '%s'", file.length()); handle = new SimpleResourceStreamHandle(file.getStream(), file.length()); } updateDownloadStats(file); return handle; } private void updateDownloadStats(VfsFile file) { if (descriptor.isReal() && ConstantValues.downloadStatsEnabled.getBoolean()) { // stats only for real repos, if enabled statsService.fileDownloaded(file.getRepoPath(), authorizationService.currentUsername(), System.currentTimeMillis()); } } public boolean shouldProtectPathDeletion(PathDeletionContext pathDeletionContext) { String path = pathDeletionContext.getPath(); if (NamingUtils.isChecksum(path)) { //Never protect checksums return false; } if (pathDeletionContext.isAssertOverwrite()) { if (MavenNaming.isMavenMetadata(path)) { return false; } org.artifactory.repo.StoringRepo owningRepo = getOwningRepo(); if (owningRepo.isCache()) { if (pathDeletionContext.isForceExpiryCheck()) { return false; } if ((ContextHelper.get().beanForType(CacheExpiry.class).isExpirable( ((LocalCacheRepo) owningRepo), path))) { return false; } } else { if (ContextHelper.get().beanForType(LocalNonCacheOverridable.class) .isOverridable(((LocalRepo) owningRepo), path)) { return false; } } return shouldProtectPathDeletion(path, pathDeletionContext.getRequestSha1()); } return true; } /** * Should protect path deletion for these conditions: * - If the item is a file (means that is also exists), protect. * - If this is a deploy with checksum, and the request checksum matches the repoPath one, don't protect. * - If the item is not a file (it's either a folder or doesn't exist), don't protect. */ protected boolean shouldProtectPathDeletion(String path, @Nullable String requestSha1) { RepoPath repoPath = InternalRepoPathFactory.create(getKey(), path); if (requestSha1 == null) { return repositoryService.exists(repoPath); } else { try { String existingSha1 = repositoryService.getFileInfo(repoPath).getSha1(); return !existingSha1.equals(requestSha1); //protect if requestSha1 not equal to existing one } catch (ItemNotFoundRuntimeException e) { return false; } } } }
apache-2.0
googleapis/java-billingbudgets
proto-google-cloud-billingbudgets-v1/src/main/java/com/google/cloud/billing/budgets/v1/CustomPeriodOrBuilder.java
2941
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/billing/budgets/v1/budget_model.proto package com.google.cloud.billing.budgets.v1; public interface CustomPeriodOrBuilder extends // @@protoc_insertion_point(interface_extends:google.cloud.billing.budgets.v1.CustomPeriod) com.google.protobuf.MessageOrBuilder { /** * * * <pre> * Required. The start date must be after January 1, 2017. * </pre> * * <code>.google.type.Date start_date = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return Whether the startDate field is set. */ boolean hasStartDate(); /** * * * <pre> * Required. The start date must be after January 1, 2017. * </pre> * * <code>.google.type.Date start_date = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The startDate. */ com.google.type.Date getStartDate(); /** * * * <pre> * Required. The start date must be after January 1, 2017. * </pre> * * <code>.google.type.Date start_date = 1 [(.google.api.field_behavior) = REQUIRED];</code> */ com.google.type.DateOrBuilder getStartDateOrBuilder(); /** * * * <pre> * Optional. The end date of the time period. Budgets with elapsed end date * won't be processed. If unset, specifies to track all usage incurred since * the start_date. * </pre> * * <code>.google.type.Date end_date = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return Whether the endDate field is set. */ boolean hasEndDate(); /** * * * <pre> * Optional. The end date of the time period. Budgets with elapsed end date * won't be processed. If unset, specifies to track all usage incurred since * the start_date. * </pre> * * <code>.google.type.Date end_date = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The endDate. */ com.google.type.Date getEndDate(); /** * * * <pre> * Optional. The end date of the time period. Budgets with elapsed end date * won't be processed. If unset, specifies to track all usage incurred since * the start_date. * </pre> * * <code>.google.type.Date end_date = 2 [(.google.api.field_behavior) = OPTIONAL];</code> */ com.google.type.DateOrBuilder getEndDateOrBuilder(); }
apache-2.0
wanliwang/cayman
cm-idea/src/main/java/com/bjorktech/cayman/idea/designpattern/create/factorymethod/CustomBean.java
356
package com.bjorktech.cayman.idea.designpattern.create.factorymethod; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * User: sheshan * Date: 04/07/2018 * content: */ @Data @NoArgsConstructor @AllArgsConstructor public class CustomBean extends AbstractBean { private String name; private int age; }
apache-2.0
oehme/analysing-gradle-performance
my-app/src/main/java/org/gradle/test/performance/mediummonolithicjavaproject/p452/Production9041.java
1891
package org.gradle.test.performance.mediummonolithicjavaproject.p452; public class Production9041 { private String property0; public String getProperty0() { return property0; } public void setProperty0(String value) { property0 = value; } private String property1; public String getProperty1() { return property1; } public void setProperty1(String value) { property1 = value; } private String property2; public String getProperty2() { return property2; } public void setProperty2(String value) { property2 = value; } private String property3; public String getProperty3() { return property3; } public void setProperty3(String value) { property3 = value; } private String property4; public String getProperty4() { return property4; } public void setProperty4(String value) { property4 = value; } private String property5; public String getProperty5() { return property5; } public void setProperty5(String value) { property5 = value; } private String property6; public String getProperty6() { return property6; } public void setProperty6(String value) { property6 = value; } private String property7; public String getProperty7() { return property7; } public void setProperty7(String value) { property7 = value; } private String property8; public String getProperty8() { return property8; } public void setProperty8(String value) { property8 = value; } private String property9; public String getProperty9() { return property9; } public void setProperty9(String value) { property9 = value; } }
apache-2.0
oehme/analysing-gradle-performance
my-app/src/test/java/org/gradle/test/performance/mediummonolithicjavaproject/p55/Test1103.java
2110
package org.gradle.test.performance.mediummonolithicjavaproject.p55; import org.junit.Test; import static org.junit.Assert.*; public class Test1103 { Production1103 objectUnderTest = new Production1103(); @Test public void testProperty0() { String value = "value"; objectUnderTest.setProperty0(value); assertEquals(value, objectUnderTest.getProperty0()); } @Test public void testProperty1() { String value = "value"; objectUnderTest.setProperty1(value); assertEquals(value, objectUnderTest.getProperty1()); } @Test public void testProperty2() { String value = "value"; objectUnderTest.setProperty2(value); assertEquals(value, objectUnderTest.getProperty2()); } @Test public void testProperty3() { String value = "value"; objectUnderTest.setProperty3(value); assertEquals(value, objectUnderTest.getProperty3()); } @Test public void testProperty4() { String value = "value"; objectUnderTest.setProperty4(value); assertEquals(value, objectUnderTest.getProperty4()); } @Test public void testProperty5() { String value = "value"; objectUnderTest.setProperty5(value); assertEquals(value, objectUnderTest.getProperty5()); } @Test public void testProperty6() { String value = "value"; objectUnderTest.setProperty6(value); assertEquals(value, objectUnderTest.getProperty6()); } @Test public void testProperty7() { String value = "value"; objectUnderTest.setProperty7(value); assertEquals(value, objectUnderTest.getProperty7()); } @Test public void testProperty8() { String value = "value"; objectUnderTest.setProperty8(value); assertEquals(value, objectUnderTest.getProperty8()); } @Test public void testProperty9() { String value = "value"; objectUnderTest.setProperty9(value); assertEquals(value, objectUnderTest.getProperty9()); } }
apache-2.0
viant/CacheStore
client/src/main/java/com/sm/store/client/TCPClientFactory.java
3058
/* * * * Copyright 2012-2015 Viant. * * * * 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.sm.store.client; import com.sm.localstore.impl.HessianSerializer; import com.sm.storage.Serializer; import com.sm.store.client.grizzly.ClusterClientFilter; import com.sm.store.client.netty.ClusterClientHandler; import com.sm.store.cluster.Connection; import com.sm.transport.Client; import com.sm.transport.grizzly.codec.RequestCodecFilter; import org.glassfish.grizzly.filterchain.BaseFilter; public class TCPClientFactory { public static enum ClientType { Netty ((byte) 1), Grizzly ((byte) 2) ; final byte value; ClientType(byte value) { this.value = value; } public static ClientType getClientType(byte value) { switch ( value ) { case 0 : return Netty; case 1 : return Netty; case 2 : return Grizzly; default: return Netty; } } } public static final Serializer EmbeddedSerializer = new HessianSerializer(); public static Client createClient(ClientType clientType, String url, long timeout) { String[] strs = url.split(":"); if ( strs.length != 2 ) throw new RuntimeException("malform url "+url); if ( clientType == ClientType.Netty ) { ClusterClientHandler handler = new ClusterClientHandler(timeout, EmbeddedSerializer); return com.sm.transport.netty.TCPClient.start(strs[0], Integer.valueOf(strs[1]), handler, (byte) 1); } else { BaseFilter requestCodecFilter = new RequestCodecFilter( (byte) 1); return com.sm.transport.grizzly.TCPClient.start(strs[0], Integer.valueOf(strs[1]), requestCodecFilter, new ClusterClientFilter(timeout) ); } } public static Client createClient(ClientType clientType, Connection connection, long timeout) { if ( clientType == ClientType.Netty ) { ClusterClientHandler handler = new ClusterClientHandler(timeout, EmbeddedSerializer); return com.sm.transport.netty.TCPClient.start(connection.getHost(), connection.getPort(), handler, (byte) 1); } else { BaseFilter requestCodecFilter = new RequestCodecFilter( (byte) 1); return com.sm.transport.grizzly.TCPClient.start(connection.getHost(), connection.getPort(), requestCodecFilter, new ClusterClientFilter(timeout) ); } } }
apache-2.0
mpi2/PhenotypeData
register-interest/src/main/java/org/mousephenotype/cda/ri/entities/ContactGene.java
2149
/******************************************************************************* * Copyright © 2017 EMBL - European Bioinformatics Institute * * Licensed under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the * License. ******************************************************************************/ package org.mousephenotype.cda.ri.entities; import java.util.Date; /** * Created by mrelac on 12/05/2017. * This entity class maps to the contact_gene table. */ public class ContactGene { private int pk; private int contactPk; private String geneAccessionId; private Date createdAt; private Date updatedAt; public String buildContactGeneKey() { return contactPk + "_" + geneAccessionId; } public static String buildContactGeneKey(int contactPk, String geneAccessionId) { return contactPk + "_" + geneAccessionId; } public int getPk() { return pk; } public void setPk(int pk) { this.pk = pk; } public int getContactPk() { return contactPk; } public void setContactPk(int contactPk) { this.contactPk = contactPk; } public String getGeneAccessionId() { return geneAccessionId; } public void setGeneAccessionId(String geneAccessionId) { this.geneAccessionId = geneAccessionId; } public Date getCreatedAt() { return createdAt; } public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; } public Date getUpdatedAt() { return updatedAt; } public void setUpdatedAt(Date updatedAt) { this.updatedAt = updatedAt; } }
apache-2.0
bonprix/vaadin-grid-enhancements
GridEnhancements/src/main/java/org/vaadin/grid/enhancements/client/navigation/BodyNaviagtionHandler.java
2334
package org.vaadin.grid.enhancements.client.navigation; import com.google.gwt.core.client.Scheduler; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.Node; import com.google.gwt.dom.client.NodeList; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.user.client.Command; import com.vaadin.client.WidgetUtil; import com.vaadin.client.widget.grid.CellReference; import com.vaadin.client.widget.grid.events.BodyKeyDownHandler; import com.vaadin.client.widget.grid.events.GridKeyDownEvent; public class BodyNaviagtionHandler implements BodyKeyDownHandler { @Override public void onKeyDown(GridKeyDownEvent event) { switch (event.getNativeKeyCode()) { case KeyCodes.KEY_ENTER: if (isCellContainingComponent(event.getFocusedCell())) { // Don't propagate enter to component event.preventDefault(); event.stopPropagation(); final Element componentElement = extractComponentElement(event.getFocusedCell()); // Run focus as deferred command so the Navigation handler // doesn't catch the event. Scheduler .get() .scheduleDeferred(new Command() { @Override public void execute() { WidgetUtil.focus(componentElement); NavigationUtil.focusInputField(componentElement); } }); } break; } } private Element extractComponentElement(CellReference cell) { // Only check recursively if we are looking at a table if (cell.getElement() .getNodeName() .equals("TD")) { return NavigationUtil.getInputElement(cell .getElement() .getChildNodes()); } return null; } private boolean isCellContainingComponent(CellReference cell) { // Only check recursively if we are looking at a table if (cell.getElement() .getNodeName() .equals("TD")) { return containsInput(cell .getElement() .getChildNodes()); } return false; } private boolean containsInput(NodeList<Node> nodes) { for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.getItem(i); if (node.getNodeName() .equals("INPUT") || node .getNodeName() .equals("BUTTON")) { return true; } else if (node .getChildNodes() .getLength() > 0) { if (containsInput(node.getChildNodes())) { return true; } } } return false; } }
apache-2.0
googleapis/google-api-java-client-services
clients/google-api-services-dialogflow/v3/1.31.0/com/google/api/services/dialogflow/v3/model/GoogleCloudDialogflowCxV3beta1EnvironmentVersionConfig.java
2408
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.dialogflow.v3.model; /** * Configuration for the version. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Dialogflow API. For a detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class GoogleCloudDialogflowCxV3beta1EnvironmentVersionConfig extends com.google.api.client.json.GenericJson { /** * Required. Format: projects//locations//agents//flows//versions/. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String version; /** * Required. Format: projects//locations//agents//flows//versions/. * @return value or {@code null} for none */ public java.lang.String getVersion() { return version; } /** * Required. Format: projects//locations//agents//flows//versions/. * @param version version or {@code null} for none */ public GoogleCloudDialogflowCxV3beta1EnvironmentVersionConfig setVersion(java.lang.String version) { this.version = version; return this; } @Override public GoogleCloudDialogflowCxV3beta1EnvironmentVersionConfig set(String fieldName, Object value) { return (GoogleCloudDialogflowCxV3beta1EnvironmentVersionConfig) super.set(fieldName, value); } @Override public GoogleCloudDialogflowCxV3beta1EnvironmentVersionConfig clone() { return (GoogleCloudDialogflowCxV3beta1EnvironmentVersionConfig) super.clone(); } }
apache-2.0
virtualdataset/metagen-java
virtdata-lib-curves4/src/main/java/org/apache/commons/math4/linear/SingularValueDecomposition.java
28974
/* * 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.commons.math4.linear; import org.apache.commons.math4.exception.NumberIsTooLargeException; import org.apache.commons.math4.exception.util.LocalizedFormats; import org.apache.commons.math4.util.FastMath; import org.apache.commons.numbers.core.Precision; /** * Calculates the compact Singular Value Decomposition of a matrix. * <p> * The Singular Value Decomposition of matrix A is a set of three matrices: U, * &Sigma; and V such that A = U &times; &Sigma; &times; V<sup>T</sup>. Let A be * a m &times; n matrix, then U is a m &times; p orthogonal matrix, &Sigma; is a * p &times; p diagonal matrix with positive or null elements, V is a p &times; * n orthogonal matrix (hence V<sup>T</sup> is also orthogonal) where * p=min(m,n). * </p> * <p>This class is similar to the class with similar name from the * <a href="http://math.nist.gov/javanumerics/jama/">JAMA</a> library, with the * following changes:</p> * <ul> * <li>the {@code norm2} method which has been renamed as {@link #getNorm() * getNorm},</li> * <li>the {@code cond} method which has been renamed as {@link * #getConditionNumber() getConditionNumber},</li> * <li>the {@code rank} method which has been renamed as {@link #getRank() * getRank},</li> * <li>a {@link #getUT() getUT} method has been added,</li> * <li>a {@link #getVT() getVT} method has been added,</li> * <li>a {@link #getSolver() getSolver} method has been added,</li> * <li>a {@link #getCovariance(double) getCovariance} method has been added.</li> * </ul> * @see <a href="http://mathworld.wolfram.com/SingularValueDecomposition.html">MathWorld</a> * @see <a href="http://en.wikipedia.org/wiki/Singular_value_decomposition">Wikipedia</a> * @since 2.0 (changed to concrete class in 3.0) */ public class SingularValueDecomposition { /** Relative threshold for small singular values. */ private static final double EPS = 0x1.0p-52; /** Absolute threshold for small singular values. */ private static final double TINY = 0x1.0p-966; /** Computed singular values. */ private final double[] singularValues; /** max(row dimension, column dimension). */ private final int m; /** min(row dimension, column dimension). */ private final int n; /** Indicator for transposed matrix. */ private final boolean transposed; /** Cached value of U matrix. */ private final RealMatrix cachedU; /** Cached value of transposed U matrix. */ private RealMatrix cachedUt; /** Cached value of S (diagonal) matrix. */ private RealMatrix cachedS; /** Cached value of V matrix. */ private final RealMatrix cachedV; /** Cached value of transposed V matrix. */ private RealMatrix cachedVt; /** * Tolerance value for small singular values, calculated once we have * populated "singularValues". **/ private final double tol; /** * Calculates the compact Singular Value Decomposition of the given matrix. * * @param matrix Matrix to decompose. */ public SingularValueDecomposition(final RealMatrix matrix) { final double[][] A; // "m" is always the largest dimension. if (matrix.getRowDimension() < matrix.getColumnDimension()) { transposed = true; A = matrix.transpose().getData(); m = matrix.getColumnDimension(); n = matrix.getRowDimension(); } else { transposed = false; A = matrix.getData(); m = matrix.getRowDimension(); n = matrix.getColumnDimension(); } singularValues = new double[n]; final double[][] U = new double[m][n]; final double[][] V = new double[n][n]; final double[] e = new double[n]; final double[] work = new double[m]; // Reduce A to bidiagonal form, storing the diagonal elements // in s and the super-diagonal elements in e. final int nct = FastMath.min(m - 1, n); final int nrt = FastMath.max(0, n - 2); for (int k = 0; k < FastMath.max(nct, nrt); k++) { if (k < nct) { // Compute the transformation for the k-th column and // place the k-th diagonal in s[k]. // Compute 2-norm of k-th column without under/overflow. singularValues[k] = 0; for (int i = k; i < m; i++) { singularValues[k] = FastMath.hypot(singularValues[k], A[i][k]); } if (singularValues[k] != 0) { if (A[k][k] < 0) { singularValues[k] = -singularValues[k]; } for (int i = k; i < m; i++) { A[i][k] /= singularValues[k]; } A[k][k] += 1; } singularValues[k] = -singularValues[k]; } for (int j = k + 1; j < n; j++) { if (k < nct && singularValues[k] != 0) { // Apply the transformation. double t = 0; for (int i = k; i < m; i++) { t += A[i][k] * A[i][j]; } t = -t / A[k][k]; for (int i = k; i < m; i++) { A[i][j] += t * A[i][k]; } } // Place the k-th row of A into e for the // subsequent calculation of the row transformation. e[j] = A[k][j]; } if (k < nct) { // Place the transformation in U for subsequent back // multiplication. for (int i = k; i < m; i++) { U[i][k] = A[i][k]; } } if (k < nrt) { // Compute the k-th row transformation and place the // k-th super-diagonal in e[k]. // Compute 2-norm without under/overflow. e[k] = 0; for (int i = k + 1; i < n; i++) { e[k] = FastMath.hypot(e[k], e[i]); } if (e[k] != 0) { if (e[k + 1] < 0) { e[k] = -e[k]; } for (int i = k + 1; i < n; i++) { e[i] /= e[k]; } e[k + 1] += 1; } e[k] = -e[k]; if (k + 1 < m && e[k] != 0) { // Apply the transformation. for (int i = k + 1; i < m; i++) { work[i] = 0; } for (int j = k + 1; j < n; j++) { for (int i = k + 1; i < m; i++) { work[i] += e[j] * A[i][j]; } } for (int j = k + 1; j < n; j++) { final double t = -e[j] / e[k + 1]; for (int i = k + 1; i < m; i++) { A[i][j] += t * work[i]; } } } // Place the transformation in V for subsequent // back multiplication. for (int i = k + 1; i < n; i++) { V[i][k] = e[i]; } } } // Set up the final bidiagonal matrix or order p. int p = n; if (nct < n) { singularValues[nct] = A[nct][nct]; } if (m < p) { singularValues[p - 1] = 0; } if (nrt + 1 < p) { e[nrt] = A[nrt][p - 1]; } e[p - 1] = 0; // Generate U. for (int j = nct; j < n; j++) { for (int i = 0; i < m; i++) { U[i][j] = 0; } U[j][j] = 1; } for (int k = nct - 1; k >= 0; k--) { if (singularValues[k] != 0) { for (int j = k + 1; j < n; j++) { double t = 0; for (int i = k; i < m; i++) { t += U[i][k] * U[i][j]; } t = -t / U[k][k]; for (int i = k; i < m; i++) { U[i][j] += t * U[i][k]; } } for (int i = k; i < m; i++) { U[i][k] = -U[i][k]; } U[k][k] = 1 + U[k][k]; for (int i = 0; i < k - 1; i++) { U[i][k] = 0; } } else { for (int i = 0; i < m; i++) { U[i][k] = 0; } U[k][k] = 1; } } // Generate V. for (int k = n - 1; k >= 0; k--) { if (k < nrt && e[k] != 0) { for (int j = k + 1; j < n; j++) { double t = 0; for (int i = k + 1; i < n; i++) { t += V[i][k] * V[i][j]; } t = -t / V[k + 1][k]; for (int i = k + 1; i < n; i++) { V[i][j] += t * V[i][k]; } } } for (int i = 0; i < n; i++) { V[i][k] = 0; } V[k][k] = 1; } // Main iteration loop for the singular values. final int pp = p - 1; while (p > 0) { int k; int kase; // Here is where a test for too many iterations would go. // This section of the program inspects for // negligible elements in the s and e arrays. On // completion the variables kase and k are set as follows. // kase = 1 if s(p) and e[k-1] are negligible and k<p // kase = 2 if s(k) is negligible and k<p // kase = 3 if e[k-1] is negligible, k<p, and // s(k), ..., s(p) are not negligible (qr step). // kase = 4 if e(p-1) is negligible (convergence). for (k = p - 2; k >= 0; k--) { final double threshold = TINY + EPS * (FastMath.abs(singularValues[k]) + FastMath.abs(singularValues[k + 1])); // the following condition is written this way in order // to break out of the loop when NaN occurs, writing it // as "if (FastMath.abs(e[k]) <= threshold)" would loop // indefinitely in case of NaNs because comparison on NaNs // always return false, regardless of what is checked // see issue MATH-947 if (!(FastMath.abs(e[k]) > threshold)) { e[k] = 0; break; } } if (k == p - 2) { kase = 4; } else { int ks; for (ks = p - 1; ks >= k; ks--) { if (ks == k) { break; } final double t = (ks != p ? FastMath.abs(e[ks]) : 0) + (ks != k + 1 ? FastMath.abs(e[ks - 1]) : 0); if (FastMath.abs(singularValues[ks]) <= TINY + EPS * t) { singularValues[ks] = 0; break; } } if (ks == k) { kase = 3; } else if (ks == p - 1) { kase = 1; } else { kase = 2; k = ks; } } k++; // Perform the task indicated by kase. switch (kase) { // Deflate negligible s(p). case 1: { double f = e[p - 2]; e[p - 2] = 0; for (int j = p - 2; j >= k; j--) { double t = FastMath.hypot(singularValues[j], f); final double cs = singularValues[j] / t; final double sn = f / t; singularValues[j] = t; if (j != k) { f = -sn * e[j - 1]; e[j - 1] = cs * e[j - 1]; } for (int i = 0; i < n; i++) { t = cs * V[i][j] + sn * V[i][p - 1]; V[i][p - 1] = -sn * V[i][j] + cs * V[i][p - 1]; V[i][j] = t; } } } break; // Split at negligible s(k). case 2: { double f = e[k - 1]; e[k - 1] = 0; for (int j = k; j < p; j++) { double t = FastMath.hypot(singularValues[j], f); final double cs = singularValues[j] / t; final double sn = f / t; singularValues[j] = t; f = -sn * e[j]; e[j] = cs * e[j]; for (int i = 0; i < m; i++) { t = cs * U[i][j] + sn * U[i][k - 1]; U[i][k - 1] = -sn * U[i][j] + cs * U[i][k - 1]; U[i][j] = t; } } } break; // Perform one qr step. case 3: { // Calculate the shift. final double maxPm1Pm2 = FastMath.max(FastMath.abs(singularValues[p - 1]), FastMath.abs(singularValues[p - 2])); final double scale = FastMath.max(FastMath.max(FastMath.max(maxPm1Pm2, FastMath.abs(e[p - 2])), FastMath.abs(singularValues[k])), FastMath.abs(e[k])); final double sp = singularValues[p - 1] / scale; final double spm1 = singularValues[p - 2] / scale; final double epm1 = e[p - 2] / scale; final double sk = singularValues[k] / scale; final double ek = e[k] / scale; final double b = ((spm1 + sp) * (spm1 - sp) + epm1 * epm1) / 2.0; final double c = (sp * epm1) * (sp * epm1); double shift = 0; if (b != 0 || c != 0) { shift = FastMath.sqrt(b * b + c); if (b < 0) { shift = -shift; } shift = c / (b + shift); } double f = (sk + sp) * (sk - sp) + shift; double g = sk * ek; // Chase zeros. for (int j = k; j < p - 1; j++) { double t = FastMath.hypot(f, g); double cs = f / t; double sn = g / t; if (j != k) { e[j - 1] = t; } f = cs * singularValues[j] + sn * e[j]; e[j] = cs * e[j] - sn * singularValues[j]; g = sn * singularValues[j + 1]; singularValues[j + 1] = cs * singularValues[j + 1]; for (int i = 0; i < n; i++) { t = cs * V[i][j] + sn * V[i][j + 1]; V[i][j + 1] = -sn * V[i][j] + cs * V[i][j + 1]; V[i][j] = t; } t = FastMath.hypot(f, g); cs = f / t; sn = g / t; singularValues[j] = t; f = cs * e[j] + sn * singularValues[j + 1]; singularValues[j + 1] = -sn * e[j] + cs * singularValues[j + 1]; g = sn * e[j + 1]; e[j + 1] = cs * e[j + 1]; if (j < m - 1) { for (int i = 0; i < m; i++) { t = cs * U[i][j] + sn * U[i][j + 1]; U[i][j + 1] = -sn * U[i][j] + cs * U[i][j + 1]; U[i][j] = t; } } } e[p - 2] = f; } break; // Convergence. default: { // Make the singular values positive. if (singularValues[k] <= 0) { singularValues[k] = singularValues[k] < 0 ? -singularValues[k] : 0; for (int i = 0; i <= pp; i++) { V[i][k] = -V[i][k]; } } // Order the singular values. while (k < pp) { if (singularValues[k] >= singularValues[k + 1]) { break; } double t = singularValues[k]; singularValues[k] = singularValues[k + 1]; singularValues[k + 1] = t; if (k < n - 1) { for (int i = 0; i < n; i++) { t = V[i][k + 1]; V[i][k + 1] = V[i][k]; V[i][k] = t; } } if (k < m - 1) { for (int i = 0; i < m; i++) { t = U[i][k + 1]; U[i][k + 1] = U[i][k]; U[i][k] = t; } } k++; } p--; } break; } } // Set the small value tolerance used to calculate rank and pseudo-inverse tol = FastMath.max(m * singularValues[0] * EPS, FastMath.sqrt(Precision.SAFE_MIN)); if (!transposed) { cachedU = MatrixUtils.createRealMatrix(U); cachedV = MatrixUtils.createRealMatrix(V); } else { cachedU = MatrixUtils.createRealMatrix(V); cachedV = MatrixUtils.createRealMatrix(U); } } /** * Returns the matrix U of the decomposition. * <p>U is an orthogonal matrix, i.e. its transpose is also its inverse.</p> * @return the U matrix * @see #getUT() */ public RealMatrix getU() { // return the cached matrix return cachedU; } /** * Returns the transpose of the matrix U of the decomposition. * <p>U is an orthogonal matrix, i.e. its transpose is also its inverse.</p> * @return the U matrix (or null if decomposed matrix is singular) * @see #getU() */ public RealMatrix getUT() { if (cachedUt == null) { cachedUt = getU().transpose(); } // return the cached matrix return cachedUt; } /** * Returns the diagonal matrix &Sigma; of the decomposition. * <p>&Sigma; is a diagonal matrix. The singular values are provided in * non-increasing order, for compatibility with Jama.</p> * @return the &Sigma; matrix */ public RealMatrix getS() { if (cachedS == null) { // cache the matrix for subsequent calls cachedS = MatrixUtils.createRealDiagonalMatrix(singularValues); } return cachedS; } /** * Returns the diagonal elements of the matrix &Sigma; of the decomposition. * <p>The singular values are provided in non-increasing order, for * compatibility with Jama.</p> * @return the diagonal elements of the &Sigma; matrix */ public double[] getSingularValues() { return singularValues.clone(); } /** * Returns the matrix V of the decomposition. * <p>V is an orthogonal matrix, i.e. its transpose is also its inverse.</p> * @return the V matrix (or null if decomposed matrix is singular) * @see #getVT() */ public RealMatrix getV() { // return the cached matrix return cachedV; } /** * Returns the transpose of the matrix V of the decomposition. * <p>V is an orthogonal matrix, i.e. its transpose is also its inverse.</p> * @return the V matrix (or null if decomposed matrix is singular) * @see #getV() */ public RealMatrix getVT() { if (cachedVt == null) { cachedVt = getV().transpose(); } // return the cached matrix return cachedVt; } /** * Returns the n &times; n covariance matrix. * <p>The covariance matrix is V &times; J &times; V<sup>T</sup> * where J is the diagonal matrix of the inverse of the squares of * the singular values.</p> * @param minSingularValue value below which singular values are ignored * (a 0 or negative value implies all singular value will be used) * @return covariance matrix * @exception IllegalArgumentException if minSingularValue is larger than * the largest singular value, meaning all singular values are ignored */ public RealMatrix getCovariance(final double minSingularValue) { // get the number of singular values to consider final int p = singularValues.length; int dimension = 0; while (dimension < p && singularValues[dimension] >= minSingularValue) { ++dimension; } if (dimension == 0) { throw new NumberIsTooLargeException(LocalizedFormats.TOO_LARGE_CUTOFF_SINGULAR_VALUE, minSingularValue, singularValues[0], true); } final double[][] data = new double[dimension][p]; getVT().walkInOptimizedOrder(new DefaultRealMatrixPreservingVisitor() { /** {@inheritDoc} */ @Override public void visit(final int row, final int column, final double value) { data[row][column] = value / singularValues[row]; } }, 0, dimension - 1, 0, p - 1); RealMatrix jv = new Array2DRowRealMatrix(data, false); return jv.transpose().multiply(jv); } /** * Returns the L<sub>2</sub> norm of the matrix. * <p>The L<sub>2</sub> norm is max(|A &times; u|<sub>2</sub> / * |u|<sub>2</sub>), where |.|<sub>2</sub> denotes the vectorial 2-norm * (i.e. the traditional euclidian norm).</p> * @return norm */ public double getNorm() { return singularValues[0]; } /** * Return the condition number of the matrix. * @return condition number of the matrix */ public double getConditionNumber() { return singularValues[0] / singularValues[n - 1]; } /** * Computes the inverse of the condition number. * In cases of rank deficiency, the {@link #getConditionNumber() condition * number} will become undefined. * * @return the inverse of the condition number. */ public double getInverseConditionNumber() { return singularValues[n - 1] / singularValues[0]; } /** * Return the effective numerical matrix rank. * <p>The effective numerical rank is the number of non-negligible * singular values. The threshold used to identify non-negligible * terms is max(m,n) &times; ulp(s<sub>1</sub>) where ulp(s<sub>1</sub>) * is the least significant bit of the largest singular value.</p> * @return effective numerical matrix rank */ public int getRank() { int r = 0; for (int i = 0; i < singularValues.length; i++) { if (singularValues[i] > tol) { r++; } } return r; } /** * Get a solver for finding the A &times; X = B solution in least square sense. * @return a solver */ public DecompositionSolver getSolver() { return new Solver(singularValues, getUT(), getV(), getRank() == m, tol); } /** Specialized solver. */ private static class Solver implements DecompositionSolver { /** Pseudo-inverse of the initial matrix. */ private final RealMatrix pseudoInverse; /** Singularity indicator. */ private final boolean nonSingular; /** * Build a solver from decomposed matrix. * * @param singularValues Singular values. * @param uT U<sup>T</sup> matrix of the decomposition. * @param v V matrix of the decomposition. * @param nonSingular Singularity indicator. * @param tol tolerance for singular values */ private Solver(final double[] singularValues, final RealMatrix uT, final RealMatrix v, final boolean nonSingular, final double tol) { final double[][] suT = uT.getData(); for (int i = 0; i < singularValues.length; ++i) { final double a; if (singularValues[i] > tol) { a = 1 / singularValues[i]; } else { a = 0; } final double[] suTi = suT[i]; for (int j = 0; j < suTi.length; ++j) { suTi[j] *= a; } } pseudoInverse = v.multiply(new Array2DRowRealMatrix(suT, false)); this.nonSingular = nonSingular; } /** * Solve the linear equation A &times; X = B in least square sense. * <p> * The m&times;n matrix A may not be square, the solution X is such that * ||A &times; X - B|| is minimal. * </p> * @param b Right-hand side of the equation A &times; X = B * @return a vector X that minimizes the two norm of A &times; X - B * @throws org.apache.commons.math4.exception.DimensionMismatchException * if the matrices dimensions do not match. */ @Override public RealVector solve(final RealVector b) { return pseudoInverse.operate(b); } /** * Solve the linear equation A &times; X = B in least square sense. * <p> * The m&times;n matrix A may not be square, the solution X is such that * ||A &times; X - B|| is minimal. * </p> * * @param b Right-hand side of the equation A &times; X = B * @return a matrix X that minimizes the two norm of A &times; X - B * @throws org.apache.commons.math4.exception.DimensionMismatchException * if the matrices dimensions do not match. */ @Override public RealMatrix solve(final RealMatrix b) { return pseudoInverse.multiply(b); } /** * Check if the decomposed matrix is non-singular. * * @return {@code true} if the decomposed matrix is non-singular. */ @Override public boolean isNonSingular() { return nonSingular; } /** * Get the pseudo-inverse of the decomposed matrix. * * @return the inverse matrix. */ @Override public RealMatrix getInverse() { return pseudoInverse; } } }
apache-2.0
bmeurer/eui4j
src/main/java/de/benediktmeurer/eui4j/package-info.java
1068
/*- * Copyright 2012 Benedikt Meurer * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * This package provides classes to represent extended universal identifiers (EUIs) as specified by * the IEEE. * <ul> * <li>The {@link de.benediktmeurer.eui4j.EUI48} class implements 48-bit extended universal * identifiers (EUI-48), also referred to as MAC-48 or simply MAC addresses.</li> * <li>The {@link de.benediktmeurer.eui4j.EUI64} class implements 64-bit extended universal * identifiers (EUI-64).</li> * </ul> */ package de.benediktmeurer.eui4j;
apache-2.0
alex-kosarev/sandbox-springboot
sandbox-springboot-security/src/main/java/name/alexkosarev/sandbox/springboot/security/TokenAuthenticationEntryPoint.java
1014
package name.alexkosarev.sandbox.springboot.security; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import name.alexkosarev.sandbox.springboot.security.exceptions.TokenAuthenticationHeaderNotFound; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.AuthenticationEntryPoint; public class TokenAuthenticationEntryPoint implements AuthenticationEntryPoint { @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException { if (authException instanceof TokenAuthenticationHeaderNotFound) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED, authException.getMessage()); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage()); } } }
apache-2.0
mkutmon/biomartconnect
src/org/pathvisio/biomartconnect/impl/TableDialog.java
2032
package org.pathvisio.biomartconnect.impl; import java.awt.BorderLayout; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; /** * Window containing genetic variation data table. Also contains a settings button to * set attributes to be shown in the table. It also color codes various prediction attributes. * * @author rsaxena * */ public class TableDialog extends JDialog { JScrollPane jt; GeneticVariationProvider bcp; String [] attr; JPanel jp; public TableDialog(GeneticVariationProvider bcp, JScrollPane jt, String [] attr){ this.bcp = bcp; this.jt = jt; this.attr = attr; initUI(); } /** * Initializes this window and populates it with various elements */ public final void initUI(){ JLabel title = new JLabel("Variation Data Table"); JPanel master = new JPanel(); master.setLayout(new BorderLayout()); master.add(title,BorderLayout.NORTH); JScrollPane scrollpane = new JScrollPane(jt, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); master.add(scrollpane,BorderLayout.CENTER); final TableSettingsDialog tsd = new TableSettingsDialog(bcp,attr,master,scrollpane); JButton settings = new JButton("Settings"); settings.setAlignmentX(Component.CENTER_ALIGNMENT); settings.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){ tsd.setVisible(true); } }); JPanel southPanel = new JPanel(); southPanel.setLayout(new BoxLayout(southPanel, BoxLayout.PAGE_AXIS)); southPanel.add(settings); master.add(southPanel,BorderLayout.SOUTH); add(master); setDefaultCloseOperation(DISPOSE_ON_CLOSE); setLocationRelativeTo(null); setSize(900,660); } }
apache-2.0
dagnir/aws-sdk-java
aws-java-sdk-lambda/src/main/java/com/amazonaws/services/lambda/model/transform/UntagResourceRequestProtocolMarshaller.java
2580
/* * Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.lambda.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.Request; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.lambda.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * UntagResourceRequest Marshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class UntagResourceRequestProtocolMarshaller implements Marshaller<Request<UntagResourceRequest>, UntagResourceRequest> { private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.REST_JSON).requestUri("/2017-03-31/tags/{ARN}") .httpMethodName(HttpMethodName.DELETE).hasExplicitPayloadMember(false).hasPayloadMembers(false).serviceName("AWSLambda").build(); private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory; public UntagResourceRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) { this.protocolFactory = protocolFactory; } public Request<UntagResourceRequest> marshall(UntagResourceRequest untagResourceRequest) { if (untagResourceRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { final ProtocolRequestMarshaller<UntagResourceRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING, untagResourceRequest); protocolMarshaller.startMarshalling(); UntagResourceRequestMarshaller.getInstance().marshall(untagResourceRequest, protocolMarshaller); return protocolMarshaller.finishMarshalling(); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
apache-2.0
charles-cooper/idylfin
src/com/opengamma/analytics/financial/curve/generator/GeneratorCurveYieldPeriodicInterpolatedNode.java
2880
/** * Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.analytics.financial.curve.generator; import com.opengamma.analytics.financial.interestrate.YieldCurveBundle; import com.opengamma.analytics.financial.interestrate.market.description.IMarketBundle; import com.opengamma.analytics.financial.model.interestrate.curve.YieldAndDiscountCurve; import com.opengamma.analytics.financial.model.interestrate.curve.YieldPeriodicCurve; import com.opengamma.analytics.math.curve.InterpolatedDoublesCurve; import com.opengamma.analytics.math.interpolation.Interpolator1D; import com.opengamma.util.ArgumentChecker; /** * Store the details and generate the required curve. The curve is interpolated on the rate (periodically compounded). */ public class GeneratorCurveYieldPeriodicInterpolatedNode extends GeneratorYDCurve { /** * The nodes (times) on which the interpolated curves is constructed. */ private final double[] _nodePoints; /** * The interpolator used for the curve. */ private final Interpolator1D _interpolator; /** * The number of points (or nodes). Is the length of _nodePoints. */ private final int _nbPoints; /** * The number of composition periods per year for the storage curve (1 for annual, 2 for semi-annual, etc.). */ private final int _compoundingPeriodsPerYear; /** * Constructor. * @param nodePoints The node points (X) used to define the interpolated curve. * @param compoundingPeriodsPerYear The number of composition periods per year for the storage curve (1 for annual, 2 for semi-annual, etc.). * @param interpolator The interpolator. */ public GeneratorCurveYieldPeriodicInterpolatedNode(double[] nodePoints, final int compoundingPeriodsPerYear, Interpolator1D interpolator) { ArgumentChecker.notNull(nodePoints, "Node points"); ArgumentChecker.notNull(interpolator, "Interpolator"); _nodePoints = nodePoints; _nbPoints = _nodePoints.length; _interpolator = interpolator; _compoundingPeriodsPerYear = compoundingPeriodsPerYear; } @Override public int getNumberOfParameter() { return _nbPoints; } @Override public YieldAndDiscountCurve generateCurve(String name, double[] x) { ArgumentChecker.isTrue(x.length == _nbPoints, "Incorrect dimension for the rates"); return new YieldPeriodicCurve(name, _compoundingPeriodsPerYear, new InterpolatedDoublesCurve(_nodePoints, x, _interpolator, true, name)); } @Override public YieldAndDiscountCurve generateCurve(String name, YieldCurveBundle bundle, double[] parameters) { return generateCurve(name, parameters); } @Override public YieldAndDiscountCurve generateCurve(String name, IMarketBundle bundle, double[] parameters) { return generateCurve(name, parameters); } }
apache-2.0
sameeraroshan/visjs
src/main/java/org/vaadin/visjs/networkDiagram/event/node/BlurEvent.java
448
package org.vaadin.visjs.networkDiagram.event.node; import org.vaadin.visjs.networkDiagram.api.Event; import elemental.json.JsonArray; import elemental.json.JsonException; /** * Created by roshans on 11/30/14. */ public class BlurEvent extends Event { public BlurEvent(JsonArray properties) throws JsonException { super(); String nodeID = properties.getObject(0).getString("node"); getNodeIds().add(nodeID); } }
apache-2.0
iyounus/incubator-systemml
src/main/java/org/apache/sysml/api/mlcontext/ProjectInfo.java
3620
/* * 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.sysml.api.mlcontext; import java.io.IOException; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.jar.Attributes; import java.util.jar.Attributes.Name; import java.util.jar.JarFile; import java.util.jar.Manifest; /** * Obtains information that is stored in the manifest when the SystemML jar is * built. * */ public class ProjectInfo { SortedMap<String, String> properties = null; static ProjectInfo projectInfo = null; /** * Return a ProjectInfo singleton instance. * * @return the ProjectInfo singleton instance */ public static ProjectInfo getProjectInfo() { if (projectInfo == null) { projectInfo = new ProjectInfo(); } return projectInfo; } private ProjectInfo() { JarFile systemMlJar = null; try { String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath(); systemMlJar = new JarFile(path); Manifest manifest = systemMlJar.getManifest(); Attributes mainAttributes = manifest.getMainAttributes(); properties = new TreeMap<String, String>(); for (Object key : mainAttributes.keySet()) { String value = mainAttributes.getValue((Name) key); properties.put(key.toString(), value); } } catch (Exception e) { throw new MLContextException("Error trying to read from manifest in SystemML jar file", e); } finally { if (systemMlJar != null) { try { systemMlJar.close(); } catch (IOException e) { throw new MLContextException("Error closing SystemML jar file", e); } } } } @Override public String toString() { StringBuffer sb = new StringBuffer(); Set<String> keySet = properties.keySet(); for (String key : keySet) { sb.append(key + ": " + properties.get(key) + "\n"); } return sb.toString(); } /** * Obtain a manifest property value based on the key. * * @param key * the property key * @return the property value */ public String property(String key) { return properties.get(key); } /** * Obtain the project version from the manifest. * * @return the project version */ public String version() { return property("Version"); } /** * Object the artifact build time from the manifest. * * @return the artifact build time */ public String buildTime() { return property("Build-Time"); } /** * Obtain the minimum recommended Spark version from the manifest. * * @return the minimum recommended Spark version */ public String minimumRecommendedSparkVersion() { return property("Minimum-Recommended-Spark-Version"); } /** * Obtain all the properties from the manifest as a sorted map. * * @return the manifest properties as a sorted map */ public SortedMap<String, String> properties() { return properties; } }
apache-2.0
linuxtage/glt-companion
app/src/main/java/at/linuxtage/companion/model/DownloadScheduleResult.java
951
package at.linuxtage.companion.model; public class DownloadScheduleResult { private static final DownloadScheduleResult RESULT_ERROR = new DownloadScheduleResult(0); private static final DownloadScheduleResult RESULT_UP_TO_DATE = new DownloadScheduleResult(0); private final int eventsCount; private DownloadScheduleResult(int eventsCount) { this.eventsCount = eventsCount; } public static DownloadScheduleResult success(int eventsCount) { return new DownloadScheduleResult(eventsCount); } public static DownloadScheduleResult error() { return RESULT_ERROR; } public static DownloadScheduleResult upToDate() { return RESULT_UP_TO_DATE; } public boolean isSuccess() { return this != RESULT_ERROR && this != RESULT_UP_TO_DATE; } public boolean isError() { return this == RESULT_ERROR; } public boolean isUpToDate() { return this == RESULT_UP_TO_DATE; } public int getEventsCount() { return eventsCount; } }
apache-2.0
bozimmerman/CoffeeMud
com/planet_ink/coffee_mud/Abilities/Prayers/Prayer_ConsecrateLand.java
4232
package com.planet_ink.coffee_mud.Abilities.Prayers; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; /* Copyright 2004-2022 Bo Zimmerman Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ public class Prayer_ConsecrateLand extends Prayer { @Override public String ID() { return "Prayer_ConsecrateLand"; } private final static String localizedName = CMLib.lang().L("Consecrate Land"); @Override public String name() { return localizedName; } private final static String localizedStaticDisplay = CMLib.lang().L("(Consecrate Land)"); @Override public String displayText() { return localizedStaticDisplay; } @Override public int classificationCode() { return Ability.ACODE_PRAYER|Ability.DOMAIN_WARDING; } @Override public int abstractQuality() { return Ability.QUALITY_INDIFFERENT; } @Override protected int canAffectCode() { return CAN_ROOMS; } @Override protected int canTargetCode() { return CAN_ROOMS; } @Override public long flags() { return Ability.FLAG_HOLY; } @Override public boolean okMessage(final Environmental myHost, final CMMsg msg) { if(affected==null) return super.okMessage(myHost,msg); if((msg.sourceMinor()==CMMsg.TYP_CAST_SPELL) &&(msg.tool() instanceof Ability) &&((((Ability)msg.tool()).classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_PRAYER) &&(CMath.bset(((Ability)msg.tool()).flags(),Ability.FLAG_UNHOLY)) &&(!CMath.bset(((Ability)msg.tool()).flags(),Ability.FLAG_HOLY))) { msg.source().tell(L("This place is blocking unholy magic!")); return false; } return super.okMessage(myHost,msg); } @Override public boolean invoke(final MOB mob, final List<String> commands, final Physical givenTarget, final boolean auto, final int asLevel) { final Physical target=mob.location(); if(target==null) return false; if(target.fetchEffect(ID())!=null) { mob.tell(L("This place is already consecrated.")); return false; } if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; final boolean success=proficiencyCheck(mob,0,auto); if(success) { final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?"":L("^S<S-NAME> @x1 to consecrate this place.^?",prayForWord(mob))); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); setMiscText(mob.Name()); if((target instanceof Room) &&(CMLib.law().doesOwnThisLand(mob,((Room)target)))) { target.addNonUninvokableEffect((Ability)this.copyOf()); CMLib.database().DBUpdateRoom((Room)target); } else beneficialAffect(mob,target,asLevel,0); } } else beneficialWordsFizzle(mob,target,L("<S-NAME> @x1 to consecrate this place, but <S-IS-ARE> not answered.",prayForWord(mob))); return success; } }
apache-2.0
dorzey/assertj-core
src/test/java/org/assertj/core/api/url/UrlAssert_hasParameter_String_Test.java
1144
/** * 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 2012-2016 the original author or authors. */ package org.assertj.core.api.url; import static org.mockito.Mockito.verify; import org.assertj.core.api.UrlAssert; import org.assertj.core.api.UrlAssertBaseTest; public class UrlAssert_hasParameter_String_Test extends UrlAssertBaseTest { private final String name = "article"; @Override protected UrlAssert invoke_api_method() { return assertions.hasParameter(name); } @Override protected void verify_internal_effects() { verify(urls).assertHasParameter(getInfo(assertions), getActual(assertions), name); } }
apache-2.0
thebuzzmedia/universal-binary-json-java
src/main/java/org/ubjson/io/charset/StreamEncoder.java
3859
/** * Copyright 2011 The Buzz Media, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ubjson.io.charset; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; public class StreamEncoder { /** * System property name used to set the runtime value of * {@link #BUFFER_SIZE}. * <p/> * Value is: <code>org.ubjson.io.charset.encoderBufferSize</code> */ public static final String BUFFER_SIZE_PROPERTY_NAME = "org.ubjson.io.charset.encoderBufferSize"; /** * Constant used to define the size of the <code>byte[]</code> buffer this * encoder will use at runtime. * <p/> * Default value: <code>16384</code> (16KB) * <p/> * This value can be set using the {@link #BUFFER_SIZE_PROPERTY_NAME} * property at runtime. From the command line this can be done using the * <code>-D</code> argument like so: * <p/> * <code>java -cp [...] -Dorg.ubjson.io.charset.encoderBufferSize=32768 [...]</code> */ public static final int BUFFER_SIZE = Integer.getInteger( BUFFER_SIZE_PROPERTY_NAME, 16384); public static final Charset UTF8_CHARSET = Charset.forName("UTF-8"); static { if (BUFFER_SIZE < 1) throw new RuntimeException("System property [" + BUFFER_SIZE_PROPERTY_NAME + "] must be > 0 but is currently set to the value '" + BUFFER_SIZE + "'."); } private byte[] buffer; private ByteBuffer bbuffer; private CharsetEncoder encoder; public StreamEncoder() { this(UTF8_CHARSET); } public StreamEncoder(Charset charset) throws IllegalArgumentException { if (charset == null) throw new IllegalArgumentException("charset cannot be null"); /* * We need access to both the byte[] and the wrapping ByteBuffer. * * Below in encode() we need the raw byte[] to write bytes to the * provided stream and we need access to the ByteBuffer to manipulate * its pointers to keep pointing it at the new data from the encoder. */ buffer = new byte[BUFFER_SIZE]; bbuffer = ByteBuffer.wrap(buffer); encoder = charset.newEncoder(); } public void encode(CharBuffer src, OutputStream stream) throws IllegalArgumentException, IOException { if (stream == null) throw new IllegalArgumentException("stream cannot be null"); // Short-circuit. if (src == null || !src.hasRemaining()) return; encoder.reset(); /* * Encode all the remaining chars in the given buffer; the buffer's * state (position, limit) will mark the range of chars we are meant to * process. */ while (src.hasRemaining()) { bbuffer.clear(); // Encode the text into our temporary write buffer. encoder.encode(src, bbuffer, false); /* * Using direct access to the underlying byte[], write the bytes * that the decode operation produced to the output stream. */ stream.write(buffer, 0, bbuffer.position()); } // Perform the decoding finalization. bbuffer.clear(); encoder.encode(src, bbuffer, true); encoder.flush(bbuffer); // Write out any additional bytes finalization resulted in. if (bbuffer.position() > 0) stream.write(buffer, 0, bbuffer.position()); } }
apache-2.0
HubSpot/hbase
hbase-server/src/test/java/org/apache/hadoop/hbase/replication/TestReplicationWithTags.java
10471
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.replication; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Optional; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.ArrayBackedTag; import org.apache.hadoop.hbase.Cell; import org.apache.hadoop.hbase.CellUtil; import org.apache.hadoop.hbase.HBaseClassTestRule; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.HBaseTestingUtility; import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.KeyValueUtil; import org.apache.hadoop.hbase.PrivateCellUtil; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.Tag; import org.apache.hadoop.hbase.client.Admin; import org.apache.hadoop.hbase.client.Connection; import org.apache.hadoop.hbase.client.ConnectionFactory; import org.apache.hadoop.hbase.client.Durability; import org.apache.hadoop.hbase.client.Get; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.Table; import org.apache.hadoop.hbase.client.replication.ReplicationAdmin; import org.apache.hadoop.hbase.codec.KeyValueCodecWithTags; import org.apache.hadoop.hbase.coprocessor.CoprocessorHost; import org.apache.hadoop.hbase.coprocessor.ObserverContext; import org.apache.hadoop.hbase.coprocessor.RegionCoprocessor; import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment; import org.apache.hadoop.hbase.coprocessor.RegionObserver; import org.apache.hadoop.hbase.testclassification.MediumTests; import org.apache.hadoop.hbase.testclassification.ReplicationTests; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.wal.WALEdit; import org.apache.hadoop.hbase.zookeeper.MiniZooKeeperCluster; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Category({ReplicationTests.class, MediumTests.class}) public class TestReplicationWithTags { @ClassRule public static final HBaseClassTestRule CLASS_RULE = HBaseClassTestRule.forClass(TestReplicationWithTags.class); private static final Logger LOG = LoggerFactory.getLogger(TestReplicationWithTags.class); private static final byte TAG_TYPE = 1; private static Configuration conf1 = HBaseConfiguration.create(); private static Configuration conf2; private static ReplicationAdmin replicationAdmin; private static Connection connection1; private static Connection connection2; private static Table htable1; private static Table htable2; private static HBaseTestingUtility utility1; private static HBaseTestingUtility utility2; private static final long SLEEP_TIME = 500; private static final int NB_RETRIES = 10; private static final TableName TABLE_NAME = TableName.valueOf("TestReplicationWithTags"); private static final byte[] FAMILY = Bytes.toBytes("f"); private static final byte[] ROW = Bytes.toBytes("row"); @BeforeClass public static void setUpBeforeClass() throws Exception { conf1.setInt("hfile.format.version", 3); conf1.set(HConstants.ZOOKEEPER_ZNODE_PARENT, "/1"); conf1.setInt("replication.source.size.capacity", 10240); conf1.setLong("replication.source.sleepforretries", 100); conf1.setInt("hbase.regionserver.maxlogs", 10); conf1.setLong("hbase.master.logcleaner.ttl", 10); conf1.setInt("zookeeper.recovery.retry", 1); conf1.setInt("zookeeper.recovery.retry.intervalmill", 10); conf1.setLong(HConstants.THREAD_WAKE_FREQUENCY, 100); conf1.setInt("replication.stats.thread.period.seconds", 5); conf1.setBoolean("hbase.tests.use.shortcircuit.reads", false); conf1.setStrings(HConstants.REPLICATION_CODEC_CONF_KEY, KeyValueCodecWithTags.class.getName()); conf1.setStrings(CoprocessorHost.USER_REGION_COPROCESSOR_CONF_KEY, TestCoprocessorForTagsAtSource.class.getName()); utility1 = new HBaseTestingUtility(conf1); utility1.startMiniZKCluster(); MiniZooKeeperCluster miniZK = utility1.getZkCluster(); // Have to reget conf1 in case zk cluster location different // than default conf1 = utility1.getConfiguration(); LOG.info("Setup first Zk"); // Base conf2 on conf1 so it gets the right zk cluster. conf2 = HBaseConfiguration.create(conf1); conf2.setInt("hfile.format.version", 3); conf2.set(HConstants.ZOOKEEPER_ZNODE_PARENT, "/2"); conf2.setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 6); conf2.setBoolean("hbase.tests.use.shortcircuit.reads", false); conf2.setStrings(HConstants.REPLICATION_CODEC_CONF_KEY, KeyValueCodecWithTags.class.getName()); conf2.setStrings(CoprocessorHost.USER_REGION_COPROCESSOR_CONF_KEY, TestCoprocessorForTagsAtSink.class.getName()); utility2 = new HBaseTestingUtility(conf2); utility2.setZkCluster(miniZK); LOG.info("Setup second Zk"); utility1.startMiniCluster(2); utility2.startMiniCluster(2); replicationAdmin = new ReplicationAdmin(conf1); ReplicationPeerConfig rpc = new ReplicationPeerConfig(); rpc.setClusterKey(utility2.getClusterKey()); replicationAdmin.addPeer("2", rpc, null); HTableDescriptor table = new HTableDescriptor(TABLE_NAME); HColumnDescriptor fam = new HColumnDescriptor(FAMILY); fam.setMaxVersions(3); fam.setScope(HConstants.REPLICATION_SCOPE_GLOBAL); table.addFamily(fam); try (Connection conn = ConnectionFactory.createConnection(conf1); Admin admin = conn.getAdmin()) { admin.createTable(table, HBaseTestingUtility.KEYS_FOR_HBA_CREATE_TABLE); } try (Connection conn = ConnectionFactory.createConnection(conf2); Admin admin = conn.getAdmin()) { admin.createTable(table, HBaseTestingUtility.KEYS_FOR_HBA_CREATE_TABLE); } htable1 = utility1.getConnection().getTable(TABLE_NAME); htable2 = utility2.getConnection().getTable(TABLE_NAME); } @AfterClass public static void tearDownAfterClass() throws Exception { utility2.shutdownMiniCluster(); utility1.shutdownMiniCluster(); } @Test public void testReplicationWithCellTags() throws Exception { LOG.info("testSimplePutDelete"); Put put = new Put(ROW); put.setAttribute("visibility", Bytes.toBytes("myTag3")); put.addColumn(FAMILY, ROW, ROW); htable1 = utility1.getConnection().getTable(TABLE_NAME); htable1.put(put); Get get = new Get(ROW); try { for (int i = 0; i < NB_RETRIES; i++) { if (i == NB_RETRIES - 1) { fail("Waited too much time for put replication"); } Result res = htable2.get(get); if (res.isEmpty()) { LOG.info("Row not available"); Thread.sleep(SLEEP_TIME); } else { assertArrayEquals(ROW, res.value()); assertEquals(1, TestCoprocessorForTagsAtSink.TAGS.size()); Tag tag = TestCoprocessorForTagsAtSink.TAGS.get(0); assertEquals(TAG_TYPE, tag.getType()); break; } } } finally { TestCoprocessorForTagsAtSink.TAGS = null; } } public static class TestCoprocessorForTagsAtSource implements RegionCoprocessor, RegionObserver { @Override public Optional<RegionObserver> getRegionObserver() { return Optional.of(this); } @Override public void prePut(final ObserverContext<RegionCoprocessorEnvironment> e, final Put put, final WALEdit edit, final Durability durability) throws IOException { byte[] attribute = put.getAttribute("visibility"); byte[] cf = null; List<Cell> updatedCells = new ArrayList<>(); if (attribute != null) { for (List<? extends Cell> edits : put.getFamilyCellMap().values()) { for (Cell cell : edits) { KeyValue kv = KeyValueUtil.ensureKeyValue(cell); if (cf == null) { cf = CellUtil.cloneFamily(kv); } Tag tag = new ArrayBackedTag(TAG_TYPE, attribute); List<Tag> tagList = new ArrayList<>(1); tagList.add(tag); KeyValue newKV = new KeyValue(CellUtil.cloneRow(kv), 0, kv.getRowLength(), CellUtil.cloneFamily(kv), 0, kv.getFamilyLength(), CellUtil.cloneQualifier(kv), 0, kv.getQualifierLength(), kv.getTimestamp(), KeyValue.Type.codeToType(kv.getTypeByte()), CellUtil.cloneValue(kv), 0, kv.getValueLength(), tagList); ((List<Cell>) updatedCells).add(newKV); } } put.getFamilyCellMap().remove(cf); // Update the family map put.getFamilyCellMap().put(cf, updatedCells); } } } public static class TestCoprocessorForTagsAtSink implements RegionCoprocessor, RegionObserver { private static List<Tag> TAGS = null; @Override public Optional<RegionObserver> getRegionObserver() { return Optional.of(this); } @Override public void postGetOp(ObserverContext<RegionCoprocessorEnvironment> e, Get get, List<Cell> results) throws IOException { if (results.size() > 0) { // Check tag presence in the 1st cell in 1st Result if (!results.isEmpty()) { Cell cell = results.get(0); TAGS = PrivateCellUtil.getTags(cell); } } } } }
apache-2.0
strapdata/cassandra
src/java/org/apache/cassandra/tools/nodetool/DescribeRing.java
1874
/* * 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.cassandra.tools.nodetool; import static org.apache.commons.lang3.StringUtils.EMPTY; import io.airlift.command.Arguments; import io.airlift.command.Command; import java.io.IOException; import java.io.PrintStream; import org.apache.cassandra.tools.NodeProbe; import org.apache.cassandra.tools.NodeTool.NodeToolCmd; @Command(name = "describering", description = "Shows the token ranges info of a given keyspace") public class DescribeRing extends NodeToolCmd { @Arguments(description = "The keyspace name", required = true) String keyspace = EMPTY; @Override public void execute(NodeProbe probe) { PrintStream out = probe.output().out; out.println("Schema Version:" + probe.getSchemaVersion()); out.println("TokenRange: "); try { for (String tokenRangeString : probe.describeRing(keyspace)) { out.println("\t" + tokenRangeString); } } catch (IOException e) { throw new RuntimeException(e); } } }
apache-2.0
usc/demo
src/main/java/org/usc/demo/beanutils/test/UserForTypeTest.java
2957
package org.usc.demo.beanutils.test; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.beanutils.ConvertUtils; import org.apache.commons.beanutils.converters.DateConverter; import org.apache.commons.beanutils.converters.DateTimeConverter; import org.usc.demo.beanutils.convert.SimpleListConverter; import org.usc.demo.beanutils.convert.SimpleMapConverter; import org.usc.demo.beanutils.model.UserForType; import java.util.List; import java.util.Map; public class UserForTypeTest { static { DateTimeConverter dateConverter = new DateConverter(); dateConverter.setPattern("yyyy-MM-dd hh:mm:ss"); ConvertUtils.register(dateConverter, java.util.Date.class); ConvertUtils.register(new SimpleListConverter(), List.class); ConvertUtils.register(new SimpleMapConverter(), Map.class); // ConvertUtils.register(new SimpleListConverter(Collections.EMPTY_LIST), List.class); // ConvertUtils.register(new SimpleMapConverter(Collections.EMPTY_MAP), Map.class); } public static void main(String[] args) throws Exception { UserForType ut = new UserForType(); BeanUtils.setProperty(ut, "sS", "s"); BeanUtils.setProperty(ut, "i", "1"); BeanUtils.setProperty(ut, "b", "1"); BeanUtils.setProperty(ut, "l", "10000000"); BeanUtils.setProperty(ut, "d", "100.0"); BeanUtils.setProperty(ut, "f", "100.0"); BeanUtils.setProperty(ut, "de", "2013-05-12 12:01:02"); BeanUtils.setProperty(ut, "sa", "1.0,2-3,3"); BeanUtils.setProperty(ut, "sl", "1.0,2-3,3=4,5 6*7,2|3"); BeanUtils.setProperty(ut, "m", "1.0=2-0,2-3=4,3,1=2|3|4"); // BeanUtils.setProperty(ut, "sl", null); // BeanUtils.setProperty(ut, "m", null); // BeanUtils.setProperty(ut, "sl", Arrays.asList("1", "2")); // Map<String, String> map = new HashMap<String, String>(); // map.put("1", "2"); // BeanUtils.setProperty(ut, "m", map); BeanUtils.setProperty(ut, "xxoo", "nofiled"); System.out.println(ut); // System.out.println(ut.getSa().length); // // System.out.println(ut.getSl().size()); // System.out.println(ut.getM().size()); // // Map<String, String> properties = new HashMap<String, String>(); // properties.put("s", "s"); // properties.put("i", "1"); // properties.put("b", "1"); // properties.put("l", "10000000"); // properties.put("d", "100.0"); // properties.put("f", "100.0"); // properties.put("de", "2013-05-12 12:00:00"); // properties.put("sa", "1.0,2-3,3"); // properties.put("sl", null); // properties.put("m", "1.0=2-0,2-3=4,3,1=2|3|4"); // // UserForType newUT = new UserForType(); // BeanUtils.populate(newUT, properties); // // System.out.println(newUT); } }
apache-2.0
lorislab/armonitor
armonitor-agent-rs/src/main/java/org/lorislab/armonitor/agent/rs/model/Request.java
925
/* * Copyright 2013 lorislab.org. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.lorislab.armonitor.agent.rs.model; /** * The request. * * @author Andrej Petras */ public class Request { /** * The UID for this request. */ public String uid; /** * The manifest. */ public boolean manifest; /** * The service. */ public String service; }
apache-2.0
dernasherbrezon/jradio
src/main/java/ru/r2cloud/jradio/ao73/WholeOrbitDataBatch.java
1164
package ru.r2cloud.jradio.ao73; import java.io.IOException; import java.nio.charset.StandardCharsets; import ru.r2cloud.jradio.util.BitInputStream; public class WholeOrbitDataBatch { private WholeOrbit[] data = new WholeOrbit[104]; private String callsign; private int sequenceNumber; public WholeOrbitDataBatch() { // do nothing } public WholeOrbitDataBatch(int sequenceNumber, byte[] rawData) throws IOException { this.sequenceNumber = sequenceNumber; BitInputStream dis = new BitInputStream(rawData); for (int i = 0; i < data.length; i++) { data[i] = new WholeOrbit(dis); } byte[] callsignBytes = new byte[8]; dis.readFully(callsignBytes); callsign = new String(callsignBytes, StandardCharsets.ISO_8859_1).trim(); } public WholeOrbit[] getData() { return data; } public void setData(WholeOrbit[] data) { this.data = data; } public String getCallsign() { return callsign; } public void setCallsign(String callsign) { this.callsign = callsign; } public int getSequenceNumber() { return sequenceNumber; } public void setSequenceNumber(int sequenceNumber) { this.sequenceNumber = sequenceNumber; } }
apache-2.0
SnappyDataInc/snappy-store
gemfire-shared/src/main/java/com/gemstone/gemfire/internal/shared/LauncherBase.java
22233
/* * Copyright (c) 2010-2015 Pivotal Software, Inc. 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. See accompanying * LICENSE file. */ /* * Changes for SnappyData distributed computational and data platform. * * Portions Copyright (c) 2017-2019 TIBCO Software Inc. 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. See accompanying * LICENSE file. */ package com.gemstone.gemfire.internal.shared; import java.io.Console; import java.io.IOException; import java.io.OutputStreamWriter; import java.lang.management.ManagementFactory; import java.lang.management.OperatingSystemMXBean; import java.lang.reflect.Method; import java.net.InetAddress; import java.nio.file.Files; import java.nio.file.Path; import java.text.MessageFormat; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.concurrent.TimeUnit; import com.gemstone.gemfire.internal.cache.Status; public abstract class LauncherBase { public static final String LOG_FILE = "log-file"; public static final String HOST_DATA = "host-data"; public static final String THRESHOLD_THICKNESS_PROP = "gemfire.thresholdThickness"; public static final String THRESHOLD_THICKNESS_EVICT_PROP = "gemfire.eviction-thresholdThickness"; public static final String EVICTION_BURST_PERCENT_PROP = "gemfire.HeapLRUCapacityController.evictionBurstPercentage"; public static final String CRITICAL_HEAP_PERCENTAGE = "critical-heap-percentage"; public static final String EVICTION_HEAP_PERCENTAGE = "eviction-heap-percentage"; public static final String CRITICAL_OFF_HEAP_PERCENTAGE = "critical-off-heap-percentage"; public static final String EVICTION_OFF_HEAP_PERCENTAGE = "eviction-off-heap-percentage"; public static final String POLLER_INTERVAL_PROP = "gemfire.heapPollerInterval"; public static final String EVICT_HIGH_ENTRY_COUNT_BUCKETS_FIRST_PROP = "gemfire.HeapLRUCapacityController.evictHighEntryCountBucketsFirst"; public static final String EVICT_HIGH_ENTRY_COUNT_BUCKETS_FIRST_FOR_EVICTOR_PROP = "gemfire.HeapLRUCapacityController.evictHighEntryCountBucketsFirstForEvictor"; // no internalization here (bundles not part of GemFire for a long time) public static final String LAUNCHER_SEE_LOG_FILE = "See log file for details."; public static final String LAUNCHER_NO_AVAILABLE_STATUS = "No available status. Either status file \"{0}\" is not readable or " + "reading the status file timed out."; public static final String LAUNCHER_STOPPED = "The {0} on {1} has stopped."; public static final String LAUNCHER_TIMEOUT_WAITING_FOR_SHUTDOWN = "Timeout waiting for {0} to shutdown on {1}, status is: {2}"; public static final String LAUNCHER_NO_STATUS_FILE = "The specified working directory ({0}) on {1} contains no status file"; public static final String LAUNCHER_UNREADABLE_STATUS_FILE = "The status file {0} cannot be read due to: {1}. Delete the file if " + "no node is running in the directory."; public static final String LAUNCHER_UNKNOWN_ARGUMENT = "Unknown argument: {0}"; public static final String LAUNCHER_WORKING_DIRECTORY_DOES_NOT_EXIST = "The input working directory does not exist: {0}"; public static final String LAUNCHER_LOGS_GENERATED_IN = "Logs generated in {0}"; public static final String LAUNCH_IN_PROGRESS = "The server is still starting. " + "{0} seconds have elapsed since the last log message: \n {1}"; public static final String LAUNCHER_IS_ALREADY_RUNNING_IN_DIRECTORY = "WARN: A {0} is already running in directory \"{1}\" in \"{2}\" state"; private static final String LAUNCHER_EXPECTED_BOOLEAN = "Expected true or false for \"{0}=<value>\" but was \"{1}\""; // in-built property names which are treated in a special way by launcher protected static final String DIR = "dir"; protected static final String CLASSPATH = "classpath"; protected static final String HEAP_SIZE = "heap-size"; protected static final String WAIT_FOR_SYNC = "sync"; protected static final String VMARGS = "vmArgs"; protected static final String ENVARGS = "envArgs"; protected static final String ENV1 = "env_1"; protected static final String ENV2 = "env_2"; protected static final String ENV_MARKER = "PLAIN:"; protected static final int FORCE_STATUS_FILE_READ_ITERATION_COUNT = 10; private static final long STATUS_WAIT_TIME = SystemProperties.getServerInstance() .getLong("launcher.STATUS_WAIT_TIME_MS", 15000L); private static final long SHUTDOWN_WAIT_TIME = SystemProperties.getServerInstance() .getLong("launcher.SHUTDOWN_WAIT_TIME_MS", 15000L); public static final long LARGE_RAM_LIMIT = 14L << 30L; public static final double oneGB = 1024.0 * 1024.0 * 1024.0; private static final double twoGB = 2.0 * oneGB; protected final String baseName; protected final String defaultLogFileName; protected final String startLogFileName; protected final String pidFileName; protected final String statusName; protected final String hostName; protected volatile Status status; /** * wait for startup to complete, or exit once region GII wait begins */ protected boolean waitForData; protected final String jvmVendor; protected final String jvmName; protected String maxHeapSize; protected String initialHeapSize; @SuppressWarnings("WeakerAccess") protected boolean useThriftServerDefault = ClientSharedUtils.isThriftDefault(); protected LauncherBase(String displayName, String baseName) { if (baseName == null) { baseName = getBaseName(displayName); } this.baseName = displayName; this.defaultLogFileName = baseName + ".log"; this.startLogFileName = "start_" + this.defaultLogFileName; this.pidFileName = baseName + ".pid"; this.statusName = "." + baseName + ".stat"; InetAddress host = null; try { host = InetAddress.getLocalHost(); } catch (Exception ex) { try { host = ClientSharedUtils.getLocalHost(); } catch (Exception ignored) { } } this.hostName = host != null ? host.getCanonicalHostName() : "localhost"; // wait for data sync by default this.waitForData = true; this.jvmVendor = System.getProperty("java.vendor"); this.jvmName = System.getProperty("java.vm.name"); } protected String getBaseName(final String name) { return name != null ? name.toLowerCase().replace(" ", "") : null; } /** determine the total physical RAM in bytes */ public static long getPhysicalRAMSize() { long totalMemory = 0L; OperatingSystemMXBean bean = ManagementFactory .getOperatingSystemMXBean(); Object memSize = null; try { Method m = bean.getClass().getMethod("getTotalPhysicalMemorySize"); m.setAccessible(true); memSize = m.invoke(bean); } catch (Exception e) { // ignore exception and return zero } if (memSize instanceof Number) { totalMemory = ((Number)memSize).longValue(); } return totalMemory; } protected long getDefaultHeapSizeMB(boolean hostData) { return getDefaultHeapSizeMB(getPhysicalRAMSize(), hostData); } public static long getDefaultHeapSizeMB(long ramSize, boolean hostData) { int numProcs = Runtime.getRuntime().availableProcessors(); if (hostData) { // use 6GB or 8GB for hosts having large number of cores and sufficient RAM else 4GB if (numProcs > 12 && ramSize > LARGE_RAM_LIMIT + (2L << 30L)) return 8192L; else if (numProcs > 8 && ramSize > LARGE_RAM_LIMIT) return 6144L; return 4096L; } else { // use 8GB or 6GB or 4GB or 2GB as per available RAM and number of cores if (numProcs > 16 && ramSize > LARGE_RAM_LIMIT + (4L << 30L)) return 8192L; else if (numProcs > 12 && ramSize > LARGE_RAM_LIMIT + (2L << 30L)) return 6144L; else if (numProcs > 2) return 4096L; else return 2048L; } } protected long getDefaultSmallHeapSizeMB(boolean hostData) { return hostData ? 2048L : 1024L; } protected void processHeapSize(String value, List<String> vmArgs) { if (this.maxHeapSize == null) { vmArgs.add("-Xmx" + value); this.maxHeapSize = value; } if (this.initialHeapSize == null) { vmArgs.add("-Xms" + value); this.initialHeapSize = value; } } protected void processWaitForSync(String value) { boolean isTrue = "true".equalsIgnoreCase(value); if (!isTrue && !"false".equalsIgnoreCase(value)) { throw new IllegalArgumentException(MessageFormat.format( LAUNCHER_EXPECTED_BOOLEAN, WAIT_FOR_SYNC, value)); } this.waitForData = isTrue; } protected void processVMArg(String vmArg, List<String> vmArgs) { String thriftArg; if (vmArg.startsWith("-Xmx")) { this.maxHeapSize = vmArg.substring(4); } else if (vmArg.startsWith("-Xms")) { this.initialHeapSize = vmArg.substring(4); } else if (vmArg.startsWith(thriftArg = ("-D" + SystemProperties.getServerInstance().getSystemPropertyNamePrefix() + ClientSharedUtils.USE_THRIFT_AS_DEFAULT_PROP))) { int len = thriftArg.length(); if (vmArg.length() > (len + 1) && vmArg.charAt(len) == '=') { this.useThriftServerDefault = Boolean.parseBoolean(vmArg.substring( len + 1).trim()); } } vmArgs.add(vmArg); } protected void setDefaultVMArgs(Map<String, Object> map, boolean hostData, List<String> vmArgs) { // determine the total physical RAM long totalMemory = getPhysicalRAMSize(); float evictPercent = 0.0f; float criticalPercent = 0.0f; // If either the max heap or initial heap is null, set the one that is null // equal to the one that isn't. if (this.maxHeapSize == null) { if (this.initialHeapSize != null) { vmArgs.add("-Xmx" + this.initialHeapSize); this.maxHeapSize = this.initialHeapSize; } else { long defaultMemoryMB = getDefaultHeapSizeMB(hostData); if (defaultMemoryMB > 0 && totalMemory > 0L) { // Try some sane default for heapSize if none specified. // Set it only if total RAM is more than 1.5X of the default. long defaultMemory = defaultMemoryMB * 1024L * 1024L; if ((totalMemory * 2) < (defaultMemory * 3)) { defaultMemoryMB = getDefaultSmallHeapSizeMB(hostData); defaultMemory = defaultMemoryMB * 1024L * 1024L; if ((totalMemory * 2) < (defaultMemory * 3)) { defaultMemoryMB = 0; } } if (defaultMemoryMB > 0) { this.maxHeapSize = this.initialHeapSize = Long.toString(defaultMemoryMB) + 'm'; vmArgs.add("-Xmx" + this.maxHeapSize); vmArgs.add("-Xms" + this.initialHeapSize); } } } } else if (this.initialHeapSize == null) { vmArgs.add("-Xms" + this.maxHeapSize); this.initialHeapSize = this.maxHeapSize; } final String maxHeapStr = this.maxHeapSize; if (maxHeapStr != null && maxHeapStr.equals(this.initialHeapSize)) { String criticalHeapStr = (String)map.get(CRITICAL_HEAP_PERCENTAGE); if (criticalHeapStr == null) { // for larger heaps, keep critical as 95-99% and 90% for smaller ones; // also limit memory remaining beyond critical to 4GB double heapSize = ClientSharedUtils.parseMemorySize(maxHeapStr, 0L, 0); if (heapSize > (40.0 * 1024.0 * 1024.0 * 1024.0)) { // calculate percent that will leave out at max 1GB criticalPercent = (float)(100.0 * (1.0 - oneGB / heapSize)); } else if (heapSize >= twoGB) { // leave out max 200MB criticalPercent = (float)(100.0 * (1.0 - (200.0 * 1024.0 * 1024.0) / heapSize)); } else { criticalPercent = 90.0f; } // don't exceed 99% if (criticalPercent > 99.0f) criticalPercent = 99.0f; map.put(CRITICAL_HEAP_PERCENTAGE, "-" + CRITICAL_HEAP_PERCENTAGE + '=' + String.format(Locale.ENGLISH, "%.2f", criticalPercent)); } else { criticalPercent = Float.parseFloat(criticalHeapStr.substring( criticalHeapStr.indexOf('=') + 1).trim()); } String evictHeapStr = (String)map.get(EVICTION_HEAP_PERCENTAGE); if (evictHeapStr == null) { // reduce the critical-heap-percentage by 10% to get // eviction-heap-percentage evictPercent = criticalPercent * 0.9f; map.put(EVICTION_HEAP_PERCENTAGE, "-" + EVICTION_HEAP_PERCENTAGE + '=' + String.format(Locale.ENGLISH, "%.2f", evictPercent)); } else { evictPercent = Float.parseFloat(evictHeapStr.substring( evictHeapStr.indexOf('=') + 1).trim()); } } if (jvmVendor != null && (jvmVendor.contains("Sun") || jvmVendor.contains("Oracle") || jvmVendor.contains("OpenJDK") || jvmName.contains("OpenJDK"))) { vmArgs.add("-XX:+UseParNewGC"); vmArgs.add("-XX:+UseConcMarkSweepGC"); vmArgs.add("-XX:CMSInitiatingOccupancyFraction=50"); vmArgs.add("-XX:+CMSClassUnloadingEnabled"); vmArgs.add("-XX:-DontCompileHugeMethods"); // reduce the compile threshold for generated code of low latency jobs vmArgs.add("-XX:CompileThreshold=2000"); vmArgs.add("-XX:+UnlockDiagnosticVMOptions"); vmArgs.add("-XX:ParGCCardsPerStrideChunk=4k"); // limit thread-local cached direct buffers to reduce overhead vmArgs.add("-Djdk.nio.maxCachedBufferSize=131072"); } // If heap and off-heap sizes were both specified, then the critical and // eviction values for heap will be used. if (evictPercent != 0.0f) { // set the thickness to a more reasonable value than 2% float criticalThickness = criticalPercent * 0.05f; vmArgs.add("-D" + THRESHOLD_THICKNESS_PROP + '=' + criticalThickness); // set the eviction thickness to a more reasonable value than 2% float evictThickness = evictPercent * 0.1f; vmArgs.add("-D" + THRESHOLD_THICKNESS_EVICT_PROP + '=' + evictThickness); // set the eviction burst percentage to a more reasonable value than 0.4% float evictBurstPercent = evictPercent * 0.02f; vmArgs.add("-D" + EVICTION_BURST_PERCENT_PROP + '=' + evictBurstPercent); // reduce the heap poller interval to something more practical for high // concurrency putAlls vmArgs.add("-D" + POLLER_INTERVAL_PROP + "=200"); // always force EVICT_HIGH_ENTRY_COUNT_BUCKETS_FIRST to false and // EVICT_HIGH_ENTRY_COUNT_BUCKETS_FIRST_FOR_EVICTOR to true vmArgs.add("-D" + EVICT_HIGH_ENTRY_COUNT_BUCKETS_FIRST_PROP + "=false"); vmArgs.add("-D" + EVICT_HIGH_ENTRY_COUNT_BUCKETS_FIRST_FOR_EVICTOR_PROP + "=true"); } } /** * Get the path to working directory (should be absolute) */ protected abstract Path getWorkingDirPath(); protected Path getStatusPath() { return getWorkingDirPath().resolve(this.statusName); } protected long getLastModifiedStatusNanos() throws IOException { return Files.getLastModifiedTime(getStatusPath()).to(TimeUnit.NANOSECONDS); } /** * Verify and clear the status. If a server is detected as already running * then returns an error string else null. */ protected int verifyAndClearStatus() throws IOException { final Status status = getStatus(); if (status != null && status.state != Status.SHUTDOWN) { System.err.println(MessageFormat.format(LAUNCHER_IS_ALREADY_RUNNING_IN_DIRECTORY, this.baseName, getWorkingDirPath(), status.getStateString(status.state))); return status.state; } deleteStatus(); return Status.SHUTDOWN; } protected final void setStatusField(Status s) { this.status = s; } protected final Status createStatus(final int state, final int pid) { return Status.create(this.baseName, state, pid, getStatusPath()); } protected final Status createStatus(final int state, final int pid, final String msg, final Throwable t) { return Status.create(this.baseName, state, pid, msg, t, getStatusPath()); } /** * Returns the <code>Status</code> of the cache server in the * <code>workingDir</code>. */ protected Status getStatus() { Path statusPath = getStatusPath(); Status status; if (Files.exists(statusPath)) { status = spinReadStatus(statusPath); // See bug 32456 } else { // no pid since the cache server is not running status = createStatus(Status.SHUTDOWN, 0); } return status; } /** * Reads a node's status. If the status file cannot be read * because of I/O problems, it will try again. */ protected Status spinReadStatus(Path statusPath) { return Status.spinRead(this.baseName, statusPath); } /** * Removes a cache server's status file */ protected void deleteStatus() throws IOException { Status.delete(getStatusPath()); } /** * Wait for node to go to RUNNING. * Returns the exit code (success is 0 else failure). */ protected int waitForRunning(String logFilePath) throws IOException, InterruptedException { Path statusPath = getStatusPath(); Status status = spinReadStatus(statusPath); String lastReadMessage = null; String lastReportedMessage = null; long lastReadTime = System.nanoTime(); if (status == null) { throw new IOException(MessageFormat.format(LAUNCHER_NO_AVAILABLE_STATUS, this.statusName)); } else { if (logFilePath != null) { System.out.println(MessageFormat.format( LAUNCHER_LOGS_GENERATED_IN, logFilePath)); } if (checkStatusForWait(status)) { long lastModified, oldModified = getLastModifiedStatusNanos(); int count = 0; // re-read status for a while... while (checkStatusForWait(status)) { Thread.sleep(100); // fix for bug 36998 lastModified = getLastModifiedStatusNanos(); if (lastModified != oldModified || count++ == FORCE_STATUS_FILE_READ_ITERATION_COUNT) { count = 0; oldModified = lastModified; status = spinReadStatus(statusPath); } if (status == null) { throw new IOException(MessageFormat.format( LAUNCHER_NO_AVAILABLE_STATUS, this.statusName)); } //check to see if the status message has changed if (status.dsMsg != null && !status.dsMsg.equals(lastReadMessage)) { lastReadMessage = status.dsMsg; lastReadTime = System.nanoTime(); } //if the status message has not changed for 15 seconds, print //out the message. long elapsed = System.nanoTime() - lastReadTime; if (TimeUnit.NANOSECONDS.toMillis(elapsed) > STATUS_WAIT_TIME && lastReadMessage != null && !lastReadMessage.equals(lastReportedMessage)) { long elapsedSec = TimeUnit.NANOSECONDS.toSeconds(elapsed); System.out.println(MessageFormat.format( LAUNCH_IN_PROGRESS, elapsedSec, status.dsMsg)); lastReportedMessage = lastReadMessage; } } if (status.state == Status.SHUTDOWN) { System.out.println(status); return 1; } } writePidToFile(status); System.out.println(status); if (statusWaiting(status)) { return 2; } return 0; } } /** * Creates a new pid file and writes this process's pid into it. */ private void writePidToFile(Status status) throws IOException { final Path pidFile = getWorkingDirPath().resolve(this.pidFileName); try (OutputStreamWriter writer = new OutputStreamWriter( Files.newOutputStream(pidFile))) { writer.write(String.valueOf(status.pid)); writer.flush(); } } protected void pollCacheServerForShutdown(Path statusFile) throws IOException { long clock = System.currentTimeMillis(); // wait for a default total of 15s final long end = clock + SHUTDOWN_WAIT_TIME; while (clock < end) { try { this.status = spinReadStatus(statusFile); if (this.status.state == Status.SHUTDOWN) { break; } Thread.sleep(200); clock = System.currentTimeMillis(); } catch (InterruptedException ie) { break; } } } protected boolean checkStatusForWait(Status status) { // start node even in WAITING state if the "-sync" option is false return (status.state == Status.STARTING || (this.waitForData && status.state == Status.WAITING)); } protected boolean statusWaiting(Status status) { return !this.waitForData && status.state == Status.WAITING; } public static String readPassword(String prompt) { final Console cons = System.console(); if (cons == null) { throw new IllegalStateException( "No console found for reading the password."); } final char[] pwd = cons.readPassword(prompt); return pwd != null ? new String(pwd) : null; } }
apache-2.0
cubedtear/jcubit
jcubit-gameEngine/src/main/java/io/github/cubedtear/jcubit/awt/gameEngine/events/MouseReleasedEvent.java
417
package io.github.cubedtear.jcubit.awt.gameEngine.events; import io.github.cubedtear.jcubit.math.Vec2i; /** * @author Aritz Lopez */ public class MouseReleasedEvent extends MouseEvent { public MouseReleasedEvent(Vec2i pos, MouseButton button) { super(pos, button); } @Override public MouseEvent move(Vec2i delta) { return new MouseReleasedEvent(pos.add(delta), button); } }
apache-2.0
yuleizone/android_test
MyWeather/app/src/main/java/com/example/yln1172/myweather/db/MyWeatherDB.java
4124
package com.example.yln1172.myweather.db; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.example.yln1172.myweather.model.City; import com.example.yln1172.myweather.model.County; import com.example.yln1172.myweather.model.Province; import java.util.ArrayList; import java.util.List; /** * Created by yln1172 on 2017/2/6. */ public class MyWeatherDB { public static String DB_NAME = "myzone_weather"; public static final int VERSION = 1; private static MyWeatherDB myWeatherDB; private SQLiteDatabase db; public MyWeatherDB(Context context){ MyWeatherDBHelper dbHelper = new MyWeatherDBHelper(context,DB_NAME,null,VERSION); db = dbHelper.getWritableDatabase(); } public synchronized static MyWeatherDB getInstance(Context context){ if(myWeatherDB == null){ myWeatherDB = new MyWeatherDB(context); } return myWeatherDB; } public void saveProvince (Province province){ if(province != null){ ContentValues values = new ContentValues(); values.put("province_name",province.getProvinceName()); values.put("province_code",province.getProvinceCode()); db.insert("Province",null,values); } } public List<Province> loadProvinces(){ List<Province> list = new ArrayList<>(); Cursor cursor = db.query("Province",null,null,null,null,null,null); if(cursor.moveToFirst()){ do{ Province province = new Province(); province.setId(cursor.getInt(cursor.getColumnIndex("id"))); province.setProvinceName(cursor.getString(cursor.getColumnIndex("province_name"))); province.setProvinceCode(cursor.getString(cursor.getColumnIndex("province_code"))); list.add(province); }while(cursor.moveToNext()); } return list; } public void saveCity (City city){ if(city != null){ ContentValues values = new ContentValues(); values.put("city_name",city.getCityName()); values.put("city_code",city.getCityCode()); values.put("province_id",city.getProvinceId()); db.insert("City",null,values); } } public List<City> loadCities(int provinceId){ List<City> list = new ArrayList<>(); Cursor cursor = db.query("City",null,"province_id = ?",new String[]{String.valueOf(provinceId)},null,null,null); if(cursor.moveToFirst()){ do{ City province = new City(); province.setId(cursor.getInt(cursor.getColumnIndex("id"))); province.setCityName(cursor.getString(cursor.getColumnIndex("city_name"))); province.setCityCode(cursor.getString(cursor.getColumnIndex("city_code"))); list.add(province); }while(cursor.moveToNext()); } return list; } public void saveCounty (County county){ if(county != null){ ContentValues values = new ContentValues(); values.put("county_name",county.getCountyName()); values.put("county_code",county.getCountyCode()); values.put("city_id",county.getCityId()); db.insert("County",null,values); } } public List<County> loadCounties(int cityId){ List<County> list = new ArrayList<>(); Cursor cursor = db.query("County",null,"city_id = ?",new String[]{String.valueOf(cityId)},null,null,null); if(cursor.moveToFirst()){ do{ County province = new County(); province.setId(cursor.getInt(cursor.getColumnIndex("id"))); province.setCountyName(cursor.getString(cursor.getColumnIndex("county_name"))); province.setCountyCode(cursor.getString(cursor.getColumnIndex("county_code"))); list.add(province); }while(cursor.moveToNext()); } return list; } }
apache-2.0
PkayJava/fintech
src/main/java/com/angkorteam/fintech/helper/RecurringHelper.java
327
package com.angkorteam.fintech.helper; import com.angkorteam.fintech.IMifos; import io.github.openunirest.http.JsonNode; public class RecurringHelper { public static JsonNode create(IMifos session, JsonNode object) { return Helper.performServerPost(session, "/api/v1/recurringdepositproducts", object); } }
apache-2.0
tduehr/cas
api/cas-server-core-api-configuration-model/src/main/java/org/apereo/cas/configuration/model/support/pac4j/saml/Pac4jSamlClientProperties.java
5882
package org.apereo.cas.configuration.model.support.pac4j.saml; import org.apereo.cas.configuration.model.support.pac4j.Pac4jBaseClientProperties; import org.apereo.cas.configuration.support.RequiredProperty; import org.apereo.cas.configuration.support.RequiresModule; import lombok.Getter; import lombok.Setter; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * This is {@link Pac4jSamlClientProperties}. * * @author Misagh Moayyed * @since 5.2.0 */ @RequiresModule(name = "cas-server-support-pac4j-webflow") @Getter @Setter public class Pac4jSamlClientProperties extends Pac4jBaseClientProperties { private static final long serialVersionUID = -862819796533384951L; /** * The destination binding to use * when creating authentication requests. */ private String destinationBinding = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"; /** * The password to use when generating the SP/CAS keystore. */ @RequiredProperty private String keystorePassword; /** * The password to use when generating the private key for the SP/CAS keystore. */ @RequiredProperty private String privateKeyPassword; /** * Location of the keystore to use and generate the SP/CAS keystore. */ @RequiredProperty private String keystorePath; /** * The metadata location of the identity provider that is to handle authentications. */ @RequiredProperty private String identityProviderMetadataPath; /** * Once you have an authenticated session on the identity provider, usually it won't prompt you again to enter your * credentials and it will automatically generate a new assertion for you. By default, the SAML client * will accept assertions based on a previous authentication for one hour. * You can adjust this behavior by modifying this setting. The unit of time here is seconds. */ private int maximumAuthenticationLifetime = 600; /** * The entity id of the SP/CAS that is used in the SP metadata generation process. */ @RequiredProperty private String serviceProviderEntityId; /** * Location of the SP metadata to use and generate. */ @RequiredProperty private String serviceProviderMetadataPath; /** * Whether authentication requests should be tagged as forced auth. */ private boolean forceAuth; /** * Whether authentication requests should be tagged as passive. */ private boolean passive; /** * Requested authentication context class in authn requests. */ private String authnContextClassRef; /** * Specifies the comparison rule that should be used to evaluate the specified authentication methods. * For example, if exact is specified, the authentication method used must match one of the authentication * methods specified by the AuthnContextClassRef elements. * AuthContextClassRef element require comparison rule to be used to evaluate the specified * authentication methods. If not explicitly specified "exact" rule will be used by default. * Other acceptable values are minimum, maximum, better. */ private String authnContextComparisonType = "exact"; /** * The key alias used in the keystore. */ private String keystoreAlias; /** * NameID policy to request in the authentication requests. */ private String nameIdPolicyFormat; /** * Whether metadata should be marked to request sign assertions. */ private boolean wantsAssertionsSigned; /** * AttributeConsumingServiceIndex attribute of AuthnRequest element. * The given index points out a specific AttributeConsumingService structure, declared into the * Service Provider (SP)'s metadata, to be used to specify all the attributes that the Service Provider * is asking to be released within the authentication assertion returned by the Identity Provider (IdP). * This attribute won't be sent with the request unless a positive value (including 0) is defined. */ private int attributeConsumingServiceIndex; /** * Allows the SAML client to select a specific ACS url from the metadata, if defined. * A negative value de-activates the selection process and is the default. */ private int assertionConsumerServiceIndex = -1; /** * Whether name qualifiers should be produced * in the final saml response. */ private boolean useNameQualifier = true; /** * The attribute found in the saml response * that may be used to establish the authenticated * user and build a profile for CAS. */ private String principalIdAttribute; /** * Whether or not SAML SP metadata should be signed when generated. */ private boolean signServiceProviderMetadata; /** * List of attributes requested by the service provider * that would be put into the service provider metadata. */ private List<ServiceProviderRequestedAttribute> requestedAttributes = new ArrayList<>(); @RequiresModule(name = "cas-server-support-pac4j-webflow") @Getter @Setter public static class ServiceProviderRequestedAttribute implements Serializable { private static final long serialVersionUID = -862819796533384951L; /** * Attribute name. */ private String name; /** * Attribute friendly name. */ private String friendlyName; /** * Attribute name format. */ private String nameFormat = "urn:oasis:names:tc:SAML:2.0:attrname-format:uri"; /** * Whether this attribute is required and should * be marked so in the metadata. */ private boolean required; } }
apache-2.0
remibergsma/cosmic
cosmic-core/nucleo/src/main/java/com/cloud/agent/api/PingRoutingCommand.java
1059
package com.cloud.agent.api; import com.cloud.host.Host; import java.util.Map; public class PingRoutingCommand extends PingCommand { Map<String, HostVmStateReportEntry> _hostVmStateReport; boolean _gatewayAccessible = true; boolean _vnetAccessible = true; protected PingRoutingCommand() { } public PingRoutingCommand(final Host.Type type, final long id, final Map<String, HostVmStateReportEntry> hostVmStateReport) { super(type, id); this._hostVmStateReport = hostVmStateReport; } public Map<String, HostVmStateReportEntry> getHostVmStateReport() { return this._hostVmStateReport; } public boolean isGatewayAccessible() { return _gatewayAccessible; } public void setGatewayAccessible(final boolean gatewayAccessible) { _gatewayAccessible = gatewayAccessible; } public boolean isVnetAccessible() { return _vnetAccessible; } public void setVnetAccessible(final boolean vnetAccessible) { _vnetAccessible = vnetAccessible; } }
apache-2.0
emmaviento/training_java_for_testing
addressbook-web-tests/src/test/java/ru/test/addressbook/tests/HbConnectionTest.java
1618
package ru.test.addressbook.tests; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import ru.test.addressbook.model.ContactData; import java.util.List; /** * Created by Александра Гудкина on 21.05.2016. */ public class HbConnectionTest { private SessionFactory sessionFactory; @BeforeClass protected void setUp() throws Exception{ final StandardServiceRegistry registry = new StandardServiceRegistryBuilder() .configure() // configures settings from hibernate.cfg.xml .build(); try { sessionFactory = new MetadataSources( registry ).buildMetadata().buildSessionFactory(); } catch (Exception e) { e.printStackTrace(); StandardServiceRegistryBuilder.destroy( registry ); } } @Test public void testHibernateConnection(){ Session session = sessionFactory.openSession(); session.beginTransaction(); List<ContactData> result = session.createQuery("from ContactData where deprecated='0000-00-00'").list(); for (ContactData contact : result){ System.out.println(contact); System.out.println(contact.getGroups()); System.out.println(contact.getGroups().size()); } session.getTransaction().commit(); session.close(); } }
apache-2.0
openengsb-labs/labs-liquibase
extender/src/main/java/org/openengsb/labs/liquibase/extender/internal/LiquibaseMigrationCenterConfiguration.java
1187
/** * Licensed to the Austrian Association for Software Tool Integration (AASTI) * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. The AASTI 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.openengsb.labs.liquibase.extender.internal; import org.openengsb.labs.liquibase.extender.DatabaseMigrationException; public interface LiquibaseMigrationCenterConfiguration { void register(Long bundleId, DatabaseMigrationBundle databaseMigrationBundle) throws DatabaseMigrationException; void cancelBundleRegistration(Long bundleId); }
apache-2.0
GIP-RECIA/cas
api/cas-server-core-api-configuration-model/src/main/java/org/apereo/cas/configuration/model/support/dynamodb/AbstractDynamoDbProperties.java
1260
package org.apereo.cas.configuration.model.support.dynamodb; import org.apereo.cas.configuration.model.support.aws.BaseAmazonWebServicesProperties; import lombok.Getter; import lombok.Setter; /** * This is {@link AbstractDynamoDbProperties}. * * @author Misagh Moayyed * @since 5.1.0 */ @Getter @Setter public abstract class AbstractDynamoDbProperties extends BaseAmazonWebServicesProperties { private static final long serialVersionUID = -8349917272283787550L; /** * Flag that indicates whether to drop tables on start up. */ private boolean dropTablesOnStartup; /** * Flag that indicates whether to prevent CAS from creating tables. */ private boolean preventTableCreationOnStartup; /** * Time offset. */ private int timeOffset; /** * Read capacity. */ private long readCapacity = 10; /** * Write capacity. */ private long writeCapacity = 10; /** * Indicates that the database instance is local to the deployment * that does not require or use any credentials or other configuration * other than host and region. This is mostly used during development * and testing. */ private boolean localInstance; }
apache-2.0
markkerzner/nn_kove
hadoop/src/hdfs/org/apache/hadoop/hdfs/server/namenode/mapdb/AsyncWriteEngine.java
19355
/* * Copyright (c) 2012 Jan Kotek * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hdfs.server.namenode.mapdb; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.LockSupport; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.apache.hadoop.hdfs.server.namenode.SerializerPojo; /** * {@link Engine} wrapper which provides asynchronous serialization and asynchronous write. * This class takes an object instance, passes it to background writer thread (using Write Cache) * where it is serialized and written to disk. Async write does not affect commit durability, * write cache is flushed into disk on each commit. Modified records are held in small instance cache, * until they are written into disk. * * This feature is enabled by default and can be disabled by calling {@link DBMaker#asyncWriteDisable()}. * Write Cache is flushed in regular intervals or when it becomes full. Flush interval is 100 ms by default and * can be controlled by {@link DBMaker#asyncFlushDelay(int)}. Increasing this interval may improve performance * in scenarios where frequently modified items should be cached, typically {@link BTreeMap} import where keys * are presorted. * * Asynchronous write does not affect commit durability. Write Cache is flushed during each commit, rollback and close call. * You may also flush Write Cache manually by using {@link org.mapdb.AsyncWriteEngine#clearCache()} method. * There is global lock which prevents record being updated while commit is in progress. * * This wrapper starts one threads named `MapDB writer #N` (where N is static counter). * Async Writer takes modified records from Write Cache and writes them into store. * It also preallocates new recids, as finding empty `recids` takes time so small stash is pre-allocated. * It runs as `daemon`, so it does not prevent JVM to exit. * * Asynchronous Writes have several advantages (especially for single threaded user). But there are two things * user should be aware of: * * * Because data are serialized on back-ground thread, they need to be thread safe or better immutable. * When you insert record into MapDB and modify it latter, this modification may happen before item * was serialized and you may not be sure what version was persisted * * * Asynchronous writes have some overhead and introduce single bottle-neck. This usually not issue for * single or two threads, but in multi-threaded environment it may decrease performance. * So in truly concurrent environments with many updates (network servers, parallel computing ) * you should disable Asynchronous Writes. * * * @see Engine * @see EngineWrapper * * @author Jan Kotek * * * */ public class AsyncWriteEngine extends EngineWrapper implements Engine { /** ensures thread name is followed by number */ protected static final AtomicLong threadCounter = new AtomicLong(); /** used to signal that object was deleted*/ protected static final Object TOMBSTONE = new Object(); /** Queue of pre-allocated `recids`. Filled by `MapDB Writer` thread * and consumed by {@link AsyncWriteEngine#put(Object, Serializer)} method */ protected final ArrayBlockingQueue<Long> newRecids = new ArrayBlockingQueue<Long>(CC.ASYNC_RECID_PREALLOC_QUEUE_SIZE); /** Associates `recid` from Write Queue with record data and serializer. */ protected final LongConcurrentHashMap<Fun.Tuple2<Object, Serializer>> writeCache = new LongConcurrentHashMap<Fun.Tuple2<Object, Serializer>>(); /** Each insert to Write Queue must hold read lock. * Commit, rollback and close operations must hold write lock */ protected final ReentrantReadWriteLock commitLock = new ReentrantReadWriteLock(); /** number of active threads running, used to await thread termination on close */ protected final CountDownLatch activeThreadsCount = new CountDownLatch(1); /** If background thread fails with exception, it is stored here, and rethrown to all callers.*/ protected volatile Throwable threadFailedException = null; /** indicates that `close()` was called and background threads are being terminated*/ protected volatile boolean closeInProgress = false; /** flush Write Queue every N milliseconds */ protected final int asyncFlushDelay; protected final AtomicReference<CountDownLatch> action = new AtomicReference<CountDownLatch>(null); /** * Construct new class and starts background threads. * User may provide executor in which background tasks will be executed, * otherwise MapDB starts two daemon threads. * * @param engine which stores data. * @param _asyncFlushDelay flush Write Queue every N milliseconds * @param executor optional executor to run tasks. If null daemon threads will be created */ public AsyncWriteEngine(Engine engine, int _asyncFlushDelay,Executor executor) { super(engine); this.asyncFlushDelay = _asyncFlushDelay; startThreads(executor); } public AsyncWriteEngine(Engine engine) { this(engine, CC.ASYNC_WRITE_FLUSH_DELAY, null); } /** * Starts background threads. * You may override this if you wish to start thread different way * * @param executor optional executor to run tasks, if null deamon threads will be created */ protected void startThreads(Executor executor) { //TODO background threads should exit, when `AsyncWriteEngine` was garbage-collected final Runnable writerRun = new Runnable(){ @Override public void run() { runWriter(); } }; if(executor!=null){ executor.execute(writerRun); return; } final long threadNum = threadCounter.incrementAndGet(); Thread writerThread = new Thread(writerRun,"MapDB writer #"+threadNum); writerThread.setDaemon(true); writerThread.start(); } /** runs on background thread. Takes records from Write Queue, serializes and writes them.*/ protected void runWriter() { try{ for(;;){ if(threadFailedException !=null) return; //other thread has failed, no reason to continue //if conditions are right, slow down writes a bit if(asyncFlushDelay!=0 ){ LockSupport.parkNanos(1000L * 1000L * asyncFlushDelay); } final CountDownLatch latch = action.getAndSet(null); do{ LongMap.LongMapIterator<Fun.Tuple2<Object, Serializer>> iter = writeCache.longMapIterator(); while(iter.moveToNext()){ //usual write final long recid = iter.key(); Fun.Tuple2<Object, Serializer> item = iter.value(); if(item == null) continue; //item was already written if(item.a==TOMBSTONE){ //item was not updated, but deleted AsyncWriteEngine.super.delete(recid, item.b); }else{ //call update as usual AsyncWriteEngine.super.update(recid, item.a, item.b); } //record has been written to underlying Engine, so remove it from cache with CAS writeCache.remove(recid, item); } }while(latch!=null && !writeCache.isEmpty()); runWritePrealloc(); //TODO call it more frequently //operations such as commit,close, compact or close needs to be executed in Writer Thread //for this case CountDownLatch is used, it also signals when operations has been completed //CountDownLatch is used as special case to signalise special operation if(latch!=null){ if(!writeCache.isEmpty()) throw new InternalError(); final long count = latch.getCount(); if(count == 0){ //close operation return; }else if(count == 1){ //commit operation AsyncWriteEngine.super.commit(); latch.countDown(); }else if(count==2){ //rollback operation AsyncWriteEngine.super.rollback(); newRecids.clear(); latch.countDown(); latch.countDown(); }else if(count==3){ //compact operation AsyncWriteEngine.super.compact(); latch.countDown(); latch.countDown(); latch.countDown(); }else{throw new InternalError();} } } } catch (Throwable e) { e.printStackTrace(); System.out.println("ERROR --> " + e.getMessage()); threadFailedException = e; }finally { activeThreadsCount.countDown(); } } protected void runWritePrealloc() throws InterruptedException { final int capacity = newRecids.remainingCapacity(); for(int i=0;i<capacity;i++){ Long newRecid = getWrappedEngine().put(Utils.EMPTY_STRING, Serializer.EMPTY_SERIALIZER); if(!newRecids.offer(newRecid)){ getWrappedEngine().delete(newRecid,Serializer.EMPTY_SERIALIZER); return; } } } /** checks that background threads are ready and throws exception if not */ protected void checkState() { if(closeInProgress) throw new IllegalAccessError("db has been closed"); if(threadFailedException !=null) throw new RuntimeException("Writer thread failed", threadFailedException); } /** * {@inheritDoc} * * Recids are managed by underlying Engine. Finding free or allocating new recids * may take some time, so for this reason recids are preallocated by Writer Thread * and stored in queue. This method just takes preallocated recid from queue with minimal * delay. * * Newly inserted records are not written synchronously, but forwarded to background Writer Thread via queue. * * ![async-put](async-put.png) * @uml async-put.png actor user participant "put method" as put participant "Writer Thread" as wri note over wri: has preallocated \n recids in queue activate put user -> put: User calls put method wri-> put: takes preallocated recid put -> wri: forward record into Write Queue put -> user: return recid to user deactivate put note over wri: eventually\n writes record\n before commit */ @Override public <A> long put(A value, Serializer<A> serializer) { commitLock.readLock().lock(); try{ Long recid = newRecids.poll(); if(recid==null) recid = super.put(Utils.EMPTY_STRING, Serializer.EMPTY_SERIALIZER); update(recid, value, serializer); return recid; }finally{ commitLock.readLock().unlock(); } } /** * {@inheritDoc} * * This method first looks up into Write Cache if record is not currently being written. * If not it continues as usually * * */ @Override public <A> A get(long recid, Serializer<A> serializer) { commitLock.readLock().lock(); try{ checkState(); Fun.Tuple2<Object,Serializer> item = writeCache.get(recid); if(item!=null){ if(item.a == TOMBSTONE) return null; return (A) item.a; } return super.get(recid, serializer); }finally{ commitLock.readLock().unlock(); } } /** * {@inheritDoc} * * This methods forwards record into Writer Thread and returns asynchronously. * * ![async-update](async-update.png) * @uml async-update.png * actor user * participant "update method" as upd * participant "Writer Thread" as wri * activate upd * user -> upd: User calls update method * upd -> wri: forward record into Write Queue * upd -> user: returns * deactivate upd * note over wri: eventually\n writes record\n before commit */ @Override public <A> void update(long recid, A value, Serializer<A> serializer) { if(serializer!=SerializerPojo.serializer) commitLock.readLock().lock(); try{ checkState(); writeCache.put(recid, new Fun.Tuple2(value, serializer)); }finally{ if(serializer!=SerializerPojo.serializer) commitLock.readLock().unlock(); } } /** * {@inheritDoc} * * This method first looks up Write Cache if record is not currently being written. * Successful modifications are forwarded to Write Thread and method returns asynchronously. * Asynchronicity does not affect atomicity. */ @Override public <A> boolean compareAndSwap(long recid, A expectedOldValue, A newValue, Serializer<A> serializer) { commitLock.writeLock().lock(); try{ checkState(); Fun.Tuple2<Object, Serializer> existing = writeCache.get(recid); A oldValue = existing!=null? (A) existing.a : super.get(recid, serializer); if(oldValue == expectedOldValue || (oldValue!=null && oldValue.equals(expectedOldValue))){ writeCache.put(recid, new Fun.Tuple2(newValue, serializer)); return true; }else{ return false; } }finally{ commitLock.writeLock().unlock(); } } /** * {@inheritDoc} * * This method places 'tombstone' into Write Queue so record is eventually * deleted asynchronously. However record is visible as deleted immediately. */ @Override public <A> void delete(long recid, Serializer<A> serializer) { update(recid, (A) TOMBSTONE, serializer); } /** * {@inheritDoc} * * This method blocks until Write Queue is flushed and Writer Thread writes all records and finishes. * When this method was called `closeInProgress` is set and no record can be modified. */ @Override public void close() { commitLock.writeLock().lock(); try { if(closeInProgress) return; checkState(); closeInProgress = true; //notify background threads if(!action.compareAndSet(null,new CountDownLatch(0)))throw new InternalError(); //wait for background threads to shutdown activeThreadsCount.await(); //put preallocated recids back to store for(Long recid = newRecids.poll(); recid!=null; recid = newRecids.poll()){ super.delete(recid, Serializer.EMPTY_SERIALIZER); } AsyncWriteEngine.super.close(); } catch (InterruptedException e) { throw new RuntimeException(e); }finally { commitLock.writeLock().unlock(); } } /** * {@inheritDoc} * * This method blocks until Write Queue is flushed. * All put/update/delete methods are blocked while commit is in progress (via global ReadWrite Commit Lock). * After this method returns, commit lock is released and other operations may continue */ @Override public void commit() { commitLock.writeLock().lock(); try{ checkState(); //notify background threads CountDownLatch msg = new CountDownLatch(1); if(!action.compareAndSet(null,msg))throw new InternalError(); //wait for response from writer thread while(!msg.await(1,TimeUnit.SECONDS)){ checkState(); } } catch (InterruptedException e) { throw new RuntimeException(e); }finally { commitLock.writeLock().unlock(); } } /** * {@inheritDoc} * * This method blocks until Write Queue is cleared. * All put/update/delete methods are blocked while rollback is in progress (via global ReadWrite Commit Lock). * After this method returns, commit lock is released and other operations may continue */ @Override public void rollback() { commitLock.writeLock().lock(); try{ checkState(); //notify background threads CountDownLatch msg = new CountDownLatch(2); if(!action.compareAndSet(null,msg))throw new InternalError(); //wait for response from writer thread while(!msg.await(1,TimeUnit.SECONDS)){ checkState(); } } catch (InterruptedException e) { throw new RuntimeException(e); }finally { commitLock.writeLock().unlock(); } } /** * {@inheritDoc} * * This method blocks all put/update/delete operations until it finishes (via global ReadWrite Commit Lock). * */ @Override public void compact() { commitLock.writeLock().lock(); try{ checkState(); //notify background threads CountDownLatch msg = new CountDownLatch(3); if(!action.compareAndSet(null,msg))throw new InternalError(); //wait for response from writer thread while(!msg.await(1,TimeUnit.SECONDS)){ checkState(); } } catch (InterruptedException e) { throw new RuntimeException(e); }finally { commitLock.writeLock().unlock(); } } /** * {@inheritDoc} * * This method blocks until Write Queue is empty (written into disk). * It also blocks any put/update/delete operations until it finishes (via global ReadWrite Commit Lock). */ @Override public void clearCache() { commitLock.writeLock().lock(); try{ checkState(); //wait for response from writer thread while(!writeCache.isEmpty()){ checkState(); Thread.sleep(250); } } catch (InterruptedException e) { throw new RuntimeException(e); }finally { commitLock.writeLock().unlock(); } super.clearCache(); } }
apache-2.0
apache/wss4j
ws-security-dom/src/test/java/org/apache/wss4j/dom/saml/SamlTokenHOKTest.java
11741
/** * 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.wss4j.dom.saml; import org.apache.wss4j.common.saml.SamlAssertionWrapper; import org.apache.wss4j.dom.WSConstants; import org.apache.wss4j.dom.common.KeystoreCallbackHandler; import org.apache.wss4j.dom.common.SAML1CallbackHandler; import org.apache.wss4j.dom.common.SAML2CallbackHandler; import org.apache.wss4j.dom.common.SOAPUtil; import org.apache.wss4j.dom.common.SecurityTestUtil; import org.apache.wss4j.dom.engine.WSSConfig; import org.apache.wss4j.dom.engine.WSSecurityEngine; import org.apache.wss4j.dom.engine.WSSecurityEngineResult; import org.apache.wss4j.dom.handler.RequestData; import org.apache.wss4j.dom.handler.WSHandlerResult; import org.apache.wss4j.common.crypto.Crypto; import org.apache.wss4j.common.crypto.CryptoFactory; import org.apache.wss4j.common.saml.SAMLCallback; import org.apache.wss4j.common.saml.SAMLUtil; import org.apache.wss4j.common.saml.builder.SAML1Constants; import org.apache.wss4j.common.saml.builder.SAML2Constants; import org.apache.wss4j.common.util.XMLUtils; import org.apache.wss4j.dom.message.WSSecHeader; import org.apache.wss4j.dom.message.WSSecSAMLToken; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Test; import org.w3c.dom.Document; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; /** * Test-case for sending and processing a signed (holder-of-key) SAML Assertion. These tests * just cover the case of creating and signing the Assertion, and not using the credential * information in the SAML Subject to sign the SOAP body. */ public class SamlTokenHOKTest { private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(SamlTokenHOKTest.class); private WSSecurityEngine secEngine = new WSSecurityEngine(); private Crypto crypto; @AfterAll public static void cleanup() throws Exception { SecurityTestUtil.cleanup(); } public SamlTokenHOKTest() throws Exception { WSSConfig config = WSSConfig.getNewInstance(); secEngine.setWssConfig(config); crypto = CryptoFactory.getInstance("crypto.properties"); } /** * Test that creates, sends and processes a signed SAML 1.1 authentication assertion. */ @Test public void testSAML1AuthnAssertion() throws Exception { SAML1CallbackHandler callbackHandler = new SAML1CallbackHandler(); callbackHandler.setStatement(SAML1CallbackHandler.Statement.AUTHN); callbackHandler.setConfirmationMethod(SAML1Constants.CONF_HOLDER_KEY); callbackHandler.setIssuer("www.example.com"); SAMLCallback samlCallback = new SAMLCallback(); SAMLUtil.doSAMLCallback(callbackHandler, samlCallback); SamlAssertionWrapper samlAssertion = new SamlAssertionWrapper(samlCallback); samlAssertion.signAssertion("16c73ab6-b892-458f-abf5-2f875f74882e", "security", crypto, false); Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG); WSSecHeader secHeader = new WSSecHeader(doc); secHeader.insertSecurityHeader(); WSSecSAMLToken wsSign = new WSSecSAMLToken(secHeader); Document signedDoc = wsSign.build(samlAssertion); if (LOG.isDebugEnabled()) { LOG.debug("SAML 1.1 Authn Assertion (holder-of-key):"); String outputString = XMLUtils.prettyDocumentToString(signedDoc); LOG.debug(outputString); } WSHandlerResult results = verify(signedDoc); WSSecurityEngineResult actionResult = results.getActionResults().get(WSConstants.ST_SIGNED).get(0); SamlAssertionWrapper receivedSamlAssertion = (SamlAssertionWrapper) actionResult.get(WSSecurityEngineResult.TAG_SAML_ASSERTION); assertNotNull(receivedSamlAssertion); assertTrue(receivedSamlAssertion.isSigned()); assertNotNull(receivedSamlAssertion.assertionToString()); } /** * Test that creates, sends and processes a signed SAML 1.1 attribute assertion. */ @Test public void testSAML1AttrAssertion() throws Exception { SAML1CallbackHandler callbackHandler = new SAML1CallbackHandler(); callbackHandler.setStatement(SAML1CallbackHandler.Statement.ATTR); callbackHandler.setConfirmationMethod(SAML1Constants.CONF_HOLDER_KEY); callbackHandler.setIssuer("www.example.com"); SAMLCallback samlCallback = new SAMLCallback(); SAMLUtil.doSAMLCallback(callbackHandler, samlCallback); SamlAssertionWrapper samlAssertion = new SamlAssertionWrapper(samlCallback); samlAssertion.signAssertion("16c73ab6-b892-458f-abf5-2f875f74882e", "security", crypto, false); Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG); WSSecHeader secHeader = new WSSecHeader(doc); secHeader.insertSecurityHeader(); WSSecSAMLToken wsSign = new WSSecSAMLToken(secHeader); Document signedDoc = wsSign.build(samlAssertion); if (LOG.isDebugEnabled()) { LOG.debug("SAML 1.1 Attr Assertion (holder-of-key):"); String outputString = XMLUtils.prettyDocumentToString(signedDoc); LOG.debug(outputString); } RequestData requestData = new RequestData(); requestData.setValidateSamlSubjectConfirmation(false); requestData.setCallbackHandler(new KeystoreCallbackHandler()); Crypto decCrypto = CryptoFactory.getInstance("wss40.properties"); requestData.setDecCrypto(decCrypto); requestData.setSigVerCrypto(crypto); WSHandlerResult results = secEngine.processSecurityHeader(doc, requestData); String outputString = XMLUtils.prettyDocumentToString(doc); assertTrue(outputString.indexOf("counter_port_type") > 0 ? true : false); WSSecurityEngineResult actionResult = results.getActionResults().get(WSConstants.ST_SIGNED).get(0); SamlAssertionWrapper receivedSamlAssertion = (SamlAssertionWrapper) actionResult.get(WSSecurityEngineResult.TAG_SAML_ASSERTION); assertNotNull(receivedSamlAssertion); assertTrue(receivedSamlAssertion.isSigned()); } /** * Test that creates, sends and processes an unsigned SAML 2 authentication assertion. */ @Test public void testSAML2AuthnAssertion() throws Exception { SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler(); callbackHandler.setStatement(SAML2CallbackHandler.Statement.AUTHN); callbackHandler.setConfirmationMethod(SAML2Constants.CONF_HOLDER_KEY); callbackHandler.setIssuer("www.example.com"); SAMLCallback samlCallback = new SAMLCallback(); SAMLUtil.doSAMLCallback(callbackHandler, samlCallback); SamlAssertionWrapper samlAssertion = new SamlAssertionWrapper(samlCallback); samlAssertion.signAssertion("16c73ab6-b892-458f-abf5-2f875f74882e", "security", crypto, false); Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG); WSSecHeader secHeader = new WSSecHeader(doc); secHeader.insertSecurityHeader(); WSSecSAMLToken wsSign = new WSSecSAMLToken(secHeader); Document unsignedDoc = wsSign.build(samlAssertion); if (LOG.isDebugEnabled()) { LOG.debug("SAML 2 Authn Assertion (holder-of-key):"); String outputString = XMLUtils.prettyDocumentToString(unsignedDoc); LOG.debug(outputString); } WSHandlerResult results = verify(unsignedDoc); WSSecurityEngineResult actionResult = results.getActionResults().get(WSConstants.ST_SIGNED).get(0); SamlAssertionWrapper receivedSamlAssertion = (SamlAssertionWrapper) actionResult.get(WSSecurityEngineResult.TAG_SAML_ASSERTION); assertNotNull(receivedSamlAssertion); assertTrue(receivedSamlAssertion.isSigned()); } /** * Test that creates, sends and processes an unsigned SAML 2 attribute assertion. */ @Test public void testSAML2AttrAssertion() throws Exception { SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler(); callbackHandler.setStatement(SAML2CallbackHandler.Statement.ATTR); callbackHandler.setConfirmationMethod(SAML2Constants.CONF_HOLDER_KEY); callbackHandler.setIssuer("www.example.com"); SAMLCallback samlCallback = new SAMLCallback(); SAMLUtil.doSAMLCallback(callbackHandler, samlCallback); SamlAssertionWrapper samlAssertion = new SamlAssertionWrapper(samlCallback); samlAssertion.signAssertion("16c73ab6-b892-458f-abf5-2f875f74882e", "security", crypto, false); Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG); WSSecHeader secHeader = new WSSecHeader(doc); secHeader.insertSecurityHeader(); WSSecSAMLToken wsSign = new WSSecSAMLToken(secHeader); Document unsignedDoc = wsSign.build(samlAssertion); if (LOG.isDebugEnabled()) { LOG.debug("SAML 2 Attr Assertion (holder-of-key):"); String outputString = XMLUtils.prettyDocumentToString(unsignedDoc); LOG.debug(outputString); } RequestData requestData = new RequestData(); requestData.setValidateSamlSubjectConfirmation(false); requestData.setCallbackHandler(new KeystoreCallbackHandler()); Crypto decCrypto = CryptoFactory.getInstance("wss40.properties"); requestData.setDecCrypto(decCrypto); requestData.setSigVerCrypto(crypto); WSHandlerResult results = secEngine.processSecurityHeader(doc, requestData); String outputString = XMLUtils.prettyDocumentToString(doc); assertTrue(outputString.indexOf("counter_port_type") > 0 ? true : false); WSSecurityEngineResult actionResult = results.getActionResults().get(WSConstants.ST_SIGNED).get(0); SamlAssertionWrapper receivedSamlAssertion = (SamlAssertionWrapper) actionResult.get(WSSecurityEngineResult.TAG_SAML_ASSERTION); assertNotNull(receivedSamlAssertion); } /** * Verifies the soap envelope * <p/> * * @param envelope * @throws Exception Thrown when there is a problem in verification */ private WSHandlerResult verify(Document doc) throws Exception { RequestData requestData = new RequestData(); requestData.setDecCrypto(crypto); requestData.setSigVerCrypto(crypto); requestData.setValidateSamlSubjectConfirmation(false); WSHandlerResult results = secEngine.processSecurityHeader(doc, requestData); String outputString = XMLUtils.prettyDocumentToString(doc); assertTrue(outputString.indexOf("counter_port_type") > 0 ? true : false); return results; } }
apache-2.0
neykov/incubator-brooklyn
software/webapp/src/test/java/brooklyn/entity/webapp/jboss/Jboss7DockerLiveTest.java
2720
/* * 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 brooklyn.entity.webapp.jboss; import brooklyn.entity.proxying.EntitySpec; import brooklyn.entity.software.AbstractDockerLiveTest; import brooklyn.location.Location; import brooklyn.test.Asserts; import brooklyn.test.HttpTestUtils; import com.google.common.collect.ImmutableList; import org.testng.annotations.Test; import java.net.URL; import static com.google.common.base.Preconditions.checkNotNull; import static org.testng.Assert.assertNotNull; /** * A simple test of installing+running on Docker, using various OS distros and versions. */ public class Jboss7DockerLiveTest extends AbstractDockerLiveTest { private URL warUrl = checkNotNull(getClass().getClassLoader().getResource("hello-world.war")); @Override protected void doTest(Location loc) throws Exception { final JBoss7Server server = app.createAndManageChild(EntitySpec.create(JBoss7Server.class) .configure("war", warUrl.toString())); app.start(ImmutableList.of(loc)); String url = server.getAttribute(JBoss7Server.ROOT_URL); HttpTestUtils.assertHttpStatusCodeEventuallyEquals(url, 200); HttpTestUtils.assertContentContainsText(url, "Hello"); Asserts.succeedsEventually(new Runnable() { @Override public void run() { assertNotNull(server.getAttribute(JBoss7Server.REQUEST_COUNT)); assertNotNull(server.getAttribute(JBoss7Server.ERROR_COUNT)); assertNotNull(server.getAttribute(JBoss7Server.TOTAL_PROCESSING_TIME)); assertNotNull(server.getAttribute(JBoss7Server.MAX_PROCESSING_TIME)); assertNotNull(server.getAttribute(JBoss7Server.BYTES_RECEIVED)); assertNotNull(server.getAttribute(JBoss7Server.BYTES_SENT)); } }); } @Test(enabled = false) public void testDummy() { } // Convince testng IDE integration that this really does have test methods }
apache-2.0
maddingo/sojo
src/test/java/test/net/sf/sojo/model/TestExceptionWithBadConstructor.java
1065
/* * Copyright 2002-2005 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package test.net.sf.sojo.model; import java.math.BigDecimal; public class TestExceptionWithBadConstructor extends Exception { private static final long serialVersionUID = 3228299026937206814L; private BigDecimal bigDecimal = null; public TestExceptionWithBadConstructor(BigDecimal pvBigDecimal) { this.bigDecimal = pvBigDecimal; } public BigDecimal getBigDecimal() { return bigDecimal; } }
apache-2.0
McLeodMoores/starling
projects/integration-rest-client/src/main/java/com/opengamma/integration/tool/depgraphambiguity/FindViewAmbiguities.java
15589
/** * Copyright (C) 2013 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.integration.tool.depgraphambiguity; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.fudgemsg.FudgeMsg; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import com.opengamma.OpenGammaRuntimeException; import com.opengamma.component.ComponentRepository; import com.opengamma.component.factory.engine.RemoteEngineContextsComponentFactory; import com.opengamma.component.tool.AbstractTool; import com.opengamma.core.config.impl.ConfigItem; import com.opengamma.engine.depgraph.ambiguity.FullRequirementResolution; import com.opengamma.engine.depgraph.ambiguity.FullRequirementResolutionPrinter; import com.opengamma.engine.depgraph.ambiguity.RequirementResolution; import com.opengamma.engine.depgraph.ambiguity.ViewDefinitionAmbiguityTest; import com.opengamma.engine.function.CachingFunctionRepositoryCompiler; import com.opengamma.engine.function.CompiledFunctionDefinition; import com.opengamma.engine.function.CompiledFunctionService; import com.opengamma.engine.function.FunctionCompilationContext; import com.opengamma.engine.function.config.FunctionConfigurationSource; import com.opengamma.engine.function.exclusion.FunctionExclusionGroups; import com.opengamma.engine.function.resolver.DefaultFunctionResolver; import com.opengamma.engine.function.resolver.FunctionPriority; import com.opengamma.engine.function.resolver.FunctionResolver; import com.opengamma.engine.value.ValueSpecification; import com.opengamma.engine.view.ViewDefinition; import com.opengamma.financial.function.rest.RemoteFunctionConfigurationSource; import com.opengamma.financial.tool.ToolContext; import com.opengamma.id.VersionCorrection; import com.opengamma.scripts.Scriptable; import com.opengamma.transport.jaxrs.UriEndPointDescriptionProvider; import com.opengamma.util.ClassUtils; /** * Tool class that compiles a view against a function repository to identify any ambiguities. * <p> * The configuration is fetched from the server, but the function exclusion groups and priorities must be specified manually as these are not readily available * via REST interfaces (at the moment - there is no reason why the data couldn't be available). Any ambiguities are written to a nominated output file. * <p> * Note that this can be an expensive operation - very expensive if there are multiple deep ambiguities which will cause an incredibly large number of possible * terminal output resolutions (based on the cross product of all possible inputs). It is normally only necessary to run on small portfolio samples, for example * by setting the system property <code>SimplePortfolioNode.debugFlag</code> to <code>TRUE</code>. */ @Scriptable public class FindViewAmbiguities extends AbstractTool<ToolContext> { /** Logger */ private static final Logger LOGGER = LoggerFactory.getLogger(FindViewAmbiguities.class); private static final String VIEW_NAME_OPTION = "v"; private static final String VIEW_NAME_OPTION_LONG = "view"; // -xg com.opengamma.web.spring.DemoFunctionExclusionGroupsFactoryBean private static final String EXCLUSION_GROUPS_OPTION = "xg"; private static final String EXCLUSION_GROUPS_OPTION_LONG = "exclusionGroups"; // -fp com.opengamma.web.spring.DemoFunctionResolverFactoryBean$Priority private static final String FUNCTION_PRIORITY_OPTION = "fp"; private static final String FUNCTION_PRIOTITY_OPTION_LONG = "functionPriority"; private static final String OUTPUT_OPTION = "o"; private static final String OUTPUT_OPTION_LONG = "output"; private static final String VERBOSE_OPTION = "f"; private static final String VERBOSE_OPTION_LONG = "full"; private final AtomicInteger _resolutions = new AtomicInteger(); private final AtomicInteger _ambiguities = new AtomicInteger(); // ------------------------------------------------------------------------- /** * Main method to run the tool. * * @param args * the standard tool arguments, not null */ public static void main(final String[] args) { // CSIGNORE new FindViewAmbiguities().invokeAndTerminate(args); } // ------------------------------------------------------------------------- private final class ViewDefinitionAmbiguityTestImpl extends ViewDefinitionAmbiguityTest { private final PrintStream _out; private FunctionResolver _functionResolver; ViewDefinitionAmbiguityTestImpl(final PrintStream out) { _out = out; } @Override protected FunctionCompilationContext createFunctionCompilationContext() { final ComponentRepository repo = (ComponentRepository) getToolContext().getContextManager(); return repo.getInstance(FunctionCompilationContext.class, "main"); } protected FunctionPriority createFunctionPrioritizer() { // TODO: The prioritizer could be exposed over the network (sending the function identifier) and cached final String functionPriorities = getCommandLine().getOptionValue(FUNCTION_PRIORITY_OPTION); if (functionPriorities != null) { try { final Class<?> functionPrioritiesClass = ClassUtils.loadClass(functionPriorities); Object prioritiesObject = functionPrioritiesClass.newInstance(); if (prioritiesObject instanceof InitializingBean) { ((InitializingBean) prioritiesObject).afterPropertiesSet(); } if (prioritiesObject instanceof FactoryBean) { prioritiesObject = ((FactoryBean<?>) prioritiesObject).getObject(); } if (prioritiesObject instanceof FunctionPriority) { return (FunctionPriority) prioritiesObject; } } catch (final Exception e) { throw new OpenGammaRuntimeException("Error loading function priorities", e); } } return new FunctionPriority() { @Override public int getPriority(final CompiledFunctionDefinition function) { return 0; } }; } @Override protected FunctionResolver createFunctionResolver() { if (_functionResolver == null) { final FunctionCompilationContext context = createFunctionCompilationContext(); final FudgeMsg configMsg = RemoteEngineContextsComponentFactory.getConfiguration(context); final URI configUri = RemoteEngineContextsComponentFactory.getConfigurationUri(context); final URI functionsUri; final ExecutorService executor = Executors.newCachedThreadPool(); try { functionsUri = UriEndPointDescriptionProvider.getAccessibleURI(executor, configUri, configMsg.getMessage("functionRepositoryConfiguration")); } finally { executor.shutdown(); } LOGGER.debug("Fetching remote functions from {}", functionsUri); final FunctionConfigurationSource functions = new RemoteFunctionConfigurationSource(functionsUri); final CompiledFunctionService compiledFunctionService = new CompiledFunctionService(functions, new CachingFunctionRepositoryCompiler(), context); compiledFunctionService.initialize(); _functionResolver = new DefaultFunctionResolver(compiledFunctionService, createFunctionPrioritizer()); } return _functionResolver; } @Override protected FunctionExclusionGroups createFunctionExclusionGroups() { // TODO: The exclusion groups could be exposed over the network (sending the function identifier) and cached final String exclusionGroups = getCommandLine().getOptionValue(EXCLUSION_GROUPS_OPTION); if (exclusionGroups != null) { try { final Class<?> exclusionGroupsClass = ClassUtils.loadClass(exclusionGroups); Object groupsObject = exclusionGroupsClass.newInstance(); if (groupsObject instanceof InitializingBean) { ((InitializingBean) groupsObject).afterPropertiesSet(); } if (groupsObject instanceof FactoryBean) { groupsObject = ((FactoryBean<?>) groupsObject).getObject(); } if (groupsObject instanceof FunctionExclusionGroups) { return (FunctionExclusionGroups) groupsObject; } throw new IllegalArgumentException("Couldn't set exclusion groups to " + exclusionGroups + " (got " + groupsObject + ")"); } catch (final Exception e) { throw new OpenGammaRuntimeException("Error loading exclusion groups", e); } } return null; } @Override protected void resolved(final FullRequirementResolution resolution) { resolvedImpl(resolution); final int count = _resolutions.incrementAndGet(); if (count % 100 == 0) { LOGGER.info("Checked {} resolutions", count); } if (resolution.isDeeplyAmbiguous() && getCommandLine().hasOption(VERBOSE_OPTION)) { synchronized (this) { new FullRequirementResolutionPrinter(_out).print(resolution); } } } protected void resolvedImpl(final FullRequirementResolution resolution) { super.resolved(resolution); } @Override protected synchronized void directAmbiguity(final FullRequirementResolution resolution) { final int count = _ambiguities.incrementAndGet(); if (count % 10 == 0) { LOGGER.info("Found {} ambiguities", count); } _out.println(resolution.getRequirement()); for (final Collection<RequirementResolution> nestedResolutions : resolution.getResolutions()) { final List<String> functions = new ArrayList<>(); final List<ValueSpecification> specifications = new ArrayList<>(); boolean failure = false; for (final RequirementResolution nestedResolution : nestedResolutions) { if (nestedResolution != null) { functions.add(nestedResolution.getFunction().getFunctionId()); specifications.add(nestedResolution.getSpecification()); } else { failure = true; } } for (final String function : functions) { _out.println("\t" + function); } if (failure) { _out.println("\t+ failure(s)"); } for (final ValueSpecification specification : specifications) { _out.println("\t" + specification); } _out.println(); } } @Override protected synchronized void deepAmbiguity(final FullRequirementResolution resolution) { for (final Collection<RequirementResolution> nestedResolutions : resolution.getResolutions()) { for (final RequirementResolution nestedResolution : nestedResolutions) { for (final FullRequirementResolution inputResolution : nestedResolution.getInputs()) { resolvedImpl(inputResolution); } } } _out.println(resolution.getRequirement()); for (final Collection<RequirementResolution> nestedResolutions : resolution.getResolutions()) { for (final RequirementResolution nestedResolution : nestedResolutions) { _out.println("\t" + nestedResolution.getSpecification()); } } _out.println(); } } private static Option createViewNameOption() { final Option option = new Option(VIEW_NAME_OPTION, VIEW_NAME_OPTION_LONG, true, "the view to check, omit to check all"); option.setArgName("view"); option.setRequired(false); return option; } private static Option createFunctionExclusionGroupsBeanOption() { final Option option = new Option(EXCLUSION_GROUPS_OPTION, EXCLUSION_GROUPS_OPTION_LONG, true, "the exclusion groups to use"); option.setArgName("class"); option.setRequired(false); return option; } private static Option createFunctionPrioritiesOption() { final Option option = new Option(FUNCTION_PRIORITY_OPTION, FUNCTION_PRIOTITY_OPTION_LONG, true, "the function prioritizer to use"); option.setArgName("class"); option.setRequired(false); return option; } private static Option createOutputOption() { final Option option = new Option(OUTPUT_OPTION, OUTPUT_OPTION_LONG, true, "the output file to write"); option.setArgName("filename"); option.setRequired(false); return option; } private static Option createVerboseOption() { final Option option = new Option(VERBOSE_OPTION, VERBOSE_OPTION_LONG, false, "whether to write out ambiguities in full"); option.setRequired(false); return option; } private static PrintStream openStream(final String filename) throws IOException { if (filename == null || "stdout".equals(filename)) { return System.out; } else if ("stderr".equals(filename)) { return System.err; } else { return new PrintStream(new FileOutputStream(filename)); } } // AbstractTool @Override protected void doRun() throws Exception { final PrintStream out = openStream(getCommandLine().getOptionValue(OUTPUT_OPTION)); final ViewDefinitionAmbiguityTest test = new ViewDefinitionAmbiguityTestImpl(out); final String viewName = getCommandLine().getOptionValue(VIEW_NAME_OPTION); int count = 0; if (viewName != null) { LOGGER.info("Testing {}", viewName); final ViewDefinition viewDefinition = getToolContext().getConfigSource().getLatestByName(ViewDefinition.class, viewName); if (viewDefinition == null) { throw new IllegalArgumentException("View definition " + viewName + " not found"); } out.println("View = " + viewName); test.runAmbiguityTest(viewDefinition); count++; } else { final Collection<ConfigItem<ViewDefinition>> viewDefinitions = getToolContext().getConfigSource().getAll(ViewDefinition.class, VersionCorrection.LATEST); LOGGER.info("Testing {} view definition(s)", viewDefinitions.size()); for (final ConfigItem<ViewDefinition> viewDefinitionConfig : viewDefinitions) { final ViewDefinition viewDefinition = viewDefinitionConfig.getValue(); LOGGER.info("Testing {}", viewDefinition.getName()); out.println("View = " + viewDefinition.getName()); final int resolutions = _resolutions.get(); final int ambiguities = _ambiguities.get(); test.runAmbiguityTest(viewDefinition); count++; out.println("Resolutions = " + (_resolutions.get() - resolutions)); out.println("Ambiguities = " + (_ambiguities.get() - ambiguities)); } } LOGGER.info("{} view(s) tested", count); out.println("Total resolutions = " + _resolutions.get()); out.println("Total ambiguities = " + _ambiguities.get()); out.close(); } @Override protected Options createOptions(final boolean mandatoryConfigResource) { final Options options = super.createOptions(mandatoryConfigResource); options.addOption(createViewNameOption()); options.addOption(createFunctionExclusionGroupsBeanOption()); options.addOption(createFunctionPrioritiesOption()); options.addOption(createOutputOption()); options.addOption(createVerboseOption()); return options; } }
apache-2.0
kagel/elasticsearch
src/test/java/org/elasticsearch/rest/action/admin/indices/upgrade/UpgradeTest.java
14735
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.rest.action.admin.indices.upgrade; import com.google.common.base.Predicate; import org.apache.http.impl.client.HttpClients; import org.elasticsearch.ExceptionsHelper; import org.elasticsearch.Version; import org.elasticsearch.action.admin.indices.segments.IndexSegments; import org.elasticsearch.action.admin.indices.segments.IndexShardSegments; import org.elasticsearch.action.admin.indices.segments.IndicesSegmentResponse; import org.elasticsearch.action.admin.indices.segments.ShardSegments; import org.elasticsearch.action.index.IndexRequestBuilder; import org.elasticsearch.cluster.routing.allocation.decider.ConcurrentRebalanceAllocationDecider; import org.elasticsearch.cluster.routing.allocation.decider.EnableAllocationDecider; import org.elasticsearch.common.logging.ESLogger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.json.JsonXContent; import org.elasticsearch.index.engine.Segment; import org.elasticsearch.node.internal.InternalNode; import org.elasticsearch.test.ElasticsearchBackwardsCompatIntegrationTest; import org.elasticsearch.test.ElasticsearchIntegrationTest; import org.elasticsearch.test.rest.client.http.HttpRequestBuilder; import org.elasticsearch.test.rest.client.http.HttpResponse; import org.elasticsearch.test.rest.json.JsonPath; import org.junit.BeforeClass; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.List; import java.util.Map; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; @ElasticsearchIntegrationTest.ClusterScope(scope = ElasticsearchIntegrationTest.Scope.TEST) // test scope since we set cluster wide settings public class UpgradeTest extends ElasticsearchBackwardsCompatIntegrationTest { @BeforeClass public static void checkUpgradeVersion() { boolean luceneVersionMatches = globalCompatibilityVersion().luceneVersion.equals(Version.CURRENT.luceneVersion); assumeFalse("lucene versions must be different to run upgrade test", luceneVersionMatches); } @Override protected int minExternalNodes() { return 2; } public void testUpgrade() throws Exception { // allow the cluster to rebalance quickly - 2 concurrent rebalance are default we can do higher ImmutableSettings.Builder builder = ImmutableSettings.builder(); builder.put(ConcurrentRebalanceAllocationDecider.CLUSTER_ROUTING_ALLOCATION_CLUSTER_CONCURRENT_REBALANCE, 100); client().admin().cluster().prepareUpdateSettings().setPersistentSettings(builder).get(); int numIndexes = randomIntBetween(2, 4); String[] indexNames = new String[numIndexes]; for (int i = 0; i < numIndexes; ++i) { final String indexName = "test" + i; indexNames[i] = indexName; Settings settings = ImmutableSettings.builder() .put("index.routing.allocation.exclude._name", backwardsCluster().newNodePattern()) // don't allow any merges so that we can check segments are upgraded // by the upgrader, and not just regular merging .put("index.merge.policy.segments_per_tier", 1000000f) .put(indexSettings()) .build(); assertAcked(prepareCreate(indexName).setSettings(settings)); ensureGreen(indexName); assertAllShardsOnNodes(indexName, backwardsCluster().backwardsNodePattern()); int numDocs = scaledRandomIntBetween(100, 1000); List<IndexRequestBuilder> docs = new ArrayList<>(); for (int j = 0; j < numDocs; ++j) { String id = Integer.toString(j); docs.add(client().prepareIndex(indexName, "type1", id).setSource("text", "sometext")); } indexRandom(true, docs); ensureGreen(indexName); if (globalCompatibilityVersion().before(Version.V_1_4_0_Beta1)) { // before 1.4 and the wait_if_ongoing flag, flushes could fail randomly, so we // need to continue to try flushing until all shards succeed assertTrue(awaitBusy(new Predicate<Object>() { @Override public boolean apply(Object o) { return flush(indexName).getFailedShards() == 0; } })); } else { assertEquals(0, flush(indexName).getFailedShards()); } // index more docs that won't be flushed numDocs = scaledRandomIntBetween(100, 1000); docs = new ArrayList<>(); for (int j = 0; j < numDocs; ++j) { String id = Integer.toString(j); docs.add(client().prepareIndex(indexName, "type2", id).setSource("text", "someothertext")); } indexRandom(true, docs); ensureGreen(indexName); } logger.debug("--> Upgrading nodes"); logClusterState(); logSegmentsState(null); backwardsCluster().allowOnAllNodes(indexNames); ensureGreen(); // disable allocation entirely until all nodes are upgraded builder = ImmutableSettings.builder(); builder.put(EnableAllocationDecider.CLUSTER_ROUTING_ALLOCATION_ENABLE, EnableAllocationDecider.Allocation.NONE); client().admin().cluster().prepareUpdateSettings().setTransientSettings(builder).get(); backwardsCluster().upgradeAllNodes(); builder = ImmutableSettings.builder(); // disable rebalanceing entirely for the time being otherwise we might get relocations / rebalance from nodes with old segments builder.put(EnableAllocationDecider.CLUSTER_ROUTING_REBALANCE_ENABLE, EnableAllocationDecider.Rebalance.NONE); builder.put(EnableAllocationDecider.CLUSTER_ROUTING_ALLOCATION_ENABLE, EnableAllocationDecider.Allocation.ALL); client().admin().cluster().prepareUpdateSettings().setTransientSettings(builder).get(); ensureGreen(); logger.debug("--> Nodes upgrade complete"); logClusterState(); logSegmentsState(null); final HttpRequestBuilder httpClient = httpClient(); assertNotUpgraded(httpClient, null); final String indexToUpgrade = "test" + randomInt(numIndexes - 1); logger.debug("--> Running upgrade on index " + indexToUpgrade); logClusterState(); logSegmentsState(indexToUpgrade); runUpgrade(httpClient, indexToUpgrade); awaitBusy(new Predicate<Object>() { @Override public boolean apply(Object o) { try { return isUpgraded(httpClient, indexToUpgrade); } catch (Exception e) { throw ExceptionsHelper.convertToRuntime(e); } } }); logger.debug("--> Single index upgrade complete"); logClusterState(); logSegmentsState(indexToUpgrade); logger.debug("--> Running upgrade on the rest of the indexes"); logClusterState(); logSegmentsState(null); runUpgrade(httpClient, null, "wait_for_completion", "true"); logger.debug("--> Full upgrade complete"); logClusterState(); logSegmentsState(null); assertUpgraded(httpClient, null); } void logSegmentsState(String index) throws Exception { // double check using the segments api that all segments are actually upgraded IndicesSegmentResponse segsRsp; if (index == null) { segsRsp = client().admin().indices().prepareSegments().get(); } else { segsRsp = client().admin().indices().prepareSegments(index).get(); } XContentBuilder builder = JsonXContent.contentBuilder(); logger.debug("Segments State: \n\n" + segsRsp.toXContent(builder.prettyPrint(), ToXContent.EMPTY_PARAMS).string()); } static String upgradePath(String index) { String path = "/_upgrade"; if (index != null) { path = "/" + index + path; } return path; } static void assertNotUpgraded(HttpRequestBuilder httpClient, String index) throws Exception { for (UpgradeStatus status : getUpgradeStatus(httpClient, upgradePath(index))) { assertTrue("index " + status.indexName + " should not be zero sized", status.totalBytes != 0); // TODO: it would be better for this to be strictly greater, but sometimes an extra flush // mysteriously happens after the second round of docs are indexed assertTrue("index " + status.indexName + " should have recovered some segments from transaction log", status.totalBytes >= status.toUpgradeBytes); assertTrue("index " + status.indexName + " should need upgrading", status.toUpgradeBytes != 0); } } static void assertUpgraded(HttpRequestBuilder httpClient, String index) throws Exception { for (UpgradeStatus status : getUpgradeStatus(httpClient, upgradePath(index))) { assertTrue("index " + status.indexName + " should not be zero sized", status.totalBytes != 0); assertEquals("index " + status.indexName + " should be upgraded", 0, status.toUpgradeBytes); } // double check using the segments api that all segments are actually upgraded IndicesSegmentResponse segsRsp; if (index == null) { segsRsp = client().admin().indices().prepareSegments().execute().actionGet(); } else { segsRsp = client().admin().indices().prepareSegments(index).execute().actionGet(); } for (IndexSegments indexSegments : segsRsp.getIndices().values()) { for (IndexShardSegments shard : indexSegments) { for (ShardSegments segs : shard.getShards()) { for (Segment seg : segs.getSegments()) { assertEquals("Index " + indexSegments.getIndex() + " has unupgraded segment " + seg.toString(), Version.CURRENT.luceneVersion, seg.version); } } } } } static boolean isUpgraded(HttpRequestBuilder httpClient, String index) throws Exception { ESLogger logger = Loggers.getLogger(UpgradeTest.class); int toUpgrade = 0; for (UpgradeStatus status : getUpgradeStatus(httpClient, upgradePath(index))) { logger.info("Index: " + status.indexName + ", total: " + status.totalBytes + ", toUpgrade: " + status.toUpgradeBytes); toUpgrade += status.toUpgradeBytes; } return toUpgrade == 0; } static class UpgradeStatus { public final String indexName; public final int totalBytes; public final int toUpgradeBytes; public UpgradeStatus(String indexName, int totalBytes, int toUpgradeBytes) { this.indexName = indexName; this.totalBytes = totalBytes; this.toUpgradeBytes = toUpgradeBytes; } } static void runUpgrade(HttpRequestBuilder httpClient, String index, String... params) throws Exception { assert params.length % 2 == 0; HttpRequestBuilder builder = httpClient.method("POST").path(upgradePath(index)); for (int i = 0; i < params.length; i += 2) { builder.addParam(params[i], params[i + 1]); } HttpResponse rsp = builder.execute(); assertNotNull(rsp); assertEquals(200, rsp.getStatusCode()); } static List<UpgradeStatus> getUpgradeStatus(HttpRequestBuilder httpClient, String path) throws Exception { HttpResponse rsp = httpClient.method("GET").path(path).execute(); Map<String,Object> data = validateAndParse(rsp); List<UpgradeStatus> ret = new ArrayList<>(); for (String index : data.keySet()) { Map<String, Object> status = (Map<String,Object>)data.get(index); assertTrue("missing key size_in_bytes for index " + index, status.containsKey("size_in_bytes")); Object totalBytes = status.get("size_in_bytes"); assertTrue("size_in_bytes for index " + index + " is not an integer", totalBytes instanceof Integer); assertTrue("missing key size_to_upgrade_in_bytes for index " + index, status.containsKey("size_to_upgrade_in_bytes")); Object toUpgradeBytes = status.get("size_to_upgrade_in_bytes"); assertTrue("size_to_upgrade_in_bytes for index " + index + " is not an integer", toUpgradeBytes instanceof Integer); ret.add(new UpgradeStatus(index, ((Integer)totalBytes).intValue(), ((Integer)toUpgradeBytes).intValue())); } return ret; } static Map<String, Object> validateAndParse(HttpResponse rsp) throws Exception { assertNotNull(rsp); assertEquals(200, rsp.getStatusCode()); assertTrue(rsp.hasBody()); return (Map<String,Object>)new JsonPath(rsp.getBody()).evaluate(""); } HttpRequestBuilder httpClient() { InetSocketAddress[] addresses = cluster().httpAddresses(); InetSocketAddress address = addresses[randomInt(addresses.length - 1)]; return new HttpRequestBuilder(HttpClients.createDefault()).host(address.getHostName()).port(address.getPort()); } @Override protected Settings nodeSettings(int nodeOrdinal) { return ImmutableSettings.builder().put(super.nodeSettings(nodeOrdinal)) .put(InternalNode.HTTP_ENABLED, true).build(); } }
apache-2.0
MaTriXy/auto
value/src/main/java/com/google/auto/value/processor/ExtensionContext.java
2166
/* * Copyright (C) 2015 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.auto.value.processor; import com.google.auto.value.extension.AutoValueExtension; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import java.util.Map; import java.util.Set; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; class ExtensionContext implements AutoValueExtension.Context { private final ProcessingEnvironment processingEnvironment; private final TypeElement typeElement; private final ImmutableMap<String, ExecutableElement> properties; private final ImmutableSet<ExecutableElement> abstractMethods; ExtensionContext( ProcessingEnvironment processingEnvironment, TypeElement typeElement, ImmutableMap<String, ExecutableElement> properties, ImmutableSet<ExecutableElement> abstractMethods) { this.processingEnvironment = processingEnvironment; this.typeElement = typeElement; this.properties = properties; this.abstractMethods = abstractMethods; } @Override public ProcessingEnvironment processingEnvironment() { return processingEnvironment; } @Override public String packageName() { return TypeSimplifier.packageNameOf(typeElement); } @Override public TypeElement autoValueClass() { return typeElement; } @Override public Map<String, ExecutableElement> properties() { return properties; } @Override public Set<ExecutableElement> abstractMethods() { return abstractMethods; } }
apache-2.0
pdef/pdef
java/pdef/src/test/java/io/pdef/PdefJsonTest.java
1974
/* * Copyright: 2013 Ivan Korobkov <ivan.korobkov@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.pdef; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import io.pdef.test.TestException; import io.pdef.test.TestNumber; import io.pdef.test.TestStruct; import static org.fest.assertions.api.Assertions.assertThat; import org.junit.Test; import java.util.Date; public class PdefJsonTest { @Test public void testStruct() throws Exception { TestStruct struct0 = fixtureStruct(); String json = struct0.toJson(); TestStruct struct1 = TestStruct.parseJson(json); assertThat(struct1).isEqualTo(struct0); } @Test public void testException() throws Exception { TestException e = new TestException() .setStruct0(fixtureStruct()) .setMessage("Hello, world"); String json = e.toJson(); TestException e1 = TestException.parseJson(json); assertThat(e1).isEqualTo(e); } private TestStruct fixtureStruct() { return new TestStruct() .setBool0(true) .setShort0((short) -16) .setInt0(-32) .setLong0(-64) .setFloat0(-1.5f) .setDouble0(-2.5f) .setString0("Привет") .setDatetime0(new Date(0)) .setList0(ImmutableList.of(1, 2, 3)) .setSet0(ImmutableSet.of(4, 5, 6)) .setMap0(ImmutableMap.of(1, "a", 2, "b")) .setEnum0(TestNumber.ONE) .setStruct0(new TestStruct()); } }
apache-2.0
PetrGasparik/midpoint
model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestSegregationOfDuties.java
12739
/* * Copyright (c) 2010-2015 Evolveum * * 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.evolveum.midpoint.model.intest; import java.io.File; import java.util.ArrayList; import java.util.Collection; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; import org.testng.AssertJUnit; import org.testng.annotations.Test; import com.evolveum.midpoint.model.api.PolicyViolationException; import com.evolveum.midpoint.prism.delta.ItemDelta; import com.evolveum.midpoint.prism.delta.ObjectDelta; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.util.MiscSchemaUtil; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.xml.ns._public.common.common_3.RoleType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; /** * @author semancik * */ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestSegregationOfDuties extends AbstractInitializedModelIntegrationTest { protected static final File TEST_DIR = new File("src/test/resources", "rbac"); @Test public void test110SimpleExclusion1() throws Exception { final String TEST_NAME = "test110SimpleExclusion1"; TestUtil.displayTestTile(this, TEST_NAME); Task task = taskManager.createTaskInstance(TestSegregationOfDuties.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); // This should go well assignRole(USER_JACK_OID, ROLE_PIRATE_OID, task, result); try { // This should die assignRole(USER_JACK_OID, ROLE_JUDGE_OID, task, result); AssertJUnit.fail("Expected policy violation after adding judge role, but it went well"); } catch (PolicyViolationException e) { // This is expected } unassignRole(USER_JACK_OID, ROLE_PIRATE_OID, task, result); assertAssignedNoRole(USER_JACK_OID, task, result); } @Test public void test112SimpleExclusion1Deprecated() throws Exception { final String TEST_NAME = "test112SimpleExclusion1Deprecated"; TestUtil.displayTestTile(this, TEST_NAME); Task task = taskManager.createTaskInstance(TestSegregationOfDuties.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); // This should go well assignRole(USER_JACK_OID, ROLE_PIRATE_OID, task, result); try { // This should die assignRole(USER_JACK_OID, ROLE_JUDGE_DEPRECATED_OID, task, result); AssertJUnit.fail("Expected policy violation after adding judge role, but it went well"); } catch (PolicyViolationException e) { // This is expected } unassignRole(USER_JACK_OID, ROLE_PIRATE_OID, task, result); assertAssignedNoRole(USER_JACK_OID, task, result); } /** * Same thing as before but other way around */ @Test public void test120SimpleExclusion2() throws Exception { final String TEST_NAME = "test120SimpleExclusion2"; TestUtil.displayTestTile(this, TEST_NAME); Task task = taskManager.createTaskInstance(TestSegregationOfDuties.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); // This should go well assignRole(USER_JACK_OID, ROLE_JUDGE_OID, task, result); try { // This should die assignRole(USER_JACK_OID, ROLE_PIRATE_OID, task, result); AssertJUnit.fail("Expected policy violation after adding pirate role, but it went well"); } catch (PolicyViolationException e) { // This is expected } unassignRole(USER_JACK_OID, ROLE_JUDGE_OID, task, result); assertAssignedNoRole(USER_JACK_OID, task, result); } /** * Same thing as before but other way around */ @Test public void test122SimpleExclusion2Deprecated() throws Exception { final String TEST_NAME = "test122SimpleExclusion2Deprecated"; TestUtil.displayTestTile(this, TEST_NAME); Task task = taskManager.createTaskInstance(TestSegregationOfDuties.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); // This should go well assignRole(USER_JACK_OID, ROLE_JUDGE_DEPRECATED_OID, task, result); try { // This should die assignRole(USER_JACK_OID, ROLE_PIRATE_OID, task, result); AssertJUnit.fail("Expected policy violation after adding pirate role, but it went well"); } catch (PolicyViolationException e) { // This is expected } unassignRole(USER_JACK_OID, ROLE_JUDGE_DEPRECATED_OID, task, result); assertAssignedNoRole(USER_JACK_OID, task, result); } @Test public void test130SimpleExclusionBoth1() throws Exception { final String TEST_NAME = "test130SimpleExclusionBoth1"; TestUtil.displayTestTile(this, TEST_NAME); Task task = taskManager.createTaskInstance(TestSegregationOfDuties.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); Collection<ItemDelta<?,?>> modifications = new ArrayList<>(); modifications.add((createAssignmentModification(ROLE_JUDGE_OID, RoleType.COMPLEX_TYPE, null, null, null, true))); modifications.add((createAssignmentModification(ROLE_PIRATE_OID, RoleType.COMPLEX_TYPE, null, null, null, true))); ObjectDelta<UserType> userDelta = ObjectDelta.createModifyDelta(USER_JACK_OID, modifications, UserType.class, prismContext); try { modelService.executeChanges(MiscSchemaUtil.createCollection(userDelta), null, task, result); AssertJUnit.fail("Expected policy violation, but it went well"); } catch (PolicyViolationException e) { // This is expected } assertAssignedNoRole(USER_JACK_OID, task, result); } @Test public void test132SimpleExclusionBoth1Deprecated() throws Exception { final String TEST_NAME = "test132SimpleExclusionBoth1Deprecated"; TestUtil.displayTestTile(this, TEST_NAME); Task task = taskManager.createTaskInstance(TestSegregationOfDuties.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); Collection<ItemDelta<?,?>> modifications = new ArrayList<>(); modifications.add((createAssignmentModification(ROLE_JUDGE_DEPRECATED_OID, RoleType.COMPLEX_TYPE, null, null, null, true))); modifications.add((createAssignmentModification(ROLE_PIRATE_OID, RoleType.COMPLEX_TYPE, null, null, null, true))); ObjectDelta<UserType> userDelta = ObjectDelta.createModifyDelta(USER_JACK_OID, modifications, UserType.class, prismContext); try { modelService.executeChanges(MiscSchemaUtil.createCollection(userDelta), null, task, result); AssertJUnit.fail("Expected policy violation, but it went well"); } catch (PolicyViolationException e) { // This is expected } assertAssignedNoRole(USER_JACK_OID, task, result); } @Test public void test140SimpleExclusionBoth2() throws Exception { final String TEST_NAME = "test140SimpleExclusionBoth2"; TestUtil.displayTestTile(this, TEST_NAME); Task task = taskManager.createTaskInstance(TestSegregationOfDuties.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); Collection<ItemDelta<?,?>> modifications = new ArrayList<>(); modifications.add((createAssignmentModification(ROLE_PIRATE_OID, RoleType.COMPLEX_TYPE, null, null, null, true))); modifications.add((createAssignmentModification(ROLE_JUDGE_OID, RoleType.COMPLEX_TYPE, null, null, null, true))); ObjectDelta<UserType> userDelta = ObjectDelta.createModifyDelta(USER_JACK_OID, modifications, UserType.class, prismContext); try { modelService.executeChanges(MiscSchemaUtil.createCollection(userDelta), null, task, result); AssertJUnit.fail("Expected policy violation, but it went well"); } catch (PolicyViolationException e) { // This is expected } assertAssignedNoRole(USER_JACK_OID, task, result); } @Test public void test142SimpleExclusionBoth2Deprecated() throws Exception { final String TEST_NAME = "test142SimpleExclusionBoth2Deprecated"; TestUtil.displayTestTile(this, TEST_NAME); Task task = taskManager.createTaskInstance(TestSegregationOfDuties.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); Collection<ItemDelta<?,?>> modifications = new ArrayList<>(); modifications.add((createAssignmentModification(ROLE_PIRATE_OID, RoleType.COMPLEX_TYPE, null, null, null, true))); modifications.add((createAssignmentModification(ROLE_JUDGE_DEPRECATED_OID, RoleType.COMPLEX_TYPE, null, null, null, true))); ObjectDelta<UserType> userDelta = ObjectDelta.createModifyDelta(USER_JACK_OID, modifications, UserType.class, prismContext); try { modelService.executeChanges(MiscSchemaUtil.createCollection(userDelta), null, task, result); AssertJUnit.fail("Expected policy violation, but it went well"); } catch (PolicyViolationException e) { // This is expected } assertAssignedNoRole(USER_JACK_OID, task, result); } @Test public void test150SimpleExclusionBothBidirectional1() throws Exception { final String TEST_NAME = "test150SimpleExclusionBothBidirectional1"; TestUtil.displayTestTile(this, TEST_NAME); Task task = taskManager.createTaskInstance(TestSegregationOfDuties.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); Collection<ItemDelta<?,?>> modifications = new ArrayList<>(); modifications.add((createAssignmentModification(ROLE_THIEF_OID, RoleType.COMPLEX_TYPE, null, null, null, true))); modifications.add((createAssignmentModification(ROLE_JUDGE_OID, RoleType.COMPLEX_TYPE, null, null, null, true))); ObjectDelta<UserType> userDelta = ObjectDelta.createModifyDelta(USER_JACK_OID, modifications, UserType.class, prismContext); try { modelService.executeChanges(MiscSchemaUtil.createCollection(userDelta), null, task, result); AssertJUnit.fail("Expected policy violation, but it went well"); } catch (PolicyViolationException e) { // This is expected } assertAssignedNoRole(USER_JACK_OID, task, result); } @Test public void test160SimpleExclusionBothBidirectional2() throws Exception { final String TEST_NAME = "test160SimpleExclusionBothBidirectional2"; TestUtil.displayTestTile(this, TEST_NAME); Task task = taskManager.createTaskInstance(TestSegregationOfDuties.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); Collection<ItemDelta<?,?>> modifications = new ArrayList<>(); modifications.add((createAssignmentModification(ROLE_JUDGE_OID, RoleType.COMPLEX_TYPE, null, null, null, true))); modifications.add((createAssignmentModification(ROLE_THIEF_OID, RoleType.COMPLEX_TYPE, null, null, null, true))); ObjectDelta<UserType> userDelta = ObjectDelta.createModifyDelta(USER_JACK_OID, modifications, UserType.class, prismContext); try { modelService.executeChanges(MiscSchemaUtil.createCollection(userDelta), null, task, result); AssertJUnit.fail("Expected policy violation, but it went well"); } catch (PolicyViolationException e) { // This is expected } assertAssignedNoRole(USER_JACK_OID, task, result); } }
apache-2.0
jjYBdx4IL/misc
ecs/src/main/java/org/apache/ecs/html/Center.java
7980
/* * ==================================================================== * * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2003 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Jakarta Element Construction Set", * "Jakarta ECS" , and "Apache Software Foundation" must not be used * to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * "Jakarta Element Construction Set" nor "Jakarta ECS" nor may "Apache" * appear in their names without prior written permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ecs.html; import org.apache.ecs.*; /** This class creates a &lt;CENTER&gt; tag. @version $Id: Center.java,v 1.4 2003/04/27 09:21:31 rdonkin Exp $ @author <a href="mailto:snagy@servletapi.com">Stephan Nagy</a> @author <a href="mailto:jon@clearink.com">Jon S. Stevens</a> */ public class Center extends MultiPartElement implements Printable, MouseEvents, KeyEvents { /** Private initialization routine. */ { setElementType("center"); } /** Basic constructor. */ public Center() { } /** Basic constructor. @param element Adds an Element to the element. */ public Center(Element element) { addElement(element); } /** Basic constructor. @param element Adds an Element to the element. */ public Center(String element) { addElement(element); } /** Adds an Element to the element. @param hashcode name of element for hash table @param element Adds an Element to the element. */ public Center addElement(String hashcode,Element element) { addElementToRegistry(hashcode,element); return(this); } /** Adds an Element to the element. @param hashcode name of element for hash table @param element Adds an Element to the element. */ public Center addElement(String hashcode,String element) { addElementToRegistry(hashcode,element); return(this); } /** Adds an Element to the element. @param element Adds an Element to the element. */ public Center addElement(Element element) { addElementToRegistry(element); return(this); } /** Adds an Element to the element. @param element Adds an Element to the element. */ public Center addElement(String element) { addElementToRegistry(element); return(this); } /** Removes an Element from the element. @param hashcode the name of the element to be removed. */ public Center removeElement(String hashcode) { removeElementFromRegistry(hashcode); return(this); } /** The onclick event occurs when the pointing device button is clicked over an element. This attribute may be used with most elements. @param The script */ public void setOnClick(String script) { addAttribute ( "onClick", script ); } /** The ondblclick event occurs when the pointing device button is double clicked over an element. This attribute may be used with most elements. @param The script */ public void setOnDblClick(String script) { addAttribute ( "onDblClick", script ); } /** The onmousedown event occurs when the pointing device button is pressed over an element. This attribute may be used with most elements. @param The script */ public void setOnMouseDown(String script) { addAttribute ( "onMouseDown", script ); } /** The onmouseup event occurs when the pointing device button is released over an element. This attribute may be used with most elements. @param The script */ public void setOnMouseUp(String script) { addAttribute ( "onMouseUp", script ); } /** The onmouseover event occurs when the pointing device is moved onto an element. This attribute may be used with most elements. @param The script */ public void setOnMouseOver(String script) { addAttribute ( "onMouseOver", script ); } /** The onmousemove event occurs when the pointing device is moved while it is over an element. This attribute may be used with most elements. @param The script */ public void setOnMouseMove(String script) { addAttribute ( "onMouseMove", script ); } /** The onmouseout event occurs when the pointing device is moved away from an element. This attribute may be used with most elements. @param The script */ public void setOnMouseOut(String script) { addAttribute ( "onMouseOut", script ); } /** The onkeypress event occurs when a key is pressed and released over an element. This attribute may be used with most elements. @param The script */ public void setOnKeyPress(String script) { addAttribute ( "onKeyPress", script ); } /** The onkeydown event occurs when a key is pressed down over an element. This attribute may be used with most elements. @param The script */ public void setOnKeyDown(String script) { addAttribute ( "onKeyDown", script ); } /** The onkeyup event occurs when a key is released over an element. This attribute may be used with most elements. @param The script */ public void setOnKeyUp(String script) { addAttribute ( "onKeyUp", script ); } }
apache-2.0
immutables/immutables
value-fixture/test/org/immutables/fixture/ValuesTest.java
18236
/* Copyright 2013-2018 Immutables Authors and Contributors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.immutables.fixture; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import nonimmutables.GetterAnnotation; import org.immutables.fixture.ImmutableSampleCopyOfTypes.ByBuilder; import org.immutables.fixture.ImmutableSampleCopyOfTypes.ByConstructorAndWithers; import org.immutables.fixture.style.ImmutableOptionalWithNullable; import org.immutables.fixture.style.ImmutableOptionalWithoutNullable; import org.junit.jupiter.api.Test; import javax.ws.rs.POST; import java.io.IOException; import java.lang.annotation.RetentionPolicy; import java.lang.reflect.AnnotatedType; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicInteger; import static org.immutables.check.Checkers.check; import static org.junit.jupiter.api.Assertions.assertThrows; public class ValuesTest { @Test public void generateCopyAnnotations() throws Exception { ImmutableGetters g = ImmutableGetters.builder().ab(0).cd("").ef(true).build(); check(g.getClass().getMethod("cd").isAnnotationPresent(POST.class)); check(g.getClass().getMethod("ef").getAnnotation(GetterAnnotation.class).value()).hasSize(2); } @Test public void internCustomHashCode() { ImmutableInternCustomHashCode i1 = ImmutableInternCustomHashCode.builder() .a(1) .build(); // customized hash code check(i1.hashCode()).is(0); // due to overriden equals and interning check(i1).same(ImmutableInternCustomHashCode.builder() .a(2) .build()); } @SuppressWarnings("CheckReturnValue") @Test public void orderAndNullCheckForConstructor() { assertThrows(NullPointerException.class, () -> ImmutableHostWithPort.of(1, null)); } @Test public void builderFrom() { SampleValue sv1 = ImmutableSampleValue.builder() .addC(1, 2) .a(3) .oi(1) .build(); SampleValue sv2 = ImmutableSampleValue.builder() .a(1) .addC(3, 4) .os("") .build(); SampleValue svAll = ImmutableSampleValue.builder() .from(sv1) .from(sv2) .build(); check(svAll.a()).is(1); check(svAll.c()).isOf(1, 2, 3, 4); check(svAll.oi().orElse(-1)).is(1); check(svAll.os()).isOf(""); } @Test public void resetCollectionTest() { OrderAttributeValue a = ImmutableOrderAttributeValue.builder() .addNatural(0) .natural(ImmutableList.of(3, 2, 4, 1)) .addReverse("") .reverse(ImmutableList.of("a", "z", "b", "y")) .putNavigableMap(1, "2") .navigableMap(ImmutableMap.of(2, "2")) .reverseMap(ImmutableMap.of("a", "a")) .addNaturalMultiset(10, 10, 11) .addReverseMultiset("x", "y", "y") .naturalMultiset(ImmutableList.of(20, 13, 20)) .reverseMultiset(ImmutableList.of("w", "z", "z")) .build(); OrderAttributeValue b = ImmutableOrderAttributeValue.builder() .addNatural(3, 2, 4, 1) .addReverse("a", "z", "b", "y") .putNavigableMap(2, "2") .putReverseMap("a", "a") .addNaturalMultiset(20, 13, 20) .addReverseMultiset("w", "z", "z") .build(); check(a).is(b); } @Test public void extendingBuilder() { ExtendingInnerBuilderValue.Builder builder = new ExtendingInnerBuilderValue.Builder(); ExtendingInnerBuilderValue value = builder.addList("").build(); check(value.attribute()).is(1); check(value.list()).isOf(""); } @Test public void defaultAsDefault() { DefaultAsDefault d = ImmutableDefaultAsDefault.builder() .b(1) .build(); check(d.a()).is(1); check(d.b()).is(1); } @Test public void extendsBuilderIfaceValue() { ExtendedBuilderInterface ifc = ExtendedBuilderInterface.builder() .a(1) .b(2) .build(); check(ifc.a()).is(1); check(ifc.b()).is(2); } @Test public void ifaceValue() { check(ImmutableIfaceValue.builder().number(1).build()).is(ImmutableIfaceValue.of(1)); } @Test public void ordering() { OrderAttributeValue value = ImmutableOrderAttributeValue.builder() .addNatural(3, 2, 4, 1) .addReverse("a", "z", "b", "y") .putNavigableMap(2, "2") .putNavigableMap(1, "1") .putReverseMap("a", "a") .putReverseMap("b", "b") .addNaturalMultiset(20, 13, 20) .addReverseMultiset("w", "z", "z") .build(); check(value.natural()).isOf(1, 2, 3, 4); check(value.reverse()).isOf("z", "y", "b", "a"); check(value.navigableMap().keySet()).isOf(1, 2); check(value.reverseMap().keySet()).isOf("b", "a"); check(value.naturalMultiset()).isOf(13, 20, 20); check(value.reverseMultiset()).isOf("z", "z", "w"); } @Test public void primitiveDefault() { check(ImmutablePrimitiveDefault.builder().build().def()); check(ImmutablePrimitiveDefault.builder().def(true).build().def()); check(!ImmutablePrimitiveDefault.builder().def(false).build().def()); } @Test public void sourceOrdering() { check(ImmutableAttributeOrdering.SourceOrderingEntity.builder() .b(2) // b from inherited in source order .a(1) // a from inherited in source order, y skipped because overriden next .z(4) // z directly declared in source order .y(3) // y overriden here, in source order .build()).hasToString("SourceOrderingEntity{b=2, a=1, z=4, y=3}"); } @Test public void moreSourceOrdering() { check(ImmutableAttributeOrdering.D.builder() .a1(1) .a2(2) .b1(3) .b2(4) .c1(5) .c2(6) .d(7) .build()).hasToString("D{a1=1, a2=2, b1=3, b2=4, c1=5, c2=6, d=7}"); } @Test @SuppressWarnings("CheckReturnValue") public void requiredAttributesSetChecked() { try { ImmutableIfaceValue.builder().build(); check(false); } catch (Exception ex) { check(ex.getMessage()).contains("number"); } } @Test public void auxiliary() { ImmutableIfaceValue includesAuxiliary = ImmutableIfaceValue.builder().number(1).addAuxiliary("x").build(); ImmutableIfaceValue excludesAuxiliary = ImmutableIfaceValue.of(1); check(includesAuxiliary).is(excludesAuxiliary); check(includesAuxiliary.hashCode()).is(excludesAuxiliary.hashCode()); check(includesAuxiliary).asString().not().contains("auxiliary"); } @Test public void auxiliaryOnForcedSingleton() { check(ImmutableAuxDefaultOnForcedSingleton.of().withAux(66).aux()).is(66); } @Test public void builderInheritence() { check(ImmutableSillyExtendedBuilder.builder().inheritedField); } @Test public void nullable() { ImmutableHasNullable hasNullable = ImmutableHasNullable.builder().build(); check(hasNullable.def()).isNull(); check(hasNullable.der()).isNull(); check(hasNullable.in()).isNull(); check(ImmutableHasNullable.of(null)).is(hasNullable); check(ImmutableHasNullable.of()).is(hasNullable); check(ImmutableHasNullable.of().hashCode()).is(hasNullable.hashCode()); check(hasNullable).hasToString("HasNullable{}"); } @Test public void checkForNull() { ImmutableCheckForNullAttributes build = ImmutableCheckForNullAttributes.builder() .a(null) .b(null) .build(); check(build.a()).isNull(); check(build.b()).isNull(); } @Test public void nullableArray() { NullableArray n1 = ImmutableNullableArray.builder() .array((byte[]) null) .build(); NullableArray n2 = ImmutableNullableArray.builder() .build(); check(n1).is(n2); check(n1.array()).isNull(); } @Test public void java8TypeAnnotation() throws Exception { Method method = ImmutableHasTypeAnnotation.class.getMethod("str"); AnnotatedType returnType = method.getAnnotatedReturnType(); check(returnType.getAnnotation(TypeA.class)).notNull(); check(returnType.getAnnotation(TypeB.class)).notNull(); } @Test @SuppressWarnings("CheckReturnValue") public void withMethods() { ImmutableSillyValidatedBuiltValue value = ImmutableSillyValidatedBuiltValue.builder() .value(-10) .negativeOnly(true) .build(); try { value.withValue(10); check(false); } catch (Exception ex) { } check(value.withNegativeOnly(false).withValue(5).value()).is(5); } @Test public void withMethodSetsAndMaps() { ImmutableSillyMapHolder holder = ImmutableSillyMapHolder.builder() .addZz(RetentionPolicy.CLASS) .build(); check(holder.withZz(Collections.<RetentionPolicy>emptySet()).zz()).isEmpty(); check(holder.withHolder2(ImmutableMap.of(1, "")).holder2().size()).is(1); } @Test public void lazyValue() { SillyLazy v = ImmutableSillyLazy.of(new AtomicInteger()); check(v.counter().get()).is(0); check(v.val1()).is(1); check(v.counter().get()).is(1); check(v.val2()).is(2); check(v.val1()).is(1); check(v.counter().get()).is(2); } @Test public void packagePrivateClassGeneration() { check(Modifier.isPublic(SillyEmpty.class.getModifiers())); check(Modifier.isPublic(ImmutableSillyEmpty.class.getModifiers())); check(!Modifier.isPublic(SillyExtendedBuilder.class.getModifiers())); check(!Modifier.isPublic(ImmutableSillyExtendedBuilder.class.getModifiers())); } @Test public void internedInstanceConstruction() { check(ImmutableSillyInterned.of(1, 2)).is(ImmutableSillyInterned.of(1, 2)); check(ImmutableSillyInterned.of(1, 2)).same(ImmutableSillyInterned.of(1, 2)); check(ImmutableSillyInterned.of(1, 2)).not(ImmutableSillyInterned.of(2, 2)); check(ImmutableSillyInterned.builder() .arg1(1) .arg2(2) .build()) .same(ImmutableSillyInterned.of(1, 2)); check(ImmutableSillyInterned.of(1, 2).hashCode()).is(ImmutableSillyInterned.of(1, 2).hashCode()); check(ImmutableSillyInterned.of(1, 2).hashCode()).not(ImmutableSillyInterned.of(2, 2).hashCode()); } @SuppressWarnings("CheckReturnValue") @Test public void cannotBuildWrongInvariants() { assertThrows(IllegalStateException.class, () -> ImmutableSillyValidatedBuiltValue.builder() .value(10) .negativeOnly(true) .build()); } @Test public void copyConstructor() { ByBuilder wasCopiedByBuilder = ImmutableSampleCopyOfTypes.ByBuilder.copyOf(new SampleCopyOfTypes.ByBuilder() { @Override public int value() { return 2; } }); check(wasCopiedByBuilder.value()).is(2); ByConstructorAndWithers wasCopiedByConstructorAndWithers = ImmutableSampleCopyOfTypes.ByConstructorAndWithers.copyOf(new SampleCopyOfTypes.ByConstructorAndWithers() { @Override public int value() { return 1; } @Override public List<String> additional() { return Arrays.asList("3"); } }); check(wasCopiedByConstructorAndWithers.value()).is(1); check(wasCopiedByConstructorAndWithers.additional()).isOf("3"); SampleCopyOfTypes.ByConstructorAndWithers value2 = ImmutableSampleCopyOfTypes.ByConstructorAndWithers.of(2); check(ImmutableSampleCopyOfTypes.ByConstructorAndWithers.copyOf(value2)) .same(ImmutableSampleCopyOfTypes.ByConstructorAndWithers.copyOf(value2)); } @SuppressWarnings("unlikely-arg-type") @Test public void underwriteHashcodeToStringEquals() { ImmutableUnderwrite v = ImmutableUnderwrite.builder() .value(1) .build(); check(v.hashCode()).is(2); check(v).hasToString("U"); check(v.equals("U")); } @SuppressWarnings("unlikely-arg-type") @Test public void underwriteEqualsWithTypeAnnotationOnParameter() { // custom equals returns true even if null is passed // if it will not be properly undewritten and the equals methid will be generated // we will get false when passing null check(ImmutableCustomEqualsWithTypeAnnotation.builder().build().equals(null)); } @SuppressWarnings("unlikely-arg-type") @Test public void noUnderwriteInheritedHashcodeToStringEquals() { ImmutableNoUnderwrite v = ImmutableNoUnderwrite.builder() .value(1) .build(); check(v.hashCode()).not(2); check(v.toString()).not("N"); check(!v.equals("N")); } @Test public void recalculateDerivedOnCopy() { ImmutableWitherDerived value = ImmutableWitherDerived.builder() .set(1) .build(); check(value.derived()).is(value.set() + 1); value = value.withSet(2); check(value.derived()).is(value.set() + 1); } @Test @SuppressWarnings("CheckReturnValue") public void canBuildCorrectInvariants() { ImmutableSillyValidatedBuiltValue.builder() .value(-10) .negativeOnly(true) .build(); ImmutableSillyValidatedBuiltValue.builder() .value(10) .negativeOnly(false) .build(); ImmutableSillyValidatedBuiltValue.builder() .value(-10) .negativeOnly(false) .build(); } @SuppressWarnings("CheckReturnValue") @Test public void cannotConstructWithWrongInvariants() { assertThrows(IllegalStateException.class, () -> ImmutableSillyValidatedConstructedValue.of(10, true)); } @Test @SuppressWarnings("CheckReturnValue") public void canConstructWithCorrectInvariants() { ImmutableSillyValidatedConstructedValue.of(-10, true); ImmutableSillyValidatedConstructedValue.of(10, false); ImmutableSillyValidatedConstructedValue.of(-10, false); } @Test @SuppressWarnings("CheckReturnValue") public void optionalWhichAcceptsNullable() { ImmutableOptionalWithNullable.builder() .guavaOptional((String) null) .javaOptional((String) null) .javaOptionalInteger((Integer) null) .build(); } @SuppressWarnings("CheckReturnValue") @Test public void optionalWhichDoesntAcceptsNullable() { assertThrows(NullPointerException.class, () -> ImmutableOptionalWithoutNullable.builder() .javaOptional((String) null) .build()); } @Test @SuppressWarnings("CheckReturnValue") public void properInitInternNoBuilder() { ImmutableProperInitInternNoBuilder.of(); } @Test public void normalize() { check(ImmutableNormalize.builder() .value(-2) .build() .value()).is(2); } @Test @SuppressWarnings("CheckReturnValue") public void primitiveOptional() { ImmutablePrimitiveOptionals.builder() .v1(1) .v2(0.2) .v3(2) .v4(true) .v5("a") .v6("b") .v7(1) .v8(0.1) .v9(2L) .build() .withV1(2) .withV2(0.3); } @SuppressWarnings("CheckReturnValue") public void multipleCheck0() { ImmutableMultipleChecks.C.builder().a(1).b(1).build(); } @SuppressWarnings("CheckReturnValue") @Test public void multipleCheck1() { assertThrows(IllegalStateException.class, () -> ImmutableMultipleChecks.C.builder().a(0).b(1).build()); } @SuppressWarnings("CheckReturnValue") @Test public void multipleCheck2() { assertThrows(IllegalStateException.class, () -> ImmutableMultipleChecks.C.builder().a(1).b(0).build()); } @Test public void redactedCompletely() { ImmutableRedacted b = ImmutableRedacted.builder() .id(2) .code(1) .data("a", "b") .ssn("000-00-000") .build(); check(b).hasToString("Redacted{id=2}"); } @Test public void redactedMask() { ImmutableRedactedMask m = ImmutableRedactedMask.builder() .code(1) .build(); check(m).hasToString("RedactedMask{code=####}"); } @Test public void redactedMaskJdkOnly() { ImmutableRedactedMaskJdkOnly m = ImmutableRedactedMaskJdkOnly.builder() .code(1) .build(); check(m).hasToString("RedactedMaskJdkOnly{code=$$$$}"); } @Test public void redactedMaskJdkOnlyOpt() { ImmutableRedactedMaskJdkOnlyOpt m = ImmutableRedactedMaskJdkOnlyOpt.builder() .code(1) .build(); check(m).hasToString("RedactedMaskJdkOnlyOpt{code=????}"); } @Test public void withStringEqualsRegardlessOfTypeAnnotation() { ImmutableWithThisCheckForNoNilString o = ImmutableWithThisCheckForNoNilString.builder() .a("a") .b("b") .build(); // with should use equals short-circuit check to return this, not reference equality // so we create "new String" check(o.withA(new String("a"))).same(o); check(o.withB(new String("b"))).same(o); check(o.withA("other")).not().same(o); } @Test public void lazyThrows() { ImmutableThrowsClauses t = ImmutableThrowsClauses.builder() .a(1) .b("b") .build(); Exception previousEx = null; boolean returned = false; try { returned = t.d(); check(false); } catch (IOException | ExecutionException ex) { previousEx = ex; check(ex.getMessage()).is("d"); } // not memoising and thrown again new exception try { returned = t.d(); check(false); } catch (IOException | ExecutionException ex) { check(previousEx).notNull(); check(previousEx).not().same(ex); check(ex.getMessage()).is("d"); } check(!returned); // this is just for compiler error prone so that we read d() and also use it } }
apache-2.0
gawkermedia/googleads-java-lib
modules/dfp_axis/src/main/java/com/google/api/ads/dfp/axis/v201505/ContactServiceSoapBindingStub.java
39303
/** * ContactServiceSoapBindingStub.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter. */ package com.google.api.ads.dfp.axis.v201505; public class ContactServiceSoapBindingStub extends org.apache.axis.client.Stub implements com.google.api.ads.dfp.axis.v201505.ContactServiceInterface { private java.util.Vector cachedSerClasses = new java.util.Vector(); private java.util.Vector cachedSerQNames = new java.util.Vector(); private java.util.Vector cachedSerFactories = new java.util.Vector(); private java.util.Vector cachedDeserFactories = new java.util.Vector(); static org.apache.axis.description.OperationDesc [] _operations; static { _operations = new org.apache.axis.description.OperationDesc[3]; _initOperationDesc1(); } private static void _initOperationDesc1(){ org.apache.axis.description.OperationDesc oper; org.apache.axis.description.ParameterDesc param; oper = new org.apache.axis.description.OperationDesc(); oper.setName("createContacts"); param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "contacts"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "Contact"), com.google.api.ads.dfp.axis.v201505.Contact[].class, false, false); param.setOmittable(true); oper.addParameter(param); oper.setReturnType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "Contact")); oper.setReturnClass(com.google.api.ads.dfp.axis.v201505.Contact[].class); oper.setReturnQName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "rval")); oper.setStyle(org.apache.axis.constants.Style.WRAPPED); oper.setUse(org.apache.axis.constants.Use.LITERAL); oper.addFault(new org.apache.axis.description.FaultDesc( new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "ApiExceptionFault"), "com.google.api.ads.dfp.axis.v201505.ApiException", new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "ApiException"), true )); _operations[0] = oper; oper = new org.apache.axis.description.OperationDesc(); oper.setName("getContactsByStatement"); param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "statement"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "Statement"), com.google.api.ads.dfp.axis.v201505.Statement.class, false, false); param.setOmittable(true); oper.addParameter(param); oper.setReturnType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "ContactPage")); oper.setReturnClass(com.google.api.ads.dfp.axis.v201505.ContactPage.class); oper.setReturnQName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "rval")); oper.setStyle(org.apache.axis.constants.Style.WRAPPED); oper.setUse(org.apache.axis.constants.Use.LITERAL); oper.addFault(new org.apache.axis.description.FaultDesc( new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "ApiExceptionFault"), "com.google.api.ads.dfp.axis.v201505.ApiException", new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "ApiException"), true )); _operations[1] = oper; oper = new org.apache.axis.description.OperationDesc(); oper.setName("updateContacts"); param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "contacts"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "Contact"), com.google.api.ads.dfp.axis.v201505.Contact[].class, false, false); param.setOmittable(true); oper.addParameter(param); oper.setReturnType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "Contact")); oper.setReturnClass(com.google.api.ads.dfp.axis.v201505.Contact[].class); oper.setReturnQName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "rval")); oper.setStyle(org.apache.axis.constants.Style.WRAPPED); oper.setUse(org.apache.axis.constants.Use.LITERAL); oper.addFault(new org.apache.axis.description.FaultDesc( new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "ApiExceptionFault"), "com.google.api.ads.dfp.axis.v201505.ApiException", new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "ApiException"), true )); _operations[2] = oper; } public ContactServiceSoapBindingStub() throws org.apache.axis.AxisFault { this(null); } public ContactServiceSoapBindingStub(java.net.URL endpointURL, javax.xml.rpc.Service service) throws org.apache.axis.AxisFault { this(service); super.cachedEndpoint = endpointURL; } public ContactServiceSoapBindingStub(javax.xml.rpc.Service service) throws org.apache.axis.AxisFault { if (service == null) { super.service = new org.apache.axis.client.Service(); } else { super.service = service; } ((org.apache.axis.client.Service)super.service).setTypeMappingVersion("1.2"); java.lang.Class cls; javax.xml.namespace.QName qName; javax.xml.namespace.QName qName2; java.lang.Class beansf = org.apache.axis.encoding.ser.BeanSerializerFactory.class; java.lang.Class beandf = org.apache.axis.encoding.ser.BeanDeserializerFactory.class; java.lang.Class enumsf = org.apache.axis.encoding.ser.EnumSerializerFactory.class; java.lang.Class enumdf = org.apache.axis.encoding.ser.EnumDeserializerFactory.class; java.lang.Class arraysf = org.apache.axis.encoding.ser.ArraySerializerFactory.class; java.lang.Class arraydf = org.apache.axis.encoding.ser.ArrayDeserializerFactory.class; java.lang.Class simplesf = org.apache.axis.encoding.ser.SimpleSerializerFactory.class; java.lang.Class simpledf = org.apache.axis.encoding.ser.SimpleDeserializerFactory.class; java.lang.Class simplelistsf = org.apache.axis.encoding.ser.SimpleListSerializerFactory.class; java.lang.Class simplelistdf = org.apache.axis.encoding.ser.SimpleListDeserializerFactory.class; qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "ApiError"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.ApiError.class; cachedSerClasses.add(cls); cachedSerFactories.add(beansf); cachedDeserFactories.add(beandf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "ApiException"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.ApiException.class; cachedSerClasses.add(cls); cachedSerFactories.add(beansf); cachedDeserFactories.add(beandf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "ApiVersionError"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.ApiVersionError.class; cachedSerClasses.add(cls); cachedSerFactories.add(beansf); cachedDeserFactories.add(beandf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "ApiVersionError.Reason"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.ApiVersionErrorReason.class; cachedSerClasses.add(cls); cachedSerFactories.add(enumsf); cachedDeserFactories.add(enumdf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "ApplicationException"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.ApplicationException.class; cachedSerClasses.add(cls); cachedSerFactories.add(beansf); cachedDeserFactories.add(beandf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "AuthenticationError"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.AuthenticationError.class; cachedSerClasses.add(cls); cachedSerFactories.add(beansf); cachedDeserFactories.add(beandf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "AuthenticationError.Reason"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.AuthenticationErrorReason.class; cachedSerClasses.add(cls); cachedSerFactories.add(enumsf); cachedDeserFactories.add(enumdf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "BaseContact"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.BaseContact.class; cachedSerClasses.add(cls); cachedSerFactories.add(beansf); cachedDeserFactories.add(beandf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "BooleanValue"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.BooleanValue.class; cachedSerClasses.add(cls); cachedSerFactories.add(beansf); cachedDeserFactories.add(beandf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "CollectionSizeError"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.CollectionSizeError.class; cachedSerClasses.add(cls); cachedSerFactories.add(beansf); cachedDeserFactories.add(beandf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "CollectionSizeError.Reason"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.CollectionSizeErrorReason.class; cachedSerClasses.add(cls); cachedSerFactories.add(enumsf); cachedDeserFactories.add(enumdf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "CommonError"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.CommonError.class; cachedSerClasses.add(cls); cachedSerFactories.add(beansf); cachedDeserFactories.add(beandf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "CommonError.Reason"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.CommonErrorReason.class; cachedSerClasses.add(cls); cachedSerFactories.add(enumsf); cachedDeserFactories.add(enumdf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "Contact"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.Contact.class; cachedSerClasses.add(cls); cachedSerFactories.add(beansf); cachedDeserFactories.add(beandf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "Contact.Status"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.ContactStatus.class; cachedSerClasses.add(cls); cachedSerFactories.add(enumsf); cachedDeserFactories.add(enumdf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "ContactError"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.ContactError.class; cachedSerClasses.add(cls); cachedSerFactories.add(beansf); cachedDeserFactories.add(beandf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "ContactError.Reason"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.ContactErrorReason.class; cachedSerClasses.add(cls); cachedSerFactories.add(enumsf); cachedDeserFactories.add(enumdf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "ContactPage"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.ContactPage.class; cachedSerClasses.add(cls); cachedSerFactories.add(beansf); cachedDeserFactories.add(beandf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "Date"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.Date.class; cachedSerClasses.add(cls); cachedSerFactories.add(beansf); cachedDeserFactories.add(beandf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "DateTime"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.DateTime.class; cachedSerClasses.add(cls); cachedSerFactories.add(beansf); cachedDeserFactories.add(beandf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "DateTimeValue"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.DateTimeValue.class; cachedSerClasses.add(cls); cachedSerFactories.add(beansf); cachedDeserFactories.add(beandf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "DateValue"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.DateValue.class; cachedSerClasses.add(cls); cachedSerFactories.add(beansf); cachedDeserFactories.add(beandf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "FeatureError"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.FeatureError.class; cachedSerClasses.add(cls); cachedSerFactories.add(beansf); cachedDeserFactories.add(beandf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "FeatureError.Reason"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.FeatureErrorReason.class; cachedSerClasses.add(cls); cachedSerFactories.add(enumsf); cachedDeserFactories.add(enumdf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "InternalApiError"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.InternalApiError.class; cachedSerClasses.add(cls); cachedSerFactories.add(beansf); cachedDeserFactories.add(beandf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "InternalApiError.Reason"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.InternalApiErrorReason.class; cachedSerClasses.add(cls); cachedSerFactories.add(enumsf); cachedDeserFactories.add(enumdf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "InvalidEmailError"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.InvalidEmailError.class; cachedSerClasses.add(cls); cachedSerFactories.add(beansf); cachedDeserFactories.add(beandf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "InvalidEmailError.Reason"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.InvalidEmailErrorReason.class; cachedSerClasses.add(cls); cachedSerFactories.add(enumsf); cachedDeserFactories.add(enumdf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "NotNullError"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.NotNullError.class; cachedSerClasses.add(cls); cachedSerFactories.add(beansf); cachedDeserFactories.add(beandf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "NotNullError.Reason"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.NotNullErrorReason.class; cachedSerClasses.add(cls); cachedSerFactories.add(enumsf); cachedDeserFactories.add(enumdf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "NumberValue"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.NumberValue.class; cachedSerClasses.add(cls); cachedSerFactories.add(beansf); cachedDeserFactories.add(beandf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "ObjectValue"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.ObjectValue.class; cachedSerClasses.add(cls); cachedSerFactories.add(beansf); cachedDeserFactories.add(beandf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "ParseError"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.ParseError.class; cachedSerClasses.add(cls); cachedSerFactories.add(beansf); cachedDeserFactories.add(beandf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "ParseError.Reason"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.ParseErrorReason.class; cachedSerClasses.add(cls); cachedSerFactories.add(enumsf); cachedDeserFactories.add(enumdf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "PermissionError"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.PermissionError.class; cachedSerClasses.add(cls); cachedSerFactories.add(beansf); cachedDeserFactories.add(beandf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "PermissionError.Reason"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.PermissionErrorReason.class; cachedSerClasses.add(cls); cachedSerFactories.add(enumsf); cachedDeserFactories.add(enumdf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "PublisherQueryLanguageContextError"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.PublisherQueryLanguageContextError.class; cachedSerClasses.add(cls); cachedSerFactories.add(beansf); cachedDeserFactories.add(beandf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "PublisherQueryLanguageContextError.Reason"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.PublisherQueryLanguageContextErrorReason.class; cachedSerClasses.add(cls); cachedSerFactories.add(enumsf); cachedDeserFactories.add(enumdf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "PublisherQueryLanguageSyntaxError"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.PublisherQueryLanguageSyntaxError.class; cachedSerClasses.add(cls); cachedSerFactories.add(beansf); cachedDeserFactories.add(beandf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "PublisherQueryLanguageSyntaxError.Reason"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.PublisherQueryLanguageSyntaxErrorReason.class; cachedSerClasses.add(cls); cachedSerFactories.add(enumsf); cachedDeserFactories.add(enumdf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "QuotaError"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.QuotaError.class; cachedSerClasses.add(cls); cachedSerFactories.add(beansf); cachedDeserFactories.add(beandf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "QuotaError.Reason"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.QuotaErrorReason.class; cachedSerClasses.add(cls); cachedSerFactories.add(enumsf); cachedDeserFactories.add(enumdf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "RequiredCollectionError"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.RequiredCollectionError.class; cachedSerClasses.add(cls); cachedSerFactories.add(beansf); cachedDeserFactories.add(beandf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "RequiredCollectionError.Reason"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.RequiredCollectionErrorReason.class; cachedSerClasses.add(cls); cachedSerFactories.add(enumsf); cachedDeserFactories.add(enumdf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "RequiredError"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.RequiredError.class; cachedSerClasses.add(cls); cachedSerFactories.add(beansf); cachedDeserFactories.add(beandf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "RequiredError.Reason"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.RequiredErrorReason.class; cachedSerClasses.add(cls); cachedSerFactories.add(enumsf); cachedDeserFactories.add(enumdf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "ServerError"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.ServerError.class; cachedSerClasses.add(cls); cachedSerFactories.add(beansf); cachedDeserFactories.add(beandf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "ServerError.Reason"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.ServerErrorReason.class; cachedSerClasses.add(cls); cachedSerFactories.add(enumsf); cachedDeserFactories.add(enumdf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "SetValue"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.SetValue.class; cachedSerClasses.add(cls); cachedSerFactories.add(beansf); cachedDeserFactories.add(beandf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "SoapRequestHeader"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.SoapRequestHeader.class; cachedSerClasses.add(cls); cachedSerFactories.add(beansf); cachedDeserFactories.add(beandf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "SoapResponseHeader"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.SoapResponseHeader.class; cachedSerClasses.add(cls); cachedSerFactories.add(beansf); cachedDeserFactories.add(beandf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "Statement"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.Statement.class; cachedSerClasses.add(cls); cachedSerFactories.add(beansf); cachedDeserFactories.add(beandf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "StatementError"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.StatementError.class; cachedSerClasses.add(cls); cachedSerFactories.add(beansf); cachedDeserFactories.add(beandf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "StatementError.Reason"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.StatementErrorReason.class; cachedSerClasses.add(cls); cachedSerFactories.add(enumsf); cachedDeserFactories.add(enumdf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "String_ValueMapEntry"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.String_ValueMapEntry.class; cachedSerClasses.add(cls); cachedSerFactories.add(beansf); cachedDeserFactories.add(beandf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "StringLengthError"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.StringLengthError.class; cachedSerClasses.add(cls); cachedSerFactories.add(beansf); cachedDeserFactories.add(beandf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "StringLengthError.Reason"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.StringLengthErrorReason.class; cachedSerClasses.add(cls); cachedSerFactories.add(enumsf); cachedDeserFactories.add(enumdf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "TextValue"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.TextValue.class; cachedSerClasses.add(cls); cachedSerFactories.add(beansf); cachedDeserFactories.add(beandf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "UniqueError"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.UniqueError.class; cachedSerClasses.add(cls); cachedSerFactories.add(beansf); cachedDeserFactories.add(beandf); qName = new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "Value"); cachedSerQNames.add(qName); cls = com.google.api.ads.dfp.axis.v201505.Value.class; cachedSerClasses.add(cls); cachedSerFactories.add(beansf); cachedDeserFactories.add(beandf); } protected org.apache.axis.client.Call createCall() throws java.rmi.RemoteException { try { org.apache.axis.client.Call _call = super._createCall(); if (super.maintainSessionSet) { _call.setMaintainSession(super.maintainSession); } if (super.cachedUsername != null) { _call.setUsername(super.cachedUsername); } if (super.cachedPassword != null) { _call.setPassword(super.cachedPassword); } if (super.cachedEndpoint != null) { _call.setTargetEndpointAddress(super.cachedEndpoint); } if (super.cachedTimeout != null) { _call.setTimeout(super.cachedTimeout); } if (super.cachedPortName != null) { _call.setPortName(super.cachedPortName); } java.util.Enumeration keys = super.cachedProperties.keys(); while (keys.hasMoreElements()) { java.lang.String key = (java.lang.String) keys.nextElement(); _call.setProperty(key, super.cachedProperties.get(key)); } // All the type mapping information is registered // when the first call is made. // The type mapping information is actually registered in // the TypeMappingRegistry of the service, which // is the reason why registration is only needed for the first call. synchronized (this) { if (firstCall()) { // must set encoding style before registering serializers _call.setEncodingStyle(null); for (int i = 0; i < cachedSerFactories.size(); ++i) { java.lang.Class cls = (java.lang.Class) cachedSerClasses.get(i); javax.xml.namespace.QName qName = (javax.xml.namespace.QName) cachedSerQNames.get(i); java.lang.Object x = cachedSerFactories.get(i); if (x instanceof Class) { java.lang.Class sf = (java.lang.Class) cachedSerFactories.get(i); java.lang.Class df = (java.lang.Class) cachedDeserFactories.get(i); _call.registerTypeMapping(cls, qName, sf, df, false); } else if (x instanceof javax.xml.rpc.encoding.SerializerFactory) { org.apache.axis.encoding.SerializerFactory sf = (org.apache.axis.encoding.SerializerFactory) cachedSerFactories.get(i); org.apache.axis.encoding.DeserializerFactory df = (org.apache.axis.encoding.DeserializerFactory) cachedDeserFactories.get(i); _call.registerTypeMapping(cls, qName, sf, df, false); } } } } return _call; } catch (java.lang.Throwable _t) { throw new org.apache.axis.AxisFault("Failure trying to get the Call object", _t); } } public com.google.api.ads.dfp.axis.v201505.Contact[] createContacts(com.google.api.ads.dfp.axis.v201505.Contact[] contacts) throws java.rmi.RemoteException, com.google.api.ads.dfp.axis.v201505.ApiException { if (super.cachedEndpoint == null) { throw new org.apache.axis.NoEndPointException(); } org.apache.axis.client.Call _call = createCall(); _call.setOperation(_operations[0]); _call.setUseSOAPAction(true); _call.setSOAPActionURI(""); _call.setEncodingStyle(null); _call.setProperty(org.apache.axis.client.Call.SEND_TYPE_ATTR, Boolean.FALSE); _call.setProperty(org.apache.axis.AxisEngine.PROP_DOMULTIREFS, Boolean.FALSE); _call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS); _call.setOperationName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "createContacts")); setRequestHeaders(_call); setAttachments(_call); try { java.lang.Object _resp = _call.invoke(new java.lang.Object[] {contacts}); if (_resp instanceof java.rmi.RemoteException) { throw (java.rmi.RemoteException)_resp; } else { extractAttachments(_call); try { return (com.google.api.ads.dfp.axis.v201505.Contact[]) _resp; } catch (java.lang.Exception _exception) { return (com.google.api.ads.dfp.axis.v201505.Contact[]) org.apache.axis.utils.JavaUtils.convert(_resp, com.google.api.ads.dfp.axis.v201505.Contact[].class); } } } catch (org.apache.axis.AxisFault axisFaultException) { if (axisFaultException.detail != null) { if (axisFaultException.detail instanceof java.rmi.RemoteException) { throw (java.rmi.RemoteException) axisFaultException.detail; } if (axisFaultException.detail instanceof com.google.api.ads.dfp.axis.v201505.ApiException) { throw (com.google.api.ads.dfp.axis.v201505.ApiException) axisFaultException.detail; } } throw axisFaultException; } } public com.google.api.ads.dfp.axis.v201505.ContactPage getContactsByStatement(com.google.api.ads.dfp.axis.v201505.Statement statement) throws java.rmi.RemoteException, com.google.api.ads.dfp.axis.v201505.ApiException { if (super.cachedEndpoint == null) { throw new org.apache.axis.NoEndPointException(); } org.apache.axis.client.Call _call = createCall(); _call.setOperation(_operations[1]); _call.setUseSOAPAction(true); _call.setSOAPActionURI(""); _call.setEncodingStyle(null); _call.setProperty(org.apache.axis.client.Call.SEND_TYPE_ATTR, Boolean.FALSE); _call.setProperty(org.apache.axis.AxisEngine.PROP_DOMULTIREFS, Boolean.FALSE); _call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS); _call.setOperationName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "getContactsByStatement")); setRequestHeaders(_call); setAttachments(_call); try { java.lang.Object _resp = _call.invoke(new java.lang.Object[] {statement}); if (_resp instanceof java.rmi.RemoteException) { throw (java.rmi.RemoteException)_resp; } else { extractAttachments(_call); try { return (com.google.api.ads.dfp.axis.v201505.ContactPage) _resp; } catch (java.lang.Exception _exception) { return (com.google.api.ads.dfp.axis.v201505.ContactPage) org.apache.axis.utils.JavaUtils.convert(_resp, com.google.api.ads.dfp.axis.v201505.ContactPage.class); } } } catch (org.apache.axis.AxisFault axisFaultException) { if (axisFaultException.detail != null) { if (axisFaultException.detail instanceof java.rmi.RemoteException) { throw (java.rmi.RemoteException) axisFaultException.detail; } if (axisFaultException.detail instanceof com.google.api.ads.dfp.axis.v201505.ApiException) { throw (com.google.api.ads.dfp.axis.v201505.ApiException) axisFaultException.detail; } } throw axisFaultException; } } public com.google.api.ads.dfp.axis.v201505.Contact[] updateContacts(com.google.api.ads.dfp.axis.v201505.Contact[] contacts) throws java.rmi.RemoteException, com.google.api.ads.dfp.axis.v201505.ApiException { if (super.cachedEndpoint == null) { throw new org.apache.axis.NoEndPointException(); } org.apache.axis.client.Call _call = createCall(); _call.setOperation(_operations[2]); _call.setUseSOAPAction(true); _call.setSOAPActionURI(""); _call.setEncodingStyle(null); _call.setProperty(org.apache.axis.client.Call.SEND_TYPE_ATTR, Boolean.FALSE); _call.setProperty(org.apache.axis.AxisEngine.PROP_DOMULTIREFS, Boolean.FALSE); _call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS); _call.setOperationName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "updateContacts")); setRequestHeaders(_call); setAttachments(_call); try { java.lang.Object _resp = _call.invoke(new java.lang.Object[] {contacts}); if (_resp instanceof java.rmi.RemoteException) { throw (java.rmi.RemoteException)_resp; } else { extractAttachments(_call); try { return (com.google.api.ads.dfp.axis.v201505.Contact[]) _resp; } catch (java.lang.Exception _exception) { return (com.google.api.ads.dfp.axis.v201505.Contact[]) org.apache.axis.utils.JavaUtils.convert(_resp, com.google.api.ads.dfp.axis.v201505.Contact[].class); } } } catch (org.apache.axis.AxisFault axisFaultException) { if (axisFaultException.detail != null) { if (axisFaultException.detail instanceof java.rmi.RemoteException) { throw (java.rmi.RemoteException) axisFaultException.detail; } if (axisFaultException.detail instanceof com.google.api.ads.dfp.axis.v201505.ApiException) { throw (com.google.api.ads.dfp.axis.v201505.ApiException) axisFaultException.detail; } } throw axisFaultException; } } }
apache-2.0