code
stringlengths 4
1.01M
| language
stringclasses 2
values |
|---|---|
package ai.api.test;
/***********************************************************************************************************************
*
* API.AI Java SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2014 by Speaktoit, Inc. (https://www.speaktoit.com)
* https://www.api.ai
*
***********************************************************************************************************************
*
* 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 ProtocolProdTest extends ProtocolTestBase {
// Testing keys
protected static final String ACCESS_TOKEN = "3485a96fb27744db83e78b8c4bc9e7b7";
protected String getAccessToken() {
return ACCESS_TOKEN;
}
@Override
protected String getSecondAccessToken() {
return "968235e8e4954cf0bb0dc07736725ecd";
}
protected String getRuAccessToken(){
return "07806228a357411d83064309a279c7fd";
}
protected String getBrAccessToken(){
// TODO
return "";
}
protected String getPtBrAccessToken(){
return "42db6ad6a51c47088318a8104833b66c";
}
@Override
protected String getJaAccessToken() {
// TODO
return "";
}
}
|
Java
|
class AddResourceToVersions < ActiveRecord::Migration[6.0]
def change
add_column :versions, :resource_id, :integer
add_column :versions, :resource_type, :string
add_index :versions, [:resource_type, :resource_id]
end
end
|
Java
|
package org.drools.persistence;
import javax.transaction.xa.XAResource;
public interface PersistenceManager {
XAResource getXAResource();
Transaction getTransaction();
void save();
void load();
}
|
Java
|
/*
* 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 org.jboss.netty.handler.codec.serialization;
import java.util.concurrent.Executor;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.socket.oio.OioClientSocketChannelFactory;
import org.jboss.netty.channel.socket.oio.OioServerSocketChannelFactory;
public class OioOioSocketCompatibleObjectStreamEchoTest extends AbstractSocketCompatibleObjectStreamEchoTest {
@Override
protected ChannelFactory newClientSocketChannelFactory(Executor executor) {
return new OioClientSocketChannelFactory(executor);
}
@Override
protected ChannelFactory newServerSocketChannelFactory(Executor executor) {
return new OioServerSocketChannelFactory(executor, executor);
}
}
|
Java
|
package com.coolweather.android;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.preference.PreferenceManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ScrollingView;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.coolweather.android.gson.Forecast;
import com.coolweather.android.gson.Weather;
import com.coolweather.android.service.AutoUpdateService;
import com.coolweather.android.util.HttpUtil;
import com.coolweather.android.util.Utility;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class WeatherActivity extends AppCompatActivity {
private ScrollView weatherLayout;
private TextView titleCity;
private TextView titleUpdateTime;
private TextView degreeText;
private TextView weatherInfoText;
private LinearLayout forecastLayout;
private TextView aqiText;
private TextView pm25Text;
private TextView comfortText;
private TextView carWashText;
private TextView sportText;
private ImageView bingPicImg;
public SwipeRefreshLayout swipeRefreshLayout;
private String mWeatherId;
public DrawerLayout drawerLayout;
private Button navButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= 21) {
View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
getWindow().setStatusBarColor(Color.TRANSPARENT);
}
setContentView(R.layout.activity_weather);
//初始条件
weatherLayout = (ScrollView) findViewById(R.id.weather_layout);
titleCity = (TextView) findViewById(R.id.title_city);
titleUpdateTime = (TextView) findViewById(R.id.title_update_time);
degreeText = (TextView) findViewById(R.id.degree_text);
weatherInfoText = (TextView) findViewById(R.id.weather_info_text);
forecastLayout = (LinearLayout) findViewById(R.id.forecast_layout);
aqiText = (TextView) findViewById(R.id.aqi_text);
pm25Text = (TextView) findViewById(R.id.pm25_text);
comfortText = (TextView) findViewById(R.id.comfort_text);
carWashText = (TextView) findViewById(R.id.car_wash_text);
sportText = (TextView) findViewById(R.id.sport_text);
bingPicImg = (ImageView) findViewById(R.id.bing_pic_img);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
navButton = (Button) findViewById(R.id.nav_button);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh);
swipeRefreshLayout.setColorSchemeResources(R.color.colorTopic);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String weatherString = prefs.getString("weather", null);
if (weatherString != null) {
//有缓存时直接解析天气数据
Weather weather = Utility.handleWeatherResponse(weatherString);
mWeatherId = weather.basic.weatherId;
showWeatherInfo(weather);
} else {
//无缓存时去服务器查询天气
mWeatherId = getIntent().getStringExtra("weather_id");
String weatherId = getIntent().getStringExtra("weather_id");
weatherLayout.setVisibility(View.INVISIBLE);
requestWeather(weatherId);
}
navButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
drawerLayout.openDrawer(GravityCompat.START);
}
});
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
requestWeather(mWeatherId);
}
});
String bingPic = prefs.getString("bing_pic", null);
if (bingPic != null) {
Glide.with(this).load(bingPic).into(bingPicImg);
} else {
loadBingPic();
}
}
/**
* 根据天气ID请求城市天气信息
*/
public void requestWeather(final String weatherId) {
String weatherUtl = "http://guolin.tech/api/weather?cityid=" + weatherId + "&key=04ae9fa43fb341b596f719aa6d6babda";
HttpUtil.sendOkHttpRequest(weatherUtl, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(WeatherActivity.this, "获取天气信息失败", Toast.LENGTH_SHORT).show();
swipeRefreshLayout.setRefreshing(false);
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String responseText = response.body().string();
final Weather weather = Utility.handleWeatherResponse(responseText);
runOnUiThread(new Runnable() {
@Override
public void run() {
if (weather != null && "ok".equals(weather.status)) {
SharedPreferences.Editor editor = PreferenceManager
.getDefaultSharedPreferences(WeatherActivity.this).edit();
editor.putString("weather", responseText);
editor.apply();
Toast.makeText(WeatherActivity.this, "成功更新最新天气", Toast.LENGTH_SHORT).show();
showWeatherInfo(weather);
} else {
Toast.makeText(WeatherActivity.this, "获取天气信息失败", Toast.LENGTH_SHORT).show();
}
swipeRefreshLayout.setRefreshing(false);
}
});
}
});
loadBingPic();
}
private void loadBingPic() {
String requestBingPic = "http://guolin.tech/api/bing_pic";
HttpUtil.sendOkHttpRequest(requestBingPic, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String bingPic = response.body().string();
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
editor.putString("bing_pic", bingPic);
editor.apply();
runOnUiThread(new Runnable() {
@Override
public void run() {
Glide.with(WeatherActivity.this).load(bingPic).into(bingPicImg);
}
});
}
});
}
/**
* 处理并展示Weather实体类中的数据
*/
private void showWeatherInfo(Weather weather) {
String cityName = weather.basic.cityName;
String updateTime = "更新时间: " + weather.basic.update.updateTime.split(" ")[1];
String degree = weather.now.temperature + "ºC";
String weatherInfo = weather.now.more.info;
titleCity.setText(cityName);
titleUpdateTime.setText(updateTime);
degreeText.setText(degree);
weatherInfoText.setText(weatherInfo);
forecastLayout.removeAllViews();
for (Forecast forecast : weather.forecastList) {
View view = LayoutInflater.from(this).inflate(R.layout.forecast_item, forecastLayout, false);
TextView dateText = (TextView) view.findViewById(R.id.date_text);
TextView infoText = (TextView) view.findViewById(R.id.info_text);
TextView maxText = (TextView) view.findViewById(R.id.max_text);
TextView minText = (TextView) view.findViewById(R.id.min_text);
dateText.setText(forecast.date);
infoText.setText(forecast.more.info);
maxText.setText(forecast.temperature.max);
minText.setText(forecast.temperature.min);
forecastLayout.addView(view);
}
if (weather.aqi != null) {
aqiText.setText(weather.aqi.city.aqi);
pm25Text.setText(weather.aqi.city.pm25);
}
String comfort = "舒适度:" + weather.suggestion.comfort.info;
String catWash = "洗车指数:" + weather.suggestion.carWash.info;
String sport = "运动指数:" + weather.suggestion.sport.info;
comfortText.setText(comfort);
carWashText.setText(catWash);
sportText.setText(sport);
weatherLayout.setVisibility(View.VISIBLE);
if (weather != null && "ok".equals(weather.status)) {
Intent intent = new Intent(this, AutoUpdateService.class);
startService(intent);
} else {
Toast.makeText(WeatherActivity.this, "获取天气信息失败", Toast.LENGTH_SHORT).show();
}
}
}
|
Java
|
# 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
#
# 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 Google::Ads::GoogleAds::V9::Enums::BudgetDeliveryMethodEnum;
use strict;
use warnings;
use Const::Exporter enums => [
UNSPECIFIED => "UNSPECIFIED",
UNKNOWN => "UNKNOWN",
STANDARD => "STANDARD",
ACCELERATED => "ACCELERATED"
];
1;
|
Java
|
package com.example.cdm.huntfun.activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.widget.TextView;
import com.example.cdm.huntfun.R;
import com.example.cdm.huntfun.photoView.ImageDetailFragment;
import com.example.cdm.huntfun.widget.HackyViewPager;
import java.util.List;
/**
* 图片查看器
*/
public class ImagePagerActivity extends FragmentActivity {
private static final String STATE_POSITION = "STATE_POSITION";
public static final String EXTRA_IMAGE_INDEX = "image_index";
public static final String EXTRA_IMAGE_URLS = "image_urls";
private HackyViewPager mPager;
private int pagerPosition;
private TextView indicator;
// public static Drawable DEFAULTDRAWABLE;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.umessage_image_detail_pager);
// DEFAULTDRAWABLE=this.getResources().getDrawable(R.drawable.umessage_load_default);
pagerPosition = getIntent().getIntExtra(EXTRA_IMAGE_INDEX, 0);
List<String> urls = getIntent().getStringArrayListExtra(EXTRA_IMAGE_URLS);
mPager = (HackyViewPager) findViewById(R.id.pager);
ImagePagerAdapter mAdapter = new ImagePagerAdapter(getSupportFragmentManager(), urls);
mPager.setAdapter(mAdapter);
indicator = (TextView) findViewById(R.id.indicator);
CharSequence text = getString(R.string.xq_viewpager_indicator, 1, mPager.getAdapter().getCount());
indicator.setText(text);
// 更新下标
mPager.addOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageScrollStateChanged(int arg0) {
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
@Override
public void onPageSelected(int arg0) {
CharSequence text = getString(R.string.xq_viewpager_indicator, arg0 + 1, mPager.getAdapter().getCount());
indicator.setText(text);
}
});
if (savedInstanceState != null) {
pagerPosition = savedInstanceState.getInt(STATE_POSITION);
}
mPager.setCurrentItem(pagerPosition);
}
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putInt(STATE_POSITION, mPager.getCurrentItem());
}
private class ImagePagerAdapter extends FragmentStatePagerAdapter {
public List<String> fileList;
public ImagePagerAdapter(FragmentManager fm, List<String> fileList) {
super(fm);
this.fileList = fileList;
}
@Override
public int getCount() {
return fileList == null ? 0 : fileList.size();
}
@Override
public Fragment getItem(int position) {
String url = fileList.get(position);
return ImageDetailFragment.newInstance(url);
}
}
}
|
Java
|
/*
Copyright 2015 The Kubernetes 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 http
import (
"fmt"
"net"
"net/http"
"net/http/httptest"
"net/url"
"os"
"strconv"
"strings"
"testing"
"time"
"k8s.io/kubernetes/pkg/probe"
)
const FailureCode int = -1
func setEnv(key, value string) func() {
originalValue := os.Getenv(key)
os.Setenv(key, value)
if len(originalValue) > 0 {
return func() {
os.Setenv(key, originalValue)
}
}
return func() {}
}
func unsetEnv(key string) func() {
originalValue := os.Getenv(key)
os.Unsetenv(key)
if len(originalValue) > 0 {
return func() {
os.Setenv(key, originalValue)
}
}
return func() {}
}
func TestHTTPProbeProxy(t *testing.T) {
res := "welcome to http probe proxy"
localProxy := "http://127.0.0.1:9098/"
defer setEnv("http_proxy", localProxy)()
defer setEnv("HTTP_PROXY", localProxy)()
defer unsetEnv("no_proxy")()
defer unsetEnv("NO_PROXY")()
prober := New()
go func() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, res)
})
err := http.ListenAndServe(":9098", nil)
if err != nil {
t.Errorf("Failed to start foo server: localhost:9098")
}
}()
// take some time to wait server boot
time.Sleep(2 * time.Second)
url, err := url.Parse("http://example.com")
if err != nil {
t.Errorf("proxy test unexpected error: %v", err)
}
_, response, _ := prober.Probe(url, http.Header{}, time.Second*3)
if response == res {
t.Errorf("proxy test unexpected error: the probe is using proxy")
}
}
func TestHTTPProbeChecker(t *testing.T) {
handleReq := func(s int, body string) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(s)
w.Write([]byte(body))
}
}
// Echo handler that returns the contents of request headers in the body
headerEchoHandler := func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
output := ""
for k, arr := range r.Header {
for _, v := range arr {
output += fmt.Sprintf("%s: %s\n", k, v)
}
}
w.Write([]byte(output))
}
redirectHandler := func(s int, bad bool) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" {
http.Redirect(w, r, "/new", s)
} else if bad && r.URL.Path == "/new" {
w.WriteHeader(http.StatusInternalServerError)
}
}
}
prober := New()
testCases := []struct {
handler func(w http.ResponseWriter, r *http.Request)
reqHeaders http.Header
health probe.Result
accBody string
notBody string
}{
// The probe will be filled in below. This is primarily testing that an HTTP GET happens.
{
handler: handleReq(http.StatusOK, "ok body"),
health: probe.Success,
accBody: "ok body",
},
{
handler: headerEchoHandler,
reqHeaders: http.Header{
"X-Muffins-Or-Cupcakes": {"muffins"},
},
health: probe.Success,
accBody: "X-Muffins-Or-Cupcakes: muffins",
},
{
handler: headerEchoHandler,
reqHeaders: http.Header{
"User-Agent": {"foo/1.0"},
},
health: probe.Success,
accBody: "User-Agent: foo/1.0",
},
{
handler: headerEchoHandler,
reqHeaders: http.Header{
"User-Agent": {""},
},
health: probe.Success,
notBody: "User-Agent",
},
{
handler: headerEchoHandler,
reqHeaders: http.Header{},
health: probe.Success,
accBody: "User-Agent: kube-probe/",
},
{
// Echo handler that returns the contents of Host in the body
handler: func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
w.Write([]byte(r.Host))
},
reqHeaders: http.Header{
"Host": {"muffins.cupcakes.org"},
},
health: probe.Success,
accBody: "muffins.cupcakes.org",
},
{
handler: handleReq(FailureCode, "fail body"),
health: probe.Failure,
},
{
handler: handleReq(http.StatusInternalServerError, "fail body"),
health: probe.Failure,
},
{
handler: func(w http.ResponseWriter, r *http.Request) {
time.Sleep(3 * time.Second)
},
health: probe.Failure,
},
{
handler: redirectHandler(http.StatusMovedPermanently, false), // 301
health: probe.Success,
},
{
handler: redirectHandler(http.StatusMovedPermanently, true), // 301
health: probe.Failure,
},
{
handler: redirectHandler(http.StatusFound, false), // 302
health: probe.Success,
},
{
handler: redirectHandler(http.StatusFound, true), // 302
health: probe.Failure,
},
{
handler: redirectHandler(http.StatusTemporaryRedirect, false), // 307
health: probe.Success,
},
{
handler: redirectHandler(http.StatusTemporaryRedirect, true), // 307
health: probe.Failure,
},
{
handler: redirectHandler(http.StatusPermanentRedirect, false), // 308
health: probe.Success,
},
{
handler: redirectHandler(http.StatusPermanentRedirect, true), // 308
health: probe.Failure,
},
}
for i, test := range testCases {
func() {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
test.handler(w, r)
}))
defer server.Close()
u, err := url.Parse(server.URL)
if err != nil {
t.Errorf("case %d: unexpected error: %v", i, err)
}
_, port, err := net.SplitHostPort(u.Host)
if err != nil {
t.Errorf("case %d: unexpected error: %v", i, err)
}
_, err = strconv.Atoi(port)
if err != nil {
t.Errorf("case %d: unexpected error: %v", i, err)
}
health, output, err := prober.Probe(u, test.reqHeaders, 1*time.Second)
if test.health == probe.Unknown && err == nil {
t.Errorf("case %d: expected error", i)
}
if test.health != probe.Unknown && err != nil {
t.Errorf("case %d: unexpected error: %v", i, err)
}
if health != test.health {
t.Errorf("case %d: expected %v, got %v", i, test.health, health)
}
if health != probe.Failure && test.health != probe.Failure {
if !strings.Contains(output, test.accBody) {
t.Errorf("Expected response body to contain %v, got %v", test.accBody, output)
}
if test.notBody != "" && strings.Contains(output, test.notBody) {
t.Errorf("Expected response not to contain %v, got %v", test.notBody, output)
}
}
}()
}
}
|
Java
|
/* Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0
* http://www.apache.org/licenses/LICENSE-2.0 */
package net.sf.mmm.util.version.impl;
import net.sf.mmm.util.version.api.DevelopmentPhase;
import net.sf.mmm.util.version.api.VersionIdentifier;
/**
* This is the implementation of {@link net.sf.mmm.util.lang.api.Formatter} for the {@link DevelopmentPhase#getValue()
* value} of the {@link VersionIdentifier#getPhase() phase}.
*
* @author Joerg Hohwiller (hohwille at users.sourceforge.net)
* @since 3.0.0
*/
public class VersionIdentifierFormatterPhaseValue extends AbstractVersionIdentifierFormatterString {
/**
* The constructor.
*
* @param prefix is the static prefix to append before the {@link VersionIdentifier#getPhase() phase}. Will be omitted
* if {@link VersionIdentifier#getPhase() phase} is {@code null}.
* @param maximumLength is the maximum number of letters for the {@link VersionIdentifier#getPhase() phase}. The
* default is {@link Integer#MAX_VALUE}.
*/
public VersionIdentifierFormatterPhaseValue(String prefix, int maximumLength) {
super(prefix, maximumLength);
}
@Override
protected String getString(VersionIdentifier value) {
DevelopmentPhase phase = value.getPhase();
if (phase != null) {
return phase.getValue();
}
return null;
}
}
|
Java
|
---
title: "Guía para ser un buen freelance por Paul Jarvis"
date: 2015-08-5 10:00:00
description: Renuncié a mi trabajo en una agencia y busqué trabajar en otra agencia. Mi plan después de renunciar, era ir a la librería (no te rías, esto fue en los 90´s) para aprender como debía escribir mi CV. Como fui contratado directamente desde la escuela, no había escrito uno antes.
image: '../assets/images/posts/freelance.jpg'
label: Diseño
---
Renuncié a mi trabajo en una agencia y busqué trabajar en otra agencia. Mi plan después de renunciar, era ir a la librería (no te rías, esto fue en los 90´s) para aprender como debía escribir mi CV. Como fui contratado directamente desde la escuela, no había escrito uno antes.
> Me convertí en freelance por accidente
Fue curioso y gracioso recibir llamadas de los clientes con los que había trabajado en la agencia mientras iba a la biblioteca, preguntándome cual iba a ser mi siguiente trabajo. Yo manejaba practicamente todo lo relacionado con ellos y ellos apreciaban mi atención y servicio. Tanto que ellos querían continuar trabajando conmigo y estarían dispuestos a seguirme a donde fuera mi próximo trabajo.
Luego de 3 o 4 llamadas después de haber renunciado, tuve una idea...
"Tal vez pueda trabajar por mi cuenta con estos clientes, en vez de llevarlos a que trabajen con otra agencia" ¡Voy a hacerlo!. Esta decisión me acercó al mundo del freelance por el que e vivido los últimos 17 años.
Pero hay más que eso, y aunque no haya un camino para garantizar el éxito como freelance, el plan que tenía podía ayudarme. Y no solo ayudarme a hacer dinero, sino ayudarte a que disfrutes la carrera que estás construyendo. Porqué eres el jefe ahora. Si odias tu trabajo, es tu culpa.
### El plan maestro del freelance:
Las marcas no son solo para las compañias que odias. Tu marca no es un logo, eso es algo que solo va en tus tarjetas de presentación o tu web. Cuando trabajas para ti solo, tu eres tu propia marca. Todo lo que haces y dices es parte de tu marca persona.
Esto es algo bueno, porque mientras vayas adquiriendo éxito como freelance irás destacando. Haces esto contando tu historia y siendo tu mismo en tus artículos, videos, pitch de ventas, newsletters y todo lo demás. También lo haces compartiendo la historia de tus clientes, ellos son el resultado de trabajar contigo, se convierten en tus casos de estudio, portafolio, post de blog y casos de éxito.
Puedes estar atraído por compañias con unas guías de marca y estilos de copy para su web. Después de todo, si quieres ser un profesional, debes sonar como uno ¿Cierto? ERROR. Mientras demuestres más confianza, suenes natural y real, tu marca empezará a hacerse más f uerte. No tengas miedo de tener una opinión.
Tu marca funciona cuando dejas lo que realmente eres brille a través de ti, como una luz en la oscuridad. El efecto se puede ver porqué las personas correctas (las personas con las que quieres trabajar) van a aparecer junto a ti, y todos los demás serán empujados lejos.
### Se exigente
- Le digo no a varios clientes potenciales por buenas razones:
- Decir que no significa que estoy 100% comprometido con lo que actualmente estoy trabajando o haciendo, y esos clientes tienen toda mi atención y creatividad, porque luego ellos volverán por más.
- Decir que no me ayuda a no poner estres ineseariamente para completar todo o trabajar 20 horas al día.
- Decir que no podría significar rechazar el ingreso en un corto plazo, pero también significa que las person que me pagan terminan tan felices que se convierten en mi equipo de ventas en un futuro (es decir, muchos más ingresos).
- Decir que no, no significa necesariamente que no voy a trabajar con un cliente, puede también no ser ahora, pero si lo hago cuando tengo espacios para trabajar.
- Decir que no aveces significa que tengo el presentimiento que puede ser complicado trabajar con un cliente o que no encaje con la forma en que yo trabajo. Esta bien rechazar proyectos cuando sientas que no van a ir bien, porqué es probable que no lo serán. Confio en tus entrañas.
Habrá ocasiones en las que decir "no" no será una opción (no tienes trabajo pero sí cuentas que pagar), pero cuando la opción está disponible puedes hacerlo. El plan A es adherirse a tu visión y no hacer cosas que puedan no encajar. El plan B es hacer lo que se necesita para poder sobrevivir. Yo eligo la A, aunque también la B está bien, lo que me trae a mi siguiente punto.
### Conoce tu propósito
Define por qué el trabajo que haces crea una decisión de alto impacto. Conocer tu propósito te hace más facil poder elegir tus clientes, lo que compartes, lo que rechazas y lo que te mueve.
Pregúntate a ti mismo lo sigiuente:
- ¿Qué representa tu trabajo?
- ¿Cuáles son los objetivos y la visión de tu trabajo?
- ¿Qué hace la diferencia de cualquier otro feelance que comparte tus habilidades?
- ¿Qué quieres conseguir para ti mismo y un logro para tus clientes?
El instinto es un reflejo de tu propósito, si has sido honesto contigo mismo en como lo definiste. Si no lo defines bien podrás tener inquietut y ser persistente con un nuevo proyecto o un cliente, incluso si no hay ningún problema en la superficie. O sientir la necesidad de cambiar la audiencia con la que trabajas y los problemas que estás resolviendo. Tu instinto es tu evaluador interno de tu propósito, y será notorio si te desvías de el o si necesitas hacer un cambio.
### 50% trabajo, 50% prisa
No puedes solo abrir una tienda y actualizar tu bandeja de entrada (trabajar como freelance no funciona así... en realidad, nada funciona así).
No hay anda de malo con salir y vender lo que haces. Nadie vendrá a tomar tu licensia de creatividad y la va a poner una etiqueta de "vendedor empalagoso" en tu frente.
Cuando trabajas para ti, tu eres el jefe de ventas. Eso está bien, vender no significa tuitear en mayúsculas COMPRA TODAS MIS COSAS. Vender es conectar y construir confianza. Cualquiera puede hacer eso.
No importa cuales son tus habilidades o que ofreces como freelance, obtener nuevos negocios se reduce a quienes conoces. Entre más personas lleguen a saber lo que haces, más oportunidades tendrás de trabajar con más clientes. No conozcas personas dándoles un discruso extenso de todo lo que haces, empieza a conectarte con ellos (asiste a eventos, participa en comunidades online, incluso pregúntales si pueden hacer una llamada por Skype y hablar sobre lo que hacen).
**Se trata sobre conexiones reales con personas reales, hacer las preguntas correctas y concentrare en escuchar lo que tienen que decir.**
### Acá no hay competencia
En el mundo corporativo, hemos venido chocando con la competencia. Para ser mejores que ellos, para ofrecer más que ellos y hacer más por menos. Decimos lo que necesitamos decir para estar un paso por delante de ellos, ellos son el enemigo que nos va a destruir cuando tengan la oportunidad.
*Ser freelance no es nada parecido a eso, de hecho, puede ser lo opuesto.*
Los freelances son personas que hacen las mismas cosas o muy parecidas a las que nosotros hacmeos. Tienen habilidades parecidas, conocimiento e incluso pasan por las mismas pruebas y los mismos problemas que nosotros. Pero también son lo suficientemente diferentes para tener una perspectiva de las cosas a como las vemos.
Entonces, ¿Por qué los vemos como enemigos? Ellos hacen parte de nuestra misma comunidad más que cualquier otra persona.
### Presta atención a la actividad de tu negocio
No solo estás creando un trabajo para que tus clientes te paguen por el, también estas administrando proyectos, cuentas y haces seguimiento de los gastos, haciendo reuniones y documentando todo lo que haces.
### Ser freelance es un negocio
Trata tu trabajo como si fuera un negocio y de seguro destacarás sobre el 90% de otras personas que ven el trabajo como "lo haré cuando me sienta interesado por el."
Ser un freelance que hace su trabajo no significa ser excéntrico, significa combinar tus habilidades y tus capacidades de hacer negocios.
### Comparte lo que sabes
Pensar en los líderes actuales de la industria. Esos que obtienen toda la atención, trabajan con los mejores clientes, y parecen reservados a unos precios que parecen casi ridiculos.
#### ¿Qué tenemos en común?
Ellos no son los únicos con talento (aunque están muy cerca), pero todos, sin duda, comparten su conocimiento con su audiencia por mail, libros, conferencias, tutoriales, podcast, artículos y más artículos. Así es como probablemente ellos se dan a conocer, como clientes potenciales los encuentran y como tu sabes sus nombres.
Pero tu puedes hacer lo mismo. Ellos no son guardianes que te impiden agregar tu contenido a tu propia web (o Medium, Linkedin, tumblr, etc...) eres capaz de compartir tus pensamientos, opiniones e ideas en todo internet.
Agregar valor a lo que las personas les interesa hacen que quiran contratarte. ¿Cómo sabes que ellos lo valoran? Pregúntales. O escucha los problemas que tienen, lo que están tratanto de aprender o lo que quieren descubrir.
### Ama el trabajo, no los premios
Tenemos derecho a trabajar, no a los frutos por ese trabajo. El Bhagavad Gita (un antiguo texto sagrado hinduista) dice algo similar, no tenemos derecho a los frutos de nuestra labor, pero solo el trabajo en si mismo. Si se logra entender así, podremos mantener ese derecho.
Tu trabajo se verá afectado si lo haces por likes en Dribbble o retweets de personas que solo te importan por el trabajo que tienen (y no clientes con los que trabajas) porqué estás concentrado en la atención en vez de solucionar un problema. Si te gusta o no, la intención es evidente, así que asegurate de que lo que haces es ciertamente lo que quieres que otros vean y conozcan.
### No tengas miedo
No hay nada de malo con ganar dinero cuando trabajas como freelance. De hecho, ¡es asombroso! Aunque el dinero puede ser incómodo, especialmente cuando proviene de clientes que imponen sus precios. Necesitas estar 100% seguro de lo que cobras, porqué si estás inseguro de eso, tu cliente probablemente también lo será y dudará de ti.
Por suerte puedes prácticar, con amigos o compañeros (o esas personas de otro campo que conoces). Puedes prácticar con clientes potenciales. Incluso si eres la reencarnación de Dale Carnegie, tus primeras impresiones pueden no ser tan claras como te gustaría. Pero con el tiempo vas a ir tomando ritmo para explicarles porqué vales lo que les estás cobrando.
Una regla de oro es que si todos están de acuerdo a trabajar contigo cuando tu les dices tu precio, no te estás sobrecargando.
Recuerda que hacer dinero es bueno, pero hacer dinero gracias a tu propia creatividad en una forma donde se alinea con tu propósito es realmente asombroso.
### Para resumir
Las personas que realmente hacen bien su trabajo no lo hacen por dinero, para comprarse su yate privado o recibir ovaciones (en facebook), ellos lo hacen porqué quieren agregar valor mientras que otros lideran su vida como mejor les parece.
En orden de ideas, para tener una carrera duradera como freelance donde te sientas feliz con ella, tienes que prestar atención, no solo es la forma en que haces las cosas, es en como haces negocios.
No hay un camino para "triunfar como freelance", solo unas cuantas cosas (como las de arriba) a las que les debes poner atención. Anbox and start hitting refresh.
hora regresa a tu bandeja de entrada y empieza a refrescar.
Solo bromeaba.
Todo el mundo sabe que el correo se actualiza solo en estos días...
[Leer artículo original][original]
[original]: https://medium.pjrvs.com/master-working-for-yourself-without-crushing-your-soul-b8a980763d43
|
Java
|
package Escape;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import Escape.Controller.Controller;
import Escape.Model.Arena;
import Escape.Service.Service;
import Escape.View.Rank;
import Escape.View.View;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.LogManager;
/**
* The main class of the program.
*/
public class Escape extends JFrame {
static {
InputStream in = Escape.class.getResourceAsStream("/logging.properties");
if (in != null) {
try {
LogManager.getLogManager().readConfiguration(in);
} catch(IOException e) {
e.printStackTrace();
}
}
}
/**
* The <code>serialVersionUID</code> of the class.
*/
private static final long serialVersionUID = -3689415169655758824L;
/**
* The main JPanel of the <code>frame</code>.
*/
private JPanel contentPane;
/**
* The main <code>Arena</code> object of the program.
*/
private Arena arena;
/**
* Part of the Game tab, the main <code>View</code> object.
*/
private View view;
/**
* The main <code>Controller</code> object of the program.
*/
private Controller control;
/**
* Part of the Rank tab, the main <code>Rank</code> object.
*/
private Rank rank;
/**
* The name of the player.
* Default is "Guest".
*/
private String username = "Guest";
/**
* The password for the database.
*/
private String DAOpassword = "pwd";
/**
* Main method of the program.
* Creates the main JFrame object and asks the user to set <code>DAOpassword</code>
* and <code>username</code> before start the game.
*
* @param args command-line parameters
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Escape frame = new Escape();
frame.setVisible(true);
do{
frame.DAOpassword = JOptionPane.showInputDialog(frame, "Enter password for database!");
} while(frame.DAOpassword.equals("pwd"));
do{
frame.username = JOptionPane.showInputDialog(frame, "Enter your in-game name!");
} while(frame.username.equals("") || frame.username == null);
frame.rank.setDAOpassword(frame.DAOpassword);
frame.rank.refreshRank();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Constructor for the main JFrame object.
* Sets the <code>frame</code> and initialize the <code>arena</code>, <code>view</code>,
* <code>control</code>, <code>rank</code> variables, add tabs.
* Calls the <code>initMenu</code> for add menu.
*/
public Escape() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Escape");
setBounds(300, 0, 0, 0);
pack();
Insets insets = getInsets();
setSize(new Dimension(insets.left + insets.right + 600,
insets.top + insets.bottom + 630));
contentPane = new JPanel();
contentPane.setBackground(Color.WHITE);
arena = new Arena(6, 600);
view = new View(arena);
control = new Controller(arena, view);
view.setControl(control);
rank = new Rank();
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout());
createMenuBar();
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("Game", view);
tabbedPane.addTab("Rank", rank);
tabbedPane.setFocusable(false);
contentPane.add(tabbedPane);
setLocationRelativeTo(view.getPlayer());
}
/**
* Creates the Menu and add to the main JFrame.
* Creates the "New Game", "Save Game" and "Exit" items and
* add ActionListener for control actions.
*/
private void createMenuBar() {
JMenuBar menubar = new JMenuBar();
JMenu file = new JMenu("File");
file.setMnemonic(KeyEvent.VK_F);
JMenuItem newGameMenuItem = new JMenuItem("New Game");
newGameMenuItem.setMnemonic(KeyEvent.VK_E);
newGameMenuItem.setToolTipText("Start a new game");
newGameMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
Service.newGame(arena, control, view);
}
});
JMenuItem saveGameMenuItem = new JMenuItem("Save Game");
saveGameMenuItem.setMnemonic(KeyEvent.VK_E);
saveGameMenuItem.setToolTipText("Save the actual score and start a new game!");
saveGameMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
System.out.println(control.getPlayerScore()+control.getEnemyScore());
Service.saveGame(control, username, DAOpassword);
Service.newGame(arena, control, view);
}
});
JMenuItem exitMenuItem = new JMenuItem("Exit");
exitMenuItem.setMnemonic(KeyEvent.VK_E);
exitMenuItem.setToolTipText("Exit application");
exitMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
file.add(newGameMenuItem);
file.add(saveGameMenuItem);
file.add(exitMenuItem);
menubar.add(file);
setJMenuBar(menubar);
}
}
|
Java
|
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.influxdb;
import org.apache.camel.Consumer;
import org.apache.camel.Processor;
import org.apache.camel.Producer;
import org.apache.camel.support.DefaultEndpoint;
import org.apache.camel.spi.Metadata;
import org.apache.camel.spi.UriEndpoint;
import org.apache.camel.spi.UriParam;
import org.apache.camel.spi.UriPath;
import org.apache.camel.support.CamelContextHelper;
import org.influxdb.InfluxDB;
/**
* The influxdb component allows you to interact with <a href="https://influxdata.com/time-series-platform/influxdb/">InfluxDB</a>, a time series database.
*/
@UriEndpoint(firstVersion = "2.18.0", scheme = "influxdb", title = "InfluxDB", syntax = "influxdb:connectionBean", label = "database", producerOnly = true)
public class InfluxDbEndpoint extends DefaultEndpoint {
private InfluxDB influxDB;
@UriPath
@Metadata(required = "true")
private String connectionBean;
@UriParam
private String databaseName;
@UriParam(defaultValue = "default")
private String retentionPolicy = "default";
@UriParam(defaultValue = "false")
private boolean batch;
@UriParam(defaultValue = InfluxDbOperations.INSERT)
private String operation = InfluxDbOperations.INSERT;
@UriParam
private String query;
public InfluxDbEndpoint(String uri, InfluxDbComponent component) {
super(uri, component);
}
@Override
public Producer createProducer() throws Exception {
return new InfluxDbProducer(this);
}
@Override
public Consumer createConsumer(Processor processor) throws Exception {
throw new UnsupportedOperationException("You cannot receive messages from this endpoint");
}
@Override
protected void doStart() throws Exception {
influxDB = CamelContextHelper.mandatoryLookup(getCamelContext(), connectionBean, InfluxDB.class);
log.debug("Resolved the connection with the name {} as {}", connectionBean, influxDB);
super.doStart();
}
@Override
protected void doStop() throws Exception {
super.doStop();
}
@Override
public boolean isSingleton() {
return true;
}
public InfluxDB getInfluxDB() {
return influxDB;
}
/**
* The Influx DB to use
*/
public void setInfluxDB(InfluxDB influxDB) {
this.influxDB = influxDB;
}
public String getDatabaseName() {
return databaseName;
}
/**
* The name of the database where the time series will be stored
*/
public void setDatabaseName(String databaseName) {
this.databaseName = databaseName;
}
public String getRetentionPolicy() {
return retentionPolicy;
}
/**
* The string that defines the retention policy to the data created by the endpoint
*/
public void setRetentionPolicy(String retentionPolicy) {
this.retentionPolicy = retentionPolicy;
}
public String getConnectionBean() {
return connectionBean;
}
/**
* Connection to the influx database, of class InfluxDB.class
*/
public void setConnectionBean(String connectionBean) {
this.connectionBean = connectionBean;
}
public boolean isBatch() {
return batch;
}
/**
* Define if this operation is a batch operation or not
*/
public void setBatch(boolean batch) {
this.batch = batch;
}
public String getOperation() {
return operation;
}
/**
* Define if this operation is an insert or a query
*/
public void setOperation(String operation) {
this.operation = operation;
}
public String getQuery() {
return query;
}
/**
* Define the query in case of operation query
*/
public void setQuery(String query) {
this.query = query;
}
}
|
Java
|
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.xiaomi.smarthome.common.ui.dialog;
import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import java.lang.ref.WeakReference;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.CursorAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import com.xiaomi.common.R;
public class MLAlertController {
private static final int BIT_BUTTON_POSITIVE = 1;
private static final int BIT_BUTTON_NEGATIVE = 2;
private static final int BIT_BUTTON_NEUTRAL = 4;
private final Context mContext;
private final DialogInterface mDialogInterface;
private final Window mWindow;
private CharSequence mTitle;
private CharSequence mMessage;
private ListView mListView;
private View mView;
private int mViewSpacingLeft;
private int mViewSpacingTop;
private int mViewSpacingRight;
private int mViewSpacingBottom;
private boolean mViewSpacingSpecified = false;
private Button mButtonPositive;
private CharSequence mButtonPositiveText;
private Message mButtonPositiveMessage;
private Button mButtonNegative;
private CharSequence mButtonNegativeText;
private Message mButtonNegativeMessage;
private Button mButtonNeutral;
private CharSequence mButtonNeutralText;
private Message mButtonNeutralMessage;
private ScrollView mScrollView;
private int mIconId = -1;
private Drawable mIcon;
private ImageView mIconView;
private TextView mTitleView;
private TextView mMessageView;
private View mCustomTitleView;
private boolean mForceInverseBackground;
private ListAdapter mAdapter;
private int mCheckedItem = -1;
private int mAlertDialogLayout;
private int mListLayout;
private int mListLayoutWithTitle;
private int mMultiChoiceItemLayout;
private int mSingleChoiceItemLayout;
private int mListItemLayout;
// add by afei for progressDialog Top and normal is Bottom
private int mGravity;
private Handler mHandler;
private boolean mTransplantBg = false;
private boolean mAutoDismiss = true; // 对话框在点击按钮之后是否自动消失
private boolean mCustomBgTransplant = false;
View.OnClickListener mButtonHandler = new View.OnClickListener() {
public void onClick(View v) {
Message m = null;
if (v == mButtonPositive && mButtonPositiveMessage != null) {
m = Message.obtain(mButtonPositiveMessage);
} else if (v == mButtonNegative && mButtonNegativeMessage != null) {
m = Message.obtain(mButtonNegativeMessage);
} else if (v == mButtonNeutral && mButtonNeutralMessage != null) {
m = Message.obtain(mButtonNeutralMessage);
}
if (m != null) {
m.sendToTarget();
}
if (mAutoDismiss) {
// Post a message so we dismiss after the above handlers are
// executed
mHandler.obtainMessage(ButtonHandler.MSG_DISMISS_DIALOG, mDialogInterface)
.sendToTarget();
}
}
};
private static final class ButtonHandler extends Handler {
// Button clicks have Message.what as the BUTTON{1,2,3} constant
private static final int MSG_DISMISS_DIALOG = 1;
private WeakReference<DialogInterface> mDialog;
public ButtonHandler(DialogInterface dialog) {
mDialog = new WeakReference<DialogInterface>(dialog);
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case DialogInterface.BUTTON_POSITIVE:
case DialogInterface.BUTTON_NEGATIVE:
case DialogInterface.BUTTON_NEUTRAL:
((DialogInterface.OnClickListener) msg.obj).onClick(mDialog.get(), msg.what);
break;
case MSG_DISMISS_DIALOG:
((DialogInterface) msg.obj).dismiss();
}
}
}
public void sendDismissMessage() {
mHandler.obtainMessage(ButtonHandler.MSG_DISMISS_DIALOG, mDialogInterface).sendToTarget();
}
public MLAlertController(Context context, DialogInterface di, Window window) {
this(context, di, window, Gravity.BOTTOM);
}
public MLAlertController(Context context, DialogInterface di, Window window, int gravity) {
mContext = context;
mDialogInterface = di;
mWindow = window;
mHandler = new ButtonHandler(di);
mAlertDialogLayout = R.layout.ml_alert_dialog;
mListLayout = R.layout.ml_select_dialog;
mListLayoutWithTitle = R.layout.ml_select_dialog_center;
mMultiChoiceItemLayout = R.layout.ml_select_dialog_multichoice;
mSingleChoiceItemLayout = R.layout.ml_select_dialog_singlechoice;
mListItemLayout = R.layout.ml_select_dialog_item;
mGravity = gravity;
}
static boolean canTextInput(View v) {
if (v.onCheckIsTextEditor()) {
return true;
}
if (!(v instanceof ViewGroup)) {
return false;
}
ViewGroup vg = (ViewGroup) v;
int i = vg.getChildCount();
while (i > 0) {
i--;
v = vg.getChildAt(i);
if (canTextInput(v)) {
return true;
}
}
return false;
}
public void installContent() {
/* We use a custom title so never request a window title */
mWindow.requestFeature(Window.FEATURE_NO_TITLE);
mWindow.setGravity(mGravity);
if (mView == null || !canTextInput(mView)) {
mWindow.setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
}
mWindow.setContentView(mAlertDialogLayout);
setupView();
}
public void setTitle(CharSequence title) {
mTitle = title;
if (mTitleView != null) {
mTitleView.setText(title);
}
}
/**
* @see android.app.AlertDialog.Builder#setCustomTitle(View)
*/
public void setCustomTitle(View customTitleView) {
mCustomTitleView = customTitleView;
}
public void setAudoDismiss(boolean autoDismiss) {
mAutoDismiss = autoDismiss;
}
public void setMessage(CharSequence message) {
mMessage = message;
if (mMessageView != null) {
mMessageView.setText(message);
}
}
/**
* Set the view to display in the dialog.
*/
public void setView(View view) {
mView = view;
mViewSpacingSpecified = false;
}
public void setCustomTransplant(boolean b) {
mCustomBgTransplant = b;
}
/**
* Set the view to display in the dialog along with the spacing around that
* view
*/
public void setView(View view, int viewSpacingLeft, int viewSpacingTop, int viewSpacingRight,
int viewSpacingBottom) {
mView = view;
mViewSpacingSpecified = true;
mViewSpacingLeft = viewSpacingLeft;
mViewSpacingTop = viewSpacingTop;
mViewSpacingRight = viewSpacingRight;
mViewSpacingBottom = viewSpacingBottom;
}
/**
* Sets a click listener or a message to be sent when the button is clicked.
* You only need to pass one of {@code listener} or {@code msg}.
*
* @param whichButton Which button, can be one of
* {@link DialogInterface#BUTTON_POSITIVE},
* {@link DialogInterface#BUTTON_NEGATIVE}, or
* {@link DialogInterface#BUTTON_NEUTRAL}
* @param text The text to display in positive button.
* @param listener The
* {@link DialogInterface.OnClickListener} to
* use.
* @param msg The {@link Message} to be sent when clicked.
*/
public void setButton(int whichButton, CharSequence text,
DialogInterface.OnClickListener listener, Message msg) {
if (msg == null && listener != null) {
msg = mHandler.obtainMessage(whichButton, listener);
}
switch (whichButton) {
case DialogInterface.BUTTON_POSITIVE:
mButtonPositiveText = text;
mButtonPositiveMessage = msg;
break;
case DialogInterface.BUTTON_NEGATIVE:
mButtonNegativeText = text;
mButtonNegativeMessage = msg;
break;
case DialogInterface.BUTTON_NEUTRAL:
mButtonNeutralText = text;
mButtonNeutralMessage = msg;
break;
default:
throw new IllegalArgumentException("Button does not exist");
}
}
/**
* Set resId to 0 if you don't want an icon.
*
* @param resId the resourceId of the drawable to use as the icon or 0 if
* you don't want an icon.
*/
public void setIcon(int resId) {
mIconId = resId;
if (mIconView != null) {
if (resId > 0) {
mIconView.setImageResource(mIconId);
} else if (resId == 0) {
mIconView.setVisibility(View.GONE);
}
}
}
public void setIcon(Drawable icon) {
mIcon = icon;
if ((mIconView != null) && (mIcon != null)) {
mIconView.setImageDrawable(icon);
}
}
public void setInverseBackgroundForced(boolean forceInverseBackground) {
mForceInverseBackground = forceInverseBackground;
}
public ListView getListView() {
return mListView;
}
public View getView() {
return mView;
}
public Button getButton(int whichButton) {
switch (whichButton) {
case DialogInterface.BUTTON_POSITIVE:
return mButtonPositive;
case DialogInterface.BUTTON_NEGATIVE:
return mButtonNegative;
case DialogInterface.BUTTON_NEUTRAL:
return mButtonNeutral;
default:
return null;
}
}
@SuppressWarnings({
"UnusedDeclaration"
})
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU && mListView != null
&& mListView.getVisibility() == View.VISIBLE) {
this.mDialogInterface.dismiss();
}
return mScrollView != null && mScrollView.executeKeyEvent(event);
}
@SuppressWarnings({
"UnusedDeclaration"
})
public boolean onKeyUp(int keyCode, KeyEvent event) {
return mScrollView != null && mScrollView.executeKeyEvent(event);
}
private void setupView() {
LinearLayout contentPanel = (LinearLayout) mWindow.findViewById(R.id.contentPanel);
setupContent(contentPanel);
boolean hasButtons = setupButtons();
LinearLayout topPanel = (LinearLayout) mWindow.findViewById(R.id.topPanel);
boolean hasTitle = setupTitle(topPanel);
View buttonPanel = mWindow.findViewById(R.id.buttonPanel);
if (!hasButtons) {
buttonPanel.setVisibility(View.GONE);
}
FrameLayout customPanel = (FrameLayout) mWindow.findViewById(R.id.customPanel);
if (mView != null) {
// 自定义dialog透明背景
// mWindow.findViewById(R.id.parentPanel).setBackgroundColor(mContext.getResources().getColor(android.R.color.transparent));
FrameLayout custom = (FrameLayout) mWindow.findViewById(R.id.custom);
custom.addView(mView);
if (mViewSpacingSpecified) {
custom.setPadding(mViewSpacingLeft, mViewSpacingTop, mViewSpacingRight,
mViewSpacingBottom);
if (mCustomBgTransplant)
mTransplantBg = true;
}
if (mListView != null) {
((LinearLayout.LayoutParams) customPanel.getLayoutParams()).weight = 0;
}
} else {
customPanel.setVisibility(View.GONE);
}
if (mTransplantBg) {
mWindow.findViewById(R.id.parentPanel).setBackgroundColor(
mContext.getResources().getColor(android.R.color.transparent));
} else {
// mWindow.findViewById(R.id.parentPanel).setBackgroundColor(0xffffffff);
}
if (mListView != null) {
// Listview有分割线divider,因此header和listview需要显示分割线
mWindow.findViewById(R.id.title_divider_line).setVisibility(View.VISIBLE);
mWindow.findViewById(R.id.title_divider_line_bottom).setVisibility(View.VISIBLE);
} else {
mWindow.findViewById(R.id.title_divider_line).setVisibility(View.GONE);
mWindow.findViewById(R.id.title_divider_line_bottom).setVisibility(View.GONE);
}
/**
* Add margin top for the button panel if we have not any panel
*/
if (topPanel.getVisibility() == View.GONE && contentPanel.getVisibility() == View.GONE
&& customPanel.getVisibility() == View.GONE && hasButtons) {
buttonPanel.setPadding(buttonPanel.getPaddingLeft(), buttonPanel.getPaddingBottom(),
buttonPanel.getPaddingRight(), buttonPanel.getPaddingBottom());
}
/*
* Only display the divider if we have a title and a custom view or a
* message.
*/
if (hasTitle) {
// View divider = null;
// if (mMessage != null || mView != null || mListView != null) {
// divider = mWindow.findViewById(R.id.titleDivider);
// } else {
// divider = mWindow.findViewById(R.id.titleDividerTop);
// }
//
// if (divider != null) {
// divider.setVisibility(View.VISIBLE);
// }
}
setBackground(topPanel, contentPanel, customPanel, hasButtons, hasTitle, buttonPanel);
if (TextUtils.isEmpty(mTitle) && TextUtils.isEmpty(mMessage)) {
mWindow.findViewById(R.id.empty_view).setVisibility(View.GONE);
}
}
private boolean setupTitle(LinearLayout topPanel) {
boolean hasTitle = true;
if (mCustomTitleView != null) {
// Add the custom title view directly to the topPanel layout
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
topPanel.addView(mCustomTitleView, 0, lp);
// Hide the title template
View titleTemplate = mWindow.findViewById(R.id.title_template);
titleTemplate.setVisibility(View.GONE);
} else {
final boolean hasTextTitle = !TextUtils.isEmpty(mTitle);
mIconView = (ImageView) mWindow.findViewById(R.id.icon);
if (hasTextTitle) {
/* Display the title if a title is supplied, else hide it */
mTitleView = (TextView) mWindow.findViewById(R.id.alertTitle);
mTitleView.setText(mTitle);
/*
* Do this last so that if the user has supplied any icons we
* use them instead of the default ones. If the user has
* specified 0 then make it disappear.
*/
if (mIconId > 0) {
mIconView.setImageResource(mIconId);
} else if (mIcon != null) {
mIconView.setImageDrawable(mIcon);
} else if (mIconId == 0) {
/*
* Apply the padding from the icon to ensure the title is
* aligned correctly.
*/
mTitleView.setPadding(mIconView.getPaddingLeft(),
mIconView.getPaddingTop(),
mIconView.getPaddingRight(),
mIconView.getPaddingBottom());
mIconView.setVisibility(View.GONE);
}
} else {
// Hide the title template
View titleTemplate = mWindow.findViewById(R.id.title_template);
titleTemplate.setVisibility(View.GONE);
mIconView.setVisibility(View.GONE);
topPanel.setVisibility(View.GONE);
hasTitle = false;
}
}
return hasTitle;
}
private void setupContent(LinearLayout contentPanel) {
mScrollView = (ScrollView) mWindow.findViewById(R.id.scrollView);
mScrollView.setFocusable(false);
// Special case for users that only want to display a String
mMessageView = (TextView) mWindow.findViewById(R.id.message);
if (mMessageView == null) {
return;
}
if (mMessage != null) {
mMessageView.setText(mMessage);
} else {
mMessageView.setVisibility(View.GONE);
mScrollView.removeView(mMessageView);
if (mListView != null) {
contentPanel.removeView(mWindow.findViewById(R.id.scrollView));
contentPanel.addView(mListView,
new LinearLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT));
contentPanel.setLayoutParams(new LinearLayout.LayoutParams(MATCH_PARENT, 0, 1.0f));
} else {
contentPanel.setVisibility(View.GONE);
}
}
}
private boolean setupButtons() {
int whichButtons = 0;
mButtonPositive = (Button) mWindow.findViewById(R.id.button1);
mButtonPositive.setOnClickListener(mButtonHandler);
if (TextUtils.isEmpty(mButtonPositiveText)) {
mButtonPositive.setVisibility(View.GONE);
} else {
mButtonPositive.setText(mButtonPositiveText);
mButtonPositive.setVisibility(View.VISIBLE);
whichButtons = whichButtons | BIT_BUTTON_POSITIVE;
}
mButtonNegative = (Button) mWindow.findViewById(R.id.button2);
mButtonNegative.setOnClickListener(mButtonHandler);
if (TextUtils.isEmpty(mButtonNegativeText)) {
mButtonNegative.setVisibility(View.GONE);
} else {
mButtonNegative.setText(mButtonNegativeText);
mButtonNegative.setVisibility(View.VISIBLE);
whichButtons = whichButtons | BIT_BUTTON_NEGATIVE;
}
mButtonNeutral = (Button) mWindow.findViewById(R.id.button3);
mButtonNeutral.setOnClickListener(mButtonHandler);
if (TextUtils.isEmpty(mButtonNeutralText)) {
mButtonNeutral.setVisibility(View.GONE);
} else {
mButtonNeutral.setText(mButtonNeutralText);
mButtonNeutral.setVisibility(View.VISIBLE);
whichButtons = whichButtons | BIT_BUTTON_NEUTRAL;
}
if (shouldCenterSingleButton(whichButtons)) {
if (whichButtons == BIT_BUTTON_POSITIVE) {
centerButton(mButtonPositive);
} else if (whichButtons == BIT_BUTTON_NEGATIVE) {
centerButton(mButtonNegative);
} else if (whichButtons == BIT_BUTTON_NEUTRAL) {
centerButton(mButtonNeutral);
}
}
return whichButtons != 0;
}
private static boolean shouldCenterSingleButton(int whichButton) {
return whichButton == BIT_BUTTON_POSITIVE
|| whichButton == BIT_BUTTON_NEGATIVE
|| whichButton == BIT_BUTTON_NEUTRAL;
}
private void centerButton(TextView button) {
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) button.getLayoutParams();
params.gravity = Gravity.CENTER_HORIZONTAL;
params.weight = 0.5f;
button.setLayoutParams(params);
button.setBackgroundResource(R.drawable.common_button);
}
private void setBackground(LinearLayout topPanel, LinearLayout contentPanel,
View customPanel, boolean hasButtons, boolean hasTitle,
View buttonPanel) {
if (mTransplantBg) {
/* Get all the different background required */
int fullDark = mContext.getResources().getColor(android.R.color.transparent);
int topDark = mContext.getResources().getColor(android.R.color.transparent);
int centerDark = mContext.getResources().getColor(android.R.color.transparent);
int bottomDark = mContext.getResources().getColor(android.R.color.transparent);
int fullBright = mContext.getResources().getColor(android.R.color.transparent);
int topBright = mContext.getResources().getColor(android.R.color.transparent);
int centerBright = mContext.getResources().getColor(android.R.color.transparent);
int bottomBright = mContext.getResources().getColor(android.R.color.transparent);
int bottomMedium = mContext.getResources().getColor(android.R.color.transparent);
/*
* We now set the background of all of the sections of the alert.
* First collect together each section that is being displayed along
* with whether it is on a light or dark background, then run
* through them setting their backgrounds. This is complicated
* because we need to correctly use the full, top, middle, and
* bottom graphics depending on how many views they are and where
* they appear.
*/
View[] views = new View[4];
boolean[] light = new boolean[4];
View lastView = null;
boolean lastLight = false;
int pos = 0;
if (hasTitle) {
views[pos] = topPanel;
light[pos] = false;
pos++;
}
/*
* The contentPanel displays either a custom text message or a
* ListView. If it's text we should use the dark background for
* ListView we should use the light background. If neither are there
* the contentPanel will be hidden so set it as null.
*/
views[pos] = (contentPanel.getVisibility() == View.GONE)
? null : contentPanel;
light[pos] = mListView != null;
pos++;
if (customPanel != null) {
views[pos] = customPanel;
light[pos] = mForceInverseBackground;
pos++;
}
if (hasButtons) {
views[pos] = buttonPanel;
light[pos] = true;
}
boolean setView = false;
for (pos = 0; pos < views.length; pos++) {
View v = views[pos];
if (v == null) {
continue;
}
if (lastView != null) {
if (!setView) {
lastView.setBackgroundResource(lastLight ? topBright : topDark);
} else {
lastView.setBackgroundResource(lastLight ? centerBright : centerDark);
}
setView = true;
}
lastView = v;
lastLight = light[pos];
}
if (lastView != null) {
if (setView) {
/*
* ListViews will use the Bright background but buttons use
* the Medium background.
*/
lastView.setBackgroundResource(
lastLight ? (hasButtons ? bottomMedium : bottomBright) : bottomDark);
} else {
lastView.setBackgroundResource(lastLight ? fullBright : fullDark);
}
}
}
if ((mListView != null) && (mAdapter != null)) {
mListView.setAdapter(mAdapter);
if (mCheckedItem > -1) {
mListView.setItemChecked(mCheckedItem, true);
mListView.setSelection(mCheckedItem);
}
}
}
public static class RecycleListView extends ListView {
boolean mRecycleOnMeasure = true;
public RecycleListView(Context context) {
super(context);
}
public RecycleListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public RecycleListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
protected boolean recycleOnMeasure() {
return mRecycleOnMeasure;
}
}
public static class AlertParams {
public final Context mContext;
public final LayoutInflater mInflater;
public int mIconId = 0;
public Drawable mIcon;
public CharSequence mTitle;
public View mCustomTitleView;
public CharSequence mMessage;
public CharSequence mPositiveButtonText;
public DialogInterface.OnClickListener mPositiveButtonListener;
public CharSequence mNegativeButtonText;
public DialogInterface.OnClickListener mNegativeButtonListener;
public CharSequence mNeutralButtonText;
public DialogInterface.OnClickListener mNeutralButtonListener;
public boolean mCancelable;
public DialogInterface.OnCancelListener mOnCancelListener;
public DialogInterface.OnKeyListener mOnKeyListener;
public CharSequence[] mItems;
public ListAdapter mAdapter;
public DialogInterface.OnClickListener mOnClickListener;
public View mView;
public int mViewSpacingLeft;
public int mViewSpacingTop;
public int mViewSpacingRight;
public int mViewSpacingBottom;
public boolean mViewSpacingSpecified = false;
public boolean[] mCheckedItems;
public boolean mIsMultiChoice;
public boolean mIsSingleChoice;
public int mCheckedItem = -1;
public DialogInterface.OnMultiChoiceClickListener mOnCheckboxClickListener;
public Cursor mCursor;
public String mLabelColumn;
public String mIsCheckedColumn;
public boolean mForceInverseBackground;
public AdapterView.OnItemSelectedListener mOnItemSelectedListener;
public OnPrepareListViewListener mOnPrepareListViewListener;
public boolean mRecycleOnMeasure = true;
public boolean mAutoDismiss = true;
public MLAlertDialog.DismissCallBack mDismissCallBack;
public CharSequence mCustomTitle;
public boolean mCustomBgTransplant = false;
/**
* Interface definition for a callback to be invoked before the ListView
* will be bound to an adapter.
*/
public interface OnPrepareListViewListener {
/**
* Called before the ListView is bound to an adapter.
*
* @param listView The ListView that will be shown in the dialog.
*/
void onPrepareListView(ListView listView);
}
public AlertParams(Context context) {
mContext = context;
mCancelable = true;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void apply(MLAlertController dialog) {
if (mCustomTitleView != null) {
dialog.setCustomTitle(mCustomTitleView);
} else {
if (mTitle != null) {
dialog.setTitle(mTitle);
}
if (mIcon != null) {
dialog.setIcon(mIcon);
}
if (mIconId >= 0) {
dialog.setIcon(mIconId);
}
}
if (mMessage != null) {
dialog.setMessage(mMessage);
}
if (mPositiveButtonText != null) {
dialog.setButton(DialogInterface.BUTTON_POSITIVE, mPositiveButtonText,
mPositiveButtonListener, null);
}
if (mNegativeButtonText != null) {
dialog.setButton(DialogInterface.BUTTON_NEGATIVE, mNegativeButtonText,
mNegativeButtonListener, null);
}
if (mNeutralButtonText != null) {
dialog.setButton(DialogInterface.BUTTON_NEUTRAL, mNeutralButtonText,
mNeutralButtonListener, null);
}
if (mForceInverseBackground) {
dialog.setInverseBackgroundForced(true);
}
// For a list, the client can either supply an array of items or an
// adapter or a cursor
dialog.mTransplantBg = false;
if ((mItems != null) || (mCursor != null) || (mAdapter != null)) {
if (dialog.mGravity == Gravity.CENTER) {
createCenterListView(dialog);
} else {
createListView(dialog);
}
}
if (mView != null) {
if (mViewSpacingSpecified) {
dialog.setView(mView, mViewSpacingLeft, mViewSpacingTop, mViewSpacingRight,
mViewSpacingBottom);
} else {
dialog.setView(mView);
}
}
dialog.setAudoDismiss(mAutoDismiss);
dialog.setCustomTransplant(mCustomBgTransplant);
}
private void createCenterListView(final MLAlertController dialog) {
final LinearLayout customView = (LinearLayout)
mInflater.inflate(dialog.mListLayoutWithTitle, null);
final RecycleListView listView = (RecycleListView) customView
.findViewById(R.id.select_dialog_listview);
ListAdapter adapter;
int layout = R.layout.ml_center_item;
if (mCursor == null) {
adapter = (mAdapter != null) ? mAdapter
: new ArrayAdapter<CharSequence>(mContext, layout, R.id.text1, mItems);
} else {
adapter = new SimpleCursorAdapter(mContext, layout,
mCursor, new String[] {
mLabelColumn
}, new int[] {
R.id.text1
});
}
if (mCustomTitle != null) {
((TextView) (customView.findViewById(R.id.title))).setText(mCustomTitle);
}
if (mOnPrepareListViewListener != null) {
mOnPrepareListViewListener.onPrepareListView(listView);
}
/*
* Don't directly set the adapter on the ListView as we might want
* to add a footer to the ListView later.
*/
dialog.mAdapter = adapter;
listView.setAdapter(adapter);
dialog.mCheckedItem = mCheckedItem;
if (mOnClickListener != null) {
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
mOnClickListener.onClick(dialog.mDialogInterface, position);
if (!mIsSingleChoice) {
dialog.mDialogInterface.dismiss();
}
}
});
} else if (mOnCheckboxClickListener != null) {
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
if (mCheckedItems != null) {
mCheckedItems[position] = listView.isItemChecked(position);
}
mOnCheckboxClickListener.onClick(
dialog.mDialogInterface, position, listView.isItemChecked(position));
}
});
}
// Attach a given OnItemSelectedListener to the ListView
if (mOnItemSelectedListener != null) {
listView.setOnItemSelectedListener(mOnItemSelectedListener);
}
if (mOnItemSelectedListener != null) {
listView.setOnItemSelectedListener(mOnItemSelectedListener);
}
if (mIsSingleChoice) {
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
} else if (mIsMultiChoice) {
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
listView.mRecycleOnMeasure = mRecycleOnMeasure;
dialog.mView = customView;
dialog.mTransplantBg = true;
dialog.setCustomTransplant(mCustomBgTransplant);
}
private void createListView(final MLAlertController dialog) {
final RecycleListView listView = (RecycleListView)
mInflater.inflate(dialog.mListLayout, null);
ListAdapter adapter;
if (mIsMultiChoice) {
if (mCursor == null) {
adapter = new ArrayAdapter<CharSequence>(
mContext, dialog.mMultiChoiceItemLayout, R.id.text1, mItems) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
if (mCheckedItems != null) {
boolean isItemChecked = mCheckedItems[position];
if (isItemChecked) {
listView.setItemChecked(position, true);
}
}
return view;
}
};
} else {
adapter = new CursorAdapter(mContext, mCursor, false) {
private final int mLabelIndex;
private final int mIsCheckedIndex;
{
final Cursor cursor = getCursor();
mLabelIndex = cursor.getColumnIndexOrThrow(mLabelColumn);
mIsCheckedIndex = cursor.getColumnIndexOrThrow(mIsCheckedColumn);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
CheckedTextView text = (CheckedTextView) view.findViewById(R.id.text1);
text.setText(cursor.getString(mLabelIndex));
listView.setItemChecked(cursor.getPosition(),
cursor.getInt(mIsCheckedIndex) == 1);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return mInflater.inflate(dialog.mMultiChoiceItemLayout,
parent, false);
}
};
}
} else {
int layout = mIsSingleChoice
? dialog.mSingleChoiceItemLayout : dialog.mListItemLayout;
if (mCursor == null) {
adapter = (mAdapter != null) ? mAdapter
: new ArrayAdapter<CharSequence>(mContext, layout, R.id.text1, mItems);
} else {
adapter = new SimpleCursorAdapter(mContext, layout,
mCursor, new String[] {
mLabelColumn
}, new int[] {
R.id.text1
});
}
}
if (mOnPrepareListViewListener != null) {
mOnPrepareListViewListener.onPrepareListView(listView);
}
/*
* Don't directly set the adapter on the ListView as we might want
* to add a footer to the ListView later.
*/
dialog.mAdapter = adapter;
dialog.mCheckedItem = mCheckedItem;
if (mOnClickListener != null) {
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
mOnClickListener.onClick(dialog.mDialogInterface, position);
if (!mIsSingleChoice) {
dialog.mDialogInterface.dismiss();
}
}
});
} else if (mOnCheckboxClickListener != null) {
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
if (mCheckedItems != null) {
mCheckedItems[position] = listView.isItemChecked(position);
}
mOnCheckboxClickListener.onClick(
dialog.mDialogInterface, position, listView.isItemChecked(position));
}
});
}
// Attach a given OnItemSelectedListener to the ListView
if (mOnItemSelectedListener != null) {
listView.setOnItemSelectedListener(mOnItemSelectedListener);
}
if (mIsSingleChoice) {
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
} else if (mIsMultiChoice) {
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
listView.mRecycleOnMeasure = mRecycleOnMeasure;
dialog.mListView = listView;
dialog.setCustomTransplant(mCustomBgTransplant);
}
}
}
|
Java
|
/**
* Copyright 2011 Micheal Swiggs
*
* 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.reddcoin.net.discovery;
import com.google.reddcoin.params.MainNetParams;
import org.junit.Test;
import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
public class SeedPeersTest {
@Test
public void getPeer_one() throws Exception{
SeedPeers seedPeers = new SeedPeers(MainNetParams.get());
assertThat(seedPeers.getPeer(), notNullValue());
}
@Test
public void getPeer_all() throws Exception{
SeedPeers seedPeers = new SeedPeers(MainNetParams.get());
for(int i = 0; i < SeedPeers.seedAddrs.length; ++i){
assertThat("Failed on index: "+i, seedPeers.getPeer(), notNullValue());
}
assertThat(seedPeers.getPeer(), equalTo(null));
}
@Test
public void getPeers_length() throws Exception{
SeedPeers seedPeers = new SeedPeers(MainNetParams.get());
InetSocketAddress[] addresses = seedPeers.getPeers(0, TimeUnit.SECONDS);
assertThat(addresses.length, equalTo(SeedPeers.seedAddrs.length));
}
}
|
Java
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const options_1 = require("./options");
class TslintFixTask {
constructor(configOrPath, options) {
if (options) {
this._configOrPath = configOrPath;
this._options = options;
}
else {
this._options = configOrPath;
this._configOrPath = null;
}
}
toConfiguration() {
const path = typeof this._configOrPath == 'string' ? { tslintPath: this._configOrPath } : {};
const config = typeof this._configOrPath == 'object' && this._configOrPath !== null
? { tslintConfig: this._configOrPath }
: {};
const options = {
...this._options,
...path,
...config,
};
return { name: options_1.TslintFixName, options };
}
}
exports.TslintFixTask = TslintFixTask;
|
Java
|
// Copyright 2012-2013 The Rust Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use core::prelude::*;
use common::mode_run_pass;
use common::mode_run_fail;
use common::mode_compile_fail;
use common::mode_pretty;
use common::config;
use errors;
use header::load_props;
use header::TestProps;
use procsrv;
use util;
use util::logv;
use core::io::WriterUtil;
use core::io;
use core::os;
use core::str;
use core::uint;
use core::vec;
pub fn run(config: config, testfile: ~str) {
if config.verbose {
// We're going to be dumping a lot of info. Start on a new line.
io::stdout().write_str(~"\n\n");
}
let testfile = Path(testfile);
debug!("running %s", testfile.to_str());
let props = load_props(&testfile);
debug!("loaded props");
match config.mode {
mode_compile_fail => run_cfail_test(config, props, &testfile),
mode_run_fail => run_rfail_test(config, props, &testfile),
mode_run_pass => run_rpass_test(config, props, &testfile),
mode_pretty => run_pretty_test(config, props, &testfile),
mode_debug_info => run_debuginfo_test(config, props, &testfile)
}
}
fn run_cfail_test(config: config, props: TestProps, testfile: &Path) {
let ProcRes = compile_test(config, props, testfile);
if ProcRes.status == 0 {
fatal_ProcRes(~"compile-fail test compiled successfully!", ProcRes);
}
check_correct_failure_status(ProcRes);
let expected_errors = errors::load_errors(testfile);
if !expected_errors.is_empty() {
if !props.error_patterns.is_empty() {
fatal(~"both error pattern and expected errors specified");
}
check_expected_errors(expected_errors, testfile, ProcRes);
} else {
check_error_patterns(props, testfile, ProcRes);
}
}
fn run_rfail_test(config: config, props: TestProps, testfile: &Path) {
let ProcRes = if !config.jit {
let ProcRes = compile_test(config, props, testfile);
if ProcRes.status != 0 {
fatal_ProcRes(~"compilation failed!", ProcRes);
}
exec_compiled_test(config, props, testfile)
} else {
jit_test(config, props, testfile)
};
// The value our Makefile configures valgrind to return on failure
static valgrind_err: int = 100;
if ProcRes.status == valgrind_err {
fatal_ProcRes(~"run-fail test isn't valgrind-clean!", ProcRes);
}
check_correct_failure_status(ProcRes);
check_error_patterns(props, testfile, ProcRes);
}
fn check_correct_failure_status(ProcRes: ProcRes) {
// The value the rust runtime returns on failure
static rust_err: int = 101;
if ProcRes.status != rust_err {
fatal_ProcRes(
fmt!("failure produced the wrong error code: %d",
ProcRes.status),
ProcRes);
}
}
fn run_rpass_test(config: config, props: TestProps, testfile: &Path) {
if !config.jit {
let mut ProcRes = compile_test(config, props, testfile);
if ProcRes.status != 0 {
fatal_ProcRes(~"compilation failed!", ProcRes);
}
ProcRes = exec_compiled_test(config, props, testfile);
if ProcRes.status != 0 {
fatal_ProcRes(~"test run failed!", ProcRes);
}
} else {
let mut ProcRes = jit_test(config, props, testfile);
if ProcRes.status != 0 { fatal_ProcRes(~"jit failed!", ProcRes); }
}
}
fn run_pretty_test(config: config, props: TestProps, testfile: &Path) {
if props.pp_exact.is_some() {
logv(config, ~"testing for exact pretty-printing");
} else { logv(config, ~"testing for converging pretty-printing"); }
let rounds =
match props.pp_exact { Some(_) => 1, None => 2 };
let mut srcs = ~[io::read_whole_file_str(testfile).get()];
let mut round = 0;
while round < rounds {
logv(config, fmt!("pretty-printing round %d", round));
let ProcRes = print_source(config, testfile, srcs[round]);
if ProcRes.status != 0 {
fatal_ProcRes(fmt!("pretty-printing failed in round %d", round),
ProcRes);
}
srcs.push(ProcRes.stdout);
round += 1;
}
let mut expected =
match props.pp_exact {
Some(file) => {
let filepath = testfile.dir_path().push_rel(&file);
io::read_whole_file_str(&filepath).get()
}
None => { srcs[vec::len(srcs) - 2u] }
};
let mut actual = srcs[vec::len(srcs) - 1u];
if props.pp_exact.is_some() {
// Now we have to care about line endings
let cr = ~"\r";
actual = str::replace(actual, cr, ~"");
expected = str::replace(expected, cr, ~"");
}
compare_source(expected, actual);
// Finally, let's make sure it actually appears to remain valid code
let ProcRes = typecheck_source(config, props, testfile, actual);
if ProcRes.status != 0 {
fatal_ProcRes(~"pretty-printed source does not typecheck", ProcRes);
}
return;
fn print_source(config: config, testfile: &Path, src: ~str) -> ProcRes {
compose_and_run(config, testfile, make_pp_args(config, testfile),
~[], config.compile_lib_path, Some(src))
}
fn make_pp_args(config: config, _testfile: &Path) -> ProcArgs {
let prog = config.rustc_path;
let args = ~[~"-", ~"--pretty", ~"normal"];
return ProcArgs {prog: prog.to_str(), args: args};
}
fn compare_source(expected: ~str, actual: ~str) {
if expected != actual {
error(~"pretty-printed source does not match expected source");
let msg =
fmt!("\n\
expected:\n\
------------------------------------------\n\
%s\n\
------------------------------------------\n\
actual:\n\
------------------------------------------\n\
%s\n\
------------------------------------------\n\
\n",
expected, actual);
io::stdout().write_str(msg);
fail!();
}
}
fn typecheck_source(config: config, props: TestProps,
testfile: &Path, src: ~str) -> ProcRes {
compose_and_run_compiler(
config, props, testfile,
make_typecheck_args(config, props, testfile),
Some(src))
}
fn make_typecheck_args(config: config, props: TestProps, testfile: &Path) -> ProcArgs {
let prog = config.rustc_path;
let mut args = ~[~"-",
~"--no-trans", ~"--lib",
~"-L", config.build_base.to_str(),
~"-L",
aux_output_dir_name(config, testfile).to_str()];
args += split_maybe_args(config.rustcflags);
args += split_maybe_args(props.compile_flags);
return ProcArgs {prog: prog.to_str(), args: args};
}
}
fn run_debuginfo_test(config: config, props: TestProps, testfile: &Path) {
// do not optimize debuginfo tests
let config = match config.rustcflags {
Some(flags) => config {
rustcflags: Some(str::replace(flags, ~"-O", ~"")),
.. config
},
None => config
};
// compile test file (it shoud have 'compile-flags:-g' in the header)
let mut ProcRes = compile_test(config, props, testfile);
if ProcRes.status != 0 {
fatal_ProcRes(~"compilation failed!", ProcRes);
}
// write debugger script
let script_str = str::append(str::connect(props.debugger_cmds, "\n"),
~"\nquit\n");
debug!("script_str = %s", script_str);
dump_output_file(config, testfile, script_str, ~"debugger.script");
// run debugger script with gdb
#[cfg(windows)]
fn debugger() -> ~str { ~"gdb.exe" }
#[cfg(unix)]
fn debugger() -> ~str { ~"gdb" }
let debugger_script = make_out_name(config, testfile, ~"debugger.script");
let debugger_opts = ~[~"-quiet", ~"-batch", ~"-nx",
~"-command=" + debugger_script.to_str(),
make_exe_name(config, testfile).to_str()];
let ProcArgs = ProcArgs {prog: debugger(), args: debugger_opts};
ProcRes = compose_and_run(config, testfile, ProcArgs, ~[], ~"", None);
if ProcRes.status != 0 {
fatal(~"gdb failed to execute");
}
let num_check_lines = vec::len(props.check_lines);
if num_check_lines > 0 {
// check if each line in props.check_lines appears in the
// output (in order)
let mut i = 0u;
for str::each_line(ProcRes.stdout) |line| {
if props.check_lines[i].trim() == line.trim() {
i += 1u;
}
if i == num_check_lines {
// all lines checked
break;
}
}
if i != num_check_lines {
fatal_ProcRes(fmt!("line not found in debugger output: %s"
props.check_lines[i]), ProcRes);
}
}
}
fn check_error_patterns(props: TestProps,
testfile: &Path,
ProcRes: ProcRes) {
if vec::is_empty(props.error_patterns) {
fatal(~"no error pattern specified in " + testfile.to_str());
}
if ProcRes.status == 0 {
fatal(~"process did not return an error status");
}
let mut next_err_idx = 0u;
let mut next_err_pat = props.error_patterns[next_err_idx];
let mut done = false;
for str::each_line(ProcRes.stderr) |line| {
if str::contains(line, next_err_pat) {
debug!("found error pattern %s", next_err_pat);
next_err_idx += 1u;
if next_err_idx == vec::len(props.error_patterns) {
debug!("found all error patterns");
done = true;
break;
}
next_err_pat = props.error_patterns[next_err_idx];
}
}
if done { return; }
let missing_patterns =
vec::slice(props.error_patterns, next_err_idx,
vec::len(props.error_patterns));
if vec::len(missing_patterns) == 1u {
fatal_ProcRes(fmt!("error pattern '%s' not found!",
missing_patterns[0]), ProcRes);
} else {
for missing_patterns.each |pattern| {
error(fmt!("error pattern '%s' not found!", *pattern));
}
fatal_ProcRes(~"multiple error patterns not found", ProcRes);
}
}
fn check_expected_errors(expected_errors: ~[errors::ExpectedError],
testfile: &Path,
ProcRes: ProcRes) {
// true if we found the error in question
let mut found_flags = vec::from_elem(
vec::len(expected_errors), false);
if ProcRes.status == 0 {
fatal(~"process did not return an error status");
}
let prefixes = vec::map(expected_errors, |ee| {
fmt!("%s:%u:", testfile.to_str(), ee.line)
});
// Scan and extract our error/warning messages,
// which look like:
// filename:line1:col1: line2:col2: *error:* msg
// filename:line1:col1: line2:col2: *warning:* msg
// where line1:col1: is the starting point, line2:col2:
// is the ending point, and * represents ANSI color codes.
for str::each_line(ProcRes.stderr) |line| {
let mut was_expected = false;
for vec::eachi(expected_errors) |i, ee| {
if !found_flags[i] {
debug!("prefix=%s ee.kind=%s ee.msg=%s line=%s",
prefixes[i], ee.kind, ee.msg, line);
if (str::starts_with(line, prefixes[i]) &&
str::contains(line, ee.kind) &&
str::contains(line, ee.msg)) {
found_flags[i] = true;
was_expected = true;
break;
}
}
}
// ignore this msg which gets printed at the end
if str::contains(line, ~"aborting due to") {
was_expected = true;
}
if !was_expected && is_compiler_error_or_warning(str::from_slice(line)) {
fatal_ProcRes(fmt!("unexpected compiler error or warning: '%s'",
line),
ProcRes);
}
}
for uint::range(0u, vec::len(found_flags)) |i| {
if !found_flags[i] {
let ee = expected_errors[i];
fatal_ProcRes(fmt!("expected %s on line %u not found: %s",
ee.kind, ee.line, ee.msg), ProcRes);
}
}
}
fn is_compiler_error_or_warning(line: ~str) -> bool {
let mut i = 0u;
return
scan_until_char(line, ':', &mut i) &&
scan_char(line, ':', &mut i) &&
scan_integer(line, &mut i) &&
scan_char(line, ':', &mut i) &&
scan_integer(line, &mut i) &&
scan_char(line, ':', &mut i) &&
scan_char(line, ' ', &mut i) &&
scan_integer(line, &mut i) &&
scan_char(line, ':', &mut i) &&
scan_integer(line, &mut i) &&
scan_char(line, ' ', &mut i) &&
(scan_string(line, ~"error", &mut i) ||
scan_string(line, ~"warning", &mut i));
}
fn scan_until_char(haystack: ~str, needle: char, idx: &mut uint) -> bool {
if *idx >= haystack.len() {
return false;
}
let opt = str::find_char_from(haystack, needle, *idx);
if opt.is_none() {
return false;
}
*idx = opt.get();
return true;
}
fn scan_char(haystack: ~str, needle: char, idx: &mut uint) -> bool {
if *idx >= haystack.len() {
return false;
}
let range = str::char_range_at(haystack, *idx);
if range.ch != needle {
return false;
}
*idx = range.next;
return true;
}
fn scan_integer(haystack: ~str, idx: &mut uint) -> bool {
let mut i = *idx;
while i < haystack.len() {
let range = str::char_range_at(haystack, i);
if range.ch < '0' || '9' < range.ch {
break;
}
i = range.next;
}
if i == *idx {
return false;
}
*idx = i;
return true;
}
fn scan_string(haystack: ~str, needle: ~str, idx: &mut uint) -> bool {
let mut haystack_i = *idx;
let mut needle_i = 0u;
while needle_i < needle.len() {
if haystack_i >= haystack.len() {
return false;
}
let range = str::char_range_at(haystack, haystack_i);
haystack_i = range.next;
if !scan_char(needle, range.ch, &mut needle_i) {
return false;
}
}
*idx = haystack_i;
return true;
}
struct ProcArgs {prog: ~str, args: ~[~str]}
struct ProcRes {status: int, stdout: ~str, stderr: ~str, cmdline: ~str}
fn compile_test(config: config, props: TestProps,
testfile: &Path) -> ProcRes {
compile_test_(config, props, testfile, [])
}
fn jit_test(config: config, props: TestProps, testfile: &Path) -> ProcRes {
compile_test_(config, props, testfile, [~"--jit"])
}
fn compile_test_(config: config, props: TestProps,
testfile: &Path, extra_args: &[~str]) -> ProcRes {
let link_args = ~[~"-L", aux_output_dir_name(config, testfile).to_str()];
compose_and_run_compiler(
config, props, testfile,
make_compile_args(config, props, link_args + extra_args,
make_exe_name, testfile),
None)
}
fn exec_compiled_test(config: config, props: TestProps,
testfile: &Path) -> ProcRes {
// If testing the new runtime then set the RUST_NEWRT env var
let env = if config.newrt {
props.exec_env + ~[(~"RUST_NEWRT", ~"1")]
} else {
props.exec_env
};
compose_and_run(config, testfile,
make_run_args(config, props, testfile),
env,
config.run_lib_path, None)
}
fn compose_and_run_compiler(
config: config,
props: TestProps,
testfile: &Path,
args: ProcArgs,
input: Option<~str>) -> ProcRes {
if !props.aux_builds.is_empty() {
ensure_dir(&aux_output_dir_name(config, testfile));
}
let extra_link_args = ~[~"-L",
aux_output_dir_name(config, testfile).to_str()];
for vec::each(props.aux_builds) |rel_ab| {
let abs_ab = config.aux_base.push_rel(&Path(*rel_ab));
let aux_args =
make_compile_args(config, props, ~[~"--lib"] + extra_link_args,
|a,b| make_lib_name(a, b, testfile), &abs_ab);
let auxres = compose_and_run(config, &abs_ab, aux_args, ~[],
config.compile_lib_path, None);
if auxres.status != 0 {
fatal_ProcRes(
fmt!("auxiliary build of %s failed to compile: ",
abs_ab.to_str()),
auxres);
}
}
compose_and_run(config, testfile, args, ~[],
config.compile_lib_path, input)
}
fn ensure_dir(path: &Path) {
if os::path_is_dir(path) { return; }
if !os::make_dir(path, 0x1c0i32) {
fail!(fmt!("can't make dir %s", path.to_str()));
}
}
fn compose_and_run(config: config, testfile: &Path,
ProcArgs: ProcArgs,
procenv: ~[(~str, ~str)],
lib_path: ~str,
input: Option<~str>) -> ProcRes {
return program_output(config, testfile, lib_path,
ProcArgs.prog, ProcArgs.args, procenv, input);
}
fn make_compile_args(config: config, props: TestProps, extras: ~[~str],
xform: &fn(config, (&Path)) -> Path,
testfile: &Path) -> ProcArgs {
let prog = config.rustc_path;
let mut args = ~[testfile.to_str(),
~"-o", xform(config, testfile).to_str(),
~"-L", config.build_base.to_str()]
+ extras;
args += split_maybe_args(config.rustcflags);
args += split_maybe_args(props.compile_flags);
return ProcArgs {prog: prog.to_str(), args: args};
}
fn make_lib_name(config: config, auxfile: &Path, testfile: &Path) -> Path {
// what we return here is not particularly important, as it
// happens; rustc ignores everything except for the directory.
let auxname = output_testname(auxfile);
aux_output_dir_name(config, testfile).push_rel(&auxname)
}
fn make_exe_name(config: config, testfile: &Path) -> Path {
Path(output_base_name(config, testfile).to_str() +
str::from_slice(os::EXE_SUFFIX))
}
fn make_run_args(config: config, _props: TestProps, testfile: &Path) ->
ProcArgs {
let toolargs = {
// If we've got another tool to run under (valgrind),
// then split apart its command
let runtool =
match config.runtool {
Some(s) => Some(s),
None => None
};
split_maybe_args(runtool)
};
let args = toolargs + ~[make_exe_name(config, testfile).to_str()];
return ProcArgs {prog: args[0],
args: vec::slice(args, 1, args.len()).to_vec()};
}
fn split_maybe_args(argstr: Option<~str>) -> ~[~str] {
fn rm_whitespace(v: ~[~str]) -> ~[~str] {
v.filtered(|s| !str::is_whitespace(*s))
}
match argstr {
Some(s) => {
let mut ss = ~[];
for str::each_split_char(s, ' ') |s| { ss.push(s.to_owned()) }
rm_whitespace(ss)
}
None => ~[]
}
}
fn program_output(config: config, testfile: &Path, lib_path: ~str, prog: ~str,
args: ~[~str], env: ~[(~str, ~str)],
input: Option<~str>) -> ProcRes {
let cmdline =
{
let cmdline = make_cmdline(lib_path, prog, args);
logv(config, fmt!("executing %s", cmdline));
cmdline
};
let res = procsrv::run(lib_path, prog, args, env, input);
dump_output(config, testfile, res.out, res.err);
return ProcRes {status: res.status,
stdout: res.out,
stderr: res.err,
cmdline: cmdline};
}
// Linux and mac don't require adjusting the library search path
#[cfg(target_os = "linux")]
#[cfg(target_os = "macos")]
#[cfg(target_os = "freebsd")]
fn make_cmdline(_libpath: ~str, prog: ~str, args: ~[~str]) -> ~str {
fmt!("%s %s", prog, str::connect(args, ~" "))
}
#[cfg(target_os = "win32")]
fn make_cmdline(libpath: ~str, prog: ~str, args: ~[~str]) -> ~str {
fmt!("%s %s %s", lib_path_cmd_prefix(libpath), prog,
str::connect(args, ~" "))
}
// Build the LD_LIBRARY_PATH variable as it would be seen on the command line
// for diagnostic purposes
fn lib_path_cmd_prefix(path: ~str) -> ~str {
fmt!("%s=\"%s\"", util::lib_path_env_var(), util::make_new_path(path))
}
fn dump_output(config: config, testfile: &Path, out: ~str, err: ~str) {
dump_output_file(config, testfile, out, ~"out");
dump_output_file(config, testfile, err, ~"err");
maybe_dump_to_stdout(config, out, err);
}
fn dump_output_file(config: config, testfile: &Path,
out: ~str, extension: ~str) {
let outfile = make_out_name(config, testfile, extension);
let writer =
io::file_writer(&outfile, ~[io::Create, io::Truncate]).get();
writer.write_str(out);
}
fn make_out_name(config: config, testfile: &Path, extension: ~str) -> Path {
output_base_name(config, testfile).with_filetype(extension)
}
fn aux_output_dir_name(config: config, testfile: &Path) -> Path {
output_base_name(config, testfile).with_filetype("libaux")
}
fn output_testname(testfile: &Path) -> Path {
Path(testfile.filestem().get())
}
fn output_base_name(config: config, testfile: &Path) -> Path {
config.build_base
.push_rel(&output_testname(testfile))
.with_filetype(config.stage_id)
}
fn maybe_dump_to_stdout(config: config, out: ~str, err: ~str) {
if config.verbose {
let sep1 = fmt!("------%s------------------------------", ~"stdout");
let sep2 = fmt!("------%s------------------------------", ~"stderr");
let sep3 = ~"------------------------------------------";
io::stdout().write_line(sep1);
io::stdout().write_line(out);
io::stdout().write_line(sep2);
io::stdout().write_line(err);
io::stdout().write_line(sep3);
}
}
fn error(err: ~str) { io::stdout().write_line(fmt!("\nerror: %s", err)); }
fn fatal(err: ~str) -> ! { error(err); fail!(); }
fn fatal_ProcRes(err: ~str, ProcRes: ProcRes) -> ! {
let msg =
fmt!("\n\
error: %s\n\
command: %s\n\
stdout:\n\
------------------------------------------\n\
%s\n\
------------------------------------------\n\
stderr:\n\
------------------------------------------\n\
%s\n\
------------------------------------------\n\
\n",
err, ProcRes.cmdline, ProcRes.stdout, ProcRes.stderr);
io::stdout().write_str(msg);
fail!();
}
|
Java
|
/*
* Copyright 2007 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.core.reteoo;
import org.drools.core.base.ClassObjectType;
import org.drools.core.common.InternalFactHandle;
import org.drools.core.common.InternalWorkingMemory;
import org.drools.core.common.InternalWorkingMemoryEntryPoint;
import org.drools.core.common.PropagationContextFactory;
import org.drools.core.common.RuleBasePartitionId;
import org.drools.core.util.Iterator;
import org.drools.core.util.ObjectHashSet.ObjectEntry;
import org.drools.core.reteoo.LeftInputAdapterNode.LiaNodeMemory;
import org.drools.core.reteoo.ObjectTypeNode.ObjectTypeNodeMemory;
import org.drools.core.reteoo.builder.BuildContext;
import org.drools.core.rule.EntryPointId;
import org.drools.core.spi.ObjectType;
import org.drools.core.spi.PropagationContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* A node that is an entry point into the Rete network.
*
* As we move the design to support network partitions and concurrent processing
* of parts of the network, we also need to support multiple, independent entry
* points and this class represents that.
*
* It replaces the function of the Rete Node class in previous designs.
*
* @see ObjectTypeNode
*/
public class EntryPointNode extends ObjectSource
implements
Externalizable,
ObjectSink {
// ------------------------------------------------------------
// Instance members
// ------------------------------------------------------------
private static final long serialVersionUID = 510l;
protected static transient Logger log = LoggerFactory.getLogger(EntryPointNode.class);
/**
* The entry point ID for this node
*/
private EntryPointId entryPoint;
/**
* The object type nodes under this node
*/
private Map<ObjectType, ObjectTypeNode> objectTypeNodes;
private ObjectTypeNode queryNode;
private ObjectTypeNode activationNode;
// ------------------------------------------------------------
// Constructors
// ------------------------------------------------------------
public EntryPointNode() {
}
public EntryPointNode(final int id,
final ObjectSource objectSource,
final BuildContext context) {
this( id,
context.getPartitionId(),
context.getKnowledgeBase().getConfiguration().isMultithreadEvaluation(),
objectSource,
context.getCurrentEntryPoint() ); // irrelevant for this node, since it overrides sink management
}
public EntryPointNode(final int id,
final RuleBasePartitionId partitionId,
final boolean partitionsEnabled,
final ObjectSource objectSource,
final EntryPointId entryPoint) {
super( id,
partitionId,
partitionsEnabled,
objectSource,
999 ); // irrelevant for this node, since it overrides sink management
this.entryPoint = entryPoint;
this.objectTypeNodes = new ConcurrentHashMap<ObjectType, ObjectTypeNode>();
}
// ------------------------------------------------------------
// Instance methods
// ------------------------------------------------------------
@SuppressWarnings("unchecked")
public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException {
super.readExternal( in );
entryPoint = (EntryPointId) in.readObject();
objectTypeNodes = (Map<ObjectType, ObjectTypeNode>) in.readObject();
}
public void writeExternal(ObjectOutput out) throws IOException {
super.writeExternal( out );
out.writeObject( entryPoint );
out.writeObject( objectTypeNodes );
}
public short getType() {
return NodeTypeEnums.EntryPointNode;
}
/**
* @return the entryPoint
*/
public EntryPointId getEntryPoint() {
return entryPoint;
}
void setEntryPoint(EntryPointId entryPoint) {
this.entryPoint = entryPoint;
}
public void assertQuery(final InternalFactHandle factHandle,
final PropagationContext context,
final InternalWorkingMemory workingMemory) {
if ( queryNode == null ) {
this.queryNode = objectTypeNodes.get( ClassObjectType.DroolsQuery_ObjectType );
}
if ( queryNode != null ) {
// There may be no queries defined
this.queryNode.assertObject( factHandle, context, workingMemory );
}
}
public void retractQuery(final InternalFactHandle factHandle,
final PropagationContext context,
final InternalWorkingMemory workingMemory) {
if ( queryNode == null ) {
this.queryNode = objectTypeNodes.get( ClassObjectType.DroolsQuery_ObjectType );
}
if ( queryNode != null ) {
// There may be no queries defined
this.queryNode.retractObject( factHandle, context, workingMemory );
}
}
public void modifyQuery(final InternalFactHandle factHandle,
final PropagationContext context,
final InternalWorkingMemory workingMemory) {
if ( queryNode == null ) {
this.queryNode = objectTypeNodes.get( ClassObjectType.DroolsQuery_ObjectType );
}
if ( queryNode != null ) {
ModifyPreviousTuples modifyPreviousTuples = new ModifyPreviousTuples(factHandle.getFirstLeftTuple(), factHandle.getFirstRightTuple(), this );
factHandle.clearLeftTuples();
factHandle.clearRightTuples();
// There may be no queries defined
this.queryNode.modifyObject( factHandle, modifyPreviousTuples, context, workingMemory );
modifyPreviousTuples.retractTuples( context, workingMemory );
}
}
public ObjectTypeNode getQueryNode() {
if ( queryNode == null ) {
this.queryNode = objectTypeNodes.get( ClassObjectType.DroolsQuery_ObjectType );
}
return this.queryNode;
}
public void assertActivation(final InternalFactHandle factHandle,
final PropagationContext context,
final InternalWorkingMemory workingMemory) {
if ( activationNode == null ) {
this.activationNode = objectTypeNodes.get( ClassObjectType.Match_ObjectType );
}
if ( activationNode != null ) {
// There may be no queries defined
this.activationNode.assertObject( factHandle, context, workingMemory );
}
}
public void retractActivation(final InternalFactHandle factHandle,
final PropagationContext context,
final InternalWorkingMemory workingMemory) {
if ( activationNode == null ) {
this.activationNode = objectTypeNodes.get( ClassObjectType.Match_ObjectType );
}
if ( activationNode != null ) {
// There may be no queries defined
this.activationNode.retractObject( factHandle, context, workingMemory );
}
}
public void modifyActivation(final InternalFactHandle factHandle,
final PropagationContext context,
final InternalWorkingMemory workingMemory) {
if ( activationNode == null ) {
this.activationNode = objectTypeNodes.get( ClassObjectType.Match_ObjectType );
}
if ( activationNode != null ) {
ModifyPreviousTuples modifyPreviousTuples = new ModifyPreviousTuples(factHandle.getFirstLeftTuple(), factHandle.getFirstRightTuple(), this );
factHandle.clearLeftTuples();
factHandle.clearRightTuples();
// There may be no queries defined
this.activationNode.modifyObject( factHandle, modifyPreviousTuples, context, workingMemory );
modifyPreviousTuples.retractTuples( context, workingMemory );
}
}
public void assertObject(final InternalFactHandle handle,
final PropagationContext context,
final ObjectTypeConf objectTypeConf,
final InternalWorkingMemory workingMemory) {
if ( log.isTraceEnabled() ) {
log.trace( "Insert {}", handle.toString() );
}
ObjectTypeNode[] cachedNodes = objectTypeConf.getObjectTypeNodes();
for ( int i = 0, length = cachedNodes.length; i < length; i++ ) {
cachedNodes[i].assertObject( handle,
context,
workingMemory );
}
}
public void modifyObject(final InternalFactHandle handle,
final PropagationContext pctx,
final ObjectTypeConf objectTypeConf,
final InternalWorkingMemory wm) {
if ( log.isTraceEnabled() ) {
log.trace( "Update {}", handle.toString() );
}
ObjectTypeNode[] cachedNodes = objectTypeConf.getObjectTypeNodes();
// make a reference to the previous tuples, then null then on the handle
ModifyPreviousTuples modifyPreviousTuples = new ModifyPreviousTuples(handle.getFirstLeftTuple(), handle.getFirstRightTuple(), this );
handle.clearLeftTuples();
handle.clearRightTuples();
for ( int i = 0, length = cachedNodes.length; i < length; i++ ) {
cachedNodes[i].modifyObject( handle,
modifyPreviousTuples,
pctx, wm );
// remove any right tuples that matches the current OTN before continue the modify on the next OTN cache entry
if (i < cachedNodes.length - 1) {
RightTuple rightTuple = modifyPreviousTuples.peekRightTuple();
while ( rightTuple != null &&
(( BetaNode ) rightTuple.getRightTupleSink()).getObjectTypeNode() == cachedNodes[i] ) {
modifyPreviousTuples.removeRightTuple();
doRightDelete(pctx, wm, rightTuple);
rightTuple = modifyPreviousTuples.peekRightTuple();
}
LeftTuple leftTuple;
ObjectTypeNode otn;
while ( true ) {
leftTuple = modifyPreviousTuples.peekLeftTuple();
otn = null;
if (leftTuple != null) {
LeftTupleSink leftTupleSink = leftTuple.getLeftTupleSink();
if (leftTupleSink instanceof LeftTupleSource) {
otn = ((LeftTupleSource)leftTupleSink).getLeftTupleSource().getObjectTypeNode();
} else if (leftTupleSink instanceof RuleTerminalNode) {
otn = ((RuleTerminalNode)leftTupleSink).getObjectTypeNode();
}
}
if ( otn == null || otn == cachedNodes[i+1] ) break;
modifyPreviousTuples.removeLeftTuple();
doDeleteObject(pctx, wm, leftTuple);
}
}
}
modifyPreviousTuples.retractTuples( pctx, wm );
}
public void doDeleteObject(PropagationContext pctx, InternalWorkingMemory wm, LeftTuple leftTuple) {
LeftInputAdapterNode liaNode = (LeftInputAdapterNode) leftTuple.getLeftTupleSink().getLeftTupleSource();
LiaNodeMemory lm = ( LiaNodeMemory ) wm.getNodeMemory( liaNode );
LeftInputAdapterNode.doDeleteObject( leftTuple, pctx, lm.getSegmentMemory(), wm, liaNode, true, lm );
}
public void doRightDelete(PropagationContext pctx, InternalWorkingMemory wm, RightTuple rightTuple) {
rightTuple.setPropagationContext( pctx );
rightTuple.getRightTupleSink().retractRightTuple( rightTuple, pctx, wm );
}
public void modifyObject(InternalFactHandle factHandle,
ModifyPreviousTuples modifyPreviousTuples,
PropagationContext context,
InternalWorkingMemory workingMemory) {
// this method was silently failing, so I am now throwing an exception to make
// sure no one calls it by mistake
throw new UnsupportedOperationException( "This method should NEVER EVER be called" );
}
/**
* This is the entry point into the network for all asserted Facts. Iterates a cache
* of matching <code>ObjectTypdeNode</code>s asserting the Fact. If the cache does not
* exist it first iterates and builds the cache.
*
* @param factHandle
* The FactHandle of the fact to assert
* @param context
* The <code>PropagationContext</code> of the <code>WorkingMemory</code> action
* @param workingMemory
* The working memory session.
*/
public void assertObject(final InternalFactHandle factHandle,
final PropagationContext context,
final InternalWorkingMemory workingMemory) {
// this method was silently failing, so I am now throwing an exception to make
// sure no one calls it by mistake
throw new UnsupportedOperationException( "This method should NEVER EVER be called" );
}
/**
* Retract a fact object from this <code>RuleBase</code> and the specified
* <code>WorkingMemory</code>.
*
* @param handle
* The handle of the fact to retract.
* @param workingMemory
* The working memory session.
*/
public void retractObject(final InternalFactHandle handle,
final PropagationContext context,
final ObjectTypeConf objectTypeConf,
final InternalWorkingMemory workingMemory) {
if ( log.isTraceEnabled() ) {
log.trace( "Delete {}", handle.toString() );
}
ObjectTypeNode[] cachedNodes = objectTypeConf.getObjectTypeNodes();
if ( cachedNodes == null ) {
// it is possible that there are no ObjectTypeNodes for an object being retracted
return;
}
for ( int i = 0; i < cachedNodes.length; i++ ) {
cachedNodes[i].retractObject( handle,
context,
workingMemory );
}
}
/**
* Adds the <code>ObjectSink</code> so that it may receive
* <code>Objects</code> propagated from this <code>ObjectSource</code>.
*
* @param objectSink
* The <code>ObjectSink</code> to receive propagated
* <code>Objects</code>. Rete only accepts <code>ObjectTypeNode</code>s
* as parameters to this method, though.
*/
public void addObjectSink(final ObjectSink objectSink) {
final ObjectTypeNode node = (ObjectTypeNode) objectSink;
this.objectTypeNodes.put( node.getObjectType(),
node );
}
public void removeObjectSink(final ObjectSink objectSink) {
final ObjectTypeNode node = (ObjectTypeNode) objectSink;
this.objectTypeNodes.remove( node.getObjectType() );
}
public void attach( BuildContext context ) {
this.source.addObjectSink( this );
if (context == null ) {
return;
}
if ( context.getKnowledgeBase().getConfiguration().isPhreakEnabled() ) {
for ( InternalWorkingMemory workingMemory : context.getWorkingMemories() ) {
workingMemory.updateEntryPointsCache();
}
return;
}
for ( InternalWorkingMemory workingMemory : context.getWorkingMemories() ) {
workingMemory.updateEntryPointsCache();
PropagationContextFactory pctxFactory = workingMemory.getKnowledgeBase().getConfiguration().getComponentFactory().getPropagationContextFactory();
final PropagationContext propagationContext = pctxFactory.createPropagationContext(workingMemory.getNextPropagationIdCounter(), PropagationContext.RULE_ADDITION, null, null, null);
this.source.updateSink( this,
propagationContext,
workingMemory );
}
}
protected void doRemove(final RuleRemovalContext context,
final ReteooBuilder builder,
final InternalWorkingMemory[] workingMemories) {
}
public Map<ObjectType, ObjectTypeNode> getObjectTypeNodes() {
return this.objectTypeNodes;
}
public int hashCode() {
return this.entryPoint.hashCode();
}
public boolean equals(final Object object) {
if ( object == this ) {
return true;
}
if ( object == null || !(object instanceof EntryPointNode) ) {
return false;
}
final EntryPointNode other = (EntryPointNode) object;
return this.entryPoint.equals( other.entryPoint );
}
public void updateSink(final ObjectSink sink,
final PropagationContext context,
final InternalWorkingMemory workingMemory) {
// @todo
// JBRULES-612: the cache MUST be invalidated when a new node type is added to the network, so iterate and reset all caches.
final ObjectTypeNode node = (ObjectTypeNode) sink;
final ObjectType newObjectType = node.getObjectType();
InternalWorkingMemoryEntryPoint wmEntryPoint = (InternalWorkingMemoryEntryPoint) workingMemory.getWorkingMemoryEntryPoint( this.entryPoint.getEntryPointId() );
for ( ObjectTypeConf objectTypeConf : wmEntryPoint.getObjectTypeConfigurationRegistry().values() ) {
if ( newObjectType.isAssignableFrom( objectTypeConf.getConcreteObjectTypeNode().getObjectType() ) ) {
objectTypeConf.resetCache();
ObjectTypeNode sourceNode = objectTypeConf.getConcreteObjectTypeNode();
Iterator it = ((ObjectTypeNodeMemory) workingMemory.getNodeMemory( sourceNode )).memory.iterator();
for ( ObjectEntry entry = (ObjectEntry) it.next(); entry != null; entry = (ObjectEntry) it.next() ) {
sink.assertObject( (InternalFactHandle) entry.getValue(),
context,
workingMemory );
}
}
}
}
public boolean isObjectMemoryEnabled() {
return false;
}
public void setObjectMemoryEnabled(boolean objectMemoryEnabled) {
throw new UnsupportedOperationException( "Entry Point Node has no Object memory" );
}
public String toString() {
return "[EntryPointNode(" + this.id + ") " + this.entryPoint + " ]";
}
public void byPassModifyToBetaNode(InternalFactHandle factHandle,
ModifyPreviousTuples modifyPreviousTuples,
PropagationContext context,
InternalWorkingMemory workingMemory) {
throw new UnsupportedOperationException();
}
@Override
public long calculateDeclaredMask(List<String> settableProperties) {
throw new UnsupportedOperationException();
}
}
|
Java
|
<?php
namespace Tests\unit\Composer\Read\Register;
use ModbusTcpClient\Packet\ModbusFunction\ReadHoldingRegistersResponse;
use ModbusTcpClient\Composer\Read\Register\ByteReadRegisterAddress;
use PHPUnit\Framework\TestCase;
class ByteReadRegisterAddressTest extends TestCase
{
public function testGetSize()
{
$address = new ByteReadRegisterAddress(1, true);
$this->assertEquals(1, $address->getSize());
}
public function testGetName()
{
$address = new ByteReadRegisterAddress(1, true, 'direction');
$this->assertEquals('direction', $address->getName());
}
public function testDefaultGetName()
{
$address = new ByteReadRegisterAddress(1, true);
$this->assertEquals('byte_1_1', $address->getName());
$address = new ByteReadRegisterAddress(1, false);
$this->assertEquals('byte_1_0', $address->getName());
}
public function testExtract()
{
$responsePacket = new ReadHoldingRegistersResponse("\x02\x00\x05", 3, 33152);
$this->assertEquals(5, (new ByteReadRegisterAddress(0, true))->extract($responsePacket));
$this->assertEquals(0, (new ByteReadRegisterAddress(0, false))->extract($responsePacket));
}
public function testExtractWithCallback()
{
$responsePacket = new ReadHoldingRegistersResponse("\x02\x00\x05", 3, 33152);
$address = new ByteReadRegisterAddress(0, true, null, function ($data) {
return 'prefix_' . $data;
});
$this->assertEquals('prefix_5', $address->extract($responsePacket));
}
}
|
Java
|
/*
* 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.route53.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
* <p>
* A complex type that contains information about that can be associated with your hosted zone.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListVPCAssociationAuthorizations"
* target="_top">AWS API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ListVPCAssociationAuthorizationsRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The ID of the hosted zone for which you want a list of VPCs that can be associated with the hosted zone.
* </p>
*/
private String hostedZoneId;
/**
* <p>
* <i>Optional</i>: If a response includes a <code>NextToken</code> element, there are more VPCs that can be
* associated with the specified hosted zone. To get the next page of results, submit another request, and include
* the value of <code>NextToken</code> from the response in the <code>nexttoken</code> parameter in another
* <code>ListVPCAssociationAuthorizations</code> request.
* </p>
*/
private String nextToken;
/**
* <p>
* <i>Optional</i>: An integer that specifies the maximum number of VPCs that you want Amazon Route 53 to return. If
* you don't specify a value for <code>MaxResults</code>, Amazon Route 53 returns up to 50 VPCs per page.
* </p>
*/
private String maxResults;
/**
* <p>
* The ID of the hosted zone for which you want a list of VPCs that can be associated with the hosted zone.
* </p>
*
* @param hostedZoneId
* The ID of the hosted zone for which you want a list of VPCs that can be associated with the hosted zone.
*/
public void setHostedZoneId(String hostedZoneId) {
this.hostedZoneId = hostedZoneId;
}
/**
* <p>
* The ID of the hosted zone for which you want a list of VPCs that can be associated with the hosted zone.
* </p>
*
* @return The ID of the hosted zone for which you want a list of VPCs that can be associated with the hosted zone.
*/
public String getHostedZoneId() {
return this.hostedZoneId;
}
/**
* <p>
* The ID of the hosted zone for which you want a list of VPCs that can be associated with the hosted zone.
* </p>
*
* @param hostedZoneId
* The ID of the hosted zone for which you want a list of VPCs that can be associated with the hosted zone.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListVPCAssociationAuthorizationsRequest withHostedZoneId(String hostedZoneId) {
setHostedZoneId(hostedZoneId);
return this;
}
/**
* <p>
* <i>Optional</i>: If a response includes a <code>NextToken</code> element, there are more VPCs that can be
* associated with the specified hosted zone. To get the next page of results, submit another request, and include
* the value of <code>NextToken</code> from the response in the <code>nexttoken</code> parameter in another
* <code>ListVPCAssociationAuthorizations</code> request.
* </p>
*
* @param nextToken
* <i>Optional</i>: If a response includes a <code>NextToken</code> element, there are more VPCs that can be
* associated with the specified hosted zone. To get the next page of results, submit another request, and
* include the value of <code>NextToken</code> from the response in the <code>nexttoken</code> parameter in
* another <code>ListVPCAssociationAuthorizations</code> request.
*/
public void setNextToken(String nextToken) {
this.nextToken = nextToken;
}
/**
* <p>
* <i>Optional</i>: If a response includes a <code>NextToken</code> element, there are more VPCs that can be
* associated with the specified hosted zone. To get the next page of results, submit another request, and include
* the value of <code>NextToken</code> from the response in the <code>nexttoken</code> parameter in another
* <code>ListVPCAssociationAuthorizations</code> request.
* </p>
*
* @return <i>Optional</i>: If a response includes a <code>NextToken</code> element, there are more VPCs that can be
* associated with the specified hosted zone. To get the next page of results, submit another request, and
* include the value of <code>NextToken</code> from the response in the <code>nexttoken</code> parameter in
* another <code>ListVPCAssociationAuthorizations</code> request.
*/
public String getNextToken() {
return this.nextToken;
}
/**
* <p>
* <i>Optional</i>: If a response includes a <code>NextToken</code> element, there are more VPCs that can be
* associated with the specified hosted zone. To get the next page of results, submit another request, and include
* the value of <code>NextToken</code> from the response in the <code>nexttoken</code> parameter in another
* <code>ListVPCAssociationAuthorizations</code> request.
* </p>
*
* @param nextToken
* <i>Optional</i>: If a response includes a <code>NextToken</code> element, there are more VPCs that can be
* associated with the specified hosted zone. To get the next page of results, submit another request, and
* include the value of <code>NextToken</code> from the response in the <code>nexttoken</code> parameter in
* another <code>ListVPCAssociationAuthorizations</code> request.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListVPCAssociationAuthorizationsRequest withNextToken(String nextToken) {
setNextToken(nextToken);
return this;
}
/**
* <p>
* <i>Optional</i>: An integer that specifies the maximum number of VPCs that you want Amazon Route 53 to return. If
* you don't specify a value for <code>MaxResults</code>, Amazon Route 53 returns up to 50 VPCs per page.
* </p>
*
* @param maxResults
* <i>Optional</i>: An integer that specifies the maximum number of VPCs that you want Amazon Route 53 to
* return. If you don't specify a value for <code>MaxResults</code>, Amazon Route 53 returns up to 50 VPCs
* per page.
*/
public void setMaxResults(String maxResults) {
this.maxResults = maxResults;
}
/**
* <p>
* <i>Optional</i>: An integer that specifies the maximum number of VPCs that you want Amazon Route 53 to return. If
* you don't specify a value for <code>MaxResults</code>, Amazon Route 53 returns up to 50 VPCs per page.
* </p>
*
* @return <i>Optional</i>: An integer that specifies the maximum number of VPCs that you want Amazon Route 53 to
* return. If you don't specify a value for <code>MaxResults</code>, Amazon Route 53 returns up to 50 VPCs
* per page.
*/
public String getMaxResults() {
return this.maxResults;
}
/**
* <p>
* <i>Optional</i>: An integer that specifies the maximum number of VPCs that you want Amazon Route 53 to return. If
* you don't specify a value for <code>MaxResults</code>, Amazon Route 53 returns up to 50 VPCs per page.
* </p>
*
* @param maxResults
* <i>Optional</i>: An integer that specifies the maximum number of VPCs that you want Amazon Route 53 to
* return. If you don't specify a value for <code>MaxResults</code>, Amazon Route 53 returns up to 50 VPCs
* per page.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListVPCAssociationAuthorizationsRequest withMaxResults(String maxResults) {
setMaxResults(maxResults);
return this;
}
/**
* Returns a string representation of this object; useful for testing and debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getHostedZoneId() != null)
sb.append("HostedZoneId: ").append(getHostedZoneId()).append(",");
if (getNextToken() != null)
sb.append("NextToken: ").append(getNextToken()).append(",");
if (getMaxResults() != null)
sb.append("MaxResults: ").append(getMaxResults());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ListVPCAssociationAuthorizationsRequest == false)
return false;
ListVPCAssociationAuthorizationsRequest other = (ListVPCAssociationAuthorizationsRequest) obj;
if (other.getHostedZoneId() == null ^ this.getHostedZoneId() == null)
return false;
if (other.getHostedZoneId() != null && other.getHostedZoneId().equals(this.getHostedZoneId()) == false)
return false;
if (other.getNextToken() == null ^ this.getNextToken() == null)
return false;
if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
return false;
if (other.getMaxResults() == null ^ this.getMaxResults() == null)
return false;
if (other.getMaxResults() != null && other.getMaxResults().equals(this.getMaxResults()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getHostedZoneId() == null) ? 0 : getHostedZoneId().hashCode());
hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
hashCode = prime * hashCode + ((getMaxResults() == null) ? 0 : getMaxResults().hashCode());
return hashCode;
}
@Override
public ListVPCAssociationAuthorizationsRequest clone() {
return (ListVPCAssociationAuthorizationsRequest) super.clone();
}
}
|
Java
|
/*
* 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.kylin.invertedindex.index;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.roaringbitmap.RoaringBitmap;
/**
* @author yangli9
*/
public interface ColumnValueContainer {
void append(ImmutableBytesWritable valueBytes);
void closeForChange();
int getSize();
// works only after closeForChange()
void getValueAt(int i, ImmutableBytesWritable valueBytes);
RoaringBitmap getBitMap(Integer startId, Integer endId);
int getMaxValueId();
}
|
Java
|
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<title></title>
<link rel="stylesheet" href="css/my-css.css" media="screen" type="text/css" />
</head>
<body>
<img src="http://autoshanghai2015-cdn.prvalue.cn/img/p25.png" style="height:100%;width:100%">
</body>
</html>
|
Java
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="pl">
<head>
<!-- Generated by javadoc -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class com.google.code.play2.spm.routes.Play2RoutesSourcePositionMapper (Play! 2.x Source Position Mappers 1.0.0-beta8 API)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class com.google.code.play2.spm.routes.Play2RoutesSourcePositionMapper (Play! 2.x Source Position Mappers 1.0.0-beta8 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../com/google/code/play2/spm/routes/Play2RoutesSourcePositionMapper.html" title="class in com.google.code.play2.spm.routes">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?com/google/code/play2/spm/routes/class-use/Play2RoutesSourcePositionMapper.html" target="_top">Frames</a></li>
<li><a href="Play2RoutesSourcePositionMapper.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class com.google.code.play2.spm.routes.Play2RoutesSourcePositionMapper" class="title">Uses of Class<br>com.google.code.play2.spm.routes.Play2RoutesSourcePositionMapper</h2>
</div>
<div class="classUseContainer">No usage of com.google.code.play2.spm.routes.Play2RoutesSourcePositionMapper</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../com/google/code/play2/spm/routes/Play2RoutesSourcePositionMapper.html" title="class in com.google.code.play2.spm.routes">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?com/google/code/play2/spm/routes/class-use/Play2RoutesSourcePositionMapper.html" target="_top">Frames</a></li>
<li><a href="Play2RoutesSourcePositionMapper.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2013–2017. All rights reserved.</small></p>
</body>
</html>
|
Java
|
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<h3>
标题
</h3><!-- cellpadding="2" cellspacing="0" -->
<table style="width:100%;" border="1">
<tbody>
<tr>
<td>
<h3>标题1</h3>
</td>
<td>
<h3>标题1</h3>
</td>
</tr>
<tr>
<td>
内容1
</td>
<td>
内容2
</td>
</tr>
<tr>
<td>
内容3
</td>
<td>
内容4
</td>
</tr>
</tbody>
</table>
<p>
表格说明
</p>
</body>
</html>
|
Java
|
/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2014-2020 Couchbase, 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.
*/
#ifndef _WIN32
#include <cerrno>
#endif
#include "connect.h"
#include "ioutils.h"
#include "hostlist.h"
#include "iotable.h"
#include "ssl.h"
lcbio_CSERR lcbio_mkcserr(int syserr)
{
switch (syserr) {
case 0:
return LCBIO_CSERR_CONNECTED;
case EINTR:
return LCBIO_CSERR_INTR;
case EWOULDBLOCK:
#ifdef USE_EAGAIN
case EAGAIN:
#endif
case EINPROGRESS:
case EALREADY:
return LCBIO_CSERR_BUSY;
case EISCONN:
return LCBIO_CSERR_CONNECTED;
#ifdef _WIN32
case EINVAL:
return LCBIO_CSERR_EINVAL;
#endif
default:
return LCBIO_CSERR_EFAIL;
}
}
void lcbio_mksyserr(lcbio_OSERR in, lcbio_OSERR *out)
{
switch (in) {
case EINTR:
case EWOULDBLOCK:
#ifdef USE_EAGAIN
case EAGAIN:
#endif
case EINVAL:
case EINPROGRESS:
case EISCONN:
case EALREADY:
return;
default:
*out = in;
break;
}
}
static lcb_STATUS ioerr2lcberr(lcbio_OSERR in, const lcb_settings *settings)
{
switch (in) {
case 0:
return LCB_ERR_SOCKET_SHUTDOWN;
case ECONNREFUSED:
return LCB_ERR_CONNECTION_REFUSED;
case ENETUNREACH:
case EHOSTUNREACH:
case EHOSTDOWN:
return LCB_ERR_NODE_UNREACHABLE;
case EMFILE:
case ENFILE:
return LCB_ERR_FD_LIMIT_REACHED;
case EADDRINUSE:
case EADDRNOTAVAIL:
return LCB_ERR_CANNOT_GET_PORT;
case ECONNRESET:
case ECONNABORTED:
return LCB_ERR_CONNECTION_RESET;
default:
lcb_log(settings, "lcbio", LCB_LOG_WARN, __FILE__, __LINE__,
"OS errno %d (%s) does not have a direct client error code equivalent. Using NETWORK_ERROR", in,
strerror(in));
return LCB_ERR_NETWORK;
}
}
lcb_STATUS lcbio_mklcberr(lcbio_OSERR in, const lcb_settings *settings)
{
if (settings->detailed_neterr == 0) {
lcb_log(settings, "lcbio", LCB_LOG_WARN, __FILE__, __LINE__, "Translating errno=%d (%s), %s to LCB_ERR_NETWORK",
in, strerror(in), lcb_strerror_short(ioerr2lcberr(in, settings)));
return LCB_ERR_NETWORK;
}
return ioerr2lcberr(in, settings);
}
lcb_socket_t lcbio_E_ai2sock(lcbio_TABLE *io, struct addrinfo **ai, int *connerr)
{
lcb_socket_t ret = INVALID_SOCKET;
*connerr = 0;
for (; *ai; *ai = (*ai)->ai_next) {
ret = io->E_socket(*ai);
if (ret != INVALID_SOCKET) {
return ret;
} else {
*connerr = io->get_errno();
}
}
return ret;
}
lcb_sockdata_t *lcbio_C_ai2sock(lcbio_TABLE *io, struct addrinfo **ai, int *connerr)
{
lcb_sockdata_t *ret = nullptr;
for (; *ai; *ai = (*ai)->ai_next) {
ret = io->C_socket(*ai);
if (ret) {
return ret;
} else {
*connerr = IOT_ERRNO(io);
}
}
return ret;
}
static int saddr_to_host_and_port(struct sockaddr *saddr, int len, char *host, lcb_size_t nhost, char *port,
lcb_size_t nport)
{
return getnameinfo(saddr, len, host, nhost, port, nport, NI_NUMERICHOST | NI_NUMERICSERV);
}
static int saddr_to_string(struct sockaddr *saddr, int len, char *buf, lcb_size_t nbuf)
{
char h[NI_MAXHOST + 1];
char p[NI_MAXSERV + 1];
int rv;
rv = saddr_to_host_and_port(saddr, len, h, sizeof(h), p, sizeof(p));
if (rv < 0) {
return 0;
}
if (snprintf(buf, nbuf, "%s;%s", h, p) < 0) {
return 0;
}
return 1;
}
static void lcbio_cache_local_name(lcbio_CONNINFO *sock)
{
char addr_str[NI_MAXHOST + 1];
switch (sock->sa_local.ss_family) {
case AF_INET: {
auto *addr = (struct sockaddr_in *)&sock->sa_local;
inet_ntop(AF_INET, &(addr->sin_addr), addr_str, sizeof(addr_str));
strncpy(sock->ep_local.host, addr_str, sizeof(sock->ep_local.host));
snprintf(sock->ep_local.port, sizeof(sock->ep_local.port), "%d", (int)ntohs(addr->sin_port));
} break;
case AF_INET6: {
auto *addr = (struct sockaddr_in6 *)&sock->sa_local;
inet_ntop(AF_INET6, &(addr->sin6_addr), addr_str, sizeof(addr_str));
strncpy(sock->ep_local.host, addr_str, sizeof(sock->ep_local.host));
snprintf(sock->ep_local.port, sizeof(sock->ep_local.port), "%d", (int)ntohs(addr->sin6_port));
} break;
}
snprintf(sock->ep_local_host_and_port, sizeof(sock->ep_local_host_and_port), "%s:%s", sock->ep_local.host,
sock->ep_local.port);
}
void lcbio__load_socknames(lcbio_SOCKET *sock)
{
int n_salocal, n_saremote, rv;
struct lcb_nameinfo_st ni {
};
lcbio_CONNINFO *info = sock->info;
n_salocal = sizeof(info->sa_local);
n_saremote = sizeof(info->sa_remote);
ni.local.name = (struct sockaddr *)&info->sa_local;
ni.local.len = &n_salocal;
ni.remote.name = (struct sockaddr *)&info->sa_remote;
ni.remote.len = &n_saremote;
if (!IOT_IS_EVENT(sock->io)) {
if (!sock->u.sd) {
return;
}
rv = IOT_V1(sock->io).nameinfo(IOT_ARG(sock->io), sock->u.sd, &ni);
if (ni.local.len == nullptr || ni.remote.len == nullptr || rv < 0) {
return;
}
} else {
socklen_t sl_tmp = sizeof(info->sa_local);
if (sock->u.fd == INVALID_SOCKET) {
return;
}
rv = getsockname(sock->u.fd, ni.local.name, &sl_tmp);
n_salocal = sl_tmp;
if (rv < 0) {
return;
}
rv = getpeername(sock->u.fd, ni.remote.name, &sl_tmp);
n_saremote = sl_tmp;
if (rv < 0) {
return;
}
}
info->naddr = n_salocal;
lcbio_cache_local_name(info);
}
int lcbio_get_nameinfo(lcbio_SOCKET *sock, struct lcbio_NAMEINFO *nistrs)
{
lcbio_CONNINFO *info = sock->info;
if (!info) {
return 0;
}
if (!info->naddr) {
return 0;
}
if (!saddr_to_string((struct sockaddr *)&info->sa_remote, info->naddr, nistrs->remote, sizeof(nistrs->remote))) {
return 0;
}
if (!saddr_to_string((struct sockaddr *)&info->sa_local, info->naddr, nistrs->local, sizeof(nistrs->local))) {
return 0;
}
return 1;
}
int lcbio_is_netclosed(lcbio_SOCKET *sock, int flags)
{
lcbio_pTABLE iot = sock->io;
if (iot->is_E()) {
return iot->E_check_closed(sock->u.fd, flags);
} else {
return iot->C_check_closed(sock->u.sd, flags);
}
}
lcb_STATUS lcbio_enable_sockopt(lcbio_SOCKET *s, int cntl)
{
lcbio_pTABLE iot = s->io;
int rv;
int value = 1;
if (!iot->has_cntl()) {
return LCB_ERR_UNSUPPORTED_OPERATION;
}
if (iot->is_E()) {
rv = iot->E_cntl(s->u.fd, LCB_IO_CNTL_SET, cntl, &value);
} else {
rv = iot->C_cntl(s->u.sd, LCB_IO_CNTL_SET, cntl, &value);
}
if (rv != 0) {
return lcbio_mklcberr(IOT_ERRNO(iot), s->settings);
} else {
return LCB_SUCCESS;
}
}
const char *lcbio_strsockopt(int cntl)
{
switch (cntl) {
case LCB_IO_CNTL_TCP_KEEPALIVE:
return "TCP_KEEPALIVE";
case LCB_IO_CNTL_TCP_NODELAY:
return "TCP_NODELAY";
default:
return "FIXME: Unknown option";
}
}
int lcbio_ssl_supported(void)
{
#ifdef LCB_NO_SSL
return 0;
#else
return 1;
#endif
}
lcbio_pSSLCTX lcbio_ssl_new__fallback(const char *, const char *, const char *, int, lcb_STATUS *errp, lcb_settings *)
{
if (errp) {
*errp = LCB_ERR_SDK_FEATURE_UNAVAILABLE;
}
return nullptr;
}
#ifdef LCB_NO_SSL
void lcbio_ssl_free(lcbio_pSSLCTX) {}
lcb_STATUS lcbio_ssl_apply(lcbio_SOCKET *, lcbio_pSSLCTX)
{
return LCB_ERR_SDK_FEATURE_UNAVAILABLE;
}
int lcbio_ssl_check(lcbio_SOCKET *)
{
return 0;
}
lcb_STATUS lcbio_ssl_get_error(lcbio_SOCKET *)
{
return LCB_SUCCESS;
}
void lcbio_ssl_global_init(void) {}
lcb_STATUS lcbio_sslify_if_needed(lcbio_SOCKET *, lcb_settings *)
{
return LCB_SUCCESS;
}
#endif
|
Java
|
package org.valuereporter.observation;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.valuereporter.QueryOperations;
import org.valuereporter.WriteOperations;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
/**
* @author <a href="mailto:erik-dev@fjas.no">Erik Drolshammer</a>
*/
@Component
@Path("/observedmethods")
public class ObservedMethodsResouce {
private static final Logger log = LoggerFactory.getLogger(ObservedMethodsResouce.class);
private final QueryOperations queryOperations;
private final WriteOperations writeOperations;
private final ObjectMapper mapper;
/**
@Autowired
public ObservedMethodsResouce(QueryOperations queryOperations, WriteOperations writeOperations, ObjectMapper mapper) {
this.queryOperations = queryOperations;
this.writeOperations = writeOperations;
this.mapper = mapper;
}
**/
@Autowired
public ObservedMethodsResouce(ObservationsService observationsService, ObjectMapper mapper) {
this.queryOperations = observationsService;
this.writeOperations = observationsService;
this.mapper = mapper;
}
//http://localhost:4901/reporter/observe/observedmethods/{prefix}/{name}
/**
* A request with no filtering parameters should return a list of all observations.
*
* @param prefix prefix used to identify running process
* @param name package.classname.method
* @return List of observations
*/
@GET
@Path("/{prefix}/{name}")
@Produces(MediaType.APPLICATION_JSON)
public Response findObservationsByName(@PathParam("prefix") String prefix,@PathParam("name") String name) {
final List<ObservedMethod> observedMethods;
//Should also support no queryParams -> findAll
if (name != null ) {
log.trace("findObservationsByName name={}", name);
observedMethods = queryOperations.findObservationsByName(prefix, name);
} else {
throw new UnsupportedOperationException("You must supply a name. <package.classname.method>");
}
Writer strWriter = new StringWriter();
try {
mapper.writeValue(strWriter, observedMethods);
} catch (IOException e) {
log.error("Could not convert {} ObservedMethod to JSON.", observedMethods.size(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Error converting to requested format.").build();
}
return Response.ok(strWriter.toString()).build();
}
//http://localhost:4901/reporter/observe/observedmethods/{prefix}
@POST
@Path("/{prefix}")
@Produces(MediaType.APPLICATION_JSON)
public Response addObservationMethod(@PathParam("prefix") String prefix, String jsonBody){
log.trace("addObservationMethod prefix {} , jsonBody {}.", prefix, jsonBody);
List<ObservedMethod> observedMethods = null;
try {
observedMethods = mapper.readValue(jsonBody, new TypeReference<ArrayList<ObservedMethodJson>>(){ });
if (observedMethods != null) {
for (ObservedMethod observedMethod : observedMethods) {
observedMethod.setPrefix(prefix);
}
}
} catch (IOException e) {
log.warn("Unexpected error trying to produce list of ObservedMethod from \n prefix {} \n json {}, \n Reason {}",prefix, jsonBody, e.getMessage());
return Response.status(Response.Status.NOT_ACCEPTABLE).entity("Error converting to requested format.").build();
}
long updatedCount = writeOperations.addObservations(prefix,observedMethods);
String message = "added " + updatedCount + " observedMethods.";
Writer strWriter = new StringWriter();
try {
mapper.writeValue(strWriter, message);
} catch (IOException e) {
log.error("Could not convert {} to JSON.", updatedCount, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Error converting to requested format.").build();
}
return Response.ok(strWriter.toString()).build();
}
}
|
Java
|
package com.lee.game;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import com.lee.base.activity.BaseActivity;
import com.lee.base.application.PackageNameContainer;
import com.noobyang.log.LogUtil;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
/**
* Main Activity
* <p/>
* Created by LiYang on 2019/4/8.
*/
public class MainActivity extends BaseActivity {
private static final String ACTION_SAMPLE_CODE = "com.lee.main.action.SAMPLE_CODE_GAME";
private static final String EXTRA_NAME_PATH = "com.lee.main.Path";
private static final String PATH_DIVIDED_SYMBOLS = ".";
private static final String PATH_DIVIDED_SYMBOLS_REGEX = "\\.";
@BindView(R.id.tv_path)
TextView tvPath;
@BindView(R.id.rv_sample_code)
RecyclerView rvSampleCode;
private PackageManager packageManager;
private List<SampleCodeEntity> sampleCodeEntities;
private SampleCodeAdapter sampleCodeAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
initData();
initView();
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
updateSampleCodes();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
private void initData() {
packageManager = getPackageManager();
sampleCodeAdapter = new SampleCodeAdapter(this, sampleCodeEntities, itemClickListener);
}
private void initView() {
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
rvSampleCode.setLayoutManager(layoutManager);
rvSampleCode.setAdapter(sampleCodeAdapter);
updateSampleCodes();
}
private void updateSampleCodes() {
String path = getIntent().getStringExtra(EXTRA_NAME_PATH);
initSampleCodes(path);
sampleCodeAdapter.setData(sampleCodeEntities);
sampleCodeAdapter.notifyDataSetChanged();
setPathText(path);
}
private void setPathText(String path) {
if (TextUtils.isEmpty(path)) {
tvPath.setText(R.string.app_name);
} else {
tvPath.setText(path);
}
}
protected void initSampleCodes(String path) {
if (sampleCodeEntities == null) {
sampleCodeEntities = new ArrayList<>();
} else {
sampleCodeEntities.clear();
}
List<ResolveInfo> sampleCodeResolveInfoList = getSampleCodeResolveInfoList();
if (sampleCodeResolveInfoList == null || sampleCodeResolveInfoList.size() == 0) {
return;
}
String[] prefixPaths;
String currentPrefixPath;
Map<String, Boolean> folderLabel = new HashMap<>();
String label;
String[] labelPath;
String sampleCodeLabel;
for (ResolveInfo sampleCodeResolveInfo : sampleCodeResolveInfoList) {
if (TextUtils.isEmpty(path)) {
prefixPaths = null;
currentPrefixPath = null;
} else {
path = getRelativeName(path);
prefixPaths = path.split(PATH_DIVIDED_SYMBOLS_REGEX);
currentPrefixPath = path + PATH_DIVIDED_SYMBOLS;
}
label = getRelativeName(sampleCodeResolveInfo.activityInfo.name);
LogUtil.d("getData currentPrefixPath = " + currentPrefixPath + "---label = " + label);
if (TextUtils.isEmpty(currentPrefixPath) || label.startsWith(currentPrefixPath)) {
labelPath = label.split(PATH_DIVIDED_SYMBOLS_REGEX);
int prefixPathsLen = prefixPaths == null ? 0 : prefixPaths.length;
sampleCodeLabel = labelPath[prefixPathsLen];
if (prefixPathsLen == labelPath.length - 1) {
// activity
addActivityItem(sampleCodeEntities, sampleCodeLabel,
sampleCodeResolveInfo.activityInfo.applicationInfo.packageName,
sampleCodeResolveInfo.activityInfo.name);
} else {
// folder
if (folderLabel.get(sampleCodeLabel) == null) {
addFolderItem(sampleCodeEntities, sampleCodeLabel, currentPrefixPath);
folderLabel.put(sampleCodeLabel, true);
}
}
}
}
Collections.sort(sampleCodeEntities, comparator);
}
private String getRelativeName(String className) {
if (TextUtils.isEmpty(className)) {
return className;
}
for (String packageName : PackageNameContainer.getPackageNames()) {
if (className.startsWith(packageName + PATH_DIVIDED_SYMBOLS)) {
return className.substring(packageName.length() + 1);
}
}
return className;
}
private List<ResolveInfo> getSampleCodeResolveInfoList() {
Intent sampleCodeIntent = new Intent(ACTION_SAMPLE_CODE, null);
sampleCodeIntent.addCategory(Intent.CATEGORY_SAMPLE_CODE);
return packageManager.queryIntentActivities(sampleCodeIntent, 0);
}
private final static Comparator<SampleCodeEntity> comparator =
new Comparator<SampleCodeEntity>() {
private final Collator collator = Collator.getInstance();
public int compare(SampleCodeEntity entity1, SampleCodeEntity entity2) {
return collator.compare(entity1.getTitle(), entity2.getTitle());
}
};
private void addActivityItem(List<SampleCodeEntity> data, String sampleCodeLabel,
String packageName, String className) {
Intent activityIntent = new Intent();
activityIntent.setClassName(packageName, className);
addItem(data, SampleCodeEntity.SampleCodeType.SAMPLE_CODE_TYPE_ACTIVITY, sampleCodeLabel, activityIntent);
}
private void addFolderItem(List<SampleCodeEntity> data, String sampleCodeLabel,
String currentPrefixPath) {
Intent folderIntent = new Intent();
folderIntent.setClass(this, MainActivity.class);
String path = TextUtils.isEmpty(currentPrefixPath) ? sampleCodeLabel : currentPrefixPath + sampleCodeLabel;
folderIntent.putExtra(EXTRA_NAME_PATH, path);
addItem(data, SampleCodeEntity.SampleCodeType.SAMPLE_CODE_TYPE_FOLDER, sampleCodeLabel, folderIntent);
}
protected void addItem(List<SampleCodeEntity> data, int type, String title, Intent intent) {
SampleCodeEntity entity = new SampleCodeEntity(type, title, intent);
data.add(entity);
}
private SampleCodeAdapter.OnItemClickListener itemClickListener =
new SampleCodeAdapter.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
SampleCodeEntity entity = sampleCodeEntities.get(position);
if (entity != null) {
Intent intent = entity.getIntent();
intent.addCategory(Intent.CATEGORY_SAMPLE_CODE);
startActivity(intent);
}
}
};
}
|
Java
|
<?php
namespace Obj;
class Encoder {
private $key;
private $cipher;
private $mode;
/**
*
* args - array(
* 'hash' => hash method
* 'key' => path to private key
* 'encrypt' => encryption method
* )
*/
public function __construct($key, $cipher = MCRYPT_RIJNDAEL_128, $mode = MCRYPT_MODE_CBC) {
$keyString = file_get_contents($key, true);
$this->key = pack('H*', $keyString);
$this->cipher = $cipher;
$this->mode = $mode;
}
/**
* hash
*/
public static function hash($input, $hash = 'md5') {
return hash($hash, $input);
}
public function encrypt($plaintext) {
$key_size = strlen($this->key);
// create a random IV to use with CBC encoding
$iv_size = mcrypt_get_iv_size($this->cipher, $this->mode);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$ciphertext = mcrypt_encrypt($this->cipher, $this->key,
$plaintext, $this->mode, $iv);
$ciphertext = $iv . $ciphertext;
// encode the resulting cipher text so it can be represented by a string
$ciphertext_base64 = base64_encode($ciphertext);
return $ciphertext_base64;
}
public function decrypt($ciphertext_base64) {
$ciphertext_dec = base64_decode($ciphertext_base64);
$iv_size = mcrypt_get_iv_size($this->cipher, $this->mode);
// retrieves the IV, iv_size should be created using mcrypt_get_iv_size()
$iv_dec = substr($ciphertext_dec, 0, $iv_size);
// retrieves the cipher text (everything except the $iv_size in the front)
$ciphertext_dec = substr($ciphertext_dec, $iv_size);
// may remove 00h valued characters from end of plain text
$plaintext_dec = mcrypt_decrypt($this->cipher, $this->key,
$ciphertext_dec, $this->mode, $iv_dec);
return $plaintext_dec;
}
/**
* Generates a random string from the given charset of input length
*/
public static function randomString($length = 10, $set = null) {
if ($set == null) {
$set = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
}
$len = strlen($set);
$str = '';
while ($length--) {
$str .= $set[mt_rand(0, $len - 1)];
}
return $str;
}
}
?>
|
Java
|
<?php
/*
* Copyright 2018 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.
*/
namespace Apigee\Edge\Api\Monetization\Controller;
use Apigee\Edge\Api\Monetization\Entity\BalanceInterface;
use Apigee\Edge\Api\Monetization\Entity\PrepaidBalanceInterface;
use Apigee\Edge\Controller\EntityControllerInterface;
interface PrepaidBalanceControllerInterface extends EntityControllerInterface, PaginatedEntityListingControllerInterface
{
/**
* @param string $currencyCode
*
* @return \Apigee\Edge\Api\Monetization\Entity\BalanceInterface|null
*/
public function getByCurrency(string $currencyCode): ?BalanceInterface;
/**
* @param float $amount
* @param string $currencyCode
*
* @return \Apigee\Edge\Api\Monetization\Entity\BalanceInterface
*/
public function topUpBalance(float $amount, string $currencyCode): BalanceInterface;
/**
* Enables and modifies recurring payment settings.
*
* @param string $currencyCode
* @param string $paymentProviderId
* @param float $replenishAmount
* @param float $recurringAmount
*
* @return \Apigee\Edge\Api\Monetization\Entity\BalanceInterface
*/
public function setupRecurringPayments(string $currencyCode, string $paymentProviderId, float $replenishAmount, float $recurringAmount): BalanceInterface;
/**
* Deactivate recurring payments.
*
* @param string $currencyCode
* @param string $paymentProviderId
*
* @return \Apigee\Edge\Api\Monetization\Entity\BalanceInterface
*/
public function disableRecurringPayments(string $currencyCode, string $paymentProviderId): BalanceInterface;
/**
* Gets prepaid balances.
*
* @param \DateTimeImmutable $billingMonth
*
* @return \Apigee\Edge\Api\Monetization\Entity\PrepaidBalanceInterface[]
*/
public function getPrepaidBalance(\DateTimeImmutable $billingMonth): array;
/**
* Gets prepaid balance by currency.
*
* @param string $currencyCode
* @param \DateTimeImmutable $billingMonth
*
* @return \Apigee\Edge\Api\Monetization\Entity\PrepaidBalanceInterface|null
*/
public function getPrepaidBalanceByCurrency(string $currencyCode, \DateTimeImmutable $billingMonth): ?PrepaidBalanceInterface;
}
|
Java
|
using System;
using System.Globalization;
using System.Resources;
using System.Diagnostics;
using System.Reflection;
namespace Routrek.SSHC
{
/// <summary>
/// StringResource ÌTvÌà¾Å·B
/// </summary>
internal class StringResources {
private string _resourceName;
private ResourceManager _resMan;
public StringResources(string name, Assembly asm) {
_resourceName = name;
LoadResourceManager(name, asm);
}
public string GetString(string id)
{
try
{
return _resMan.GetString(id); //൱êªx¢æ¤Èç±ÌNXÅLbV
ÅàÂê΢¢¾ë¤
}
catch
{
return "error loading string";
}
}
private void LoadResourceManager(string name, Assembly asm) {
//ÊÍpêEú{굩µÈ¢
CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentUICulture;
//if(ci.Name.StartsWith("ja"))
//_resMan = new ResourceManager(name+"_ja", asm);
//else
_resMan = new ResourceManager(name, asm);
}
}
}
|
Java
|
/*
* Copyright 2014 http://Bither.net
*
* 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.bither.util;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import net.bither.BitherApplication;
import net.bither.bitherj.utils.Utils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class FileUtil {
// old tickerName file
private static final String HUOBI_TICKER_NAME = "huobi.ticker";
private static final String BITSTAMP_TICKER_NAME = "bitstamp.ticker";
private static final String BTCE_TICKER_NAME = "btce.ticker";
private static final String OKCOIN_TICKER_NAME = "okcoin.ticker";
private static final String CHBTC_TICKER_NAME = "chbtc.ticker";
private static final String BTCCHINA_TICKER_NAME = "btcchina.ticker";
private static final String BITHER_BACKUP_SDCARD_DIR = "BitherBackup";
private static final String BITHER_BACKUP_ROM_DIR = "backup";
private static final String BITHER_BACKUP_HOT_FILE_NAME = "keys";
private static final String EXCAHNGE_TICKER_NAME = "exchange.ticker";
private static final String EXCHANGE_KLINE_NAME = "exchange.kline";
private static final String EXCHANGE_DEPTH_NAME = "exchange.depth";
private static final String PRICE_ALERT = "price.alert";
private static final String EXCHANGERATE = "exchangerate";
private static final String CURRENCIES_RATE = "currencies_rate";
private static final String MARKET_CAHER = "mark";
private static final String IMAGE_CACHE_DIR = "image";
private static final String IMAGE_SHARE_FILE_NAME = "share.jpg";
private static final String IMAGE_CACHE_UPLOAD = IMAGE_CACHE_DIR + "/upload";
private static final String IMAGE_CACHE_612 = IMAGE_CACHE_DIR + "/612";
private static final String IMAGE_CACHE_150 = IMAGE_CACHE_DIR + "/150";
private static final String AD_CACHE = "ad";
private static final String AD_NAME = "ad.json";
private static final String AD_IMAGE_EN_CACHE = AD_CACHE + "/img_en";
private static final String AD_IMAGE_ZH_CN_CACHE = AD_CACHE + "/img_zh_CN";
private static final String AD_IMAGE_ZH_TW_CACHE = AD_CACHE + "/img_zh_TW";
/**
* sdCard exist
*/
public static boolean existSdCardMounted() {
String storageState = android.os.Environment.getExternalStorageState();
if (Utils.isEmpty(storageState)) {
return false;
}
return Utils.compareString(storageState,
android.os.Environment.MEDIA_MOUNTED);
}
public static File getSDPath() {
File sdDir = Environment.getExternalStorageDirectory();
return sdDir;
}
public static File getBackupSdCardDir() {
File backupDir = new File(getSDPath(), BITHER_BACKUP_SDCARD_DIR);
if (!backupDir.exists()) {
backupDir.mkdirs();
}
return backupDir;
}
public static File getBackupFileOfCold() {
File file = new File(getBackupSdCardDir(),
DateTimeUtil.getNameForFile(System.currentTimeMillis())
+ ".bak"
);
return file;
}
public static List<File> getBackupFileListOfCold() {
File dir = getBackupSdCardDir();
List<File> fileList = new ArrayList<File>();
File[] files = dir.listFiles();
if (files != null && files.length > 0) {
files = orderByDateDesc(files);
for (File file : files) {
if (StringUtil.checkBackupFileOfCold(file.getName())) {
fileList.add(file);
}
}
}
return fileList;
}
private static File getBackupRomDir() {
File backupDir = new File(Utils.getWalletRomCache(), BITHER_BACKUP_ROM_DIR);
if (!backupDir.exists()) {
backupDir.mkdirs();
}
return backupDir;
}
public static File getBackupKeyOfHot() {
File backupDir = getBackupRomDir();
return new File(backupDir, BITHER_BACKUP_HOT_FILE_NAME);
}
public static File getDiskDir(String dirName, Boolean createNomedia) {
File dir = getDiskCacheDir(BitherApplication.mContext, dirName);
if (!dir.exists()) {
dir.mkdirs();
if (createNomedia) {
try {
File noMediaFile = new File(dir, ".nomedia");
noMediaFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return dir;
}
public static Uri saveShareImage(Bitmap bmp) {
File dir = getDiskDir(IMAGE_CACHE_DIR, true);
File jpg = new File(dir, IMAGE_SHARE_FILE_NAME);
NativeUtil.compressBitmap(bmp, 85, jpg.getAbsolutePath(), true);
return Uri.fromFile(jpg);
}
public static File getExternalCacheDir(Context context) {
// if (SdkUtils.hasFroyo()) {
//
// return context.getCacheDir();
// }
// Before Froyo we need to construct the external cache dir ourselves
final String cacheDir = "/Android/data/" + context.getPackageName()
+ "/cache/";
return new File(Environment.getExternalStorageDirectory().getPath()
+ cacheDir);
}
public static File getDiskCacheDir(Context context, String uniqueName) {
File extCacheDir = getExternalCacheDir(context);
final String cachePath = (Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState()) || !isExternalStorageRemovable())
&& extCacheDir != null ? extCacheDir.getPath() : context
.getCacheDir().getPath();
return new File(cachePath + File.separator + uniqueName);
}
@TargetApi(9)
public static boolean isExternalStorageRemovable() {
if (SdkUtils.hasGingerbread()) {
return Environment.isExternalStorageRemovable();
}
return true;
}
private static File getMarketCache() {
return getDiskDir(MARKET_CAHER, false);
}
public static File getAdImageEnDir() {
return getDiskDir(AD_IMAGE_EN_CACHE, true);
}
public static File getAdImagZhCnDir() {
return getDiskDir(AD_IMAGE_ZH_CN_CACHE, true);
}
public static File getAdImagZhTwDir() {
return getDiskDir(AD_IMAGE_ZH_TW_CACHE, true);
}
private static File getAdDir() {
return getDiskDir(AD_CACHE, false);
}
public static File getUploadImageDir() {
return getDiskDir(IMAGE_CACHE_UPLOAD, true);
}
public static File getAvatarDir() {
return getDiskDir(IMAGE_CACHE_612, true);
}
public static File getSmallAvatarDir() {
return getDiskDir(IMAGE_CACHE_150, true);
}
public static File getExchangeRateFile() {
File file = getDiskDir("", false);
return new File(file, EXCHANGERATE);
}
public static File getCurrenciesRateFile() {
File file = getDiskDir("", false);
return new File(file, CURRENCIES_RATE);
}
public static File getTickerFile() {
File file = getMarketCache();
file = new File(file, EXCAHNGE_TICKER_NAME);
return file;
}
public static File getPriceAlertFile() {
File marketDir = getMarketCache();
return new File(marketDir, PRICE_ALERT);
}
public static File getKlineFile() {
File file = getMarketCache();
file = new File(file, EXCHANGE_KLINE_NAME);
return file;
}
public static File getDepthFile() {
File file = getMarketCache();
file = new File(file, EXCHANGE_DEPTH_NAME);
return file;
}
public static File getAdFile() {
File file = getAdDir();
file = new File(file, AD_NAME);
return file;
}
@SuppressWarnings("resource")
public static Object deserialize(File file) {
FileInputStream fos = null;
try {
if (!file.exists()) {
return null;
}
fos = new FileInputStream(file);
ObjectInputStream ois;
ois = new ObjectInputStream(fos);
Object object = ois.readObject();
return object;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void serializeObject(File file, Object object) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(object);
oos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static File[] orderByDateDesc(File[] fs) {
Arrays.sort(fs, new Comparator<File>() {
public int compare(File f1, File f2) {
long diff = f1.lastModified() - f2.lastModified();
if (diff > 0) {
return -1;//-1 f1 before f2
} else if (diff == 0) {
return 0;
} else {
return 1;
}
}
public boolean equals(Object obj) {
return true;
}
});
return fs;
}
public static void copyFile(File src, File tar) throws Exception {
if (src.isFile()) {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
InputStream is = new FileInputStream(src);
bis = new BufferedInputStream(is);
OutputStream op = new FileOutputStream(tar);
bos = new BufferedOutputStream(op);
byte[] bt = new byte[8192];
int len = bis.read(bt);
while (len != -1) {
bos.write(bt, 0, len);
len = bis.read(bt);
}
bis.close();
bos.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
}
} else if (src.isDirectory()) {
File[] files = src.listFiles();
tar.mkdir();
for (int i = 0;
i < files.length;
i++) {
copyFile(files[i].getAbsoluteFile(),
new File(tar.getAbsoluteFile() + File.separator
+ files[i].getName())
);
}
} else {
throw new FileNotFoundException();
}
}
public static void delFolder(String folderPath) {
try {
delAllFile(folderPath);
String filePath = folderPath;
filePath = filePath.toString();
java.io.File myFilePath = new java.io.File(filePath);
myFilePath.delete();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void delAllFile(String path) {
File file = new File(path);
if (!file.exists()) {
return;
}
if (!file.isDirectory()) {
return;
}
String[] tempList = file.list();
if (tempList == null) {
return;
}
File temp = null;
for (int i = 0;
i < tempList.length;
i++) {
if (path.endsWith(File.separator)) {
temp = new File(path + tempList[i]);
} else {
temp = new File(path + File.separator + tempList[i]);
}
if (temp.isFile()) {
temp.delete();
}
if (temp.isDirectory()) {
delAllFile(path + "/" + tempList[i]);
delFolder(path + "/" + tempList[i]);
}
}
}
public static void upgradeTickerFile() {
File marketDir = getMarketCache();
File file = new File(marketDir, BITSTAMP_TICKER_NAME);
fileExistAndDelete(file);
file = new File(marketDir, BTCE_TICKER_NAME);
fileExistAndDelete(file);
file = new File(marketDir, HUOBI_TICKER_NAME);
fileExistAndDelete(file);
file = new File(marketDir, OKCOIN_TICKER_NAME);
fileExistAndDelete(file);
file = new File(marketDir, CHBTC_TICKER_NAME);
fileExistAndDelete(file);
file = new File(marketDir, BTCCHINA_TICKER_NAME);
fileExistAndDelete(file);
}
public static boolean fileExistAndDelete(File file) {
return file.exists() && file.delete();
}
public static File convertUriToFile(Activity activity, Uri uri) {
File file = null;
try {
String[] proj = {MediaStore.Images.Media.DATA};
@SuppressWarnings("deprecation")
Cursor actualimagecursor = activity.managedQuery(uri, proj, null,
null, null);
if (actualimagecursor != null) {
int actual_image_column_index = actualimagecursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
actualimagecursor.moveToFirst();
String img_path = actualimagecursor
.getString(actual_image_column_index);
if (!Utils.isEmpty(img_path)) {
file = new File(img_path);
}
} else {
file = new File(new URI(uri.toString()));
if (file.exists()) {
return file;
}
}
} catch (Exception e) {
}
return file;
}
public static int getOrientationOfFile(String fileName) {
int orientation = 0;
try {
ExifInterface exif = new ExifInterface(fileName);
String orientationString = exif
.getAttribute(ExifInterface.TAG_ORIENTATION);
if (Utils.isNubmer(orientationString)) {
int orc = Integer.valueOf(orientationString);
switch (orc) {
case ExifInterface.ORIENTATION_ROTATE_90:
orientation = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
orientation = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
orientation = 270;
break;
default:
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return orientation;
}
}
|
Java
|
# Internet Exchange
An Internet exchange point, also known as IX or IXP, is an infrastructure
through which autonomous systems exchange traffic. An IX can be a single local
LAN or it can be spread across multiple locations.
## In Peering Manager
Inside Peering Manager, you create an Internet exchange to then create one or
more peering BGP sessions. Only Internet Exchange Peering Sessions can be
related to an Internet exchange. For each Internet exchange you create,
the following properties can be configured (n.b. some are optional):
* `Name`: human-readable name attached to the IX.
* `Slug`: unique configuration and URL friendly name; usually it is
automatically generated from the IXP's name.
* `Local Autonomous System`: your autonomous system connected to this IX.
* `Comments`: text to explain what the Internet exchange is for. Can use
Markdown formatting.
* `Check BGP Session States`: whether Peering Manager should poll the state
of BGP sessions at this IX.
* `Import Routing Policies`: a list of routing policies to apply when
receiving prefixes though BGP sessions at this IX.
* `Export Routing Policies`: a list of routing policies to apply when
advertising prefixes though BGP sessions at this IX.
* `PeeringDB ID`: an integer which is the ID of the IX LAN inside PeeringDB.
This setting is required for Peering Manager to discover potential
unconfigured BGP sessions.[^1]
* `IPv6 Address`: an IPv6 address used to connect to the Internet exchange
network. [^2]
* `IPv4 Address`: an IPv4 address used to connect to the Internet exchange
network. [^2]
* `Router`: a router connected to the Internet exchange. This is used to then
generate and install configurations.[^2]
* `Tags`: a list of tags to help identifying and searching for a group.
Please note that an Internet exchange is a kind of BGP group with more specific
properties aimed to match the purpose of an Internet exchange network. However
while a group can be configured on more than one router, an IX can only be
attached to a single router. This means that if you are connected more than
once to an IX, you'll have to create one IX object per connection.
[^1]: This is no longer user edible
[^2]: This moved to the [Connection](../../net/connection/) tab
|
Java
|
# Peperomia crinigera Trel. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
Java
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace pool
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
|
Java
|
package io.react2.scalata.exporters
import com.mongodb.{WriteConcern, BulkWriteOperation, BasicDBObject, MongoClient}
import io.react2.scalata.Context
import io.react2.scalata.plugins.Plugin
import scala.util.control.NonFatal
/**
* @author dbalduini
*/
class MongoExporter(val args: Plugin.Args) extends Exporter {
val verbose = args("verbose", false)
val database = args("database", "test")
val collection = args("collection", "scalata")
val host = args("host", "localhost")
val port = args("port", 27017)
val mongo = new MongoClient(host, port)
val db = mongo.getDB(database)
val coll = db.getCollection(collection)
var maybeBulk: Option[BulkWriteOperation] = None
@transient var counter = 0
val total = Context.NUMBER_OF_LINES.get
override def export(f: Any): Unit = {
val doc = f.asInstanceOf[BasicDBObject]
try {
if(verbose)
println(doc.toString)
val bulk = maybeBulk match {
case None =>
maybeBulk = Some(coll.initializeUnorderedBulkOperation)
maybeBulk.get
case Some(b) => b
}
bulk.insert(doc)
counter = counter + 1
flush()
} catch {
case NonFatal(t) =>
t.printStackTrace()
}
}
private def flush(): Unit = {
val percentage = (counter.toFloat * 100) / total
if (percentage != 0 && percentage % 10 == 0) {
println(s"Current percentage processed: $counter / $total / $percentage%")
maybeBulk match {
case Some(bulk) =>
val wc = new WriteConcern(0)
bulk.execute(wc)
maybeBulk = None
case None =>
}
}
}
}
|
Java
|
package org.cobbzilla.util.jdbc;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DbUrlUtil {
public static final Pattern JDBC_URL_REGEX = Pattern.compile("^jdbc:postgresql://[\\.\\w]+:\\d+/(.+)$");
public static String setDbName(String url, String dbName) {
final Matcher matcher = JDBC_URL_REGEX.matcher(url);
if (!matcher.find()) return url;
final String renamed = matcher.replaceFirst(dbName);
return renamed;
}
}
|
Java
|
/*
Copyright (C) 2014 by Project Tox <https://tox.im>
This file is part of qTox, a Qt-based graphical interface for Tox.
This program is libre software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the COPYING file for more details.
*/
#ifndef GROUPCHATFORM_H
#define GROUPCHATFORM_H
#include <QLabel>
#include <QWidget>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QGridLayout>
#include <QTextEdit>
#include <QScrollArea>
#include <QTime>
#include "widget/tool/chattextedit.h"
#include "ui_widget.h"
// Spacing in px inserted when the author of the last message changes
#define AUTHOR_CHANGE_SPACING 5
class Group;
class GroupChatForm : public QObject
{
Q_OBJECT
public:
GroupChatForm(Group* chatGroup);
~GroupChatForm();
void show(Ui::Widget& ui);
void setName(QString newName);
void addGroupMessage(QString message, int peerId);
void addMessage(QString author, QString message, QString date=QTime::currentTime().toString("hh:mm"));
void addMessage(QLabel* author, QLabel* message, QLabel* date);
void onUserListChanged();
signals:
void sendMessage(int, QString);
private slots:
void onSendTriggered();
void onSliderRangeChanged();
void onChatContextMenuRequested(QPoint pos);
void onSaveLogClicked();
private:
Group* group;
QHBoxLayout *headLayout, *mainFootLayout;
QVBoxLayout *headTextLayout, *mainLayout;
QGridLayout *mainChatLayout;
QLabel *avatar, *name, *nusers, *namesList;
ChatTextEdit *msgEdit;
QPushButton *sendButton;
QScrollArea *chatArea;
QWidget *main, *head, *chatAreaWidget;
QString previousName;
int curRow;
bool lockSliderToBottom;
};
#endif // GROUPCHATFORM_H
|
Java
|
'use strict';
var fs = require('fs');
var path = require('path');
var util = require('util');
var dbg = require('debug');
// process.env.TABTAB_DEBUG = process.env.TABTAB_DEBUG || '/tmp/tabtab.log';
var out = process.env.TABTAB_DEBUG ? fs.createWriteStream(process.env.TABTAB_DEBUG, { flags: 'a' }) : null;
module.exports = debug;
// Internal: Facade to debug module, which provides the exact same interface.
//
// The added benefit is with the TABTAB_DEBUG environment variable, which when
// defined, will write debug output to the specified filename.
//
// Usefull when debugging tab completion, as logs on stdout / stderr are either
// shallowed or used as tab completion results.
//
// namespace - The String namespace to use when TABTAB_DEBUG is not defined,
// delegates to debug module.
//
// Examples
//
// // Use with following command to redirect output to file
// // TABTAB_DEBUG="debug.log" tabtab ...
// debug('Foo');
function debug(namespace) {
var log = dbg(namespace);
return function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
args = args.map(function (arg) {
if (typeof arg === 'string') return arg;
return JSON.stringify(arg);
});
out && out.write(util.format.apply(util, args) + '\n');
out || log.apply(null, args);
};
}
|
Java
|
<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<title>PHPXRef 0.7.1 : Unnamed Project : Variable Reference: $_never_allowed_regex</title>
<link rel="stylesheet" href="../sample.css" type="text/css">
<link rel="stylesheet" href="../sample-print.css" type="text/css" media="print">
<style id="hilight" type="text/css"></style>
<meta http-equiv="content-type" content="text/html;charset=iso-8859-1">
</head>
<body bgcolor="#ffffff" text="#000000" link="#801800" vlink="#300540" alink="#ffffff">
<table class="pagetitle" width="100%">
<tr>
<td valign="top" class="pagetitle">
[ <a href="../index.html">Index</a> ]
</td>
<td align="right" class="pagetitle">
<h2 style="margin-bottom: 0px">PHP Cross Reference of Unnamed Project</h2>
</td>
</tr>
</table>
<!-- Generated by PHPXref 0.7.1 at Thu Oct 23 18:57:41 2014 -->
<!-- PHPXref (c) 2000-2010 Gareth Watts - gareth@omnipotent.net -->
<!-- http://phpxref.sourceforge.net/ -->
<script src="../phpxref.js" type="text/javascript"></script>
<script language="JavaScript" type="text/javascript">
<!--
ext='.html';
relbase='../';
subdir='_variables';
filename='index.html';
cookiekey='phpxref';
handleNavFrame(relbase, subdir, filename);
logVariable('_never_allowed_regex');
// -->
</script>
<script language="JavaScript" type="text/javascript">
if (gwGetCookie('xrefnav')=='off')
document.write('<p class="navlinks">[ <a href="javascript:navOn()">Show Explorer<\/a> ]<\/p>');
else
document.write('<p class="navlinks">[ <a href="javascript:navOff()">Hide Explorer<\/a> ]<\/p>');
</script>
<noscript>
<p class="navlinks">
[ <a href="../nav.html" target="_top">Show Explorer</a> ]
[ <a href="index.html" target="_top">Hide Navbar</a> ]
</p>
</noscript>
[<a href="../index.html">Top level directory</a>]<br>
<script language="JavaScript" type="text/javascript">
<!--
document.writeln('<table align="right" class="searchbox-link"><tr><td><a class="searchbox-link" href="javascript:void(0)" onMouseOver="showSearchBox()">Search</a><br>');
document.writeln('<table border="0" cellspacing="0" cellpadding="0" class="searchbox" id="searchbox">');
document.writeln('<tr><td class="searchbox-title">');
document.writeln('<a class="searchbox-title" href="javascript:showSearchPopup()">Search History +</a>');
document.writeln('<\/td><\/tr>');
document.writeln('<tr><td class="searchbox-body" id="searchbox-body">');
document.writeln('<form name="search" style="margin:0px; padding:0px" onSubmit=\'return jump()\'>');
document.writeln('<a class="searchbox-body" href="../_classes/index.html">Class<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="classname"><br>');
document.writeln('<a id="funcsearchlink" class="searchbox-body" href="../_functions/index.html">Function<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="funcname"><br>');
document.writeln('<a class="searchbox-body" href="../_variables/index.html">Variable<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="varname"><br>');
document.writeln('<a class="searchbox-body" href="../_constants/index.html">Constant<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="constname"><br>');
document.writeln('<a class="searchbox-body" href="../_tables/index.html">Table<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="tablename"><br>');
document.writeln('<input type="submit" class="searchbox-button" value="Search">');
document.writeln('<\/form>');
document.writeln('<\/td><\/tr><\/table>');
document.writeln('<\/td><\/tr><\/table>');
// -->
</script>
<div id="search-popup" class="searchpopup"><p id="searchpopup-title" class="searchpopup-title">title</p><div id="searchpopup-body" class="searchpopup-body">Body</div><p class="searchpopup-close"><a href="javascript:gwCloseActive()">[close]</a></p></div>
<h3>Variable Cross Reference</h3>
<h2><a href="index.html#_never_allowed_regex">$_never_allowed_regex</a></h2>
<b>Defined at:</b><ul>
<li><a href="../bonfire/codeigniter/core/Security.php.html">/bonfire/codeigniter/core/Security.php</A> -> <a href="../bonfire/codeigniter/core/Security.php.source.html#l91"> line 91</A></li>
</ul>
<br><b>Referenced 2 times:</b><ul>
<li><a href="../bonfire/codeigniter/core/Security.php.html">/bonfire/codeigniter/core/Security.php</a> -> <a href="../bonfire/codeigniter/core/Security.php.source.html#l91"> line 91</a></li>
<li><a href="../bonfire/codeigniter/core/Security.php.html">/bonfire/codeigniter/core/Security.php</a> -> <a href="../bonfire/codeigniter/core/Security.php.source.html#l837"> line 837</a></li>
</ul>
<!-- A link to the phpxref site in your customized footer file is appreciated ;-) -->
<br><hr>
<table width="100%">
<tr><td>Generated: Thu Oct 23 18:57:41 2014</td>
<td align="right"><i>Cross-referenced by <a href="http://phpxref.sourceforge.net/">PHPXref 0.7.1</a></i></td>
</tr>
</table>
</body></html>
|
Java
|
<?php
/**
* This is the model class for table "product_type".
*
* The followings are the available columns in table 'product_type':
* @property string $product_type_id
* @property string $parent_product_type_id
* @property string $name
* @property string $created
*
* The followings are the available model relations:
* @property Product[] $products
* @property ProductMultiDay[] $productMultiDays
* @property ProductOneDay[] $productOneDays
*/
class ProductType extends CActiveRecord
{
/**
* Returns the static model of the specified AR class.
* @param string $className active record class name.
* @return ProductType the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
/**
* @return string the associated database table name
*/
public function tableName()
{
return 'product_type';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('parent_product_type_id', 'length', 'max'=>10),
);
}
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array();
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'product_type_id' => 'Product Type',
'parent_product_type_id' => 'Parent Product Type',
'name' => 'Name',
'created' => 'Created',
);
}
}
|
Java
|
=begin
Copyright 2012-2013 inBloom, Inc. and its affiliates.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=end
require_relative '../lib/Shared/data_utility.rb'
require_relative '../lib/Shared/EntityClasses/enum/GradeLevelType.rb'
require_relative 'spec_helper'
# specifications for data utility
describe "DataUtility" do
before(:all) do
@yaml = YAML.load_file(File.join(File.dirname(__FILE__),'../config.yml'))
@prng = Random.new(@yaml['seed'])
end
after(:all) do
@yaml = nil
@prng = nil
end
describe "Generates correct _id for each supported entity" do
describe "#get_staff_unique_state_id" do
it "will generate a staff unique state id with the correct format" do
DataUtility.get_staff_unique_state_id(146724).should match("stff-0000146724")
end
end
describe "#get_teacher_unique_state_id" do
it "will generate a teacher unique state id with the correct format" do
DataUtility.get_teacher_unique_state_id(146724).should match("tech-0000146724")
end
end
end
describe "Handles requests for entities correctly" do
describe "--> request to get staff unique state id with string" do
it "will return the string that was input" do
DataUtility.get_staff_unique_state_id("rrogers").should match("rrogers")
end
end
describe "--> request to get staff unique state id with integer" do
it "will return the corresponding staff unique state id" do
DataUtility.get_staff_unique_state_id(17).should match("stff-0000000017")
end
end
describe "--> request to get teacher unique state id with string" do
it "will return the string that was input" do
DataUtility.get_teacher_unique_state_id("cgray").should match("cgray")
end
end
describe "--> request to get teacher unique state id with integer" do
it "will return the corresponding teacher unique state id" do
DataUtility.get_teacher_unique_state_id(18).should match("tech-0000000018")
end
end
describe "--> request to get random elementary school grade" do
it "will always return only grades that are in elementary school" do
grades = [:KINDERGARTEN, :FIRST_GRADE, :SECOND_GRADE, :THIRD_GRADE, :FOURTH_GRADE, :FIFTH_GRADE]
(1..25).each do
grades.include?(DataUtility.get_random_grade_for_type(@prng, "elementary")).should be_true
end
end
end
describe "--> request to get random middle school grade" do
it "will always return only grades that are in middle school" do
grades = [:SIXTH_GRADE, :SEVENTH_GRADE, :EIGHTH_GRADE]
(1..25).each do
grades.include?(DataUtility.get_random_grade_for_type(@prng, "middle")).should be_true
end
end
end
describe "--> request to get random high school grade" do
it "will always return only grades that are in high school" do
grades = [:NINTH_GRADE, :TENTH_GRADE, :ELEVENTH_GRADE, :TWELFTH_GRADE]
(1..25).each do
grades.include?(DataUtility.get_random_grade_for_type(@prng, "high")).should be_true
end
end
end
describe "--> request to get subset of choices" do
it "will return a subset of choices with correct size" do
options = [1,2,3,4,5,6,7,8,9,10]
subset = DataUtility.select_num_from_options(@prng, 5, options)
subset.size.should eq 5
subset.each do |number|
options.include?(number).should be_true
end
end
it "will return choices if the number specified is larger than the size of choices" do
options = [1,2,3,4,5,6,7,8,9,10]
subset = DataUtility.select_num_from_options(@prng, 15, options)
subset.size.should eq 10
subset.should eq options
end
it "will return an empty array is the number specified is zero" do
options = [1,2,3,4,5,6,7,8,9,10]
subset = DataUtility.select_num_from_options(@prng, 0, options)
subset.size.should eq 0
end
end
end
end
|
Java
|
from changes.api.serializer import Crumbler, register
from changes.models.node import Cluster
@register(Cluster)
class ClusterCrumbler(Crumbler):
def crumble(self, instance, attrs):
return {
'id': instance.id.hex,
'name': instance.label,
'dateCreated': instance.date_created,
}
|
Java
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>20130925</title>
<style type="text/css">
.visiNone
{
display: none;
}
.hide
{
visibility: hidden;
}
.block
{
display: block;
}
.list
{
display: list-item;
}
a:link, a:visited
{
background: #efb57c;
border: 2px outset #efb57c;
}
a
{
display: block;
width: 150px;
height: 20px;
margin-top: 10px;
text-align: center;
}
a:focus, a:hover
{
background: #daa670;
border: 2px outset #daa670;
color: black;
}
a:active
{
background: #bb8e6d;
border: 2px outset #bb8e6d;
}
.miniPhoto: hover .bigPhoto
{
display: none;
}
#popImg a, img
{
border: none;
}
#popImg a img.bigPhoto
{
height: 0;
width: 0;
border-width: 0;
}
#popImg a:hover img.bigPhoto
{
position: absolute;
top: 1000px;
left: 160px;
height: 458px;
width: 500px;
}
</style>
</head>
<body>
<h1>20130925</h1>
<p>Show a series of dynamic effect of link & image.</p>
<p class="visiNone">
<img src="../images/Prime.jpg" alt="first image" />
</p>
<p class="hide">
<img src="../images/Prime.jpg" alt="second image" />
</p>
<p class="block">
<img src="../images/Prime.jpg" alt="third image" />
</p>
<p class="list">
<img src="../images/Prime_preview.jpg" alt="small image 1" />
<img src="../images/Prime_preview.jpg" alt="small image 2" />
<img src="../images/Prime_preview.jpg" alt="small image 3" />
</p>
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
<a href="#">Link 4</a>
<div id="popImg">
<a class="checkImg" href="#">
<img class="smallPhoto" src="../images/Prime_preview.jpg" alt="mini image" />
<img class="bigPhoto" src="../images/Prime.jpg" alt="big image" />
</a>
</div>
</div>
</body>
</html>
|
Java
|
# Erodium choulettianum Coss. ex Batt. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
Java
|
/**
* 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.ozone.ozShell;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.stream.Collectors;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.hdds.cli.MissingSubcommandException;
import org.apache.hadoop.hdds.client.ReplicationFactor;
import org.apache.hadoop.hdds.conf.OzoneConfiguration;
import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
import org.apache.hadoop.hdfs.DFSUtil;
import org.apache.hadoop.ozone.MiniOzoneCluster;
import org.apache.hadoop.ozone.OzoneAcl;
import org.apache.hadoop.ozone.OzoneAcl.OzoneACLRights;
import org.apache.hadoop.ozone.OzoneAcl.OzoneACLType;
import org.apache.hadoop.ozone.OzoneConsts;
import org.apache.hadoop.ozone.client.OzoneBucket;
import org.apache.hadoop.ozone.client.OzoneKey;
import org.apache.hadoop.ozone.client.OzoneVolume;
import org.apache.hadoop.ozone.client.VolumeArgs;
import org.apache.hadoop.ozone.client.io.OzoneOutputStream;
import org.apache.hadoop.ozone.client.protocol.ClientProtocol;
import org.apache.hadoop.ozone.client.rest.OzoneException;
import org.apache.hadoop.ozone.client.rest.RestClient;
import org.apache.hadoop.ozone.client.rpc.RpcClient;
import org.apache.hadoop.ozone.om.helpers.ServiceInfo;
import org.apache.hadoop.ozone.web.ozShell.Shell;
import org.apache.hadoop.ozone.web.request.OzoneQuota;
import org.apache.hadoop.ozone.web.response.BucketInfo;
import org.apache.hadoop.ozone.web.response.KeyInfo;
import org.apache.hadoop.ozone.web.response.VolumeInfo;
import org.apache.hadoop.ozone.web.utils.JsonUtils;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.test.GenericTestUtils;
import com.google.common.base.Strings;
import org.apache.commons.lang3.RandomStringUtils;
import static org.apache.hadoop.ozone.OzoneConfigKeys.OZONE_REPLICATION;
import static org.apache.hadoop.ozone.om.OMConfigKeys.OZONE_OM_ADDRESS_KEY;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import picocli.CommandLine;
import picocli.CommandLine.ExecutionException;
import picocli.CommandLine.IExceptionHandler2;
import picocli.CommandLine.ParameterException;
import picocli.CommandLine.ParseResult;
import picocli.CommandLine.RunLast;
/**
* This test class specified for testing Ozone shell command.
*/
@RunWith(value = Parameterized.class)
public class TestOzoneShell {
private static final Logger LOG =
LoggerFactory.getLogger(TestOzoneShell.class);
/**
* Set the timeout for every test.
*/
@Rule
public Timeout testTimeout = new Timeout(300000);
private static String url;
private static File baseDir;
private static OzoneConfiguration conf = null;
private static MiniOzoneCluster cluster = null;
private static ClientProtocol client = null;
private static Shell shell = null;
private final ByteArrayOutputStream out = new ByteArrayOutputStream();
private final ByteArrayOutputStream err = new ByteArrayOutputStream();
private static final PrintStream OLD_OUT = System.out;
private static final PrintStream OLD_ERR = System.err;
@Parameterized.Parameters
public static Collection<Object[]> clientProtocol() {
Object[][] params = new Object[][] {
{RpcClient.class},
{RestClient.class}};
return Arrays.asList(params);
}
@Parameterized.Parameter
public Class clientProtocol;
/**
* Create a MiniDFSCluster for testing with using distributed Ozone
* handler type.
*
* @throws Exception
*/
@BeforeClass
public static void init() throws Exception {
conf = new OzoneConfiguration();
String path = GenericTestUtils.getTempPath(
TestOzoneShell.class.getSimpleName());
baseDir = new File(path);
baseDir.mkdirs();
shell = new Shell();
cluster = MiniOzoneCluster.newBuilder(conf)
.setNumDatanodes(3)
.build();
conf.setInt(OZONE_REPLICATION, ReplicationFactor.THREE.getValue());
conf.setQuietMode(false);
client = new RpcClient(conf);
cluster.waitForClusterToBeReady();
}
/**
* shutdown MiniDFSCluster.
*/
@AfterClass
public static void shutdown() {
if (cluster != null) {
cluster.shutdown();
}
if (baseDir != null) {
FileUtil.fullyDelete(baseDir, true);
}
}
@Before
public void setup() {
System.setOut(new PrintStream(out));
System.setErr(new PrintStream(err));
if(clientProtocol.equals(RestClient.class)) {
String hostName = cluster.getOzoneManager().getHttpServer()
.getHttpAddress().getHostName();
int port = cluster
.getOzoneManager().getHttpServer().getHttpAddress().getPort();
url = String.format("http://" + hostName + ":" + port);
} else {
List<ServiceInfo> services = null;
try {
services = cluster.getOzoneManager().getServiceList();
} catch (IOException e) {
LOG.error("Could not get service list from OM");
}
String hostName = services.stream().filter(
a -> a.getNodeType().equals(HddsProtos.NodeType.OM))
.collect(Collectors.toList()).get(0).getHostname();
String port = cluster.getOzoneManager().getRpcPort();
url = String.format("o3://" + hostName + ":" + port);
}
}
@After
public void reset() {
// reset stream after each unit test
out.reset();
err.reset();
// restore system streams
System.setOut(OLD_OUT);
System.setErr(OLD_ERR);
}
@Test
public void testCreateVolume() throws Exception {
LOG.info("Running testCreateVolume");
String volumeName = "volume" + RandomStringUtils.randomNumeric(5);
testCreateVolume(volumeName, "");
volumeName = "volume" + RandomStringUtils.randomNumeric(5);
testCreateVolume("/////" + volumeName, "");
testCreateVolume("/////", "Volume name is required");
testCreateVolume("/////vol/123",
"Invalid volume name. Delimiters (/) not allowed in volume name");
}
private void testCreateVolume(String volumeName, String errorMsg)
throws Exception {
err.reset();
String userName = "bilbo";
String[] args = new String[] {"volume", "create", url + "/" + volumeName,
"--user", userName, "--root"};
if (Strings.isNullOrEmpty(errorMsg)) {
execute(shell, args);
} else {
executeWithError(shell, args, errorMsg);
return;
}
String truncatedVolumeName =
volumeName.substring(volumeName.lastIndexOf('/') + 1);
OzoneVolume volumeInfo = client.getVolumeDetails(truncatedVolumeName);
assertEquals(truncatedVolumeName, volumeInfo.getName());
assertEquals(userName, volumeInfo.getOwner());
}
private void execute(Shell ozoneShell, String[] args) {
List<String> arguments = new ArrayList(Arrays.asList(args));
LOG.info("Executing shell command with args {}", arguments);
CommandLine cmd = ozoneShell.getCmd();
IExceptionHandler2<List<Object>> exceptionHandler =
new IExceptionHandler2<List<Object>>() {
@Override
public List<Object> handleParseException(ParameterException ex,
String[] args) {
throw ex;
}
@Override
public List<Object> handleExecutionException(ExecutionException ex,
ParseResult parseResult) {
throw ex;
}
};
cmd.parseWithHandlers(new RunLast(),
exceptionHandler, args);
}
/**
* Test to create volume without specifying --user or -u.
* @throws Exception
*/
@Test
public void testCreateVolumeWithoutUser() throws Exception {
String volumeName = "volume" + RandomStringUtils.randomNumeric(1);
String[] args = new String[] {"volume", "create", url + "/" + volumeName,
"--root"};
execute(shell, args);
String truncatedVolumeName =
volumeName.substring(volumeName.lastIndexOf('/') + 1);
OzoneVolume volumeInfo = client.getVolumeDetails(truncatedVolumeName);
assertEquals(truncatedVolumeName, volumeInfo.getName());
assertEquals(UserGroupInformation.getCurrentUser().getUserName(),
volumeInfo.getOwner());
}
@Test
public void testDeleteVolume() throws Exception {
LOG.info("Running testDeleteVolume");
String volumeName = "volume" + RandomStringUtils.randomNumeric(5);
VolumeArgs volumeArgs = VolumeArgs.newBuilder()
.setOwner("bilbo")
.setQuota("100TB")
.build();
client.createVolume(volumeName, volumeArgs);
OzoneVolume volume = client.getVolumeDetails(volumeName);
assertNotNull(volume);
String[] args = new String[] {"volume", "delete", url + "/" + volumeName};
execute(shell, args);
String output = out.toString();
assertTrue(output.contains("Volume " + volumeName + " is deleted"));
// verify if volume has been deleted
try {
client.getVolumeDetails(volumeName);
fail("Get volume call should have thrown.");
} catch (IOException e) {
GenericTestUtils.assertExceptionContains(
"Info Volume failed, error:VOLUME_NOT_FOUND", e);
}
volumeName = "volume" + RandomStringUtils.randomNumeric(5);
volumeArgs = VolumeArgs.newBuilder()
.setOwner("bilbo")
.setQuota("100TB")
.build();
client.createVolume(volumeName, volumeArgs);
volume = client.getVolumeDetails(volumeName);
assertNotNull(volume);
//volumeName prefixed with /
String volumeNameWithSlashPrefix = "/" + volumeName;
args = new String[] {"volume", "delete",
url + "/" + volumeNameWithSlashPrefix};
execute(shell, args);
output = out.toString();
assertTrue(output.contains("Volume " + volumeName + " is deleted"));
// verify if volume has been deleted
try {
client.getVolumeDetails(volumeName);
fail("Get volume call should have thrown.");
} catch (IOException e) {
GenericTestUtils.assertExceptionContains(
"Info Volume failed, error:VOLUME_NOT_FOUND", e);
}
}
@Test
public void testInfoVolume() throws Exception {
LOG.info("Running testInfoVolume");
String volumeName = "volume" + RandomStringUtils.randomNumeric(5);
VolumeArgs volumeArgs = VolumeArgs.newBuilder()
.setOwner("bilbo")
.setQuota("100TB")
.build();
client.createVolume(volumeName, volumeArgs);
//volumeName supplied as-is
String[] args = new String[] {"volume", "info", url + "/" + volumeName};
execute(shell, args);
String output = out.toString();
assertTrue(output.contains(volumeName));
assertTrue(output.contains("createdOn")
&& output.contains(OzoneConsts.OZONE_TIME_ZONE));
//volumeName prefixed with /
String volumeNameWithSlashPrefix = "/" + volumeName;
args = new String[] {"volume", "info",
url + "/" + volumeNameWithSlashPrefix};
execute(shell, args);
output = out.toString();
assertTrue(output.contains(volumeName));
assertTrue(output.contains("createdOn")
&& output.contains(OzoneConsts.OZONE_TIME_ZONE));
// test infoVolume with invalid volume name
args = new String[] {"volume", "info",
url + "/" + volumeName + "/invalid-name"};
executeWithError(shell, args, "Invalid volume name. " +
"Delimiters (/) not allowed in volume name");
// get info for non-exist volume
args = new String[] {"volume", "info", url + "/invalid-volume"};
executeWithError(shell, args, "VOLUME_NOT_FOUND");
}
@Test
public void testShellIncompleteCommand() throws Exception {
LOG.info("Running testShellIncompleteCommand");
String expectedError = "Incomplete command";
String[] args = new String[] {}; //executing 'ozone sh'
executeWithError(shell, args, expectedError,
"Usage: ozone sh [-hV] [--verbose] [-D=<String=String>]..." +
" [COMMAND]");
args = new String[] {"volume"}; //executing 'ozone sh volume'
executeWithError(shell, args, expectedError,
"Usage: ozone sh volume [-hV] [COMMAND]");
args = new String[] {"bucket"}; //executing 'ozone sh bucket'
executeWithError(shell, args, expectedError,
"Usage: ozone sh bucket [-hV] [COMMAND]");
args = new String[] {"key"}; //executing 'ozone sh key'
executeWithError(shell, args, expectedError,
"Usage: ozone sh key [-hV] [COMMAND]");
}
@Test
public void testUpdateVolume() throws Exception {
LOG.info("Running testUpdateVolume");
String volumeName = "volume" + RandomStringUtils.randomNumeric(5);
String userName = "bilbo";
VolumeArgs volumeArgs = VolumeArgs.newBuilder()
.setOwner("bilbo")
.setQuota("100TB")
.build();
client.createVolume(volumeName, volumeArgs);
OzoneVolume vol = client.getVolumeDetails(volumeName);
assertEquals(userName, vol.getOwner());
assertEquals(OzoneQuota.parseQuota("100TB").sizeInBytes(), vol.getQuota());
String[] args = new String[] {"volume", "update", url + "/" + volumeName,
"--quota", "500MB"};
execute(shell, args);
vol = client.getVolumeDetails(volumeName);
assertEquals(userName, vol.getOwner());
assertEquals(OzoneQuota.parseQuota("500MB").sizeInBytes(), vol.getQuota());
String newUser = "new-user";
args = new String[] {"volume", "update", url + "/" + volumeName,
"--user", newUser};
execute(shell, args);
vol = client.getVolumeDetails(volumeName);
assertEquals(newUser, vol.getOwner());
//volume with / prefix
String volumeWithPrefix = "/" + volumeName;
String newUser2 = "new-user2";
args = new String[] {"volume", "update", url + "/" + volumeWithPrefix,
"--user", newUser2};
execute(shell, args);
vol = client.getVolumeDetails(volumeName);
assertEquals(newUser2, vol.getOwner());
// test error conditions
args = new String[] {"volume", "update", url + "/invalid-volume",
"--user", newUser};
executeWithError(shell, args, "Info Volume failed, error:VOLUME_NOT_FOUND");
err.reset();
args = new String[] {"volume", "update", url + "/invalid-volume",
"--quota", "500MB"};
executeWithError(shell, args, "Info Volume failed, error:VOLUME_NOT_FOUND");
}
/**
* Execute command, assert exeception message and returns true if error
* was thrown.
*/
private void executeWithError(Shell ozoneShell, String[] args,
String expectedError) {
if (Strings.isNullOrEmpty(expectedError)) {
execute(ozoneShell, args);
} else {
try {
execute(ozoneShell, args);
fail("Exception is expected from command execution " + Arrays
.asList(args));
} catch (Exception ex) {
if (!Strings.isNullOrEmpty(expectedError)) {
Throwable exceptionToCheck = ex;
if (exceptionToCheck.getCause() != null) {
exceptionToCheck = exceptionToCheck.getCause();
}
Assert.assertTrue(
String.format(
"Error of shell code doesn't contain the " +
"exception [%s] in [%s]",
expectedError, exceptionToCheck.getMessage()),
exceptionToCheck.getMessage().contains(expectedError));
}
}
}
}
/**
* Execute command, assert exception message and returns true if error
* was thrown and contains the specified usage string.
*/
private void executeWithError(Shell ozoneShell, String[] args,
String expectedError, String usage) {
if (Strings.isNullOrEmpty(expectedError)) {
execute(ozoneShell, args);
} else {
try {
execute(ozoneShell, args);
fail("Exception is expected from command execution " + Arrays
.asList(args));
} catch (Exception ex) {
if (!Strings.isNullOrEmpty(expectedError)) {
Throwable exceptionToCheck = ex;
if (exceptionToCheck.getCause() != null) {
exceptionToCheck = exceptionToCheck.getCause();
}
Assert.assertTrue(
String.format(
"Error of shell code doesn't contain the " +
"exception [%s] in [%s]",
expectedError, exceptionToCheck.getMessage()),
exceptionToCheck.getMessage().contains(expectedError));
Assert.assertTrue(
exceptionToCheck instanceof MissingSubcommandException);
Assert.assertTrue(
((MissingSubcommandException)exceptionToCheck)
.getUsage().contains(usage));
}
}
}
}
@Test
public void testListVolume() throws Exception {
LOG.info("Running testListVolume");
String protocol = clientProtocol.getName().toLowerCase();
String commandOutput, commandError;
List<VolumeInfo> volumes;
final int volCount = 20;
final String user1 = "test-user-a-" + protocol;
final String user2 = "test-user-b-" + protocol;
// Create 20 volumes, 10 for user1 and another 10 for user2.
for (int x = 0; x < volCount; x++) {
String volumeName;
String userName;
if (x % 2 == 0) {
// create volume [test-vol0, test-vol2, ..., test-vol18] for user1
userName = user1;
volumeName = "test-vol-" + protocol + x;
} else {
// create volume [test-vol1, test-vol3, ..., test-vol19] for user2
userName = user2;
volumeName = "test-vol-" + protocol + x;
}
VolumeArgs volumeArgs = VolumeArgs.newBuilder()
.setOwner(userName)
.setQuota("100TB")
.build();
client.createVolume(volumeName, volumeArgs);
OzoneVolume vol = client.getVolumeDetails(volumeName);
assertNotNull(vol);
}
String[] args = new String[] {"volume", "list", url + "/abcde", "--user",
user1, "--length", "100"};
executeWithError(shell, args, "Invalid URI");
err.reset();
// test -length option
args = new String[] {"volume", "list", url + "/", "--user",
user1, "--length", "100"};
execute(shell, args);
commandOutput = out.toString();
volumes = (List<VolumeInfo>) JsonUtils
.toJsonList(commandOutput, VolumeInfo.class);
assertEquals(10, volumes.size());
for (VolumeInfo volume : volumes) {
assertEquals(volume.getOwner().getName(), user1);
assertTrue(volume.getCreatedOn().contains(OzoneConsts.OZONE_TIME_ZONE));
}
out.reset();
args = new String[] {"volume", "list", url + "/", "--user",
user1, "--length", "2"};
execute(shell, args);
commandOutput = out.toString();
volumes = (List<VolumeInfo>) JsonUtils
.toJsonList(commandOutput, VolumeInfo.class);
assertEquals(2, volumes.size());
// test --prefix option
out.reset();
args =
new String[] {"volume", "list", url + "/", "--user", user1, "--length",
"100", "--prefix", "test-vol-" + protocol + "1"};
execute(shell, args);
commandOutput = out.toString();
volumes = (List<VolumeInfo>) JsonUtils
.toJsonList(commandOutput, VolumeInfo.class);
assertEquals(5, volumes.size());
// return volume names should be [test-vol10, test-vol12, ..., test-vol18]
for (int i = 0; i < volumes.size(); i++) {
assertEquals(volumes.get(i).getVolumeName(),
"test-vol-" + protocol + ((i + 5) * 2));
assertEquals(volumes.get(i).getOwner().getName(), user1);
}
// test -start option
out.reset();
args =
new String[] {"volume", "list", url + "/", "--user", user2, "--length",
"100", "--start", "test-vol-" + protocol + "15"};
execute(shell, args);
commandOutput = out.toString();
volumes = (List<VolumeInfo>) JsonUtils
.toJsonList(commandOutput, VolumeInfo.class);
assertEquals(2, volumes.size());
assertEquals(volumes.get(0).getVolumeName(), "test-vol-" + protocol + "17");
assertEquals(volumes.get(1).getVolumeName(), "test-vol-" + protocol + "19");
assertEquals(volumes.get(0).getOwner().getName(), user2);
assertEquals(volumes.get(1).getOwner().getName(), user2);
// test error conditions
err.reset();
args = new String[] {"volume", "list", url + "/", "--user",
user2, "--length", "-1"};
executeWithError(shell, args, "the length should be a positive number");
err.reset();
args = new String[] {"volume", "list", url + "/", "--user",
user2, "--length", "invalid-length"};
executeWithError(shell, args, "For input string: \"invalid-length\"");
}
@Test
public void testCreateBucket() throws Exception {
LOG.info("Running testCreateBucket");
OzoneVolume vol = creatVolume();
String bucketName = "bucket" + RandomStringUtils.randomNumeric(5);
String[] args = new String[] {"bucket", "create",
url + "/" + vol.getName() + "/" + bucketName};
execute(shell, args);
OzoneBucket bucketInfo = vol.getBucket(bucketName);
assertEquals(vol.getName(),
bucketInfo.getVolumeName());
assertEquals(bucketName, bucketInfo.getName());
// test create a bucket in a non-exist volume
args = new String[] {"bucket", "create",
url + "/invalid-volume/" + bucketName};
executeWithError(shell, args, "Info Volume failed, error:VOLUME_NOT_FOUND");
// test createBucket with invalid bucket name
args = new String[] {"bucket", "create",
url + "/" + vol.getName() + "/" + bucketName + "/invalid-name"};
executeWithError(shell, args,
"Invalid bucket name. Delimiters (/) not allowed in bucket name");
}
@Test
public void testDeleteBucket() throws Exception {
LOG.info("Running testDeleteBucket");
OzoneVolume vol = creatVolume();
String bucketName = "bucket" + RandomStringUtils.randomNumeric(5);
vol.createBucket(bucketName);
OzoneBucket bucketInfo = vol.getBucket(bucketName);
assertNotNull(bucketInfo);
String[] args = new String[] {"bucket", "delete",
url + "/" + vol.getName() + "/" + bucketName};
execute(shell, args);
// verify if bucket has been deleted in volume
try {
vol.getBucket(bucketName);
fail("Get bucket should have thrown.");
} catch (IOException e) {
GenericTestUtils.assertExceptionContains(
"Info Bucket failed, error: BUCKET_NOT_FOUND", e);
}
// test delete bucket in a non-exist volume
args = new String[] {"bucket", "delete",
url + "/invalid-volume" + "/" + bucketName};
executeWithError(shell, args, "Info Volume failed, error:VOLUME_NOT_FOUND");
err.reset();
// test delete non-exist bucket
args = new String[] {"bucket", "delete",
url + "/" + vol.getName() + "/invalid-bucket"};
executeWithError(shell, args,
"Delete Bucket failed, error:BUCKET_NOT_FOUND");
}
@Test
public void testInfoBucket() throws Exception {
LOG.info("Running testInfoBucket");
OzoneVolume vol = creatVolume();
String bucketName = "bucket" + RandomStringUtils.randomNumeric(5);
vol.createBucket(bucketName);
String[] args = new String[] {"bucket", "info",
url + "/" + vol.getName() + "/" + bucketName};
execute(shell, args);
String output = out.toString();
assertTrue(output.contains(bucketName));
assertTrue(output.contains("createdOn")
&& output.contains(OzoneConsts.OZONE_TIME_ZONE));
// test infoBucket with invalid bucket name
args = new String[] {"bucket", "info",
url + "/" + vol.getName() + "/" + bucketName + "/invalid-name"};
executeWithError(shell, args,
"Invalid bucket name. Delimiters (/) not allowed in bucket name");
// test get info from a non-exist bucket
args = new String[] {"bucket", "info",
url + "/" + vol.getName() + "/invalid-bucket" + bucketName};
executeWithError(shell, args,
"Info Bucket failed, error: BUCKET_NOT_FOUND");
}
@Test
public void testUpdateBucket() throws Exception {
LOG.info("Running testUpdateBucket");
OzoneVolume vol = creatVolume();
String bucketName = "bucket" + RandomStringUtils.randomNumeric(5);
vol.createBucket(bucketName);
OzoneBucket bucket = vol.getBucket(bucketName);
int aclSize = bucket.getAcls().size();
String[] args = new String[] {"bucket", "update",
url + "/" + vol.getName() + "/" + bucketName, "--addAcl",
"user:frodo:rw,group:samwise:r"};
execute(shell, args);
String output = out.toString();
assertTrue(output.contains("createdOn")
&& output.contains(OzoneConsts.OZONE_TIME_ZONE));
bucket = vol.getBucket(bucketName);
assertEquals(2 + aclSize, bucket.getAcls().size());
OzoneAcl acl = bucket.getAcls().get(aclSize);
assertTrue(acl.getName().equals("frodo")
&& acl.getType() == OzoneACLType.USER
&& acl.getRights()== OzoneACLRights.READ_WRITE);
args = new String[] {"bucket", "update",
url + "/" + vol.getName() + "/" + bucketName, "--removeAcl",
"user:frodo:rw"};
execute(shell, args);
bucket = vol.getBucket(bucketName);
acl = bucket.getAcls().get(aclSize);
assertEquals(1 + aclSize, bucket.getAcls().size());
assertTrue(acl.getName().equals("samwise")
&& acl.getType() == OzoneACLType.GROUP
&& acl.getRights()== OzoneACLRights.READ);
// test update bucket for a non-exist bucket
args = new String[] {"bucket", "update",
url + "/" + vol.getName() + "/invalid-bucket", "--addAcl",
"user:frodo:rw"};
executeWithError(shell, args,
"Info Bucket failed, error: BUCKET_NOT_FOUND");
}
@Test
public void testListBucket() throws Exception {
LOG.info("Running testListBucket");
List<BucketInfo> buckets;
String commandOutput;
int bucketCount = 11;
OzoneVolume vol = creatVolume();
List<String> bucketNames = new ArrayList<>();
// create bucket from test-bucket0 to test-bucket10
for (int i = 0; i < bucketCount; i++) {
String name = "test-bucket" + i;
bucketNames.add(name);
vol.createBucket(name);
OzoneBucket bucket = vol.getBucket(name);
assertNotNull(bucket);
}
// test listBucket with invalid volume name
String[] args = new String[] {"bucket", "list",
url + "/" + vol.getName() + "/invalid-name"};
executeWithError(shell, args, "Invalid volume name. " +
"Delimiters (/) not allowed in volume name");
// test -length option
args = new String[] {"bucket", "list",
url + "/" + vol.getName(), "--length", "100"};
execute(shell, args);
commandOutput = out.toString();
buckets = (List<BucketInfo>) JsonUtils.toJsonList(commandOutput,
BucketInfo.class);
assertEquals(11, buckets.size());
// sort bucket names since the return buckets isn't in created order
Collections.sort(bucketNames);
// return bucket names should be [test-bucket0, test-bucket1,
// test-bucket10, test-bucket2, ,..., test-bucket9]
for (int i = 0; i < buckets.size(); i++) {
assertEquals(buckets.get(i).getBucketName(), bucketNames.get(i));
assertEquals(buckets.get(i).getVolumeName(), vol.getName());
assertTrue(buckets.get(i).getCreatedOn()
.contains(OzoneConsts.OZONE_TIME_ZONE));
}
out.reset();
args = new String[] {"bucket", "list", url + "/" + vol.getName(),
"--length", "3"};
execute(shell, args);
commandOutput = out.toString();
buckets = (List<BucketInfo>) JsonUtils.toJsonList(commandOutput,
BucketInfo.class);
assertEquals(3, buckets.size());
// return bucket names should be [test-bucket0,
// test-bucket1, test-bucket10]
assertEquals(buckets.get(0).getBucketName(), "test-bucket0");
assertEquals(buckets.get(1).getBucketName(), "test-bucket1");
assertEquals(buckets.get(2).getBucketName(), "test-bucket10");
// test --prefix option
out.reset();
args = new String[] {"bucket", "list", url + "/" + vol.getName(),
"--length", "100", "--prefix", "test-bucket1"};
execute(shell, args);
commandOutput = out.toString();
buckets = (List<BucketInfo>) JsonUtils.toJsonList(commandOutput,
BucketInfo.class);
assertEquals(2, buckets.size());
// return bucket names should be [test-bucket1, test-bucket10]
assertEquals(buckets.get(0).getBucketName(), "test-bucket1");
assertEquals(buckets.get(1).getBucketName(), "test-bucket10");
// test -start option
out.reset();
args = new String[] {"bucket", "list", url + "/" + vol.getName(),
"--length", "100", "--start", "test-bucket7"};
execute(shell, args);
commandOutput = out.toString();
buckets = (List<BucketInfo>) JsonUtils.toJsonList(commandOutput,
BucketInfo.class);
assertEquals(2, buckets.size());
assertEquals(buckets.get(0).getBucketName(), "test-bucket8");
assertEquals(buckets.get(1).getBucketName(), "test-bucket9");
// test error conditions
err.reset();
args = new String[] {"bucket", "list", url + "/" + vol.getName(),
"--length", "-1"};
executeWithError(shell, args, "the length should be a positive number");
}
@Test
public void testPutKey() throws Exception {
LOG.info("Running testPutKey");
OzoneBucket bucket = creatBucket();
String volumeName = bucket.getVolumeName();
String bucketName = bucket.getName();
String keyName = "key" + RandomStringUtils.randomNumeric(5);
String[] args = new String[] {"key", "put",
url + "/" + volumeName + "/" + bucketName + "/" + keyName,
createTmpFile()};
execute(shell, args);
OzoneKey keyInfo = bucket.getKey(keyName);
assertEquals(keyName, keyInfo.getName());
// test put key in a non-exist bucket
args = new String[] {"key", "put",
url + "/" + volumeName + "/invalid-bucket/" + keyName,
createTmpFile()};
executeWithError(shell, args,
"Info Bucket failed, error: BUCKET_NOT_FOUND");
}
@Test
public void testGetKey() throws Exception {
LOG.info("Running testGetKey");
String keyName = "key" + RandomStringUtils.randomNumeric(5);
OzoneBucket bucket = creatBucket();
String volumeName = bucket.getVolumeName();
String bucketName = bucket.getName();
String dataStr = "test-data";
OzoneOutputStream keyOutputStream =
bucket.createKey(keyName, dataStr.length());
keyOutputStream.write(dataStr.getBytes());
keyOutputStream.close();
String tmpPath = baseDir.getAbsolutePath() + "/testfile-"
+ UUID.randomUUID().toString();
String[] args = new String[] {"key", "get",
url + "/" + volumeName + "/" + bucketName + "/" + keyName,
tmpPath};
execute(shell, args);
byte[] dataBytes = new byte[dataStr.length()];
try (FileInputStream randFile = new FileInputStream(new File(tmpPath))) {
randFile.read(dataBytes);
}
assertEquals(dataStr, DFSUtil.bytes2String(dataBytes));
tmpPath = baseDir.getAbsolutePath() + File.separatorChar + keyName;
args = new String[] {"key", "get",
url + "/" + volumeName + "/" + bucketName + "/" + keyName,
baseDir.getAbsolutePath()};
execute(shell, args);
dataBytes = new byte[dataStr.length()];
try (FileInputStream randFile = new FileInputStream(new File(tmpPath))) {
randFile.read(dataBytes);
}
assertEquals(dataStr, DFSUtil.bytes2String(dataBytes));
}
@Test
public void testDeleteKey() throws Exception {
LOG.info("Running testDeleteKey");
String keyName = "key" + RandomStringUtils.randomNumeric(5);
OzoneBucket bucket = creatBucket();
String volumeName = bucket.getVolumeName();
String bucketName = bucket.getName();
String dataStr = "test-data";
OzoneOutputStream keyOutputStream =
bucket.createKey(keyName, dataStr.length());
keyOutputStream.write(dataStr.getBytes());
keyOutputStream.close();
OzoneKey keyInfo = bucket.getKey(keyName);
assertEquals(keyName, keyInfo.getName());
String[] args = new String[] {"key", "delete",
url + "/" + volumeName + "/" + bucketName + "/" + keyName};
execute(shell, args);
// verify if key has been deleted in the bucket
try {
bucket.getKey(keyName);
fail("Get key should have thrown.");
} catch (IOException e) {
GenericTestUtils.assertExceptionContains(
"Lookup key failed, error:KEY_NOT_FOUND", e);
}
// test delete key in a non-exist bucket
args = new String[] {"key", "delete",
url + "/" + volumeName + "/invalid-bucket/" + keyName};
executeWithError(shell, args,
"Info Bucket failed, error: BUCKET_NOT_FOUND");
err.reset();
// test delete a non-exist key in bucket
args = new String[] {"key", "delete",
url + "/" + volumeName + "/" + bucketName + "/invalid-key"};
executeWithError(shell, args, "Delete key failed, error:KEY_NOT_FOUND");
}
@Test
public void testInfoKeyDetails() throws Exception {
LOG.info("Running testInfoKey");
String keyName = "key" + RandomStringUtils.randomNumeric(5);
OzoneBucket bucket = creatBucket();
String volumeName = bucket.getVolumeName();
String bucketName = bucket.getName();
String dataStr = "test-data";
OzoneOutputStream keyOutputStream =
bucket.createKey(keyName, dataStr.length());
keyOutputStream.write(dataStr.getBytes());
keyOutputStream.close();
String[] args = new String[] {"key", "info",
url + "/" + volumeName + "/" + bucketName + "/" + keyName};
// verify the response output
execute(shell, args);
String output = out.toString();
assertTrue(output.contains(keyName));
assertTrue(
output.contains("createdOn") && output.contains("modifiedOn") && output
.contains(OzoneConsts.OZONE_TIME_ZONE));
assertTrue(
output.contains("containerID") && output.contains("localID") && output
.contains("length") && output.contains("offset"));
// reset stream
out.reset();
err.reset();
// get the info of a non-exist key
args = new String[] {"key", "info",
url + "/" + volumeName + "/" + bucketName + "/invalid-key"};
// verify the response output
// get the non-exist key info should be failed
executeWithError(shell, args, "Lookup key failed, error:KEY_NOT_FOUND");
}
@Test
public void testInfoDirKey() throws Exception {
LOG.info("Running testInfoKey for Dir Key");
String dirKeyName = "test/";
String keyNameOnly = "test";
OzoneBucket bucket = creatBucket();
String volumeName = bucket.getVolumeName();
String bucketName = bucket.getName();
String dataStr = "test-data";
OzoneOutputStream keyOutputStream =
bucket.createKey(dirKeyName, dataStr.length());
keyOutputStream.write(dataStr.getBytes());
keyOutputStream.close();
String[] args = new String[] {"key", "info",
url + "/" + volumeName + "/" + bucketName + "/" + dirKeyName};
// verify the response output
execute(shell, args);
String output = out.toString();
assertTrue(output.contains(dirKeyName));
assertTrue(output.contains("createdOn") &&
output.contains("modifiedOn") &&
output.contains(OzoneConsts.OZONE_TIME_ZONE));
args = new String[] {"key", "info",
url + "/" + volumeName + "/" + bucketName + "/" + keyNameOnly};
executeWithError(shell, args, "Lookup key failed, error:KEY_NOT_FOUND");
out.reset();
err.reset();
}
@Test
public void testListKey() throws Exception {
LOG.info("Running testListKey");
String commandOutput;
List<KeyInfo> keys;
int keyCount = 11;
OzoneBucket bucket = creatBucket();
String volumeName = bucket.getVolumeName();
String bucketName = bucket.getName();
String keyName;
List<String> keyNames = new ArrayList<>();
for (int i = 0; i < keyCount; i++) {
keyName = "test-key" + i;
keyNames.add(keyName);
String dataStr = "test-data";
OzoneOutputStream keyOutputStream =
bucket.createKey(keyName, dataStr.length());
keyOutputStream.write(dataStr.getBytes());
keyOutputStream.close();
}
// test listKey with invalid bucket name
String[] args = new String[] {"key", "list",
url + "/" + volumeName + "/" + bucketName + "/invalid-name"};
executeWithError(shell, args, "Invalid bucket name. " +
"Delimiters (/) not allowed in bucket name");
// test -length option
args = new String[] {"key", "list",
url + "/" + volumeName + "/" + bucketName, "--length", "100"};
execute(shell, args);
commandOutput = out.toString();
keys = (List<KeyInfo>) JsonUtils.toJsonList(commandOutput,
KeyInfo.class);
assertEquals(11, keys.size());
// sort key names since the return keys isn't in created order
Collections.sort(keyNames);
// return key names should be [test-key0, test-key1,
// test-key10, test-key2, ,..., test-key9]
for (int i = 0; i < keys.size(); i++) {
assertEquals(keys.get(i).getKeyName(), keyNames.get(i));
// verify the creation/modification time of key
assertTrue(keys.get(i).getCreatedOn()
.contains(OzoneConsts.OZONE_TIME_ZONE));
assertTrue(keys.get(i).getModifiedOn()
.contains(OzoneConsts.OZONE_TIME_ZONE));
}
out.reset();
args =
new String[] {"key", "list", url + "/" + volumeName + "/" + bucketName,
"--length", "3"};
execute(shell, args);
commandOutput = out.toString();
keys = (List<KeyInfo>) JsonUtils.toJsonList(commandOutput,
KeyInfo.class);
assertEquals(3, keys.size());
// return key names should be [test-key0, test-key1, test-key10]
assertEquals(keys.get(0).getKeyName(), "test-key0");
assertEquals(keys.get(1).getKeyName(), "test-key1");
assertEquals(keys.get(2).getKeyName(), "test-key10");
// test --prefix option
out.reset();
args =
new String[] {"key", "list", url + "/" + volumeName + "/" + bucketName,
"--length", "100", "--prefix", "test-key1"};
execute(shell, args);
commandOutput = out.toString();
keys = (List<KeyInfo>) JsonUtils.toJsonList(commandOutput,
KeyInfo.class);
assertEquals(2, keys.size());
// return key names should be [test-key1, test-key10]
assertEquals(keys.get(0).getKeyName(), "test-key1");
assertEquals(keys.get(1).getKeyName(), "test-key10");
// test -start option
out.reset();
args =
new String[] {"key", "list", url + "/" + volumeName + "/" + bucketName,
"--length", "100", "--start", "test-key7"};
execute(shell, args);
commandOutput = out.toString();
keys = (List<KeyInfo>) JsonUtils.toJsonList(commandOutput,
KeyInfo.class);
assertEquals(keys.get(0).getKeyName(), "test-key8");
assertEquals(keys.get(1).getKeyName(), "test-key9");
// test error conditions
err.reset();
args =
new String[] {"key", "list", url + "/" + volumeName + "/" + bucketName,
"--length", "-1"};
executeWithError(shell, args, "the length should be a positive number");
}
@Test
public void testS3BucketMapping() throws IOException {
List<ServiceInfo> services =
cluster.getOzoneManager().getServiceList();
String omHostName = services.stream().filter(
a -> a.getNodeType().equals(HddsProtos.NodeType.OM))
.collect(Collectors.toList()).get(0).getHostname();
String omPort = cluster.getOzoneManager().getRpcPort();
String setOmAddress =
"--set=" + OZONE_OM_ADDRESS_KEY + "=" + omHostName + ":" + omPort;
String s3Bucket = "bucket1";
String commandOutput;
createS3Bucket("ozone", s3Bucket);
//WHEN
String[] args =
new String[] {setOmAddress, "bucket",
"path", s3Bucket};
execute(shell, args);
//THEN
commandOutput = out.toString();
String volumeName = client.getOzoneVolumeName(s3Bucket);
assertTrue(commandOutput.contains("Volume name for S3Bucket is : " +
volumeName));
assertTrue(commandOutput.contains(OzoneConsts.OZONE_URI_SCHEME + "://" +
s3Bucket + "." + volumeName));
out.reset();
//Trying to get map for an unknown bucket
args = new String[] {setOmAddress, "bucket", "path",
"unknownbucket"};
executeWithError(shell, args, "S3_BUCKET_NOT_FOUND");
// No bucket name
args = new String[] {setOmAddress, "bucket", "path"};
executeWithError(shell, args, "Missing required parameter");
// Invalid bucket name
args = new String[] {setOmAddress, "bucket", "path", "/asd/multipleslash"};
executeWithError(shell, args, "S3_BUCKET_NOT_FOUND");
}
private void createS3Bucket(String userName, String s3Bucket) {
try {
client.createS3Bucket("ozone", s3Bucket);
} catch (IOException ex) {
GenericTestUtils.assertExceptionContains("S3_BUCKET_ALREADY_EXISTS", ex);
}
}
private OzoneVolume creatVolume() throws OzoneException, IOException {
String volumeName = RandomStringUtils.randomNumeric(5) + "volume";
VolumeArgs volumeArgs = VolumeArgs.newBuilder()
.setOwner("bilbo")
.setQuota("100TB")
.build();
try {
client.createVolume(volumeName, volumeArgs);
} catch (Exception ex) {
Assert.assertEquals("PartialGroupNameException",
ex.getCause().getClass().getSimpleName());
}
OzoneVolume volume = client.getVolumeDetails(volumeName);
return volume;
}
private OzoneBucket creatBucket() throws OzoneException, IOException {
OzoneVolume vol = creatVolume();
String bucketName = RandomStringUtils.randomNumeric(5) + "bucket";
vol.createBucket(bucketName);
OzoneBucket bucketInfo = vol.getBucket(bucketName);
return bucketInfo;
}
/**
* Create a temporary file used for putting key.
* @return the created file's path string
* @throws Exception
*/
private String createTmpFile() throws Exception {
// write a new file that used for putting key
File tmpFile = new File(baseDir,
"/testfile-" + UUID.randomUUID().toString());
FileOutputStream randFile = new FileOutputStream(tmpFile);
Random r = new Random();
for (int x = 0; x < 10; x++) {
char c = (char) (r.nextInt(26) + 'a');
randFile.write(c);
}
randFile.close();
return tmpFile.getAbsolutePath();
}
}
|
Java
|
require 'pad_utils'
require_relative '../template/test'
# Test name
test_name = "ZipExtractZip"
class ZipExtractZipTest < Test
def prepare
# Add test preparation here
end
def run_test
PadUtils.extract_zip("fixtures/archive.zip", "results/extracted")
if !PadUtils.file_exist?("results/extracted/penguin02.jpg") || !PadUtils.file_exist?("results/extracted/others/panda.jpg")
@errors << "Seems files were not extracted"
end
end
def cleanup
# Add cleanup code here
end
end
|
Java
|
/*
+----------------------------------------------------------------------+
| PHP Version 5 |
+----------------------------------------------------------------------+
| Copyright 2012 Couchbase, 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. |
+----------------------------------------------------------------------+
*/
#include "internal.h"
/* @todo This is a copy of the logic used by the cluster management
* I should refactor this out so I have a generic http execution
* method.
*/
struct flush_ctx {
lcb_error_t error;
lcb_http_status_t status;
char *payload;
};
static void rest_flush_callback(lcb_http_request_t request,
lcb_t instance,
const void *cookie,
lcb_error_t error,
const lcb_http_resp_t *resp)
{
struct flush_ctx *ctx = (void *)cookie;
assert(cookie != NULL);
ctx->error = error;
ctx->payload = NULL;
if (resp->version != 0) {
/* @todo add an error code I may use */
ctx->error = LCB_NOT_SUPPORTED;
} else {
ctx->status = resp->v.v0.status;
if (resp->v.v0.nbytes != 0) {
ctx->payload = emalloc(resp->v.v0.nbytes + 1);
if (ctx->payload != NULL) {
memcpy(ctx->payload, resp->v.v0.bytes, resp->v.v0.nbytes);
ctx->payload[resp->v.v0.nbytes] = '\0';
}
}
}
}
static void do_rest_flush(INTERNAL_FUNCTION_PARAMETERS,
int oo,
php_couchbase_res *res)
{
struct flush_ctx ctx;
lcb_error_t rc;
lcb_http_cmd_t cmd;
lcb_t instance;
char *path;
lcb_http_complete_callback old;
instance = res->handle;
path = ecalloc(strlen(res->bucket) + 80, 1);
sprintf(path, "/pools/default/buckets/%s/controller/doFlush",
res->bucket);
memset(&ctx, 0, sizeof(ctx));
memset(&cmd, 0, sizeof(cmd));
cmd.v.v0.path = path;
cmd.v.v0.npath = strlen(path);
cmd.v.v0.method = LCB_HTTP_METHOD_POST;
cmd.v.v0.content_type = "application/x-www-form-urlencoded";
old = lcb_set_http_complete_callback(instance, rest_flush_callback);
rc = lcb_make_http_request(instance, &ctx, LCB_HTTP_TYPE_MANAGEMENT,
&cmd, NULL);
old = lcb_set_http_complete_callback(instance, old);
efree(path);
if (rc == LCB_SUCCESS) {
rc = ctx.error;
}
res->rc = rc;
if (rc != LCB_SUCCESS) {
/* An error occured occurred on libcouchbase level */
if (ctx.payload) {
efree(ctx.payload);
}
couchbase_report_error(INTERNAL_FUNCTION_PARAM_PASSTHRU, oo,
cb_lcb_exception, "Failed to flush bucket: %s",
lcb_strerror(instance, rc));
return;
}
switch (ctx.status) {
case LCB_HTTP_STATUS_OK:
case LCB_HTTP_STATUS_ACCEPTED:
efree(ctx.payload);
RETURN_TRUE;
case LCB_HTTP_STATUS_UNAUTHORIZED:
couchbase_report_error(INTERNAL_FUNCTION_PARAM_PASSTHRU, oo,
cb_auth_exception, "Incorrect credentials");
break;
default:
if (ctx.payload == NULL) {
couchbase_report_error(INTERNAL_FUNCTION_PARAM_PASSTHRU, oo,
cb_server_exception,
"{\"errors\":{\"http response\": %d }}",
(int)ctx.status);
} else {
couchbase_report_error(INTERNAL_FUNCTION_PARAM_PASSTHRU, oo,
cb_server_exception,
ctx.payload);
}
}
if (ctx.payload != NULL) {
efree(ctx.payload);
}
}
static void memcached_flush_callback(lcb_t handle,
const void *cookie,
lcb_error_t error,
const lcb_flush_resp_t *resp)
{
if (error != LCB_SUCCESS) {
*((lcb_error_t *)cookie) = error;
}
}
static void do_memcached_flush(INTERNAL_FUNCTION_PARAMETERS,
int oo,
php_couchbase_res *res)
{
lcb_error_t retval;
lcb_error_t cberr = LCB_SUCCESS;
lcb_flush_cmd_t cmd;
const lcb_flush_cmd_t *const commands[] = { &cmd };
lcb_t instance;
instance = res->handle;
memset(&cmd, 0, sizeof(cmd));
lcb_set_flush_callback(instance, memcached_flush_callback);
retval = lcb_flush(instance, (const void *)&cberr, 1, commands);
if (retval == LCB_SUCCESS) {
retval = cberr;
}
res->rc = retval;
if (retval == LCB_SUCCESS) {
RETURN_TRUE;
} else {
char errmsg[256];
sprintf(errmsg, "Failed to flush bucket: %s",
lcb_strerror(instance, retval));
couchbase_report_error(INTERNAL_FUNCTION_PARAM_PASSTHRU, oo,
cb_lcb_exception, errmsg);
}
}
PHP_COUCHBASE_LOCAL
void php_couchbase_flush_impl(INTERNAL_FUNCTION_PARAMETERS, int oo)
{
php_couchbase_res *res;
lcb_t instance;
int argflags = oo ? PHP_COUCHBASE_ARG_F_OO : PHP_COUCHBASE_ARG_F_FUNCTIONAL;
PHP_COUCHBASE_GET_PARAMS(res, argflags, "");
instance = res->handle;
lcb_behavior_set_syncmode(instance, LCB_SYNCHRONOUS);
if (COUCHBASE_G(restflush)) {
do_rest_flush(INTERNAL_FUNCTION_PARAM_PASSTHRU, oo, res);
} else {
do_memcached_flush(INTERNAL_FUNCTION_PARAM_PASSTHRU, oo, res);
}
lcb_behavior_set_syncmode(instance, LCB_ASYNCHRONOUS);
}
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
|
Java
|
/*
* Copyright 2015 Adaptris Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.adaptris.core.services.jdbc;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import org.junit.Test;
import com.adaptris.core.CoreException;
import com.adaptris.core.jdbc.JdbcConnection;
import com.adaptris.core.util.JdbcUtil;
import com.adaptris.core.util.LifecycleHelper;
import com.adaptris.util.KeyValuePair;
import com.adaptris.util.KeyValuePairSet;
public abstract class JdbcMapInsertCase {
protected static final String CONTENT =
"firstname=alice\n" +
"lastname=smith\n" +
"dob=2017-01-01";
protected static final String INVALID_COLUMN =
"fi$rstname=alice\n" + "la$stname=smith\n" + "dob=2017-01-01";
protected static final String JDBC_DRIVER = "org.apache.derby.jdbc.EmbeddedDriver";
protected static final String JDBC_URL = "jdbc:derby:memory:JDCB_OBJ_DB;create=true";
protected static final String TABLE_NAME = "people";
protected static final String DROP_STMT = String.format("DROP TABLE %s", TABLE_NAME);
protected static final String CREATE_STMT = String.format("CREATE TABLE %s (firstname VARCHAR(128) NOT NULL, "
+ "lastname VARCHAR(128) NOT NULL, "
+ "dob DATE)",
TABLE_NAME);
protected static final String CREATE_QUOTED = String.format(
"CREATE TABLE %s (\"firstname\" VARCHAR(128) NOT NULL, \"lastname\" VARCHAR(128) NOT NULL, \"dob\" DATE)", TABLE_NAME);
@Test
public void testService_Init() throws Exception {
JdbcMapInsert service = createService();
try {
LifecycleHelper.init(service);
fail();
} catch (CoreException expected) {
}
service.setTable("hello");
LifecycleHelper.init(service);
}
protected abstract JdbcMapInsert createService();
protected static void doAssert(int expectedCount) throws Exception {
Connection c = null;
PreparedStatement p = null;
try {
c = createConnection();
p = c.prepareStatement(String.format("SELECT * FROM %s", TABLE_NAME));
ResultSet rs = p.executeQuery();
int count = 0;
while (rs.next()) {
count++;
assertEquals("smith", rs.getString("lastname"));
}
assertEquals(expectedCount, count);
JdbcUtil.closeQuietly(rs);
} finally {
JdbcUtil.closeQuietly(p);
JdbcUtil.closeQuietly(c);
}
}
protected static Connection createConnection() throws Exception {
Connection c = null;
Class.forName(JDBC_DRIVER);
c = DriverManager.getConnection(JDBC_URL);
c.setAutoCommit(true);
return c;
}
protected static void createDatabase() throws Exception {
createDatabase(CREATE_STMT);
}
protected static void createDatabase(String createStmt) throws Exception {
Connection c = null;
Statement s = null;
try {
c = createConnection();
s = c.createStatement();
executeQuietly(s, DROP_STMT);
s.execute(createStmt);
}
finally {
JdbcUtil.closeQuietly(s);
JdbcUtil.closeQuietly(c);
}
}
protected static void executeQuietly(Statement s, String sql) {
try {
s.execute(sql);
} catch (Exception e) {
;
}
}
protected static <T extends JdbcMapInsert> T configureForTests(T t) {
JdbcMapInsert service = t;
JdbcConnection connection = new JdbcConnection();
connection.setConnectUrl(JDBC_URL);
connection.setDriverImp(JDBC_DRIVER);
service.setConnection(connection);
KeyValuePairSet mappings = new KeyValuePairSet();
mappings.add(new KeyValuePair("dob", JdbcMapInsert.BasicType.Date.name()));
service.withTable(TABLE_NAME).withMappings(mappings);
return t;
}
}
|
Java
|
/*
* Project Scelight
*
* Copyright (c) 2013 Andras Belicza <iczaaa@gmail.com>
*
* This software is the property of Andras Belicza.
* Copying, modifying, distributing, refactoring without the author's permission
* is prohibited and protected by Law.
*/
package hu.scelight.gui.page.replist.column.impl;
import hu.scelight.gui.icon.Icons;
import hu.scelight.gui.page.replist.column.BaseColumn;
import hu.scelight.sc2.rep.repproc.RepProcessor;
import java.util.Date;
/**
* Replay date column.
*
* @author Andras Belicza
*/
public class DateColumn extends BaseColumn< Date > {
/**
* Creates a new {@link DateColumn}.
*/
public DateColumn() {
super( "Date", Icons.F_CALENDAR_BLUE, "Replay date", Date.class, true );
}
@Override
public Date getData( final RepProcessor repProc ) {
return repProc.replay.details.getTime();
}
}
|
Java
|
# Shrinker
`Shrinker` will remove all R.class and R\$\*\*.class and all constant integer fields will be inlined by [`asm`](http://asm.ow2.org/) and [`transform-api`](http://tools.android.com/tech-docs/new-build-system/transform-api).
*I have post more details on my own blog (in Chinese), [click here](http://yrom.net/blog/2018/01/12/android-gradle-plugin-for-shrinking-fields-in-dex/) to check it out.*
## Usage
 You can get `shrinker` from [jitpack](https://jitpack.io)
To apply `shrinker` to your android application:
**Step1.** Add it in your `buildscript` section of app's build.gradle
```
buildscript {
repositories {
//...
maven { url 'https://jitpack.io' }
}
dependencies {
classpath 'net.yrom:shrinker:0.2.9'
}
}
```
**Step2.** Apply it **after** the Android plugin
```
apply plugin: 'com.android.application'
//...
apply plugin: 'net.yrom.shrinker'
```
**NOTE** that `shrinker` plugin requires android gradle build tools version at least 3.0.0 and it will be disabled if run in debug build.
### Show case
There is a small [test](tree/master/test) application which depends on so many support libraries, would show how many fields `shrinked`.
Run with `shrinker`:
```
./gradlew :test:assembleRelease -PENABLE_SHRINKER
```
Run with `removeUnusedCode`:
```groovy
android {
buildTypes {
release {
...
postprocessing {
removeUnusedCode = true
}
}
}
...
}
```
Content below counts by [dexcount-gradle-plugin](https://github.com/KeepSafe/dexcount-gradle-plugin)
| options | methods | fields | classes |
| --------------------------- | ------- | ------ | ------- |
| origin | 22164 | 14367 | 2563 |
| shrinker | 21979 | 7805 | 2392 |
| removeUnusedCode | 11338 | 6655 | 1296 |
| shrinker & removeUnusedCode | 11335 | 3302 | 1274 |
## License
```
Copyright 2017 Yrom
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.
```
|
Java
|
"""Tests for the CSRF helper."""
import unittest
import mock
import webapp2
import webtest
from ctc.helpers import csrf
from ctc.testing import testutil
MOCKED_TIME = 123
# Tests don't need docstrings, so pylint: disable=C0111
# Tests can test protected members, so pylint: disable=W0212
class CsrfTests(testutil.CtcTestCase):
# Helpers
class TestHandler(csrf.CsrfHandler):
"""A handler for testing whether or not requests are CSRF protected."""
def get(self):
self.response.write('CSRF Token:%s' % self.csrf_token)
def post(self):
pass
def put(self):
pass
def delete(self):
pass
def setUp(self):
super(CsrfTests, self).setUp()
# The CSRF library uses the time, so we mock it out.
self.time_mock = mock.Mock()
csrf.time = self.time_mock
self.time_mock.time = mock.Mock(return_value=MOCKED_TIME)
# The handler tests need a WSGIApplication.
app = webapp2.WSGIApplication([('/', self.TestHandler)])
self.testapp = webtest.TestApp(app)
def test_get_secret_key(self):
first_key = csrf._get_secret_key()
self.assertEqual(len(first_key), 32)
second_key = csrf._get_secret_key()
self.assertEqual(first_key, second_key)
def test_tokens_are_equal(self):
# It should fail if the tokens aren't equal length.
self.assertFalse(csrf._tokens_are_equal('a', 'ab'))
# It should fail if the tokens are different.
self.assertFalse(csrf._tokens_are_equal('abcde', 'abcdf'))
# It should succeed if the tokens are the same.
self.assertTrue(csrf._tokens_are_equal('abcde', 'abcde'))
# Make Token
def test_make_token_includes_time(self):
self.login()
# It should get the current time.
token1 = csrf.make_token()
self.assertEqual(token1.split()[-1], str(MOCKED_TIME))
# It should use the provided time.
token2 = csrf.make_token(token_time='456')
self.assertEqual(token2.split()[-1], '456')
# Different time should cause the digest to be different.
self.assertNotEqual(token1.split()[0], token2.split()[0])
token3 = csrf.make_token(token_time='456')
self.assertEqual(token2, token3)
def test_make_token_requires_login(self):
token1 = csrf.make_token()
self.assertIsNone(token1)
self.login()
token2 = csrf.make_token()
self.assertIsNotNone(token2)
def test_make_token_includes_path(self):
self.login()
# It should get the current path.
self.testbed.setup_env(PATH_INFO='/action/1', overwrite=True)
token1 = csrf.make_token(token_time='123')
self.testbed.setup_env(PATH_INFO='/action/23', overwrite=True)
token2 = csrf.make_token(token_time='123')
token3 = csrf.make_token(token_time='123')
self.assertNotEqual(token1, token2)
self.assertEqual(token2, token3)
# It should let the client pass in a path.
token4 = csrf.make_token(path='/action/4', token_time='123')
token5 = csrf.make_token(path='/action/56', token_time='123')
token6 = csrf.make_token(path='/action/56', token_time='123')
self.assertNotEqual(token4, token5)
self.assertEqual(token5, token6)
# Token Is Valid
def test_token_is_valid(self):
self.login()
# Token is required.
self.assertFalse(csrf.token_is_valid(None))
# Token needs to have a timestamp on it.
self.assertFalse(csrf.token_is_valid('hello'))
# The timestamp needs to be within the current date range.
self.time_mock.time = mock.Mock(return_value=9999999999999)
self.assertFalse(csrf.token_is_valid('hello 123'))
# The user needs to be logged in.
token = csrf.make_token()
self.logout()
self.assertFalse(csrf.token_is_valid(token))
self.login()
# Modifying the token should break everything.
modified_token = '0' + token[1:]
if token == modified_token:
modified_token = '1' + token[1:]
self.assertFalse(csrf.token_is_valid(modified_token))
# The original token that we got should work.
self.assertTrue(csrf.token_is_valid(token))
def test_get_has_csrf_token(self):
self.login()
response = self.testapp.get('/', status=200).body
self.assertIn('CSRF Token:', response)
self.assertEqual(response.split(':')[-1], csrf.make_token())
def test_mutators_require_csrf_token(self):
self.login()
self.testapp.put('/', status=403)
self.testapp.post('/', status=403)
self.testapp.delete('/', status=403)
csrf_param = 'csrf_token=' + csrf.make_token(path='/')
self.testapp.put('/', params=csrf_param, status=200)
self.testapp.post('/', params=csrf_param, status=200)
# Though the spec allows DELETE to have a body, it tends to be ignored
# by servers (http://stackoverflow.com/questions/299628), and webapp2
# ignores it as well, so we have to put the params in the URL.
self.testapp.delete('/?' + csrf_param, status=200)
if __name__ == '__main__':
unittest.main()
|
Java
|
/*
* #%L
* FlatPack serialization code
* %%
* Copyright (C) 2012 Perka 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.
* #L%
*/
package com.getperka.flatpack.codex;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import javax.inject.Inject;
import org.junit.Test;
import com.getperka.flatpack.FlatPackTest;
import com.getperka.flatpack.HasUuid;
import com.getperka.flatpack.codexes.ArrayCodex;
import com.getperka.flatpack.codexes.ListCodex;
import com.getperka.flatpack.codexes.SetCodex;
import com.getperka.flatpack.domain.Employee;
import com.getperka.flatpack.domain.Person;
import com.getperka.flatpack.util.FlatPackCollections;
import com.google.inject.TypeLiteral;
/**
* Tests serializing collections of things.
*/
public class CollectionCodexTest extends FlatPackTest {
@Inject
private TypeLiteral<ArrayCodex<Person>> arrayPerson;
@Inject
private TypeLiteral<ArrayCodex<String>> arrayString;
@Inject
private TypeLiteral<ListCodex<Person>> listPerson;
@Inject
private TypeLiteral<ListCodex<String>> listString;
@Inject
private TypeLiteral<SetCodex<String>> setString;
@Inject
private Employee employee;
@Test
public void testArray() {
String[] in = { "Hello", " ", "", null, "World!" };
String[] out = testCodex(arrayString, in);
assertArrayEquals(in, out);
Set<HasUuid> scanned = FlatPackCollections.setForIteration();
Employee[] in2 = { employee, null, employee };
Person[] out2 = testCodex(arrayPerson, in2, scanned);
assertEquals(Collections.singleton(employee), scanned);
/*
* Because we're testing without a full flatpack structure, all we can expect is that a HasUuid
* is created with the same UUID. The concrete type would normally be specified in the data
* section, however it is missing, so we expect the configured type of the codex instead.
*/
Person p = out2[0];
assertNotNull(p);
assertEquals(Person.class, p.getClass());
assertEquals(employee.getUuid(), p.getUuid());
}
@Test
public void testList() {
List<String> in = Arrays.asList("Hello", " ", "", null, "World!");
Collection<String> out = testCodex(listString, in);
assertEquals(in, out);
Set<HasUuid> scanned = FlatPackCollections.setForIteration();
List<Person> in2 = Arrays.<Person> asList(employee, null, employee);
Collection<Person> out2 = testCodex(listPerson, in2, scanned);
assertEquals(Collections.singleton(employee), scanned);
/*
* Because we're testing without a full flatpack structure, all we can expect is that a HasUuid
* is created with the same UUID. The concrete type would normally be specified in the data
* section, however it is missing, so we expect the configured type of the codex instead.
*/
Person p = ((List<Person>) out2).get(0);
assertNotNull(p);
assertEquals(Person.class, p.getClass());
assertEquals(employee.getUuid(), p.getUuid());
}
@Test
public void testNull() {
assertNull(testCodex(arrayString, null));
assertNull(testCodex(listString, null));
assertNull(testCodex(setString, null));
}
@Test
public void testSet() {
Set<String> in = new LinkedHashSet<String>(Arrays.asList("Hello", " ", "", null, "World!"));
Set<String> out = testCodex(setString, in);
assertEquals(in, out);
}
}
|
Java
|
/**
* FreeRDP: A Remote Desktop Protocol Implementation
* RDP Settings
*
* Copyright 2009-2011 Jay Sorg
*
* 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.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "certificate.h"
#include "capabilities.h"
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <ctype.h>
#include <winpr/crt.h>
#include <winpr/file.h>
#include <winpr/path.h>
#include <winpr/sysinfo.h>
#include <winpr/registry.h>
#include <freerdp/settings.h>
#include <freerdp/build-config.h>
#include <ctype.h>
#ifdef _WIN32
#pragma warning(push)
#pragma warning(disable: 4244)
#endif
static const char client_dll[] = "C:\\Windows\\System32\\mstscax.dll";
#define REG_QUERY_DWORD_VALUE(_key, _subkey, _type, _value, _size, _result) \
_size = sizeof(DWORD); \
if (RegQueryValueEx(_key, _subkey, NULL, &_type, (BYTE*) &_value, &_size) == ERROR_SUCCESS) \
_result = _value
#define REG_QUERY_BOOL_VALUE(_key, _subkey, _type, _value, _size, _result) \
_size = sizeof(DWORD); \
if (RegQueryValueEx(_key, _subkey, NULL, &_type, (BYTE*) &_value, &_size) == ERROR_SUCCESS) \
_result = _value ? TRUE : FALSE
#define SERVER_KEY "Software\\" FREERDP_VENDOR_STRING "\\" \
FREERDP_PRODUCT_STRING "\\Server"
#define CLIENT_KEY "Software\\" FREERDP_VENDOR_STRING "\\" \
FREERDP_PRODUCT_STRING "\\Client"
#define BITMAP_CACHE_KEY CLIENT_KEY "\\BitmapCacheV2"
#define GLYPH_CACHE_KEY CLIENT_KEY "\\GlyphCache"
#define POINTER_CACHE_KEY CLIENT_KEY "\\PointerCache"
static void settings_client_load_hkey_local_machine(rdpSettings* settings)
{
HKEY hKey;
LONG status;
DWORD dwType;
DWORD dwSize;
DWORD dwValue;
status = RegOpenKeyExA(HKEY_LOCAL_MACHINE, CLIENT_KEY, 0,
KEY_READ | KEY_WOW64_64KEY, &hKey);
if (status == ERROR_SUCCESS)
{
REG_QUERY_DWORD_VALUE(hKey, _T("DesktopWidth"), dwType, dwValue, dwSize,
settings->DesktopWidth);
REG_QUERY_DWORD_VALUE(hKey, _T("DesktopHeight"), dwType, dwValue, dwSize,
settings->DesktopHeight);
REG_QUERY_BOOL_VALUE(hKey, _T("Fullscreen"), dwType, dwValue, dwSize,
settings->Fullscreen);
REG_QUERY_DWORD_VALUE(hKey, _T("ColorDepth"), dwType, dwValue, dwSize,
settings->ColorDepth);
REG_QUERY_DWORD_VALUE(hKey, _T("KeyboardType"), dwType, dwValue, dwSize,
settings->KeyboardType);
REG_QUERY_DWORD_VALUE(hKey, _T("KeyboardSubType"), dwType, dwValue, dwSize,
settings->KeyboardSubType);
REG_QUERY_DWORD_VALUE(hKey, _T("KeyboardFunctionKeys"), dwType, dwValue, dwSize,
settings->KeyboardFunctionKey);
REG_QUERY_DWORD_VALUE(hKey, _T("KeyboardLayout"), dwType, dwValue, dwSize,
settings->KeyboardLayout);
REG_QUERY_BOOL_VALUE(hKey, _T("ExtSecurity"), dwType, dwValue, dwSize,
settings->ExtSecurity);
REG_QUERY_BOOL_VALUE(hKey, _T("NlaSecurity"), dwType, dwValue, dwSize,
settings->NlaSecurity);
REG_QUERY_BOOL_VALUE(hKey, _T("TlsSecurity"), dwType, dwValue, dwSize,
settings->TlsSecurity);
REG_QUERY_BOOL_VALUE(hKey, _T("RdpSecurity"), dwType, dwValue, dwSize,
settings->RdpSecurity);
REG_QUERY_BOOL_VALUE(hKey, _T("MstscCookieMode"), dwType, dwValue, dwSize,
settings->MstscCookieMode);
REG_QUERY_DWORD_VALUE(hKey, _T("CookieMaxLength"), dwType, dwValue, dwSize,
settings->CookieMaxLength);
REG_QUERY_BOOL_VALUE(hKey, _T("BitmapCache"), dwType, dwValue, dwSize,
settings->BitmapCacheEnabled);
REG_QUERY_BOOL_VALUE(hKey, _T("OffscreenBitmapCache"), dwType, dwValue, dwSize,
settings->OffscreenSupportLevel);
REG_QUERY_DWORD_VALUE(hKey, _T("OffscreenBitmapCacheSize"), dwType, dwValue,
dwSize, settings->OffscreenCacheSize);
REG_QUERY_DWORD_VALUE(hKey, _T("OffscreenBitmapCacheEntries"), dwType, dwValue,
dwSize, settings->OffscreenCacheEntries);
RegCloseKey(hKey);
}
status = RegOpenKeyExA(HKEY_LOCAL_MACHINE, BITMAP_CACHE_KEY, 0,
KEY_READ | KEY_WOW64_64KEY, &hKey);
if (status == ERROR_SUCCESS)
{
REG_QUERY_DWORD_VALUE(hKey, _T("NumCells"), dwType, dwValue, dwSize,
settings->BitmapCacheV2NumCells);
REG_QUERY_DWORD_VALUE(hKey, _T("Cell0NumEntries"), dwType, dwValue, dwSize,
settings->BitmapCacheV2CellInfo[0].numEntries);
REG_QUERY_BOOL_VALUE(hKey, _T("Cell0Persistent"), dwType, dwValue, dwSize,
settings->BitmapCacheV2CellInfo[0].persistent);
REG_QUERY_DWORD_VALUE(hKey, _T("Cell1NumEntries"), dwType, dwValue, dwSize,
settings->BitmapCacheV2CellInfo[1].numEntries);
REG_QUERY_BOOL_VALUE(hKey, _T("Cell1Persistent"), dwType, dwValue, dwSize,
settings->BitmapCacheV2CellInfo[1].persistent);
REG_QUERY_DWORD_VALUE(hKey, _T("Cell2NumEntries"), dwType, dwValue, dwSize,
settings->BitmapCacheV2CellInfo[2].numEntries);
REG_QUERY_BOOL_VALUE(hKey, _T("Cell2Persistent"), dwType, dwValue, dwSize,
settings->BitmapCacheV2CellInfo[2].persistent);
REG_QUERY_DWORD_VALUE(hKey, _T("Cell3NumEntries"), dwType, dwValue, dwSize,
settings->BitmapCacheV2CellInfo[3].numEntries);
REG_QUERY_BOOL_VALUE(hKey, _T("Cell3Persistent"), dwType, dwValue, dwSize,
settings->BitmapCacheV2CellInfo[3].persistent);
REG_QUERY_DWORD_VALUE(hKey, _T("Cell4NumEntries"), dwType, dwValue, dwSize,
settings->BitmapCacheV2CellInfo[4].numEntries);
REG_QUERY_BOOL_VALUE(hKey, _T("Cell4Persistent"), dwType, dwValue, dwSize,
settings->BitmapCacheV2CellInfo[4].persistent);
REG_QUERY_BOOL_VALUE(hKey, _T("AllowCacheWaitingList"), dwType, dwValue, dwSize,
settings->AllowCacheWaitingList);
RegCloseKey(hKey);
}
status = RegOpenKeyExA(HKEY_LOCAL_MACHINE, GLYPH_CACHE_KEY,
0, KEY_READ | KEY_WOW64_64KEY, &hKey);
if (status == ERROR_SUCCESS)
{
REG_QUERY_DWORD_VALUE(hKey, _T("SupportLevel"), dwType, dwValue, dwSize,
settings->GlyphSupportLevel);
REG_QUERY_DWORD_VALUE(hKey, _T("Cache0NumEntries"), dwType, dwValue, dwSize,
settings->GlyphCache[0].cacheEntries);
REG_QUERY_DWORD_VALUE(hKey, _T("Cache0MaxCellSize"), dwType, dwValue, dwSize,
settings->GlyphCache[0].cacheMaximumCellSize);
REG_QUERY_DWORD_VALUE(hKey, _T("Cache1NumEntries"), dwType, dwValue, dwSize,
settings->GlyphCache[1].cacheEntries);
REG_QUERY_DWORD_VALUE(hKey, _T("Cache1MaxCellSize"), dwType, dwValue, dwSize,
settings->GlyphCache[1].cacheMaximumCellSize);
REG_QUERY_DWORD_VALUE(hKey, _T("Cache2NumEntries"), dwType, dwValue, dwSize,
settings->GlyphCache[2].cacheEntries);
REG_QUERY_DWORD_VALUE(hKey, _T("Cache2MaxCellSize"), dwType, dwValue, dwSize,
settings->GlyphCache[2].cacheMaximumCellSize);
REG_QUERY_DWORD_VALUE(hKey, _T("Cache3NumEntries"), dwType, dwValue, dwSize,
settings->GlyphCache[3].cacheEntries);
REG_QUERY_DWORD_VALUE(hKey, _T("Cache3MaxCellSize"), dwType, dwValue, dwSize,
settings->GlyphCache[3].cacheMaximumCellSize);
REG_QUERY_DWORD_VALUE(hKey, _T("Cache4NumEntries"), dwType, dwValue, dwSize,
settings->GlyphCache[4].cacheEntries);
REG_QUERY_DWORD_VALUE(hKey, _T("Cache4MaxCellSize"), dwType, dwValue, dwSize,
settings->GlyphCache[4].cacheMaximumCellSize);
REG_QUERY_DWORD_VALUE(hKey, _T("Cache5NumEntries"), dwType, dwValue, dwSize,
settings->GlyphCache[5].cacheEntries);
REG_QUERY_DWORD_VALUE(hKey, _T("Cache5MaxCellSize"), dwType, dwValue, dwSize,
settings->GlyphCache[5].cacheMaximumCellSize);
REG_QUERY_DWORD_VALUE(hKey, _T("Cache6NumEntries"), dwType, dwValue, dwSize,
settings->GlyphCache[6].cacheEntries);
REG_QUERY_DWORD_VALUE(hKey, _T("Cache6MaxCellSize"), dwType, dwValue, dwSize,
settings->GlyphCache[6].cacheMaximumCellSize);
REG_QUERY_DWORD_VALUE(hKey, _T("Cache7NumEntries"), dwType, dwValue, dwSize,
settings->GlyphCache[7].cacheEntries);
REG_QUERY_DWORD_VALUE(hKey, _T("Cache7MaxCellSize"), dwType, dwValue, dwSize,
settings->GlyphCache[7].cacheMaximumCellSize);
REG_QUERY_DWORD_VALUE(hKey, _T("Cache8NumEntries"), dwType, dwValue, dwSize,
settings->GlyphCache[8].cacheEntries);
REG_QUERY_DWORD_VALUE(hKey, _T("Cache8MaxCellSize"), dwType, dwValue, dwSize,
settings->GlyphCache[8].cacheMaximumCellSize);
REG_QUERY_DWORD_VALUE(hKey, _T("Cache9NumEntries"), dwType, dwValue, dwSize,
settings->GlyphCache[9].cacheEntries);
REG_QUERY_DWORD_VALUE(hKey, _T("Cache9MaxCellSize"), dwType, dwValue, dwSize,
settings->GlyphCache[9].cacheMaximumCellSize);
REG_QUERY_DWORD_VALUE(hKey, _T("FragCacheNumEntries"), dwType, dwValue, dwSize,
settings->FragCache->cacheEntries);
REG_QUERY_DWORD_VALUE(hKey, _T("FragCacheMaxCellSize"), dwType, dwValue, dwSize,
settings->FragCache->cacheMaximumCellSize);
RegCloseKey(hKey);
}
status = RegOpenKeyExA(HKEY_LOCAL_MACHINE, POINTER_CACHE_KEY,
0, KEY_READ | KEY_WOW64_64KEY, &hKey);
if (status == ERROR_SUCCESS)
{
REG_QUERY_BOOL_VALUE(hKey, _T("LargePointer"), dwType, dwValue, dwSize,
settings->LargePointerFlag);
REG_QUERY_BOOL_VALUE(hKey, _T("ColorPointer"), dwType, dwValue, dwSize,
settings->ColorPointerFlag);
REG_QUERY_DWORD_VALUE(hKey, _T("PointerCacheSize"), dwType, dwValue, dwSize,
settings->PointerCacheSize);
RegCloseKey(hKey);
}
}
static void settings_server_load_hkey_local_machine(rdpSettings* settings)
{
HKEY hKey;
LONG status;
DWORD dwType;
DWORD dwSize;
DWORD dwValue;
status = RegOpenKeyExA(HKEY_LOCAL_MACHINE, SERVER_KEY,
0, KEY_READ | KEY_WOW64_64KEY, &hKey);
if (status != ERROR_SUCCESS)
return;
REG_QUERY_BOOL_VALUE(hKey, _T("ExtSecurity"), dwType, dwValue, dwSize,
settings->ExtSecurity);
REG_QUERY_BOOL_VALUE(hKey, _T("NlaSecurity"), dwType, dwValue, dwSize,
settings->NlaSecurity);
REG_QUERY_BOOL_VALUE(hKey, _T("TlsSecurity"), dwType, dwValue, dwSize,
settings->TlsSecurity);
REG_QUERY_BOOL_VALUE(hKey, _T("RdpSecurity"), dwType, dwValue, dwSize,
settings->RdpSecurity);
RegCloseKey(hKey);
}
static void settings_load_hkey_local_machine(rdpSettings* settings)
{
if (settings->ServerMode)
settings_server_load_hkey_local_machine(settings);
else
settings_client_load_hkey_local_machine(settings);
}
static BOOL settings_get_computer_name(rdpSettings* settings)
{
DWORD nSize = 0;
CHAR* computerName;
if (GetComputerNameExA(ComputerNameNetBIOS, NULL, &nSize) || GetLastError() != ERROR_MORE_DATA)
return FALSE;
computerName = calloc(nSize, sizeof(CHAR));
if (!computerName)
return FALSE;
if (!GetComputerNameExA(ComputerNameNetBIOS, computerName, &nSize))
{
free(computerName);
return FALSE;
}
if (nSize > MAX_COMPUTERNAME_LENGTH)
computerName[MAX_COMPUTERNAME_LENGTH] = '\0';
settings->ComputerName = computerName;
if (!settings->ComputerName)
return FALSE;
return TRUE;
}
BOOL freerdp_settings_set_default_order_support(rdpSettings* settings)
{
if (!settings)
return FALSE;
ZeroMemory(settings->OrderSupport, 32);
settings->OrderSupport[NEG_DSTBLT_INDEX] = TRUE;
settings->OrderSupport[NEG_PATBLT_INDEX] = TRUE;
settings->OrderSupport[NEG_SCRBLT_INDEX] = TRUE;
settings->OrderSupport[NEG_OPAQUE_RECT_INDEX] = TRUE;
settings->OrderSupport[NEG_DRAWNINEGRID_INDEX] = FALSE;
settings->OrderSupport[NEG_MULTIDSTBLT_INDEX] = FALSE;
settings->OrderSupport[NEG_MULTIPATBLT_INDEX] = FALSE;
settings->OrderSupport[NEG_MULTISCRBLT_INDEX] = FALSE;
settings->OrderSupport[NEG_MULTIOPAQUERECT_INDEX] = TRUE;
settings->OrderSupport[NEG_MULTI_DRAWNINEGRID_INDEX] = FALSE;
settings->OrderSupport[NEG_LINETO_INDEX] = TRUE;
settings->OrderSupport[NEG_POLYLINE_INDEX] = TRUE;
settings->OrderSupport[NEG_MEMBLT_INDEX] = settings->BitmapCacheEnabled;
settings->OrderSupport[NEG_MEM3BLT_INDEX] = settings->BitmapCacheEnabled;
settings->OrderSupport[NEG_MEMBLT_V2_INDEX] = settings->BitmapCacheEnabled;
settings->OrderSupport[NEG_MEM3BLT_V2_INDEX] = settings->BitmapCacheEnabled;
settings->OrderSupport[NEG_SAVEBITMAP_INDEX] = FALSE;
settings->OrderSupport[NEG_GLYPH_INDEX_INDEX] = settings->GlyphSupportLevel != GLYPH_SUPPORT_NONE;
settings->OrderSupport[NEG_FAST_INDEX_INDEX] = settings->GlyphSupportLevel != GLYPH_SUPPORT_NONE;
settings->OrderSupport[NEG_FAST_GLYPH_INDEX] = settings->GlyphSupportLevel != GLYPH_SUPPORT_NONE;
settings->OrderSupport[NEG_POLYGON_SC_INDEX] = FALSE;
settings->OrderSupport[NEG_POLYGON_CB_INDEX] = FALSE;
settings->OrderSupport[NEG_ELLIPSE_SC_INDEX] = FALSE;
settings->OrderSupport[NEG_ELLIPSE_CB_INDEX] = FALSE;
return TRUE;
}
rdpSettings* freerdp_settings_new(DWORD flags)
{
char* base;
rdpSettings* settings;
settings = (rdpSettings*) calloc(1, sizeof(rdpSettings));
if (!settings)
return NULL;
settings->ServerMode = (flags & FREERDP_SETTINGS_SERVER_MODE) ? TRUE : FALSE;
settings->WaitForOutputBufferFlush = TRUE;
settings->MaxTimeInCheckLoop = 100;
settings->DesktopWidth = 1024;
settings->DesktopHeight = 768;
settings->Workarea = FALSE;
settings->Fullscreen = FALSE;
settings->GrabKeyboard = TRUE;
settings->Decorations = TRUE;
settings->RdpVersion = RDP_VERSION_5_PLUS;
settings->ColorDepth = 16;
settings->ExtSecurity = FALSE;
settings->NlaSecurity = TRUE;
settings->TlsSecurity = TRUE;
settings->RdpSecurity = TRUE;
settings->NegotiateSecurityLayer = TRUE;
settings->RestrictedAdminModeRequired = FALSE;
settings->MstscCookieMode = FALSE;
settings->CookieMaxLength = DEFAULT_COOKIE_MAX_LENGTH;
settings->ClientBuild = 2600;
settings->KeyboardType = 4;
settings->KeyboardSubType = 0;
settings->KeyboardFunctionKey = 12;
settings->KeyboardLayout = 0;
settings->UseRdpSecurityLayer = FALSE;
settings->SaltedChecksum = TRUE;
settings->ServerPort = 3389;
settings->GatewayPort = 443;
settings->DesktopResize = TRUE;
settings->ToggleFullscreen = TRUE;
settings->DesktopPosX = UINT32_MAX;
settings->DesktopPosY = UINT32_MAX;
settings->SoftwareGdi = TRUE;
settings->UnmapButtons = FALSE;
settings->PerformanceFlags = PERF_FLAG_NONE;
settings->AllowFontSmoothing = TRUE;
settings->AllowDesktopComposition = FALSE;
settings->DisableWallpaper = FALSE;
settings->DisableFullWindowDrag = TRUE;
settings->DisableMenuAnims = TRUE;
settings->DisableThemes = FALSE;
settings->ConnectionType = CONNECTION_TYPE_LAN;
settings->EncryptionMethods = ENCRYPTION_METHOD_NONE;
settings->EncryptionLevel = ENCRYPTION_LEVEL_NONE;
settings->FIPSMode = FALSE;
settings->CompressionEnabled = TRUE;
settings->LogonNotify = TRUE;
settings->BrushSupportLevel = BRUSH_COLOR_FULL;
settings->CompressionLevel = PACKET_COMPR_TYPE_RDP61;
settings->Authentication = TRUE;
settings->AuthenticationOnly = FALSE;
settings->CredentialsFromStdin = FALSE;
settings->DisableCredentialsDelegation = FALSE;
settings->AuthenticationLevel = 2;
settings->ChannelCount = 0;
settings->ChannelDefArraySize = 32;
settings->ChannelDefArray = (CHANNEL_DEF*) calloc(settings->ChannelDefArraySize,
sizeof(CHANNEL_DEF));
if (!settings->ChannelDefArray)
goto out_fail;
settings->SupportMonitorLayoutPdu = FALSE;
settings->MonitorCount = 0;
settings->MonitorDefArraySize = 32;
settings->MonitorDefArray = (rdpMonitor*) calloc(settings->MonitorDefArraySize,
sizeof(rdpMonitor));
if (!settings->MonitorDefArray)
goto out_fail;
settings->MonitorLocalShiftX = 0;
settings->MonitorLocalShiftY = 0;
settings->MonitorIds = (UINT32*) calloc(16, sizeof(UINT32));
if (!settings->MonitorIds)
goto out_fail;
if (!settings_get_computer_name(settings))
goto out_fail;
settings->ReceivedCapabilities = calloc(1, 32);
if (!settings->ReceivedCapabilities)
goto out_fail;
settings->ClientProductId = calloc(1, 32);
if (!settings->ClientProductId)
goto out_fail;
settings->ClientHostname = calloc(1, 32);
if (!settings->ClientHostname)
goto out_fail;
gethostname(settings->ClientHostname, 31);
settings->ClientHostname[31] = 0;
settings->ColorPointerFlag = TRUE;
settings->LargePointerFlag = TRUE;
settings->PointerCacheSize = 20;
settings->SoundBeepsEnabled = TRUE;
settings->DrawGdiPlusEnabled = FALSE;
settings->DrawAllowSkipAlpha = TRUE;
settings->DrawAllowColorSubsampling = FALSE;
settings->DrawAllowDynamicColorFidelity = FALSE;
settings->FrameMarkerCommandEnabled = TRUE;
settings->SurfaceFrameMarkerEnabled = TRUE;
settings->BitmapCacheV3Enabled = FALSE;
settings->BitmapCacheEnabled = TRUE;
settings->BitmapCachePersistEnabled = FALSE;
settings->AllowCacheWaitingList = TRUE;
settings->BitmapCacheV2NumCells = 5;
settings->BitmapCacheV2CellInfo = (BITMAP_CACHE_V2_CELL_INFO*) malloc(sizeof(
BITMAP_CACHE_V2_CELL_INFO) * 6);
if (!settings->BitmapCacheV2CellInfo)
goto out_fail;
settings->BitmapCacheV2CellInfo[0].numEntries = 600;
settings->BitmapCacheV2CellInfo[0].persistent = FALSE;
settings->BitmapCacheV2CellInfo[1].numEntries = 600;
settings->BitmapCacheV2CellInfo[1].persistent = FALSE;
settings->BitmapCacheV2CellInfo[2].numEntries = 2048;
settings->BitmapCacheV2CellInfo[2].persistent = FALSE;
settings->BitmapCacheV2CellInfo[3].numEntries = 4096;
settings->BitmapCacheV2CellInfo[3].persistent = FALSE;
settings->BitmapCacheV2CellInfo[4].numEntries = 2048;
settings->BitmapCacheV2CellInfo[4].persistent = FALSE;
settings->NoBitmapCompressionHeader = TRUE;
settings->RefreshRect = TRUE;
settings->SuppressOutput = TRUE;
settings->GlyphSupportLevel = GLYPH_SUPPORT_NONE;
settings->GlyphCache = malloc(sizeof(GLYPH_CACHE_DEFINITION) * 10);
if (!settings->GlyphCache)
goto out_fail;
settings->FragCache = malloc(sizeof(GLYPH_CACHE_DEFINITION));
if (!settings->FragCache)
goto out_fail;
settings->GlyphCache[0].cacheEntries = 254;
settings->GlyphCache[0].cacheMaximumCellSize = 4;
settings->GlyphCache[1].cacheEntries = 254;
settings->GlyphCache[1].cacheMaximumCellSize = 4;
settings->GlyphCache[2].cacheEntries = 254;
settings->GlyphCache[2].cacheMaximumCellSize = 8;
settings->GlyphCache[3].cacheEntries = 254;
settings->GlyphCache[3].cacheMaximumCellSize = 8;
settings->GlyphCache[4].cacheEntries = 254;
settings->GlyphCache[4].cacheMaximumCellSize = 16;
settings->GlyphCache[5].cacheEntries = 254;
settings->GlyphCache[5].cacheMaximumCellSize = 32;
settings->GlyphCache[6].cacheEntries = 254;
settings->GlyphCache[6].cacheMaximumCellSize = 64;
settings->GlyphCache[7].cacheEntries = 254;
settings->GlyphCache[7].cacheMaximumCellSize = 128;
settings->GlyphCache[8].cacheEntries = 254;
settings->GlyphCache[8].cacheMaximumCellSize = 256;
settings->GlyphCache[9].cacheEntries = 64;
settings->GlyphCache[9].cacheMaximumCellSize = 256;
settings->FragCache->cacheEntries = 256;
settings->FragCache->cacheMaximumCellSize = 256;
settings->OffscreenSupportLevel = TRUE;
settings->OffscreenCacheSize = 7680;
settings->OffscreenCacheEntries = 2000;
settings->DrawNineGridCacheSize = 2560;
settings->DrawNineGridCacheEntries = 256;
settings->ClientDir = _strdup(client_dll);
if (!settings->ClientDir)
goto out_fail;
settings->RemoteWndSupportLevel = WINDOW_LEVEL_SUPPORTED_EX;
settings->RemoteAppNumIconCaches = 3;
settings->RemoteAppNumIconCacheEntries = 12;
settings->VirtualChannelChunkSize = CHANNEL_CHUNK_LENGTH;
settings->MultifragMaxRequestSize = (flags & FREERDP_SETTINGS_SERVER_MODE) ?
0 : 0xFFFF;
settings->GatewayUseSameCredentials = FALSE;
settings->GatewayBypassLocal = FALSE;
settings->GatewayRpcTransport = TRUE;
settings->GatewayHttpTransport = TRUE;
settings->GatewayUdpTransport = TRUE;
settings->FastPathInput = TRUE;
settings->FastPathOutput = TRUE;
settings->LongCredentialsSupported = TRUE;
settings->FrameAcknowledge = 2;
settings->MouseMotion = TRUE;
settings->NSCodecColorLossLevel = 3;
settings->NSCodecAllowSubsampling = TRUE;
settings->NSCodecAllowDynamicColorFidelity = TRUE;
settings->AutoReconnectionEnabled = FALSE;
settings->AutoReconnectMaxRetries = 20;
settings->GfxThinClient = TRUE;
settings->GfxSmallCache = FALSE;
settings->GfxProgressive = FALSE;
settings->GfxProgressiveV2 = FALSE;
settings->GfxH264 = FALSE;
settings->GfxAVC444 = FALSE;
settings->GfxSendQoeAck = FALSE;
settings->ClientAutoReconnectCookie = (ARC_CS_PRIVATE_PACKET*) calloc(1,
sizeof(ARC_CS_PRIVATE_PACKET));
if (!settings->ClientAutoReconnectCookie)
goto out_fail;
settings->ServerAutoReconnectCookie = (ARC_SC_PRIVATE_PACKET*) calloc(1,
sizeof(ARC_SC_PRIVATE_PACKET));
if (!settings->ServerAutoReconnectCookie)
goto out_fail;
settings->ClientTimeZone = (LPTIME_ZONE_INFORMATION) calloc(1,
sizeof(TIME_ZONE_INFORMATION));
if (!settings->ClientTimeZone)
goto out_fail;
settings->DeviceArraySize = 16;
settings->DeviceArray = (RDPDR_DEVICE**) calloc(1,
sizeof(RDPDR_DEVICE*) * settings->DeviceArraySize);
if (!settings->DeviceArray)
goto out_fail;
settings->StaticChannelArraySize = 16;
settings->StaticChannelArray = (ADDIN_ARGV**)
calloc(1, sizeof(ADDIN_ARGV*) * settings->StaticChannelArraySize);
if (!settings->StaticChannelArray)
goto out_fail;
settings->DynamicChannelArraySize = 16;
settings->DynamicChannelArray = (ADDIN_ARGV**)
calloc(1, sizeof(ADDIN_ARGV*) * settings->DynamicChannelArraySize);
if (!settings->DynamicChannelArray)
goto out_fail;
if (!settings->ServerMode)
{
settings->RedirectClipboard = TRUE;
/* these values are used only by the client part */
settings->HomePath = GetKnownPath(KNOWN_PATH_HOME);
if (!settings->HomePath)
goto out_fail;
/* For default FreeRDP continue using same config directory
* as in old releases.
* Custom builds use <Vendor>/<Product> as config folder. */
if (_stricmp(FREERDP_VENDOR_STRING, FREERDP_PRODUCT_STRING))
{
base = GetKnownSubPath(KNOWN_PATH_XDG_CONFIG_HOME,
FREERDP_VENDOR_STRING);
if (base)
{
settings->ConfigPath = GetCombinedPath(
base,
FREERDP_PRODUCT_STRING);
}
free(base);
}
else
{
int i;
char product[sizeof(FREERDP_PRODUCT_STRING)];
memset(product, 0, sizeof(product));
for (i = 0; i < sizeof(product); i++)
product[i] = tolower(FREERDP_PRODUCT_STRING[i]);
settings->ConfigPath = GetKnownSubPath(
KNOWN_PATH_XDG_CONFIG_HOME,
product);
}
if (!settings->ConfigPath)
goto out_fail;
}
settings_load_hkey_local_machine(settings);
settings->SettingsModified = (BYTE*) calloc(1, sizeof(rdpSettings) / 8);
if (!settings->SettingsModified)
goto out_fail;
settings->ActionScript = _strdup("~/.config/freerdp/action.sh");
settings->SmartcardLogon = FALSE;
settings->TlsSecLevel = 1;
settings->OrderSupport = calloc(1, 32);
if (!settings->OrderSupport)
goto out_fail;
if (!freerdp_settings_set_default_order_support(settings))
goto out_fail;
return settings;
out_fail:
free(settings->HomePath);
free(settings->ConfigPath);
free(settings->DynamicChannelArray);
free(settings->StaticChannelArray);
free(settings->DeviceArray);
free(settings->ClientTimeZone);
free(settings->ServerAutoReconnectCookie);
free(settings->ClientAutoReconnectCookie);
free(settings->ClientDir);
free(settings->FragCache);
free(settings->GlyphCache);
free(settings->BitmapCacheV2CellInfo);
free(settings->ClientProductId);
free(settings->ClientHostname);
free(settings->OrderSupport);
free(settings->ReceivedCapabilities);
free(settings->ComputerName);
free(settings->MonitorIds);
free(settings->MonitorDefArray);
free(settings->ChannelDefArray);
free(settings);
return NULL;
}
rdpSettings* freerdp_settings_clone(rdpSettings* settings)
{
UINT32 index;
rdpSettings* _settings;
_settings = (rdpSettings*) calloc(1, sizeof(rdpSettings));
if (_settings)
{
CopyMemory(_settings, settings, sizeof(rdpSettings));
/* char* values */
#define CHECKED_STRDUP(name) if (settings->name && !(_settings->name = _strdup(settings->name))) goto out_fail
CHECKED_STRDUP(ServerHostname); /* 20 */
CHECKED_STRDUP(Username); /* 21 */
CHECKED_STRDUP(Password); /* 22 */
CHECKED_STRDUP(Domain); /* 23 */
CHECKED_STRDUP(PasswordHash); /* 24 */
CHECKED_STRDUP(AcceptedCert); /* 27 */
_settings->ClientHostname = NULL; /* 134 */
_settings->ClientProductId = NULL; /* 135 */
CHECKED_STRDUP(AlternateShell); /* 640 */
CHECKED_STRDUP(ShellWorkingDirectory); /* 641 */
CHECKED_STRDUP(ClientAddress); /* 769 */
CHECKED_STRDUP(ClientDir); /* 770 */
CHECKED_STRDUP(DynamicDSTTimeZoneKeyName); /* 897 */
CHECKED_STRDUP(RemoteAssistanceSessionId); /* 1025 */
CHECKED_STRDUP(RemoteAssistancePassStub); /* 1026 */
CHECKED_STRDUP(RemoteAssistancePassword); /* 1027 */
CHECKED_STRDUP(RemoteAssistanceRCTicket); /* 1028 */
CHECKED_STRDUP(AuthenticationServiceClass); /* 1098 */
CHECKED_STRDUP(AllowedTlsCiphers); /* 1101 */
CHECKED_STRDUP(NtlmSamFile); /* 1103 */
CHECKED_STRDUP(PreconnectionBlob); /* 1155 */
CHECKED_STRDUP(RedirectionAcceptedCert); /* 1231 */
CHECKED_STRDUP(KerberosKdc); /* 1344 */
CHECKED_STRDUP(KerberosRealm); /* 1345 */
CHECKED_STRDUP(CertificateName); /* 1409 */
CHECKED_STRDUP(CertificateFile); /* 1410 */
CHECKED_STRDUP(PrivateKeyFile); /* 1411 */
CHECKED_STRDUP(RdpKeyFile); /* 1412 */
CHECKED_STRDUP(CertificateContent); /* 1416 */
CHECKED_STRDUP(PrivateKeyContent); /* 1417 */
CHECKED_STRDUP(RdpKeyContent); /* 1418 */
CHECKED_STRDUP(WindowTitle); /* 1542 */
CHECKED_STRDUP(WmClass); /* 1549 */
CHECKED_STRDUP(ComputerName); /* 1664 */
CHECKED_STRDUP(ConnectionFile); /* 1728 */
CHECKED_STRDUP(AssistanceFile); /* 1729 */
CHECKED_STRDUP(HomePath); /* 1792 */
CHECKED_STRDUP(ConfigPath); /* 1793 */
CHECKED_STRDUP(CurrentPath); /* 1794 */
CHECKED_STRDUP(DumpRemoteFxFile); /* 1858 */
CHECKED_STRDUP(PlayRemoteFxFile); /* 1859 */
CHECKED_STRDUP(GatewayHostname); /* 1986 */
CHECKED_STRDUP(GatewayUsername); /* 1987 */
CHECKED_STRDUP(GatewayPassword); /* 1988 */
CHECKED_STRDUP(GatewayDomain); /* 1989 */
CHECKED_STRDUP(GatewayAccessToken); /* 1997 */
CHECKED_STRDUP(GatewayAcceptedCert); /* 1998 */
CHECKED_STRDUP(ProxyHostname); /* 2016 */
CHECKED_STRDUP(RemoteApplicationName); /* 2113 */
CHECKED_STRDUP(RemoteApplicationIcon); /* 2114 */
CHECKED_STRDUP(RemoteApplicationProgram); /* 2115 */
CHECKED_STRDUP(RemoteApplicationFile); /* 2116 */
CHECKED_STRDUP(RemoteApplicationGuid); /* 2117 */
CHECKED_STRDUP(RemoteApplicationCmdLine); /* 2118 */
CHECKED_STRDUP(ImeFileName); /* 2628 */
CHECKED_STRDUP(DrivesToRedirect); /* 4290 */
CHECKED_STRDUP(ActionScript);
/**
* Manual Code
*/
_settings->LoadBalanceInfo = NULL;
_settings->LoadBalanceInfoLength = 0;
_settings->TargetNetAddress = NULL;
_settings->RedirectionTargetFQDN = NULL;
_settings->RedirectionTargetNetBiosName = NULL;
_settings->RedirectionUsername = NULL;
_settings->RedirectionDomain = NULL;
_settings->RedirectionPassword = NULL;
_settings->RedirectionPasswordLength = 0;
_settings->RedirectionTsvUrl = NULL;
_settings->RedirectionTsvUrlLength = 0;
_settings->TargetNetAddressCount = 0;
_settings->TargetNetAddresses = NULL;
_settings->TargetNetPorts = NULL;
if (settings->LoadBalanceInfo && settings->LoadBalanceInfoLength)
{
_settings->LoadBalanceInfo = (BYTE*) calloc(1,
settings->LoadBalanceInfoLength + 2);
if (!_settings->LoadBalanceInfo)
goto out_fail;
CopyMemory(_settings->LoadBalanceInfo, settings->LoadBalanceInfo,
settings->LoadBalanceInfoLength);
_settings->LoadBalanceInfoLength = settings->LoadBalanceInfoLength;
}
if (_settings->ServerRandomLength)
{
_settings->ServerRandom = (BYTE*) malloc(_settings->ServerRandomLength);
if (!_settings->ServerRandom)
goto out_fail;
CopyMemory(_settings->ServerRandom, settings->ServerRandom,
_settings->ServerRandomLength);
_settings->ServerRandomLength = settings->ServerRandomLength;
}
if (_settings->ClientRandomLength)
{
_settings->ClientRandom = (BYTE*) malloc(_settings->ClientRandomLength);
if (!_settings->ClientRandom)
goto out_fail;
CopyMemory(_settings->ClientRandom, settings->ClientRandom,
_settings->ClientRandomLength);
_settings->ClientRandomLength = settings->ClientRandomLength;
}
if (settings->RdpServerCertificate)
{
_settings->RdpServerCertificate = certificate_clone(
settings->RdpServerCertificate);
if (!_settings->RdpServerCertificate)
goto out_fail;
}
_settings->ChannelCount = settings->ChannelCount;
_settings->ChannelDefArraySize = settings->ChannelDefArraySize;
if (_settings->ChannelDefArraySize > 0)
{
_settings->ChannelDefArray = (CHANNEL_DEF*) calloc(settings->ChannelDefArraySize,
sizeof(CHANNEL_DEF));
if (!_settings->ChannelDefArray)
goto out_fail;
CopyMemory(_settings->ChannelDefArray, settings->ChannelDefArray,
sizeof(CHANNEL_DEF) * settings->ChannelDefArraySize);
}
else
_settings->ChannelDefArray = NULL;
_settings->MonitorCount = settings->MonitorCount;
_settings->MonitorDefArraySize = settings->MonitorDefArraySize;
if (_settings->MonitorDefArraySize > 0)
{
_settings->MonitorDefArray = (rdpMonitor*) calloc(settings->MonitorDefArraySize,
sizeof(rdpMonitor));
if (!_settings->MonitorDefArray)
goto out_fail;
CopyMemory(_settings->MonitorDefArray, settings->MonitorDefArray,
sizeof(rdpMonitor) * settings->MonitorDefArraySize);
}
else
_settings->MonitorDefArray = NULL;
_settings->MonitorIds = (UINT32*) calloc(16, sizeof(UINT32));
if (!_settings->MonitorIds)
goto out_fail;
CopyMemory(_settings->MonitorIds, settings->MonitorIds, 16 * sizeof(UINT32));
_settings->ReceivedCapabilities = malloc(32);
if (!_settings->ReceivedCapabilities)
goto out_fail;
_settings->OrderSupport = malloc(32);
if (!_settings->OrderSupport)
goto out_fail;
if (!_settings->ReceivedCapabilities || !_settings->OrderSupport)
goto out_fail;
CopyMemory(_settings->ReceivedCapabilities, settings->ReceivedCapabilities, 32);
CopyMemory(_settings->OrderSupport, settings->OrderSupport, 32);
_settings->ClientHostname = _strdup(settings->ClientHostname);
if (!_settings->ClientHostname)
goto out_fail;
_settings->ClientProductId = _strdup(settings->ClientProductId);
if (!_settings->ClientProductId)
goto out_fail;
_settings->BitmapCacheV2CellInfo = (BITMAP_CACHE_V2_CELL_INFO*) malloc(sizeof(
BITMAP_CACHE_V2_CELL_INFO) * 6);
if (!_settings->BitmapCacheV2CellInfo)
goto out_fail;
CopyMemory(_settings->BitmapCacheV2CellInfo, settings->BitmapCacheV2CellInfo,
sizeof(BITMAP_CACHE_V2_CELL_INFO) * 6);
_settings->GlyphCache = malloc(sizeof(GLYPH_CACHE_DEFINITION) * 10);
if (!_settings->GlyphCache)
goto out_fail;
_settings->FragCache = malloc(sizeof(GLYPH_CACHE_DEFINITION));
if (!_settings->FragCache)
goto out_fail;
CopyMemory(_settings->GlyphCache, settings->GlyphCache,
sizeof(GLYPH_CACHE_DEFINITION) * 10);
CopyMemory(_settings->FragCache, settings->FragCache,
sizeof(GLYPH_CACHE_DEFINITION));
_settings->ClientAutoReconnectCookie = (ARC_CS_PRIVATE_PACKET*) malloc(sizeof(
ARC_CS_PRIVATE_PACKET));
if (!_settings->ClientAutoReconnectCookie)
goto out_fail;
_settings->ServerAutoReconnectCookie = (ARC_SC_PRIVATE_PACKET*) malloc(sizeof(
ARC_SC_PRIVATE_PACKET));
if (!_settings->ServerAutoReconnectCookie)
goto out_fail;
CopyMemory(_settings->ClientAutoReconnectCookie,
settings->ClientAutoReconnectCookie, sizeof(ARC_CS_PRIVATE_PACKET));
CopyMemory(_settings->ServerAutoReconnectCookie,
settings->ServerAutoReconnectCookie, sizeof(ARC_SC_PRIVATE_PACKET));
_settings->ClientTimeZone = (LPTIME_ZONE_INFORMATION) malloc(sizeof(
TIME_ZONE_INFORMATION));
if (!_settings->ClientTimeZone)
goto out_fail;
CopyMemory(_settings->ClientTimeZone, settings->ClientTimeZone,
sizeof(TIME_ZONE_INFORMATION));
_settings->TargetNetAddressCount = settings->TargetNetAddressCount;
if (settings->TargetNetAddressCount > 0)
{
_settings->TargetNetAddresses = (char**) calloc(settings->TargetNetAddressCount,
sizeof(char*));
if (!_settings->TargetNetAddresses)
{
_settings->TargetNetAddressCount = 0;
goto out_fail;
}
for (index = 0; index < settings->TargetNetAddressCount; index++)
{
_settings->TargetNetAddresses[index] = _strdup(
settings->TargetNetAddresses[index]);
if (!_settings->TargetNetAddresses[index])
{
while (index)
free(_settings->TargetNetAddresses[--index]);
free(_settings->TargetNetAddresses);
_settings->TargetNetAddresses = NULL;
_settings->TargetNetAddressCount = 0;
goto out_fail;
}
}
if (settings->TargetNetPorts)
{
_settings->TargetNetPorts = (UINT32*) calloc(settings->TargetNetAddressCount,
sizeof(UINT32));
if (!_settings->TargetNetPorts)
goto out_fail;
for (index = 0; index < settings->TargetNetAddressCount; index++)
_settings->TargetNetPorts[index] = settings->TargetNetPorts[index];
}
}
_settings->DeviceCount = settings->DeviceCount;
_settings->DeviceArraySize = settings->DeviceArraySize;
_settings->DeviceArray = (RDPDR_DEVICE**) calloc(_settings->DeviceArraySize,
sizeof(RDPDR_DEVICE*));
if (!_settings->DeviceArray && _settings->DeviceArraySize)
{
_settings->DeviceCount = 0;
_settings->DeviceArraySize = 0;
goto out_fail;
}
if (_settings->DeviceArraySize < _settings->DeviceCount)
{
_settings->DeviceCount = 0;
_settings->DeviceArraySize = 0;
goto out_fail;
}
for (index = 0; index < _settings->DeviceCount; index++)
{
_settings->DeviceArray[index] = freerdp_device_clone(
settings->DeviceArray[index]);
if (!_settings->DeviceArray[index])
goto out_fail;
}
_settings->StaticChannelCount = settings->StaticChannelCount;
_settings->StaticChannelArraySize = settings->StaticChannelArraySize;
_settings->StaticChannelArray = (ADDIN_ARGV**) calloc(
_settings->StaticChannelArraySize, sizeof(ADDIN_ARGV*));
if (!_settings->StaticChannelArray && _settings->StaticChannelArraySize)
{
_settings->StaticChannelArraySize = 0;
_settings->ChannelCount = 0;
goto out_fail;
}
if (_settings->StaticChannelArraySize < _settings->StaticChannelCount)
{
_settings->StaticChannelArraySize = 0;
_settings->ChannelCount = 0;
goto out_fail;
}
for (index = 0; index < _settings->StaticChannelCount; index++)
{
_settings->StaticChannelArray[index] = freerdp_static_channel_clone(
settings->StaticChannelArray[index]);
if (!_settings->StaticChannelArray[index])
goto out_fail;
}
_settings->DynamicChannelCount = settings->DynamicChannelCount;
_settings->DynamicChannelArraySize = settings->DynamicChannelArraySize;
_settings->DynamicChannelArray = (ADDIN_ARGV**) calloc(
_settings->DynamicChannelArraySize, sizeof(ADDIN_ARGV*));
if (!_settings->DynamicChannelArray && _settings->DynamicChannelArraySize)
{
_settings->DynamicChannelCount = 0;
_settings->DynamicChannelArraySize = 0;
goto out_fail;
}
if (_settings->DynamicChannelArraySize < _settings->DynamicChannelCount)
{
_settings->DynamicChannelCount = 0;
_settings->DynamicChannelArraySize = 0;
goto out_fail;
}
for (index = 0; index < _settings->DynamicChannelCount; index++)
{
_settings->DynamicChannelArray[index] = freerdp_dynamic_channel_clone(
settings->DynamicChannelArray[index]);
if (!_settings->DynamicChannelArray[index])
goto out_fail;
}
_settings->SettingsModified = (BYTE*) calloc(1, sizeof(rdpSettings) / 8);
if (!_settings->SettingsModified)
goto out_fail;
}
return _settings;
out_fail:
/* In case any memory allocation failed during clone, some bytes might leak.
*
* freerdp_settings_free can't be reliable used at this point since it could
* free memory of pointers copied by CopyMemory and detecting and freeing
* each allocation separately is quite painful.
*/
free(_settings);
return NULL;
}
void freerdp_settings_free(rdpSettings* settings)
{
if (!settings)
return;
free(settings->ServerHostname);
free(settings->Username);
free(settings->Password);
free(settings->Domain);
free(settings->PasswordHash);
free(settings->AcceptedCert);
free(settings->AlternateShell);
free(settings->ShellWorkingDirectory);
free(settings->ComputerName);
free(settings->ChannelDefArray);
free(settings->MonitorDefArray);
free(settings->MonitorIds);
free(settings->ClientAddress);
free(settings->ClientDir);
free(settings->AllowedTlsCiphers);
free(settings->NtlmSamFile);
free(settings->CertificateFile);
free(settings->PrivateKeyFile);
free(settings->ConnectionFile);
free(settings->AssistanceFile);
free(settings->ReceivedCapabilities);
free(settings->OrderSupport);
free(settings->ClientHostname);
free(settings->ClientProductId);
free(settings->ServerRandom);
free(settings->ClientRandom);
free(settings->ServerCertificate);
free(settings->RdpKeyFile);
certificate_free(settings->RdpServerCertificate);
free(settings->CertificateContent);
free(settings->PrivateKeyContent);
free(settings->RdpKeyContent);
free(settings->ClientAutoReconnectCookie);
free(settings->ServerAutoReconnectCookie);
free(settings->ClientTimeZone);
free(settings->BitmapCacheV2CellInfo);
free(settings->GlyphCache);
free(settings->FragCache);
key_free(settings->RdpServerRsaKey);
free(settings->ConfigPath);
free(settings->CurrentPath);
free(settings->HomePath);
free(settings->LoadBalanceInfo);
free(settings->TargetNetAddress);
free(settings->RedirectionTargetFQDN);
free(settings->RedirectionTargetNetBiosName);
free(settings->RedirectionUsername);
free(settings->RedirectionDomain);
free(settings->RedirectionPassword);
free(settings->RedirectionTsvUrl);
free(settings->RedirectionAcceptedCert);
free(settings->RemoteAssistanceSessionId);
free(settings->RemoteAssistancePassword);
free(settings->RemoteAssistancePassStub);
free(settings->RemoteAssistanceRCTicket);
free(settings->AuthenticationServiceClass);
free(settings->GatewayHostname);
free(settings->GatewayUsername);
free(settings->GatewayPassword);
free(settings->GatewayDomain);
free(settings->GatewayAccessToken);
free(settings->GatewayAcceptedCert);
free(settings->CertificateName);
free(settings->DynamicDSTTimeZoneKeyName);
free(settings->PreconnectionBlob);
free(settings->KerberosKdc);
free(settings->KerberosRealm);
free(settings->DumpRemoteFxFile);
free(settings->PlayRemoteFxFile);
free(settings->RemoteApplicationName);
free(settings->RemoteApplicationIcon);
free(settings->RemoteApplicationProgram);
free(settings->RemoteApplicationFile);
free(settings->RemoteApplicationGuid);
free(settings->RemoteApplicationCmdLine);
free(settings->ImeFileName);
free(settings->DrivesToRedirect);
free(settings->WindowTitle);
free(settings->WmClass);
free(settings->ActionScript);
freerdp_target_net_addresses_free(settings);
freerdp_device_collection_free(settings);
freerdp_static_channel_collection_free(settings);
freerdp_dynamic_channel_collection_free(settings);
free(settings->SettingsModified);
free(settings);
}
#ifdef _WIN32
#pragma warning(pop)
#endif
|
Java
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML
><HEAD
><TITLE
>dblink_cancel_query</TITLE
><META
NAME="GENERATOR"
CONTENT="Modular DocBook HTML Stylesheet Version 1.79"><LINK
REV="MADE"
HREF="mailto:pgsql-docs@postgresql.org"><LINK
REL="HOME"
TITLE="PostgreSQL 9.2.8 Documentation"
HREF="index.html"><LINK
REL="UP"
TITLE="dblink"
HREF="dblink.html"><LINK
REL="PREVIOUS"
TITLE="dblink_get_result"
HREF="contrib-dblink-get-result.html"><LINK
REL="NEXT"
TITLE="dblink_get_pkey"
HREF="contrib-dblink-get-pkey.html"><LINK
REL="STYLESHEET"
TYPE="text/css"
HREF="stylesheet.css"><META
HTTP-EQUIV="Content-Type"
CONTENT="text/html; charset=ISO-8859-1"><META
NAME="creation"
CONTENT="2014-03-17T19:46:29"></HEAD
><BODY
CLASS="REFENTRY"
><DIV
CLASS="NAVHEADER"
><TABLE
SUMMARY="Header navigation table"
WIDTH="100%"
BORDER="0"
CELLPADDING="0"
CELLSPACING="0"
><TR
><TH
COLSPAN="5"
ALIGN="center"
VALIGN="bottom"
><A
HREF="index.html"
>PostgreSQL 9.2.8 Documentation</A
></TH
></TR
><TR
><TD
WIDTH="10%"
ALIGN="left"
VALIGN="top"
><A
TITLE="dblink_get_result"
HREF="contrib-dblink-get-result.html"
ACCESSKEY="P"
>Prev</A
></TD
><TD
WIDTH="10%"
ALIGN="left"
VALIGN="top"
><A
HREF="dblink.html"
ACCESSKEY="U"
>Up</A
></TD
><TD
WIDTH="60%"
ALIGN="center"
VALIGN="bottom"
></TD
><TD
WIDTH="20%"
ALIGN="right"
VALIGN="top"
><A
TITLE="dblink_get_pkey"
HREF="contrib-dblink-get-pkey.html"
ACCESSKEY="N"
>Next</A
></TD
></TR
></TABLE
><HR
ALIGN="LEFT"
WIDTH="100%"></DIV
><H1
><A
NAME="CONTRIB-DBLINK-CANCEL-QUERY"
></A
>dblink_cancel_query</H1
><DIV
CLASS="REFNAMEDIV"
><A
NAME="AEN142312"
></A
><H2
>Name</H2
>dblink_cancel_query -- cancels any active query on the named connection</DIV
><DIV
CLASS="REFSYNOPSISDIV"
><A
NAME="AEN142315"
></A
><H2
>Synopsis</H2
><PRE
CLASS="SYNOPSIS"
>dblink_cancel_query(text connname) returns text</PRE
></DIV
><DIV
CLASS="REFSECT1"
><A
NAME="AEN142317"
></A
><H2
>Description</H2
><P
> <CODE
CLASS="FUNCTION"
>dblink_cancel_query</CODE
> attempts to cancel any query that
is in progress on the named connection. Note that this is not
certain to succeed (since, for example, the remote query might
already have finished). A cancel request simply improves the
odds that the query will fail soon. You must still complete the
normal query protocol, for example by calling
<CODE
CLASS="FUNCTION"
>dblink_get_result</CODE
>.
</P
></DIV
><DIV
CLASS="REFSECT1"
><A
NAME="AEN142322"
></A
><H2
>Arguments</H2
><P
></P
><DIV
CLASS="VARIABLELIST"
><DL
><DT
><TT
CLASS="PARAMETER"
>conname</TT
></DT
><DD
><P
> Name of the connection to use.
</P
></DD
></DL
></DIV
></DIV
><DIV
CLASS="REFSECT1"
><A
NAME="AEN142330"
></A
><H2
>Return Value</H2
><P
> Returns <TT
CLASS="LITERAL"
>OK</TT
> if the cancel request has been sent, or
the text of an error message on failure.
</P
></DIV
><DIV
CLASS="REFSECT1"
><A
NAME="AEN142334"
></A
><H2
>Examples</H2
><PRE
CLASS="PROGRAMLISTING"
>SELECT dblink_cancel_query('dtest1');</PRE
></DIV
><DIV
CLASS="NAVFOOTER"
><HR
ALIGN="LEFT"
WIDTH="100%"><TABLE
SUMMARY="Footer navigation table"
WIDTH="100%"
BORDER="0"
CELLPADDING="0"
CELLSPACING="0"
><TR
><TD
WIDTH="33%"
ALIGN="left"
VALIGN="top"
><A
HREF="contrib-dblink-get-result.html"
ACCESSKEY="P"
>Prev</A
></TD
><TD
WIDTH="34%"
ALIGN="center"
VALIGN="top"
><A
HREF="index.html"
ACCESSKEY="H"
>Home</A
></TD
><TD
WIDTH="33%"
ALIGN="right"
VALIGN="top"
><A
HREF="contrib-dblink-get-pkey.html"
ACCESSKEY="N"
>Next</A
></TD
></TR
><TR
><TD
WIDTH="33%"
ALIGN="left"
VALIGN="top"
>dblink_get_result</TD
><TD
WIDTH="34%"
ALIGN="center"
VALIGN="top"
><A
HREF="dblink.html"
ACCESSKEY="U"
>Up</A
></TD
><TD
WIDTH="33%"
ALIGN="right"
VALIGN="top"
>dblink_get_pkey</TD
></TR
></TABLE
></DIV
></BODY
></HTML
>
|
Java
|
// Copyright (c) 2015-2016 Yuya Ochiai
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import AutoLaunch from 'auto-launch';
import {app} from 'electron';
function shouldQuitApp(cmd) {
if (process.platform !== 'win32') {
return false;
}
const squirrelCommands = ['--squirrel-install', '--squirrel-updated', '--squirrel-uninstall', '--squirrel-obsolete'];
return squirrelCommands.includes(cmd);
}
async function setupAutoLaunch(cmd) {
const appLauncher = new AutoLaunch({
name: app.getName(),
isHidden: true,
});
if (cmd === '--squirrel-uninstall') {
// If we're uninstalling, make sure we also delete our auto launch registry key
await appLauncher.disable();
} else if (cmd === '--squirrel-install' || cmd === '--squirrel-updated') {
// If we're updating and already have an registry entry for auto launch, make sure to update the path
const enabled = await appLauncher.isEnabled();
if (enabled) {
await appLauncher.enable();
}
}
}
export default function squirrelStartup(callback) {
if (process.platform === 'win32') {
const cmd = process.argv[1];
setupAutoLaunch(cmd).then(() => {
if (require('electron-squirrel-startup') && callback) { // eslint-disable-line global-require
callback();
}
});
return shouldQuitApp(cmd);
}
return false;
}
|
Java
|
// Copyright 2018 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.location.suplclient.asn1.supl2.lpp;
// Copyright 2008 Google Inc. All Rights Reserved.
/*
* This class is AUTOMATICALLY GENERATED. Do NOT EDIT.
*/
//
//
import com.google.location.suplclient.asn1.base.Asn1Sequence;
import com.google.location.suplclient.asn1.base.Asn1Tag;
import com.google.location.suplclient.asn1.base.BitStream;
import com.google.location.suplclient.asn1.base.BitStreamReader;
import com.google.location.suplclient.asn1.base.SequenceComponent;
import com.google.common.collect.ImmutableList;
import java.util.Collection;
import javax.annotation.Nullable;
/**
*
*/
public class GNSS_RealTimeIntegrityReq extends Asn1Sequence {
//
private static final Asn1Tag TAG_GNSS_RealTimeIntegrityReq
= Asn1Tag.fromClassAndNumber(-1, -1);
public GNSS_RealTimeIntegrityReq() {
super();
}
@Override
@Nullable
protected Asn1Tag getTag() {
return TAG_GNSS_RealTimeIntegrityReq;
}
@Override
protected boolean isTagImplicit() {
return true;
}
public static Collection<Asn1Tag> getPossibleFirstTags() {
if (TAG_GNSS_RealTimeIntegrityReq != null) {
return ImmutableList.of(TAG_GNSS_RealTimeIntegrityReq);
} else {
return Asn1Sequence.getPossibleFirstTags();
}
}
/**
* Creates a new GNSS_RealTimeIntegrityReq from encoded stream.
*/
public static GNSS_RealTimeIntegrityReq fromPerUnaligned(byte[] encodedBytes) {
GNSS_RealTimeIntegrityReq result = new GNSS_RealTimeIntegrityReq();
result.decodePerUnaligned(new BitStreamReader(encodedBytes));
return result;
}
/**
* Creates a new GNSS_RealTimeIntegrityReq from encoded stream.
*/
public static GNSS_RealTimeIntegrityReq fromPerAligned(byte[] encodedBytes) {
GNSS_RealTimeIntegrityReq result = new GNSS_RealTimeIntegrityReq();
result.decodePerAligned(new BitStreamReader(encodedBytes));
return result;
}
@Override protected boolean isExtensible() {
return true;
}
@Override public boolean containsExtensionValues() {
for (SequenceComponent extensionComponent : getExtensionComponents()) {
if (extensionComponent.isExplicitlySet()) return true;
}
return false;
}
@Override public Iterable<? extends SequenceComponent> getComponents() {
ImmutableList.Builder<SequenceComponent> builder = ImmutableList.builder();
return builder.build();
}
@Override public Iterable<? extends SequenceComponent>
getExtensionComponents() {
ImmutableList.Builder<SequenceComponent> builder = ImmutableList.builder();
return builder.build();
}
@Override public Iterable<BitStream> encodePerUnaligned() {
return super.encodePerUnaligned();
}
@Override public Iterable<BitStream> encodePerAligned() {
return super.encodePerAligned();
}
@Override public void decodePerUnaligned(BitStreamReader reader) {
super.decodePerUnaligned(reader);
}
@Override public void decodePerAligned(BitStreamReader reader) {
super.decodePerAligned(reader);
}
@Override public String toString() {
return toIndentedString("");
}
public String toIndentedString(String indent) {
StringBuilder builder = new StringBuilder();
builder.append("GNSS_RealTimeIntegrityReq = {\n");
final String internalIndent = indent + " ";
for (SequenceComponent component : getComponents()) {
if (component.isExplicitlySet()) {
builder.append(internalIndent)
.append(component.toIndentedString(internalIndent));
}
}
if (isExtensible()) {
builder.append(internalIndent).append("...\n");
for (SequenceComponent component : getExtensionComponents()) {
if (component.isExplicitlySet()) {
builder.append(internalIndent)
.append(component.toIndentedString(internalIndent));
}
}
}
builder.append(indent).append("};\n");
return builder.toString();
}
}
|
Java
|
/*
* 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 modelo.formularios;
import controlador.dbConnection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;
/**
*
* @author Eisner López Acevedo <eisner.lopez at gmail.com>
*/
public class Interfaz_Factura {
private final dbConnection myLink = new dbConnection();
private final Connection conexion = dbConnection.getConnection();
private String querySQL = "";
ResultSet rs = null;
PreparedStatement pst = null;
public boolean mostrarFactura(String Buscar) {
String[] registro = new String[8];
querySQL
= "SELECT `factura_cabina`.`factura_id`, "
+ "`factura_cabina`.`cant_dia`, "
+ "`factura_cabina`.`fecha`, "
+ "`factura_cabina`.`impuesto_cabina`, "
+ "`factura_cabina`.`precio_total_cabina`, "
+ "`factura_cabina`.`cabina_cabina_id`, "
+ "`factura_cabina`.`colaborador_empleado_id`, "
+ "`factura_cabina`.`numero_factura`"
+ "FROM `pct3`.`factura_cabina`"
+ "WHERE "
+ "`factura_cabina`.`numero_factura` = '" + Buscar + "'"
+ "order by `factura_cabina`.`numero_factura`;";
try {
Statement st = conexion.createStatement();
rs = st.executeQuery(querySQL);
while (rs.next()) {
registro[0] = rs.getString(1);
registro[1] = rs.getString(2);
registro[2] = rs.getString(3);
registro[3] = rs.getString(4);
registro[4] = rs.getString(5);
registro[5] = rs.getString(6);
registro[6] = rs.getString(7);
registro[7] = rs.getString(8);
}
} catch (SQLException sqle) {
JOptionPane.showConfirmDialog(null, sqle);
}
return false;
}
}
|
Java
|
// ***************************************************************************
// * Copyright 2014 Joseph Molnar
// *
// * 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.talvish.tales.samples.userclient;
import java.time.LocalDate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.talvish.tales.businessobjects.ObjectId;
import com.talvish.tales.client.http.ResourceClient;
import com.talvish.tales.client.http.ResourceConfiguration;
import com.talvish.tales.client.http.ResourceMethod;
import com.talvish.tales.client.http.ResourceResult;
import com.talvish.tales.communication.HttpVerb;
import com.talvish.tales.parts.ArgumentParser;
import com.talvish.tales.system.configuration.ConfigurationManager;
import com.talvish.tales.system.configuration.MapSource;
import com.talvish.tales.system.configuration.PropertyFileSource;
/**
* The client for talking to the UserService.
* @author jmolnar
*
*/
public class UserClient extends ResourceClient {
private static final Logger logger = LoggerFactory.getLogger( UserClient.class );
/**
* This main is really just to demonstrate calling and would not exist in an actual client.
*/
public static void main( String[ ] theArgs ) throws Exception {
// get the configuration system up and running
ConfigurationManager configurationManager = new ConfigurationManager( );
// we prepare two sources for configurations
// first the command line source
configurationManager.addSource( new MapSource( "command-line", ArgumentParser.parse( theArgs ) ) );
// second the file source, if the command-line indicates a file is to be used
String filename = configurationManager.getStringValue( "settings.file", null ); // we will store config in a file ideally
if( !Strings.isNullOrEmpty( filename ) ) {
configurationManager.addSource( new PropertyFileSource( filename ) );
}
UserClient client = new UserClient( configurationManager.getValues( "user_service", ResourceConfiguration.class ), "sample_user_client/1.0" );
// client.setHeaderOverride( "Authorization", "random" ); //<= for testing, perhaps want to override this value, assuming server allows overrides
// next we see what mode we are in, setup or not setup
String operation = configurationManager.getStringValue( "operation", "update_user" );
ResourceResult<User> result;
switch( operation ) {
case "update_user":
result = client.getUser( new ObjectId( 1, 1, 100 ) );
if( result.getResult() != null ) {
logger.debug( "Found user: '{}'/'{}'", result.getResult().getId(), result.getResult().getFirstName( ) );
result.getResult().setFirstName( "Bilbo" );
result.getResult().getAliases( ).add( "billy" );
result.getResult().getSettings().put( "favourite_category", "games" );
result = client.updateUser( result.getResult() );
logger.debug( "Updated user: '{}'", result.getResult().getFirstName( ) );
} else {
logger.debug( "Did not find user." );
}
break;
case "create_user":
//for( int i = 0; i < 1; i += 1 ) {
User user = new User( );
user.setFirstName( "Jimmy" );
user.setMiddleName( "Scott" );
user.setLastName( "McWhalter" );
user.setBirthdate( LocalDate.of( 1992, 1, 31 ) );
user.getAliases().add( "alias1" );
result = client.createUser( user );
if( result.getResult() != null ) {
logger.debug( "Created user: '{}'/'{}'", result.getResult().getId(), result.getResult().getFirstName( ) );
} else {
logger.debug( "Did not create user." );
}
//}
break;
default:
break;
}
// TODO: this doesn't exit at the end of the main here, need to understand why
// (which is why I added the System.exit(0)
// TODO: one time when this ran it throw some form of SSL EOF related error that
// I need to track down (this happened on the server too)
System.console().writer().print( "Please <Enter> to quit ..." );
System.console().writer().flush();
System.console().readLine();
System.exit( 0 );
}
private String authToken = "Sample key=\"42349840984\"";
/**
* The constructor used to create the client.
* @param theConfiguration the configuration needed to talk to the service
* @param theUserAgent the user agent to use while talking to the service
*/
public UserClient( ResourceConfiguration theConfiguration, String theUserAgent ) {
super( theConfiguration, "/user", "20140124", theUserAgent );
// we now define the methods that we are going to expose for calling
this.methods = new ResourceMethod[ 3 ];
this.methods[ 0 ] = this.defineMethod( "get_user", User.class, HttpVerb.GET, "users/{id}" )
.definePathParameter("id", ObjectId.class )
.defineHeaderParameter( "Authorization", String.class );
this.methods[ 1 ] = this.defineMethod( "update_user", User.class, HttpVerb.POST, "users/{id}/update" )
.definePathParameter( "id", ObjectId.class )
.defineBodyParameter( "user", User.class )
.defineHeaderParameter( "Authorization", String.class );
this.methods[ 2 ] = this.defineMethod( "create_user", User.class, HttpVerb.POST, "users/create" )
.defineBodyParameter( "user", User.class )
.defineHeaderParameter( "Authorization", String.class );
}
/**
* Requests a particular user.
* @param theUserId the id of the user being requested
* @return the requested user, if found, null otherwise
* @throws InterruptedException thrown if the calling thread is interrupted
*/
public ResourceResult<User> getUser( ObjectId theUserId ) throws InterruptedException {
Preconditions.checkNotNull( theUserId, "need a user id to retrieve a user" );
return this.createRequest( this.methods[ 0 ], theUserId )
.setHeaderParameter( "Authorization", this.authToken )
.call();
}
/**
* A call to save the values of a user on the server.
* @param theUser the user to save
* @return the server returned version of the saved user
* @throws InterruptedException thrown if the calling thread is interrupted
*/
public ResourceResult<User> updateUser( User theUser ) throws InterruptedException {
Preconditions.checkNotNull( theUser, "need a user to be able to update" );
return this.createRequest( this.methods[ 1 ], theUser.getId() )
.setBodyParameter( "user", theUser )
.setHeaderParameter( "Authorization", this.authToken )
.call();
}
/**
* A call to create a new user
* @param theFirstName the first name of the user
* @param theLastName the last name of the user
* @return the freshly created user
* @throws InterruptedException thrown if the calling thread is interrupted
*/
public ResourceResult<User> createUser( User theUser) throws InterruptedException {
Preconditions.checkNotNull( theUser, "need a user" );
Preconditions.checkArgument( theUser.getId( ) == null, "user's id must be null" );
Preconditions.checkArgument( !Strings.isNullOrEmpty( theUser.getFirstName() ), "to create a user you need a first name" );
return this.createRequest( this.methods[ 2 ] )
.setBodyParameter( "user", theUser )
.setHeaderParameter( "Authorization", this.authToken )
.call();
}
}
|
Java
|
# Makefile for Tutorials
#
SHELL := /bin/bash
# You can set these variables from the command line.
TUTORIAL_OUTPUT_DIR = build
ALLENNLP_WEBSITE_DIR = ../allennlp-website
.PHONY: help
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " build to clean and build all the tutorials"
@echo " clean to wipe out the build directory"
@echo " getting-started to build the getting-started tutorials"
@echo " notebooks to build the jupyter notebook tutorials"
.PHONY: clean
clean:
@echo "Cleaning out the build directory"
@rm -rf $(TUTORIAL_OUTPUT_DIR)
.PHONY: getting-started
getting-started:
@echo "Building the getting-started tutorials"
@mkdir -p $(TUTORIAL_OUTPUT_DIR)
@cp -r getting_started/*.md $(TUTORIAL_OUTPUT_DIR)/
.PHONY: notebooks
notebooks:
@echo "Building the jupyter notebooks tutorials"
@mkdir -p $(TUTORIAL_OUTPUT_DIR)
@for file in notebooks/*.ipynb; do jupyter nbconvert --to markdown "$$file" --output-dir $(TUTORIAL_OUTPUT_DIR); done
.PHONY: hyphenate
hyphenate:
@echo "Hyphenating"
@for f in build/*.md; do if [[ $$f == *"_"* ]]; then mv "$$f" "$${f//_/-}"; fi; done
.PHONY: copy
copy:
@echo "Copying from $(TUTORIAL_OUTPUT_DIR) to $(ALLENNLP_WEBSITE_DIR)"
@cp -r $(TUTORIAL_OUTPUT_DIR) $(ALLENNLP_WEBSITE_DIR)/tutorials
.PHONY: build
build:
@make clean
@make getting-started
@make notebooks
@make hyphenate
@echo "Build finished. The md pages are in $(TUTORIAL_OUTPUT_DIR)."
|
Java
|
#! /bin/bash
# Runs the linters against dendrite
# The linters can take a lot of resources and are slow, so they can be
# configured using two environment variables:
#
# - `DENDRITE_LINT_CONCURRENCY` - number of concurrent linters to run,
# gometalinter defaults this to 8
# - `DENDRITE_LINT_DISABLE_GC` - if set then the the go gc will be disabled
# when running the linters, speeding them up but using much more memory.
set -eux
cd `dirname $0`/..
export GOPATH="$(pwd):$(pwd)/vendor"
# prefer the versions of gometalinter and the linters that we install
# to anythign that ends up on the PATH.
export PATH="$(pwd)/bin:$PATH"
args=""
if [ ${1:-""} = "fast" ]
then args="--config=linter-fast.json"
else args="--config=linter.json"
fi
if [ -n "${DENDRITE_LINT_CONCURRENCY:-}" ]
then args="$args --concurrency=$DENDRITE_LINT_CONCURRENCY"
fi
if [ -z "${DENDRITE_LINT_DISABLE_GC:-}" ]
then args="$args --enable-gc"
fi
echo "Installing lint search engine..."
gb build github.com/alecthomas/gometalinter/
gometalinter --config=linter.json ./... --install
echo "Looking for lint..."
gometalinter ./... $args
echo "Double checking spelling..."
misspell -error src *.md
|
Java
|
package com.ihtsdo.snomed.model.xml;
import java.sql.Date;
import javax.xml.bind.annotation.XmlRootElement;
import com.google.common.base.Objects;
import com.google.common.primitives.Longs;
import com.ihtsdo.snomed.dto.refset.RefsetDto;
import com.ihtsdo.snomed.model.refset.Refset;
@XmlRootElement(name="refset")
public class RefsetDtoShort {
private long id;
private XmlRefsetConcept concept;
private String publicId;
private String title;
private String description;
private Date created;
private Date lastModified;
private int memberSize;
private String snomedExtension;
private String snomedReleaseDate;
private boolean pendingChanges;
public RefsetDtoShort(Refset r){
setId(r.getId());
setConcept(new XmlRefsetConcept(r.getRefsetConcept()));
setPublicId(r.getPublicId());
setTitle(r.getTitle());
setDescription(r.getDescription());
setCreated(r.getCreationTime());
setLastModified(r.getModificationTime());
setPendingChanges(r.isPendingChanges());
setMemberSize(r.getMemberSize());
setSnomedExtension(r.getOntologyVersion().getFlavour().getPublicId());
setSnomedReleaseDate(RefsetDto.dateFormat.format(r.getOntologyVersion().getTaggedOn()));
}
public RefsetDtoShort(){}
@Override
public String toString() {
return Objects.toStringHelper(this)
.add("id", getId())
.add("concept", getConcept())
.add("publicId", getPublicId())
.add("title", getTitle())
.add("description", getDescription())
.add("created", getCreated())
.add("lastModified", getLastModified())
.add("pendingChanges", isPendingChanges())
.add("memberSize", getMemberSize())
.add("snomedExtension", getSnomedExtension())
.add("snomedReleaseDate", getSnomedReleaseDate())
.toString();
}
@Override
public int hashCode(){
return Longs.hashCode(getId());
}
@Override
public boolean equals(Object o){
if (o instanceof RefsetDtoShort){
RefsetDtoShort r = (RefsetDtoShort) o;
if (r.getId() == this.getId()){
return true;
}
}
return false;
}
public boolean isPendingChanges() {
return pendingChanges;
}
public void setPendingChanges(boolean pendingChanges) {
this.pendingChanges = pendingChanges;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public XmlRefsetConcept getConcept() {
return concept;
}
public void setConcept(XmlRefsetConcept concept) {
this.concept = concept;
}
public String getPublicId() {
return publicId;
}
public void setPublicId(String publicId) {
this.publicId = publicId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getLastModified() {
return lastModified;
}
public void setLastModified(Date lastModified) {
this.lastModified = lastModified;
}
public int getMemberSize() {
return memberSize;
}
public void setMemberSize(int memberSize) {
this.memberSize = memberSize;
}
public String getSnomedExtension() {
return snomedExtension;
}
public void setSnomedExtension(String snomedExtension) {
this.snomedExtension = snomedExtension;
}
public String getSnomedReleaseDate() {
return snomedReleaseDate;
}
public void setSnomedReleaseDate(String snomedReleaseDate) {
this.snomedReleaseDate = snomedReleaseDate;
}
public static RefsetDtoShort parse(Refset r){
return getBuilder(new XmlRefsetConcept(r.getRefsetConcept()),
r.getPublicId(),
r.getTitle(),
r.getDescription(),
r.getCreationTime(),
r.getModificationTime(),
r.isPendingChanges(),
r.getMemberSize(),
r.getOntologyVersion().getFlavour().getPublicId(),
r.getOntologyVersion().getTaggedOn()).build();
}
public static Builder getBuilder(XmlRefsetConcept concept, String publicId, String title,
String description, Date created, Date lastModified, boolean pendingChanges, int memberSize,
String snomedExtension, Date snomedReleaseDate) {
return new Builder(concept, publicId, title, description, created, lastModified, pendingChanges,
memberSize, snomedExtension, snomedReleaseDate);
}
public static class Builder {
private RefsetDtoShort built;
Builder(XmlRefsetConcept concept, String publicId, String title, String description,
Date created, Date lastModified, boolean pendingChanges, int memberSize,
String snomedExtension, Date snomedReleaseDate){
built = new RefsetDtoShort();
built.concept = concept;
built.publicId = publicId;
built.title = title;
built.description = description;
built.created = created;
built.lastModified = lastModified;
built.pendingChanges = pendingChanges;
built.memberSize = memberSize;
built.setSnomedExtension(snomedExtension);
built.setSnomedReleaseDate(RefsetDto.dateFormat.format(snomedReleaseDate));
}
public RefsetDtoShort build() {
return built;
}
}
}
|
Java
|
/*
* %CopyrightBegin%
*
* Copyright Ericsson AB 1998-2016. 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.
*
* %CopyrightEnd%
*/
#ifndef _DB_UTIL_H
#define _DB_UTIL_H
#include "global.h"
#include "erl_message.h"
/*#define HARDDEBUG 1*/
#ifdef DEBUG
/*
** DMC_DEBUG does NOT need DEBUG, but DEBUG needs DMC_DEBUG
*/
#define DMC_DEBUG 1
#endif
/*
* These values can be returned from the functions performing the
* BIF operation for different types of tables. When the
* actual operations have been performed, the BIF function
* checks for negative returns and issues BIF_ERRORS based
* upon these values.
*/
#define DB_ERROR_NONE 0 /* No error */
#define DB_ERROR_BADITEM -1 /* The item was malformed ie no
tuple or to small*/
#define DB_ERROR_BADTABLE -2 /* The Table is inconsisitent */
#define DB_ERROR_SYSRES -3 /* Out of system resources */
#define DB_ERROR_BADKEY -4 /* Returned if a key that should
exist does not. */
#define DB_ERROR_BADPARAM -5 /* Returned if a specified slot does
not exist (hash table only) or
the state parameter in db_match_object
is broken.*/
#define DB_ERROR_UNSPEC -10 /* Unspecified error */
/*#define DEBUG_CLONE*/
/*
* A datatype for a database entry stored out of a process heap
*/
typedef struct db_term {
struct erl_off_heap_header* first_oh; /* Off heap data for term. */
Uint size; /* Heap size of term in "words" */
#ifdef DEBUG_CLONE
Eterm* debug_clone; /* An uncompressed copy */
#endif
Eterm tpl[1]; /* Term data. Top tuple always first */
/* Compression: is_immed and key element are uncompressed.
Compressed elements are stored in external format after each other
last in dbterm. The top tuple elements contains byte offsets, to
the start of the data, tagged as headers.
The allocated size of the dbterm in bytes is stored at tpl[arity+1].
*/
} DbTerm;
union db_table;
typedef union db_table DbTable;
#define DB_MUST_RESIZE 1
#define DB_NEW_OBJECT 2
/* Info about a database entry while it's being updated
* (by update_counter or update_element)
*/
typedef struct {
DbTable* tb;
DbTerm* dbterm;
void** bp; /* {Hash|Tree}DbTerm** */
Uint new_size;
int flags;
void* lck;
} DbUpdateHandle;
typedef struct db_table_method
{
int (*db_create)(Process *p, DbTable* tb);
int (*db_first)(Process* p,
DbTable* tb, /* [in out] */
Eterm* ret /* [out] */);
int (*db_next)(Process* p,
DbTable* tb, /* [in out] */
Eterm key, /* [in] */
Eterm* ret /* [out] */);
int (*db_last)(Process* p,
DbTable* tb, /* [in out] */
Eterm* ret /* [out] */);
int (*db_prev)(Process* p,
DbTable* tb, /* [in out] */
Eterm key,
Eterm* ret);
int (*db_put)(DbTable* tb, /* [in out] */
Eterm obj,
int key_clash_fail); /* DB_ERROR_BADKEY if key exists */
int (*db_get)(Process* p,
DbTable* tb, /* [in out] */
Eterm key,
Eterm* ret);
int (*db_get_element)(Process* p,
DbTable* tb, /* [in out] */
Eterm key,
int index,
Eterm* ret);
int (*db_member)(DbTable* tb, /* [in out] */
Eterm key,
Eterm* ret);
int (*db_erase)(DbTable* tb, /* [in out] */
Eterm key,
Eterm* ret);
int (*db_erase_object)(DbTable* tb, /* [in out] */
Eterm obj,
Eterm* ret);
int (*db_slot)(Process* p,
DbTable* tb, /* [in out] */
Eterm slot,
Eterm* ret);
int (*db_select_chunk)(Process* p,
DbTable* tb, /* [in out] */
Eterm pattern,
Sint chunk_size,
int reverse,
Eterm* ret);
int (*db_select)(Process* p,
DbTable* tb, /* [in out] */
Eterm pattern,
int reverse,
Eterm* ret);
int (*db_select_delete)(Process* p,
DbTable* tb, /* [in out] */
Eterm pattern,
Eterm* ret);
int (*db_select_continue)(Process* p,
DbTable* tb, /* [in out] */
Eterm continuation,
Eterm* ret);
int (*db_select_delete_continue)(Process* p,
DbTable* tb, /* [in out] */
Eterm continuation,
Eterm* ret);
int (*db_select_count)(Process* p,
DbTable* tb, /* [in out] */
Eterm pattern,
Eterm* ret);
int (*db_select_count_continue)(Process* p,
DbTable* tb, /* [in out] */
Eterm continuation,
Eterm* ret);
int (*db_take)(Process *, DbTable *, Eterm, Eterm *);
int (*db_delete_all_objects)(Process* p,
DbTable* db /* [in out] */ );
int (*db_free_table)(DbTable* db /* [in out] */ );
int (*db_free_table_continue)(DbTable* db); /* [in out] */
void (*db_print)(int to,
void* to_arg,
int show,
DbTable* tb /* [in out] */ );
void (*db_foreach_offheap)(DbTable* db, /* [in out] */
void (*func)(ErlOffHeap *, void *),
void *arg);
void (*db_check_table)(DbTable* tb);
/* Lookup a dbterm for updating. Return false if not found. */
int (*db_lookup_dbterm)(Process *, DbTable *, Eterm key, Eterm obj,
DbUpdateHandle* handle);
/* Must be called for each db_lookup_dbterm that returned true, even if
** dbterm was not updated. If the handle was of a new object and cret is
** not DB_ERROR_NONE, the object is removed from the table. */
void (*db_finalize_dbterm)(int cret, DbUpdateHandle* handle);
} DbTableMethod;
typedef struct db_fixation {
Eterm pid;
Uint counter;
struct db_fixation *next;
} DbFixation;
/*
* This structure contains data for all different types of database
* tables. Note that these fields must match the same fields
* in the table-type specific structures.
* The reason it is placed here and not in db.h is that some table
* operations may be the same on different types of tables.
*/
typedef struct db_table_common {
erts_refc_t ref; /* fixation counter */
#ifdef ERTS_SMP
erts_smp_rwmtx_t rwlock; /* rw lock on table */
erts_smp_mtx_t fixlock; /* Protects fixations,megasec,sec,microsec */
int is_thread_safe; /* No fine locking inside table needed */
Uint32 type; /* table type, *read only* after creation */
#endif
Eterm owner; /* Pid of the creator */
Eterm heir; /* Pid of the heir */
UWord heir_data; /* To send in ETS-TRANSFER (is_immed or (DbTerm*) */
Uint64 heir_started_interval; /* To further identify the heir */
Eterm the_name; /* an atom */
Eterm id; /* atom | integer */
DbTableMethod* meth; /* table methods */
erts_smp_atomic_t nitems; /* Total number of items in table */
erts_smp_atomic_t memory_size;/* Total memory size. NOTE: in bytes! */
struct { /* Last fixation time */
ErtsMonotonicTime monotonic;
ErtsMonotonicTime offset;
} time;
DbFixation* fixations; /* List of processes who have done safe_fixtable,
"local" fixations not included. */
/* All 32-bit fields */
Uint32 status; /* bit masks defined below */
int slot; /* slot index in meta_main_tab */
int keypos; /* defaults to 1 */
int compress;
} DbTableCommon;
/* These are status bit patterns */
#define DB_NORMAL (1 << 0)
#define DB_PRIVATE (1 << 1)
#define DB_PROTECTED (1 << 2)
#define DB_PUBLIC (1 << 3)
#define DB_BAG (1 << 4)
#define DB_SET (1 << 5)
/*#define DB_LHASH (1 << 6)*/
#define DB_FINE_LOCKED (1 << 7) /* fine grained locking enabled */
#define DB_DUPLICATE_BAG (1 << 8)
#define DB_ORDERED_SET (1 << 9)
#define DB_DELETE (1 << 10) /* table is being deleted */
#define DB_FREQ_READ (1 << 11)
#define ERTS_ETS_TABLE_TYPES (DB_BAG|DB_SET|DB_DUPLICATE_BAG|DB_ORDERED_SET|DB_FINE_LOCKED|DB_FREQ_READ)
#define IS_HASH_TABLE(Status) (!!((Status) & \
(DB_BAG | DB_SET | DB_DUPLICATE_BAG)))
#define IS_TREE_TABLE(Status) (!!((Status) & \
DB_ORDERED_SET))
#define NFIXED(T) (erts_refc_read(&(T)->common.ref,0))
#define IS_FIXED(T) (NFIXED(T) != 0)
/*
* tplp is an untagged pointer to a tuple we know is large enough
* and dth is a pointer to a DbTableHash.
*/
#define GETKEY(dth, tplp) (*((tplp) + ((DbTableCommon*)(dth))->keypos))
ERTS_GLB_INLINE Eterm db_copy_key(Process* p, DbTable* tb, DbTerm* obj);
Eterm db_copy_from_comp(DbTableCommon* tb, DbTerm* bp, Eterm** hpp,
ErlOffHeap* off_heap);
int db_eq_comp(DbTableCommon* tb, Eterm a, DbTerm* b);
DbTerm* db_alloc_tmp_uncompressed(DbTableCommon* tb, DbTerm* org);
ERTS_GLB_INLINE Eterm db_copy_object_from_ets(DbTableCommon* tb, DbTerm* bp,
Eterm** hpp, ErlOffHeap* off_heap);
ERTS_GLB_INLINE int db_eq(DbTableCommon* tb, Eterm a, DbTerm* b);
Wterm db_do_read_element(DbUpdateHandle* handle, Sint position);
#if ERTS_GLB_INLINE_INCL_FUNC_DEF
ERTS_GLB_INLINE Eterm db_copy_key(Process* p, DbTable* tb, DbTerm* obj)
{
Eterm key = GETKEY(tb, obj->tpl);
if IS_CONST(key) return key;
else {
Uint size = size_object(key);
Eterm* hp = HAlloc(p, size);
Eterm res = copy_struct(key, size, &hp, &MSO(p));
ASSERT(EQ(res,key));
return res;
}
}
ERTS_GLB_INLINE Eterm db_copy_object_from_ets(DbTableCommon* tb, DbTerm* bp,
Eterm** hpp, ErlOffHeap* off_heap)
{
if (tb->compress) {
return db_copy_from_comp(tb, bp, hpp, off_heap);
}
else {
return copy_shallow(bp->tpl, bp->size, hpp, off_heap);
}
}
ERTS_GLB_INLINE int db_eq(DbTableCommon* tb, Eterm a, DbTerm* b)
{
if (!tb->compress) {
return EQ(a, make_tuple(b->tpl));
}
else {
return db_eq_comp(tb, a, b);
}
}
#endif /* ERTS_GLB_INLINE_INCL_FUNC_DEF */
#define DB_READ (DB_PROTECTED|DB_PUBLIC)
#define DB_WRITE DB_PUBLIC
#define DB_INFO (DB_PROTECTED|DB_PUBLIC|DB_PRIVATE)
#define ONLY_WRITER(P,T) (((T)->common.status & (DB_PRIVATE|DB_PROTECTED)) \
&& (T)->common.owner == (P)->common.id)
#define ONLY_READER(P,T) (((T)->common.status & DB_PRIVATE) && \
(T)->common.owner == (P)->common.id)
/* Function prototypes */
BIF_RETTYPE db_get_trace_control_word(Process* p);
BIF_RETTYPE db_set_trace_control_word(Process* p, Eterm tcw);
BIF_RETTYPE db_get_trace_control_word_0(BIF_ALIST_0);
BIF_RETTYPE db_set_trace_control_word_1(BIF_ALIST_1);
void db_initialize_util(void);
Eterm db_getkey(int keypos, Eterm obj);
void db_cleanup_offheap_comp(DbTerm* p);
void db_free_term(DbTable *tb, void* basep, Uint offset);
void* db_store_term(DbTableCommon *tb, DbTerm* old, Uint offset, Eterm obj);
void* db_store_term_comp(DbTableCommon *tb, DbTerm* old, Uint offset, Eterm obj);
Eterm db_copy_element_from_ets(DbTableCommon* tb, Process* p, DbTerm* obj,
Uint pos, Eterm** hpp, Uint extra);
int db_has_map(Eterm obj);
int db_has_variable(Eterm obj);
int db_is_variable(Eterm obj);
void db_do_update_element(DbUpdateHandle* handle,
Sint position,
Eterm newval);
void db_finalize_resize(DbUpdateHandle* handle, Uint offset);
Eterm db_add_counter(Eterm** hpp, Wterm counter, Eterm incr);
Eterm db_match_set_lint(Process *p, Eterm matchexpr, Uint flags);
Binary *db_match_set_compile(Process *p, Eterm matchexpr,
Uint flags);
void erts_db_match_prog_destructor(Binary *);
typedef struct match_prog {
ErlHeapFragment *term_save; /* Only if needed, a list of message
buffers for off heap copies
(i.e. binaries)*/
int single_variable; /* ets:match needs to know this. */
int num_bindings; /* Size of heap */
/* The following two are only filled in when match specs
are used for tracing */
struct erl_heap_fragment *saved_program_buf;
Eterm saved_program;
Uint heap_size; /* size of: heap + eheap + stack */
Uint stack_offset;
#ifdef DMC_DEBUG
UWord* prog_end; /* End of program */
#endif
UWord text[1]; /* Beginning of program */
} MatchProg;
/*
* The heap-eheap-stack block of a MatchProg is nowadays allocated
* when the match program is run.
* - heap: variable bindings
* - eheap: erlang heap storage
* - eheap: a "large enough" stack
*/
#define DMC_ERR_STR_LEN 100
typedef enum { dmcWarning, dmcError} DMCErrorSeverity;
typedef struct dmc_error {
char error_string[DMC_ERR_STR_LEN + 1]; /* printf format string
with %d for the variable
number (if applicable) */
int variable; /* -1 if no variable is referenced
in error string */
struct dmc_error *next;
DMCErrorSeverity severity; /* Error or warning */
} DMCError;
typedef struct dmc_err_info {
unsigned int *var_trans; /* Translations of variable names,
initiated to NULL
and free'd with sys_free if != NULL
after compilation */
int num_trans;
int error_added; /* indicates if the error list contains
any fatal errors (dmcError severity) */
DMCError *first; /* List of errors */
} DMCErrInfo;
/*
** Compilation flags
**
** The dialect is in the 3 least significant bits and are to be interspaced by
** by at least 2 (decimal), thats why ((Uint) 2) isn't used. This is to be
** able to add DBIF_GUARD or DBIF BODY to it to use in the match_spec bif
** table. The rest of the word is used like ordinary flags, one bit for each
** flag. Note that DCOMP_TABLE and DCOMP_TRACE are mutually exclusive.
*/
#define DCOMP_TABLE ((Uint) 1) /* Ets and dets. The body returns a value,
* and the parameter to the execution is a tuple. */
#define DCOMP_TRACE ((Uint) 4) /* Trace. More functions are allowed, and the
* parameter to the execution will be an array. */
#define DCOMP_DIALECT_MASK ((Uint) 0x7) /* To mask out the bits marking
dialect */
#define DCOMP_FAKE_DESTRUCTIVE ((Uint) 8) /* When this is active, no setting of
trace control words or seq_trace tokens will be done. */
/* Allow lock seizing operations on the tracee and 3rd party processes */
#define DCOMP_ALLOW_TRACE_OPS ((Uint) 0x10)
/* This is call trace */
#define DCOMP_CALL_TRACE ((Uint) 0x20)
Binary *db_match_compile(Eterm *matchexpr, Eterm *guards,
Eterm *body, int num_matches,
Uint flags,
DMCErrInfo *err_info);
/* Returns newly allocated MatchProg binary with refc == 0*/
Eterm db_match_dbterm(DbTableCommon* tb, Process* c_p, Binary* bprog,
int all, DbTerm* obj, Eterm** hpp, Uint extra);
Eterm db_prog_match(Process *p, Process *self,
Binary *prog, Eterm term,
Eterm *termp, int arity,
enum erts_pam_run_flags in_flags,
Uint32 *return_flags /* Zeroed on enter */);
/* returns DB_ERROR_NONE if matches, 1 if not matches and some db error on
error. */
DMCErrInfo *db_new_dmc_err_info(void);
/* Returns allocated error info, where errors are collected for lint. */
Eterm db_format_dmc_err_info(Process *p, DMCErrInfo *ei);
/* Formats an error info structure into a list of tuples. */
void db_free_dmc_err_info(DMCErrInfo *ei);
/* Completely free's an error info structure, including all recorded
errors */
Eterm db_make_mp_binary(Process *p, Binary *mp, Eterm **hpp);
/* Convert a match program to a erlang "magic" binary to be returned to userspace,
increments the reference counter. */
int erts_db_is_compiled_ms(Eterm term);
/*
** Convenience when compiling into Binary structures
*/
#define IsMatchProgBinary(BP) \
(((BP)->flags & BIN_FLAG_MAGIC) \
&& ERTS_MAGIC_BIN_DESTRUCTOR((BP)) == erts_db_match_prog_destructor)
#define Binary2MatchProg(BP) \
(ASSERT(IsMatchProgBinary((BP))), \
((MatchProg *) ERTS_MAGIC_BIN_DATA((BP))))
/*
** Debugging
*/
#ifdef HARDDEBUG
void db_check_tables(void); /* in db.c */
#define CHECK_TABLES() db_check_tables()
#else
#define CHECK_TABLES()
#endif
#endif /* _DB_UTIL_H */
|
Java
|
package com.fuyoul.sanwenseller.bean.pickerview;
import java.util.List;
public class ProvinceModel implements IPickerViewData {
private String name;
private List<CityModel> cityList;
@Override
public String getPickerViewText() {
return name;
}
public ProvinceModel() {
super();
}
public ProvinceModel(String name, List<CityModel> cityList) {
super();
this.name = name;
this.cityList = cityList;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<CityModel> getCityList() {
return cityList;
}
public void setCityList(List<CityModel> cityList) {
this.cityList = cityList;
}
@Override
public String toString() {
return "ProvinceModel [name=" + name + ", cityList=" + cityList + "]";
}
}
|
Java
|
var nodes = new vis.DataSet([
/* {id: a, label: b, ...}, */
{id: '192', label: 'VALUE\n13.0', color: '#31b0d5', title: 'Name: VALUE<br>Alias: null<br>Value: 13.0<br>Type: CONSTANT_VALUE<br>Id: 192<br>Formula Expression: Formula String: VALUE; Formula Values: 13.0; Formula Ptg: 13.0; Ptgs: VALUE Index in Ptgs: 0 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@301eda63'},
{id: '193', label: 'VALUE\n9.0', color: '#31b0d5', title: 'Name: VALUE<br>Alias: null<br>Value: 9.0<br>Type: CONSTANT_VALUE<br>Id: 193<br>Formula Expression: Formula String: VALUE; Formula Values: 9.0; Formula Ptg: 9.0; Ptgs: VALUE Index in Ptgs: 1 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@301eda63'},
{id: '194', label: 'VALUE\n5.0', color: '#31b0d5', title: 'Name: VALUE<br>Alias: null<br>Value: 5.0<br>Type: CONSTANT_VALUE<br>Id: 194<br>Formula Expression: Formula String: VALUE; Formula Values: 5.0; Formula Ptg: 5.0; Ptgs: VALUE Index in Ptgs: 2 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@301eda63'},
{id: '195', label: 'VALUE\n7.0', color: '#31b0d5', title: 'Name: VALUE<br>Alias: null<br>Value: 7.0<br>Type: CONSTANT_VALUE<br>Id: 195<br>Formula Expression: Formula String: VALUE; Formula Values: 7.0; Formula Ptg: 7.0; Ptgs: VALUE Index in Ptgs: 3 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@301eda63'},
{id: '196', label: 'VALUE\n12.0', color: '#31b0d5', title: 'Name: VALUE<br>Alias: null<br>Value: 12.0<br>Type: CONSTANT_VALUE<br>Id: 196<br>Formula Expression: Formula String: VALUE; Formula Values: 12.0; Formula Ptg: 12.0; Ptgs: VALUE Index in Ptgs: 4 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@301eda63'},
{id: '197', label: 'VALUE\n5.0', color: '#31b0d5', title: 'Name: VALUE<br>Alias: null<br>Value: 5.0<br>Type: CONSTANT_VALUE<br>Id: 197<br>Formula Expression: Formula String: VALUE; Formula Values: 5.0; Formula Ptg: 5.0; Ptgs: VALUE Index in Ptgs: 5 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@301eda63'},
{id: '198', label: 'VALUE\n46.0', color: '#31b0d5', title: 'Name: VALUE<br>Alias: null<br>Value: 46.0<br>Type: CONSTANT_VALUE<br>Id: 198<br>Formula Expression: Formula String: VALUE; Formula Values: 46.0; Formula Ptg: 46.0; Ptgs: VALUE Index in Ptgs: 6 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@301eda63'},
{id: '199', label: 'VALUE\n85.0', color: '#31b0d5', title: 'Name: VALUE<br>Alias: null<br>Value: 85.0<br>Type: CONSTANT_VALUE<br>Id: 199<br>Formula Expression: Formula String: VALUE; Formula Values: 85.0; Formula Ptg: 85.0; Ptgs: VALUE Index in Ptgs: 7 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@301eda63'},
{id: '200', label: 'VALUE\n15.0', color: '#31b0d5', title: 'Name: VALUE<br>Alias: null<br>Value: 15.0<br>Type: CONSTANT_VALUE<br>Id: 200<br>Formula Expression: Formula String: VALUE; Formula Values: 15.0; Formula Ptg: 15.0; Ptgs: VALUE Index in Ptgs: 8 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@301eda63'},
{id: '201', label: 'VALUE\n159.0', color: '#31b0d5', title: 'Name: VALUE<br>Alias: null<br>Value: 159.0<br>Type: CONSTANT_VALUE<br>Id: 201<br>Formula Expression: Formula String: VALUE; Formula Values: 159.0; Formula Ptg: 159.0; Ptgs: VALUE Index in Ptgs: 9 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@301eda63'},
{id: '202', label: 'VALUE\n452.0', color: '#31b0d5', title: 'Name: VALUE<br>Alias: null<br>Value: 452.0<br>Type: CONSTANT_VALUE<br>Id: 202<br>Formula Expression: Formula String: VALUE; Formula Values: 452.0; Formula Ptg: 452.0; Ptgs: VALUE Index in Ptgs: 10 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@301eda63'},
{id: '203', label: 'VALUE\n452.0', color: '#31b0d5', title: 'Name: VALUE<br>Alias: null<br>Value: 452.0<br>Type: CONSTANT_VALUE<br>Id: 203<br>Formula Expression: Formula String: VALUE; Formula Values: 452.0; Formula Ptg: 452.0; Ptgs: VALUE Index in Ptgs: 11 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@301eda63'},
{id: '204', label: 'VALUE\n365.0', color: '#31b0d5', title: 'Name: VALUE<br>Alias: null<br>Value: 365.0<br>Type: CONSTANT_VALUE<br>Id: 204<br>Formula Expression: Formula String: VALUE; Formula Values: 365.0; Formula Ptg: 365.0; Ptgs: VALUE Index in Ptgs: 12 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@301eda63'},
{id: '205', label: 'VALUE\n36.0', color: '#31b0d5', title: 'Name: VALUE<br>Alias: null<br>Value: 36.0<br>Type: CONSTANT_VALUE<br>Id: 205<br>Formula Expression: Formula String: VALUE; Formula Values: 36.0; Formula Ptg: 36.0; Ptgs: VALUE Index in Ptgs: 13 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@301eda63'},
{id: '206', label: 'VALUE\n362.0', color: '#31b0d5', title: 'Name: VALUE<br>Alias: null<br>Value: 362.0<br>Type: CONSTANT_VALUE<br>Id: 206<br>Formula Expression: Formula String: VALUE; Formula Values: 362.0; Formula Ptg: 362.0; Ptgs: VALUE Index in Ptgs: 14 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@301eda63'},
{id: '207', label: 'VALUE\n23.0', color: '#31b0d5', title: 'Name: VALUE<br>Alias: null<br>Value: 23.0<br>Type: CONSTANT_VALUE<br>Id: 207<br>Formula Expression: Formula String: VALUE; Formula Values: 23.0; Formula Ptg: 23.0; Ptgs: VALUE Index in Ptgs: 15 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@301eda63'},
{id: '208', label: 'VALUE\n236.0', color: '#31b0d5', title: 'Name: VALUE<br>Alias: null<br>Value: 236.0<br>Type: CONSTANT_VALUE<br>Id: 208<br>Formula Expression: Formula String: VALUE; Formula Values: 236.0; Formula Ptg: 236.0; Ptgs: VALUE Index in Ptgs: 16 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@301eda63'},
{id: '209', label: 'VALUE\n562.0', color: '#31b0d5', title: 'Name: VALUE<br>Alias: null<br>Value: 562.0<br>Type: CONSTANT_VALUE<br>Id: 209<br>Formula Expression: Formula String: VALUE; Formula Values: 562.0; Formula Ptg: 562.0; Ptgs: VALUE Index in Ptgs: 17 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@301eda63'},
{id: '210', label: 'VALUE\n45.0', color: '#31b0d5', title: 'Name: VALUE<br>Alias: null<br>Value: 45.0<br>Type: CONSTANT_VALUE<br>Id: 210<br>Formula Expression: Formula String: VALUE; Formula Values: 45.0; Formula Ptg: 45.0; Ptgs: VALUE Index in Ptgs: 18 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@301eda63'},
{id: '211', label: 'VALUE\n125.0', color: '#31b0d5', title: 'Name: VALUE<br>Alias: null<br>Value: 125.0<br>Type: CONSTANT_VALUE<br>Id: 211<br>Formula Expression: Formula String: VALUE; Formula Values: 125.0; Formula Ptg: 125.0; Ptgs: VALUE Index in Ptgs: 19 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@301eda63'},
{id: '212', label: 'VALUE\n23.0', color: '#31b0d5', title: 'Name: VALUE<br>Alias: null<br>Value: 23.0<br>Type: CONSTANT_VALUE<br>Id: 212<br>Formula Expression: Formula String: VALUE; Formula Values: 23.0; Formula Ptg: 23.0; Ptgs: VALUE Index in Ptgs: 20 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@301eda63'},
{id: '213', label: 'CHOOSE\n36.0', color: '#f0ad4e', title: 'Name: CHOOSE<br>Alias: null<br>Value: 36.0<br>Type: FUNCTION<br>Id: 213<br>Formula Expression: Formula String: CHOOSE(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE); Formula Values: CHOOSE(23.0, 125.0, 45.0, 562.0, 236.0, 23.0, 362.0, 36.0, 365.0, 452.0, 452.0, 159.0, 15.0, 85.0, 46.0, 5.0, 12.0, 7.0, 5.0, 9.0, 13.0); Formula Ptg: ; Ptgs: Index in Ptgs: 21 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@301eda63'},
{id: '191', label: 'B2\n36.0', color: '#31b0d5', title: 'Name: B2<br>Alias: null<br>Value: 36.0<br>Type: CELL_WITH_FORMULA<br>Id: 191<br>Formula Expression: Formula String: CHOOSE(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE); Formula Values: CHOOSE(23.0, 125.0, 45.0, 562.0, 236.0, 23.0, 362.0, 36.0, 365.0, 452.0, 452.0, 159.0, 15.0, 85.0, 46.0, 5.0, 12.0, 7.0, 5.0, 9.0, 13.0); Formula Ptg: ; Ptgs: Index in Ptgs: 0 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@301eda63'}
]);
var edges = new vis.DataSet([
/* {from: id_a, to: id_b}, */
{from: '212', to: '213'},
{from: '211', to: '213'},
{from: '210', to: '213'},
{from: '209', to: '213'},
{from: '208', to: '213'},
{from: '207', to: '213'},
{from: '206', to: '213'},
{from: '205', to: '213'},
{from: '204', to: '213'},
{from: '203', to: '213'},
{from: '213', to: '191'},
{from: '202', to: '213'},
{from: '201', to: '213'},
{from: '200', to: '213'},
{from: '199', to: '213'},
{from: '198', to: '213'},
{from: '197', to: '213'},
{from: '196', to: '213'},
{from: '195', to: '213'},
{from: '194', to: '213'},
{from: '193', to: '213'},
{from: '192', to: '213'}
]);
|
Java
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_03) on Mon Nov 19 21:41:27 CET 2007 -->
<TITLE>
Uses of Class org.springframework.core.type.filter.AnnotationTypeFilter (Spring Framework API 2.5)
</TITLE>
<META NAME="date" CONTENT="2007-11-19">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.springframework.core.type.filter.AnnotationTypeFilter (Spring Framework API 2.5)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/springframework/core/type/filter/AnnotationTypeFilter.html" title="class in org.springframework.core.type.filter"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
<a href="http://www.springframework.org/" target="_top">The Spring Framework</a></EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/springframework/core/type/filter/\class-useAnnotationTypeFilter.html" target="_top"><B>FRAMES</B></A>
<A HREF="AnnotationTypeFilter.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.springframework.core.type.filter.AnnotationTypeFilter</B></H2>
</CENTER>
No usage of org.springframework.core.type.filter.AnnotationTypeFilter
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/springframework/core/type/filter/AnnotationTypeFilter.html" title="class in org.springframework.core.type.filter"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
<a href="http://www.springframework.org/" target="_top">The Spring Framework</a></EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/springframework/core/type/filter/\class-useAnnotationTypeFilter.html" target="_top"><B>FRAMES</B></A>
<A HREF="AnnotationTypeFilter.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
<i>Copyright © 2002-2007 <a href=http://www.springframework.org/ target=_top>The Spring Framework</a>.</i>
</BODY>
</HTML>
|
Java
|
/*
* Copyright 2014-2015 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hawkular.metrics.api.jaxrs.handler;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
import static javax.ws.rs.core.MediaType.APPLICATION_XHTML_XML;
import static javax.ws.rs.core.MediaType.TEXT_HTML;
import com.wordnik.swagger.annotations.ApiOperation;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
/**
* @author mwringe
*/
@Path("/")
public class BaseHandler {
public static final String PATH = "/";
@GET
@Produces(APPLICATION_JSON)
@ApiOperation(value = "Returns some basic information about the Hawkular Metrics service.",
response = String.class, responseContainer = "Map")
public Response baseJSON(@Context ServletContext context) {
String version = context.getInitParameter("hawkular.metrics.version");
if (version == null) {
version = "undefined";
}
HawkularMetricsBase hawkularMetrics = new HawkularMetricsBase();
hawkularMetrics.version = version;
return Response.ok(hawkularMetrics).build();
}
@GET
@Produces({APPLICATION_XHTML_XML, TEXT_HTML})
public void baseHTML(@Context ServletContext context) throws Exception {
HttpServletRequest request = ResteasyProviderFactory.getContextData(HttpServletRequest.class);
HttpServletResponse response = ResteasyProviderFactory.getContextData(HttpServletResponse.class);
request.getRequestDispatcher("/static/index.html").forward(request,response);
}
private class HawkularMetricsBase {
String name = "Hawkular-Metrics";
String version;
public String getName() {
return name;
}
public void setVersion(String version) {
this.version = version;
}
public String getVersion() {
return version;
}
}
}
|
Java
|
/*
* 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.
*/
/**
* @author Dennis Ushakov
*/
package javax.accessibility;
import com.gaecompat.javax.swing.text.AttributeSet;
import com.google.code.appengine.awt.Point;
import com.google.code.appengine.awt.Rectangle;
public interface AccessibleText {
static final int CHARACTER = 1;
static final int WORD = 2;
static final int SENTENCE = 3;
int getIndexAtPoint(Point p);
Rectangle getCharacterBounds(int i);
int getCharCount();
int getCaretPosition();
String getAtIndex(int part, int index);
String getAfterIndex(int part, int index);
String getBeforeIndex(int part, int index);
AttributeSet getCharacterAttribute(int i);
int getSelectionStart();
int getSelectionEnd();
String getSelectedText();
}
|
Java
|
/**
* Copyright 2015-2016 Maven Source Dependencies
* Plugin contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.l2x6.srcdeps.core.shell;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import org.l2x6.srcdeps.core.util.SrcdepsCoreUtils;
/**
* A definition of a shell command that can be executed by {@link Shell#execute(ShellCommand)}.
*
* @author <a href="https://github.com/ppalaga">Peter Palaga</a>
*/
public class ShellCommand {
private final List<String> arguments;
private final Map<String, String> environment;
private final String executable;
private final IoRedirects ioRedirects;
private final long timeoutMs;
private final Path workingDirectory;
public ShellCommand(String executable, List<String> arguments, Path workingDirectory,
Map<String, String> environment, IoRedirects ioRedirects, long timeoutMs) {
super();
SrcdepsCoreUtils.assertArgNotNull(executable, "executable");
SrcdepsCoreUtils.assertArgNotNull(arguments, "arguments");
SrcdepsCoreUtils.assertArgNotNull(workingDirectory, "workingDirectory");
SrcdepsCoreUtils.assertArgNotNull(environment, "environment");
SrcdepsCoreUtils.assertArgNotNull(ioRedirects, "ioRedirects");
this.executable = executable;
this.arguments = arguments;
this.workingDirectory = workingDirectory;
this.environment = environment;
this.ioRedirects = ioRedirects;
this.timeoutMs = timeoutMs;
}
/**
* @return an array containing the executable and its arguments that can be passed e.g. to
* {@link ProcessBuilder#command(String...)}
*/
public String[] asCmdArray() {
String[] result = new String[arguments.size() + 1];
int i = 0;
result[i++] = executable;
for (String arg : arguments) {
result[i++] = arg;
}
return result;
}
/**
* @return the {@link List} arguments for the executable. Cannot be {@code null}.
*/
public List<String> getArguments() {
return arguments;
}
/**
* @return a {@link Map} of environment variables that should be used when executing this {@link ShellCommand}.
* Cannot be {@code null}. Note that these are just overlay variables - when a new {@link Process} is
* spawned, the environment is copied from the present process and only the variables the provided by the
* present method are overwritten.
*/
public Map<String, String> getEnvironment() {
return environment;
}
/**
* @return the executable file that should be called
*/
public String getExecutable() {
return executable;
}
/**
* @return the {@link IoRedirects} to use when the {@link Shell} spawns a new {@link Process}
*/
public IoRedirects getIoRedirects() {
return ioRedirects;
}
/**
* @return timeout in milliseconds
*/
public long getTimeoutMs() {
return timeoutMs;
}
/**
* @return the directory in which this {@link ShellCommand} should be executed
*/
public Path getWorkingDirectory() {
return workingDirectory;
}
}
|
Java
|
/*
* Powered By agile
* Web Site: http://www.agile.com
* Since 2008 - 2016
*/
package persistent.prestige.modules.edu.service;
import java.util.Map;
/**
* Organization service类
* @author 雅居乐 2016-9-10 22:28:24
* @version 1.0
*/
public interface OrganizationService{
/**
* 保存信息
* @param datas
* @return
*/
Integer saveOrganization(Map datas);
}
|
Java
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Carrot Cake</title>
<meta name="description" content="ZutatenFür den Kuchen:200 g brauner Zucker180 g Pflanzenöl (200 ml)3 EL fetter Joghurt3 Eier1 TL Vanille-Extrakt oder das Mark einer Schote250g Mehl1 TL Back...">
<link rel="stylesheet" href="/css/main.css">
<link rel="canonical" href="http://clonker.github.io/recipe/secret/2015/09/26/carrot-cake.html">
<link rel="alternate" type="application/rss+xml" title="d'oh" href="http://clonker.github.io/feed.xml" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<header class="site-header">
<div class="wrapper">
<a class="site-title" href="/">d'oh</a>
<nav class="site-nav">
<a href="#" class="menu-icon">
<svg viewBox="0 0 18 15">
<path fill="#424242" d="M18,1.484c0,0.82-0.665,1.484-1.484,1.484H1.484C0.665,2.969,0,2.304,0,1.484l0,0C0,0.665,0.665,0,1.484,0 h15.031C17.335,0,18,0.665,18,1.484L18,1.484z"/>
<path fill="#424242" d="M18,7.516C18,8.335,17.335,9,16.516,9H1.484C0.665,9,0,8.335,0,7.516l0,0c0-0.82,0.665-1.484,1.484-1.484 h15.031C17.335,6.031,18,6.696,18,7.516L18,7.516z"/>
<path fill="#424242" d="M18,13.516C18,14.335,17.335,15,16.516,15H1.484C0.665,15,0,14.335,0,13.516l0,0 c0-0.82,0.665-1.484,1.484-1.484h15.031C17.335,12.031,18,12.696,18,13.516L18,13.516z"/>
</svg>
</a>
<div class="trigger">
<a class="page-link" href="/about/">About</a>
<a class="page-link" href="/slides/">todo</a>
<a class="page-link" href="/test/test.html">Text!</a>
<a class="page-link" href="/phd/todo.html">todo</a>
</div>
</nav>
</div>
</header>
<div class="page-content">
<div class="wrapper">
<div class="hidden" id="hidden"></div>
<script type="text/javascript">
$(document).ready(function() {
var hidden = jQuery('#hidden');
var post = jQuery('#post');
post.contents().appendTo(hidden);
var pwd = prompt("Please enter the password", "");
if(pwd != null && pwd == 'doh') {
hidden.contents().appendTo(post);
} else {
var sloths = [
"https://upload.wikimedia.org/wikipedia/commons/2/25/Sloth1a.jpg",
"http://free4uwallpapers.eu/wp-content/uploads/Funny/funny-sloth-animals-hd-wallpaper.jpg"
];
var item = sloths[Math.floor(Math.random()*sloths.length)];
post.append(jQuery('<h1>Sorry, wrong password.</h1><img src="'+item+'"/>'));
}
})
</script>
<div class="post" id="post">
<header class="post-header">
<h1 class="post-title">Carrot Cake</h1>
<p class="post-meta">Sep 26, 2015</p>
</header>
<article class="post-content">
<h2>Zutaten</h2>
<h3>Für den Kuchen:</h3>
<ul>
<li>200 g brauner Zucker</li>
<li>180 g Pflanzenöl (200 ml)</li>
<li>3 EL fetter Joghurt</li>
<li>3 Eier</li>
<li>1 TL Vanille-Extrakt oder das Mark einer Schote</li>
<li>250g Mehl</li>
<li>1 TL Backpulver (besser: Natron)</li>
<li>2 TL Zimt</li>
<li>1/4 TL Muskatnuss</li>
<li>1/2 TL Salz</li>
<li>260 g geriebene Karotten</li>
<li>150 g Walnüsse</li>
</ul>
<h3>Für das Frosting:</h3>
<ul>
<li>300 g Frischkäse</li>
<li>120 g zimmerwarme Butter</li>
<li>200 g Puderzucker</li>
<li>das Mark einer Vanilleschote</li>
<li>1/2 TL Salz</li>
</ul>
<h2>Zubereitung:</h2>
<p>Braunen Zucker, Salz, Öl, Eier, Vanille, Zimt, Muskat und Joghurt in einer Schüssel verquirlen, bis eine homogene Masse entstanden ist. Mehl und Backpulver langsam unterheben und weiterrühren, bis sich die Zutaten verbunden haben. Karotten schällen und fein raspeln. Ebenfalls unter den Teig heben. Zum Schluss die Walnüsse grob hacken und auch zum Teig geben.</p>
<p>Eine Springform mit Butter ausreiben und leicht mit Zucker bestreuen. Den Teig hineinfüllen und den Kuchen bei 180°C Umluft in einem vorgeheizten Backofen für 37 min backen.</p>
<p>In der Zwischenzeit Frischkäse und Butter cremig aufschlagen und anschließend den Puderzucker unterrühren, bis eine glatte Creme entstanden ist. Mit Vanillemark und etwas Salz abschmecken. Den Kuchen nach 37 Minuten aus dem Ofen nehmen und auskühlen lassen. Das Frosting in die Mitte geben und mit einem Löffel oder einem Spatel vorsichtig kreisförmig </p>
</article>
</div>
</div>
</div>
</body>
</html>
|
Java
|
/**
--| ADAPTIVE RUNTIME PLATFORM |----------------------------------------------------------------------------------------
(C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>.
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 appli-
-cable 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.
Original author:
* Carlos Lozano Diez
<http://github.com/carloslozano>
<http://twitter.com/adaptivecoder>
<mailto:carlos@adaptive.me>
Contributors:
* Ferran Vila Conesa
<http://github.com/fnva>
<http://twitter.com/ferran_vila>
<mailto:ferran.vila.conesa@gmail.com>
* See source code files for contributors.
Release:
* @version v2.2.15
-------------------------------------------| aut inveniam viam aut faciam |--------------------------------------------
*/
using System;
namespace Adaptive.Arp.Api
{
/**
Enumeration IAdaptiveRPGroup
*/
public enum IAdaptiveRPGroup {
Application,
Commerce,
Communication,
Data,
Media,
Notification,
PIM,
Reader,
Security,
Sensor,
Social,
System,
UI,
Util,
Kernel,
Unknown
}
}
|
Java
|
package buchungstool.model.importer;
import org.junit.Test;
import static java.time.LocalDateTime.now;
import static org.assertj.core.api.Assertions.assertThat;
public class KonfigurationEventTest {
@Test
public void test() {
KonfigurationEvent konfigurationEvent = new KonfigurationEvent(now(), now(), "@Konfiguration",
"Max:16\nMin: 4");
assertThat(konfigurationEvent.getMax()).isEqualTo(16);
assertThat(konfigurationEvent.getMin()).isEqualTo(4);
}
}
|
Java
|
/*
*
* * Copyright (c) 2011-2015 EPFL DATA Laboratory
* * Copyright (c) 2014-2015 The Squall Collaboration (see NOTICE)
* *
* * 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 ch.epfl.data.squall.components.dbtoaster;
import backtype.storm.Config;
import backtype.storm.topology.TopologyBuilder;
import ch.epfl.data.squall.components.Component;
import ch.epfl.data.squall.components.JoinerComponent;
import ch.epfl.data.squall.components.AbstractJoinerComponent;
import ch.epfl.data.squall.operators.AggregateStream;
import ch.epfl.data.squall.predicates.Predicate;
import ch.epfl.data.squall.storm_components.StormComponent;
import ch.epfl.data.squall.storm_components.dbtoaster.StormDBToasterJoin;
import ch.epfl.data.squall.storm_components.synchronization.TopologyKiller;
import ch.epfl.data.squall.types.Type;
import ch.epfl.data.squall.utilities.MyUtilities;
import org.apache.log4j.Logger;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class DBToasterJoinComponent extends AbstractJoinerComponent<DBToasterJoinComponent> {
protected DBToasterJoinComponent getThis() {
return this;
}
private static final long serialVersionUID = 1L;
private static Logger LOG = Logger.getLogger(DBToasterJoinComponent.class);
private Map<String, Type[]> _parentNameColTypes;
private Set<String> _parentsWithMultiplicity;
private Map<String, AggregateStream> _parentsWithAggregator;
private String _equivalentSQL;
protected DBToasterJoinComponent(List<Component> relations, Map<String, Type[]> relationTypes,
Set<String> relationsWithMultiplicity, Map<String, AggregateStream> relationsWithAggregator,
String sql, String name) {
super(relations, name);
_parentsWithMultiplicity = relationsWithMultiplicity;
_parentsWithAggregator = relationsWithAggregator;
_parentNameColTypes = relationTypes;
_equivalentSQL = sql;
}
@Override
public void makeBolts(TopologyBuilder builder, TopologyKiller killer,
List<String> allCompNames, Config conf, int hierarchyPosition) {
// by default print out for the last component
// for other conditions, can be set via setPrintOut
if (hierarchyPosition == StormComponent.FINAL_COMPONENT
&& !getPrintOutSet())
setPrintOut(true);
MyUtilities.checkBatchOutput(getBatchOutputMillis(),
getChainOperator().getAggregation(), conf);
setStormEmitter(new StormDBToasterJoin(getParents(), this,
allCompNames,
_parentNameColTypes,
_parentsWithMultiplicity,
_parentsWithAggregator,
hierarchyPosition,
builder, killer, conf));
}
@Override
public DBToasterJoinComponent setJoinPredicate(Predicate predicate) {
throw new UnsupportedOperationException();
}
public String getSQLQuery() {
return _equivalentSQL;
}
}
|
Java
|
[
{
"title": "Ventes véhicules",
"url": "",
"imageUrl": "http://lim.local.inetpsa.com/application/images/service/car2.jpg",
"language": "fr-FR",
"order": "1",
"workplace": "All",
"department": "All",
"categoryPro": "All",
"status": "published",
"children": [
{
"title": "http://portail.inetpsa.com/sites/gpmobile/PublishingImages/car2.jpg",
"url": "http://portail.inetpsa.com/sites/gpmobile/PublishingImages/car2.jpg",
"imageUrl": "http://lim.local.inetpsa.com/application/images/service/car2.jpg",
"language": "fr-FR",
"order": 0,
"workplace": "All",
"department": "All",
"categoryPro": "All",
"status": "published"
},
{
"title": "Ventes véhicules Peugeot",
"url": "https://docinfogroupe.psa-peugeot-citroen.com/ead/dom/1000788899.fd",
"imageUrl": "http://lim.local.inetpsa.com/application/images/service/car2.jpg",
"language": "fr-FR",
"order": 1,
"workplace": "All",
"department": "All",
"categoryPro": "All",
"status": "edited"
},
{
"title": "Ventes véhicules DS",
"url": "https://docinfogroupe.psa-peugeot-citroen.com/ead/dom/1000779116.fd",
"imageUrl": "http://lim.local.inetpsa.com/application/images/service/car2.jpg",
"language": "fr-FR",
"order": 2,
"workplace": "All",
"department": "All",
"categoryPro": "All",
"status": "published"
}
]
},
{
"title": "Webmail",
"url": "https://webmail.mpsa.com/",
"imageUrl": "http://lim.local.inetpsa.com/application/images/service/webmail.jpg",
"language": "en-US",
"order": "0",
"workplace": "All",
"department": "All",
"categoryPro": "All",
"status": "published",
"children": []
},
{
"title": "Net'RH congés",
"url": "https://fr-rh.mpsa.com/rib00/ribdnins.nsf/fc583fb6947d633ac12569450031fbd2/755dcfb785421c6cc1256c7f003107c2?OpenDocument",
"imageUrl": "http://lim.local.inetpsa.com/application/images/service/holiday.jpg",
"language": "fr-FR",
"order": "3",
"workplace": "All",
"department": "All",
"categoryPro": "All",
"status": "unpublished",
"children": []
}
]
|
Java
|
/*
* Copyright 2009-2013 Aarhus University
*
* 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 dk.brics.tajs.analysis;
import dk.brics.tajs.flowgraph.BasicBlock;
import dk.brics.tajs.lattice.CallEdge;
import dk.brics.tajs.solver.CallGraph;
import dk.brics.tajs.solver.IWorkListStrategy;
/**
* Work list strategy.
*/
public class WorkListStrategy implements IWorkListStrategy<Context> {
private CallGraph<State,Context,CallEdge<State>> call_graph;
/**
* Constructs a new WorkListStrategy object.
*/
public WorkListStrategy() {}
/**
* Sets the call graph.
*/
public void setCallGraph(CallGraph<State,Context,CallEdge<State>> call_graph) {
this.call_graph = call_graph;
}
@Override
public int compare(IEntry<Context> e1, IEntry<Context> e2) {
BasicBlock n1 = e1.getBlock();
BasicBlock n2 = e2.getBlock();
int serial1 = e1.getSerial();
int serial2 = e2.getSerial();
if (serial1 == serial2)
return 0;
final int E1_FIRST = -1;
final int E2_FIRST = 1;
if (n1.getFunction().equals(n2.getFunction()) && e1.getContext().equals(e2.getContext())) {
// same function and same context: use block order
if (n1.getOrder() < n2.getOrder())
return E1_FIRST;
else if (n2.getOrder() < n1.getOrder())
return E2_FIRST;
}
int function_context_order1 = call_graph.getBlockContextOrder(e1.getContext().getEntryBlockAndContext());
int function_context_order2 = call_graph.getBlockContextOrder(e2.getContext().getEntryBlockAndContext());
// different function/context: order by occurrence number
if (function_context_order1 < function_context_order2)
return E2_FIRST;
else if (function_context_order2 < function_context_order1)
return E1_FIRST;
// strategy: breadth first
return serial1 - serial2;
}
}
|
Java
|
mod project;
mod build;
pub use self::project::{Project, Folder};
|
Java
|
#include "firestore/src/swig/equality_compare.h"
namespace {
template <typename T>
bool EqualityCompareHelper(const T* lhs, const T* rhs) {
return lhs == rhs || (lhs != nullptr && rhs != nullptr && *lhs == *rhs);
}
} // namespace
namespace firebase {
namespace firestore {
namespace csharp {
bool QueryEquals(const Query* lhs, const Query* rhs) {
return EqualityCompareHelper(lhs, rhs);
}
bool QuerySnapshotEquals(const QuerySnapshot* lhs, const QuerySnapshot* rhs) {
return EqualityCompareHelper(lhs, rhs);
}
bool DocumentSnapshotEquals(const DocumentSnapshot* lhs,
const DocumentSnapshot* rhs) {
return EqualityCompareHelper(lhs, rhs);
}
bool DocumentChangeEquals(const DocumentChange* lhs,
const DocumentChange* rhs) {
return EqualityCompareHelper(lhs, rhs);
}
} // namespace csharp
} // namespace firestore
} // namespace firebase
|
Java
|
package at.ac.tuwien.dsg.pm.resources;
import at.ac.tuwien.dsg.pm.PeerManager;
import at.ac.tuwien.dsg.pm.model.Collective;
import at.ac.tuwien.dsg.smartcom.model.CollectiveInfo;
import at.ac.tuwien.dsg.smartcom.model.Identifier;
import javax.inject.Inject;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.List;
/**
* @author Philipp Zeppezauer (philipp.zeppezauer@gmail.com)
* @version 1.0
*/
@Path("collectiveInfo")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class CollectiveInfoResource {
@Inject
private PeerManager manager;
@GET
@Path("/{id}")
public CollectiveInfo getCollectiveInfo(@PathParam("id") String id) {
Collective collective = manager.getCollective(id);
if (collective == null) {
throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND).build());
}
CollectiveInfo info = new CollectiveInfo();
info.setId(Identifier.collective(id));
info.setDeliveryPolicy(collective.getDeliveryPolicy());
List<Identifier> peers = new ArrayList<>(collective.getPeers().size());
for (String s : collective.getPeers()) {
peers.add(Identifier.peer(s));
}
info.setPeers(peers);
return info;
}
}
|
Java
|
package tutor.utils
import org.scalatest.{FunSpec, Matchers}
class FileUtilSpec extends FunSpec with Matchers {
describe("FileUtil"){
it("can extract file extension name"){
val path = "src/test/build.sbt"
FileUtil.extractExtFileName(path) shouldBe "sbt"
}
it("if file has no extension name, should give EmptyFileType constant"){
val path = "src/test/build"
FileUtil.extractExtFileName(path) shouldBe FileUtil.EmptyFileType
}
it("can extract local file path"){
val path = "src/test/build.sbt"
FileUtil.extractLocalPath(path) shouldBe "build.sbt"
}
}
}
|
Java
|
sap.ui.define(["sap/ui/integration/Designtime"], function (
Designtime
) {
"use strict";
return function () {
return new Designtime({
"form": {
"items": {
"validationGroup": {
"type": "group",
"label": "Validation"
},
"OrderID": {
"manifestpath": "/sap.card/configuration/parameters/OrderID/value",
"label": "Order Id",
"type": "integer",
"required": true
},
"stringphone": {
"manifestpath": "/sap.card/configuration/parameters/string/value",
"label": "String with Pattern validation",
"type": "string",
"translatable": false,
"required": true,
"placeholder": "555-4555",
"validation": {
"type": "error",
"maxLength": 20,
"minLength": 1,
"pattern": "^(\\([0-9]{3}\\))?[0-9]{3}-[0-9]{4}$",
"message": "The string does not match a telefone number"
}
},
"stringphonenomessage": {
"manifestpath": "/sap.card/configuration/parameters/string/value",
"label": "String with default validation message",
"type": "string",
"translatable": false,
"required": true,
"placeholder": "555-4555",
"validation": {
"type": "warning",
"maxLength": 20,
"minLength": 1,
"pattern": "^(\\([0-9]{3}\\))?[0-9]{3}-[0-9]{4}$"
}
},
"stringmaxmin": {
"manifestpath": "/sap.card/configuration/parameters/string/value",
"label": "String with Length Constrained",
"type": "string",
"translatable": false,
"required": true,
"placeholder": "MinMaxlength",
"validation": {
"type": "warning",
"maxLength": 20,
"minLength": 3
},
"hint": "Please refer to the <a href='https://www.sap.com'>documentation</a> lets see how this will behave if the text is wrapping to the next line and has <a href='https://www.sap.com'>two links</a>. good?"
},
"integerrequired": {
"manifestpath": "/sap.card/configuration/parameters/integerrequired/value",
"label": "Integer with Required",
"type": "integer",
"translatable": false,
"required": true
},
"integervalidation": {
"manifestpath": "/sap.card/configuration/parameters/integer/value",
"label": "Integer with Min Max value",
"type": "integer",
"visualization": {
"type": "Slider",
"settings": {
"value": "{currentSettings>value}",
"min": 0,
"max": 16,
"width": "100%",
"showAdvancedTooltip": true,
"showHandleTooltip": false,
"inputsAsTooltips": true,
"enabled": "{currentSettings>editable}"
}
},
"validations": [
{
"type": "warning",
"minimum": 5,
"message": "The minimum is 5."
},
{
"type": "error",
"exclusiveMaximum": 16,
"message": "The maximum is 15."
},
{
"type": "error",
"multipleOf": 5,
"message": "Has to be multiple of 5"
}
]
},
"numberrequired": {
"manifestpath": "/sap.card/configuration/parameters/number/value",
"label": "Number with validation",
"type": "number",
"translatable": false,
"required": true,
"validation": {
"type": "error",
"minimum": 0,
"maximum": 100,
"exclusiveMaximum": true,
"message": "The value should be equal or greater than 0 and be less than 100."
}
}
}
},
"preview": {
"modes": "AbstractLive"
}
});
};
});
|
Java
|
#include "list.h"
void __list_add__(list_node_t *prev, list_node_t *next, list_node_t *node)
{
next->prev = node;
node->next = next;
node->prev = prev;
prev->next = node;
}
void __list_del__(list_node_t *prev, list_node_t *next)
{
next->prev = prev;
prev->next = next;
}
void __list_erase__(list_t *list, list_node_t *node)
{
list_iter_t next, prev;
if (list_is_singular(*list)) {
list->head = list->tail = NULL;
} else {
next = node->next;
prev = node->prev;
__list_del__(node->prev, node->next);
list->head = list->head == node ? next : list->head;
list->tail = list->tail == node ? prev : list->tail;
}
node->prev = NULL;
node->next = NULL;
}
void __list_replace__(list_node_t *o, list_node_t *n)
{
n->next = o->next;
n->next->prev = n;
n->prev = o->prev;
n->prev->next = n;
}
void __list_push_back__(list_t *list, list_node_t *node)
{
if (list->head) {
__list_add__(list->head->prev, list->head, node);
list->tail = node;
} else {
list->head = list->tail = node->next = node->prev = node;
}
}
void __list_push_front__(list_t *list, list_node_t *node)
{
if (list->head) {
__list_add__(list->head->prev, list->head, node);
list->head = node;
} else {
list->head = list->tail = node->next = node->prev = node;
}
}
|
Java
|
package com.earlysleep.model;
import org.litepal.crud.DataSupport;
import java.util.ArrayList;
import java.util.List;
/**
* Created by zml on 2016/6/23.
* 介绍:
*/
public class AllData extends DataSupport {
private String music;
private int musictime;
private boolean musicchosse;
List<TimeSeting> list=new ArrayList<>();
}
|
Java
|
package org.spoofax.jsglr2.integrationtest.features;
import java.util.Arrays;
import java.util.stream.Stream;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.TestFactory;
import org.spoofax.jsglr2.integrationtest.BaseTestWithSdf3ParseTables;
import org.spoofax.jsglr2.integrationtest.OriginDescriptor;
import org.spoofax.terms.ParseError;
public class OriginsTest extends BaseTestWithSdf3ParseTables {
public OriginsTest() {
super("tokenization.sdf3");
}
@TestFactory public Stream<DynamicTest> operator() throws ParseError {
return testOrigins("x+x", Arrays.asList(
//@formatter:off
new OriginDescriptor("AddOperator", 0, 2),
new OriginDescriptor("Id", 0, 0),
new OriginDescriptor("Id", 2, 2)
//@formatter:on
));
}
}
|
Java
|
# frozen_string_literal: true
# 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.
# Auto-generated by gapic-generator-ruby. DO NOT EDIT!
require "google/cloud/access_approval/v1/access_approval"
require "google/cloud/access_approval/v1/version"
module Google
module Cloud
module AccessApproval
##
# To load this package, including all its services, and instantiate a client:
#
# @example
#
# require "google/cloud/access_approval/v1"
# client = ::Google::Cloud::AccessApproval::V1::AccessApproval::Client.new
#
module V1
end
end
end
end
helper_path = ::File.join __dir__, "v1", "_helpers.rb"
require "google/cloud/access_approval/v1/_helpers" if ::File.file? helper_path
|
Java
|
/*
* Copyright (c) 2005-2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.andes.server.handler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.andes.AMQException;
import org.wso2.andes.amqp.AMQPUtils;
import org.wso2.andes.exchange.ExchangeDefaults;
import org.wso2.andes.framing.AMQShortString;
import org.wso2.andes.framing.BasicPublishBody;
import org.wso2.andes.framing.abstraction.MessagePublishInfo;
import org.wso2.andes.protocol.AMQConstant;
import org.wso2.andes.server.AMQChannel;
import org.wso2.andes.server.exchange.Exchange;
import org.wso2.andes.server.protocol.AMQProtocolSession;
import org.wso2.andes.server.state.AMQStateManager;
import org.wso2.andes.server.state.StateAwareMethodListener;
import org.wso2.andes.server.virtualhost.VirtualHost;
public class BasicPublishMethodHandler implements StateAwareMethodListener<BasicPublishBody>
{
private static final Log _logger = LogFactory.getLog(BasicPublishMethodHandler.class);
private static final BasicPublishMethodHandler _instance = new BasicPublishMethodHandler();
public static BasicPublishMethodHandler getInstance()
{
return _instance;
}
private BasicPublishMethodHandler()
{
}
public void methodReceived(AMQStateManager stateManager, BasicPublishBody body, int channelId) throws AMQException
{
AMQProtocolSession session = stateManager.getProtocolSession();
if (_logger.isDebugEnabled())
{
_logger.debug("Publish received on channel " + channelId);
}
AMQShortString exchangeName = body.getExchange();
// TODO: check the delivery tag field details - is it unique across the broker or per subscriber?
if (exchangeName == null)
{
exchangeName = ExchangeDefaults.DEFAULT_EXCHANGE_NAME;
}
VirtualHost vHost = session.getVirtualHost();
Exchange exch = vHost.getExchangeRegistry().getExchange(exchangeName);
// if the exchange does not exist we raise a channel exception
if (exch == null)
{
throw body.getChannelException(AMQConstant.NOT_FOUND, "Unknown exchange name");
}
else
{
// The partially populated BasicDeliver frame plus the received route body
// is stored in the channel. Once the final body frame has been received
// it is routed to the exchange.
AMQChannel channel = session.getChannel(channelId);
if (channel == null)
{
throw body.getChannelNotFoundException(channelId);
}
MessagePublishInfo info = session.getMethodRegistry().getProtocolVersionMethodConverter().convertToInfo(body);
if (ExchangeDefaults.TOPIC_EXCHANGE_NAME.equals(exchangeName)
&& AMQPUtils.isWildCardDestination(info.getRoutingKey().toString())) {
throw body.getChannelException(AMQConstant.INVALID_ROUTING_KEY, "Publishing messages to a wildcard "
+ "destination is not allowed");
}
info.setExchange(exchangeName);
channel.setPublishFrame(info, exch);
}
}
}
|
Java
|
using System;
using System.Net.Http.Formatting;
using System.Web;
using System.Web.Hosting;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using NLog;
using NLog.Config;
using NLog.Targets;
using RceDoorzoeker.Configuration;
using RceDoorzoeker.Services.Mappers;
namespace RceDoorzoeker
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : HttpApplication
{
private static readonly Logger s_logger = LogManager.GetCurrentClassLogger();
public static bool ReleaseBuild
{
get
{
#if DEBUG
return false;
#else
return true;
#endif
}
}
protected void Application_Start()
{
InitializeConfiguration();
InitLogging();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
AreaRegistration.RegisterAllAreas();
BundleTable.EnableOptimizations = ReleaseBuild;
BundleConfig.RegisterBundles(BundleTable.Bundles);
RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
WebApiConfig.Register(GlobalConfiguration.Configuration);
RouteConfig.RegisterRoutes(RouteTable.Routes);
DoorzoekerModelMapper.ConfigureMapper();
var config = GlobalConfiguration.Configuration;
config.Formatters.Clear();
var jsonMediaTypeFormatter = new JsonMediaTypeFormatter
{
SerializerSettings =
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
NullValueHandling = NullValueHandling.Ignore
}
};
config.Formatters.Add(jsonMediaTypeFormatter);
s_logger.Info("Application started.");
}
private void InitLogging()
{
var cfg = new LoggingConfiguration();
var fileTarget = new FileTarget()
{
FileName = string.Format("${{basedir}}/App_Data/NLog-{0}.log", Instance.Current.Name),
Layout = "${longdate} ${level} ${logger} ${message} ${exception:format=tostring}",
ArchiveAboveSize = 2000000,
ArchiveNumbering = ArchiveNumberingMode.Sequence,
ArchiveEvery = FileArchivePeriod.Month,
MaxArchiveFiles = 10,
ConcurrentWrites = false,
KeepFileOpen = true,
EnableFileDelete = true,
ArchiveFileName = string.Format("${{basedir}}/App_Data/NLog-{0}_archive_{{###}}.log", Instance.Current.Name)
};
var traceTarget = new TraceTarget()
{
Layout = "${level} ${logger} ${message} ${exception:format=tostring}"
};
cfg.AddTarget("instancefile", fileTarget);
cfg.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, fileTarget));
cfg.AddTarget("trace", traceTarget);
cfg.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, traceTarget));
LogManager.Configuration = cfg;
}
private static void InitializeConfiguration()
{
var instanceConfig = InstanceRegistry.Current.GetBySiteName(HostingEnvironment.SiteName);
if (instanceConfig == null)
throw new ApplicationException("Can't find instance configuration for site " + HostingEnvironment.SiteName);
Instance.Current = instanceConfig;
DoorzoekerConfig.Current = DoorzoekerConfig.Load(instanceConfig.Config);
}
protected void Application_End()
{
s_logger.Info("Application ended");
}
}
}
|
Java
|
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.carbon.policy.mgt.core.task;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.ntask.common.TaskException;
import org.wso2.carbon.ntask.core.TaskInfo;
import org.wso2.carbon.ntask.core.TaskManager;
import org.wso2.carbon.ntask.core.service.TaskService;
import org.wso2.carbon.policy.mgt.common.PolicyMonitoringTaskException;
import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder;
import org.wso2.carbon.policy.mgt.core.util.PolicyManagementConstants;
import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil;
import org.wso2.carbon.ntask.core.TaskInfo.TriggerInfo;
import java.util.HashMap;
import java.util.Map;
public class TaskScheduleServiceImpl implements TaskScheduleService {
private static Log log = LogFactory.getLog(TaskScheduleServiceImpl.class);
@Override
public void startTask(int monitoringFrequency) throws PolicyMonitoringTaskException {
if (monitoringFrequency <= 0) {
throw new PolicyMonitoringTaskException("Time interval cannot be 0 or less than 0.");
}
try {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
TaskService taskService = PolicyManagementDataHolder.getInstance().getTaskService();
taskService.registerTaskType(PolicyManagementConstants.TASK_TYPE);
if (log.isDebugEnabled()) {
log.debug("Monitoring task is started for the tenant id " + tenantId);
}
TaskManager taskManager = taskService.getTaskManager(PolicyManagementConstants.TASK_TYPE);
TriggerInfo triggerInfo = new TriggerInfo();
triggerInfo.setIntervalMillis(monitoringFrequency);
triggerInfo.setRepeatCount(-1);
Map<String, String> properties = new HashMap<>();
properties.put(PolicyManagementConstants.TENANT_ID, String.valueOf(tenantId));
String taskName = PolicyManagementConstants.TASK_NAME + "_" + String.valueOf(tenantId);
TaskInfo taskInfo = new TaskInfo(taskName, PolicyManagementConstants.TASK_CLAZZ, properties, triggerInfo);
taskManager.registerTask(taskInfo);
taskManager.rescheduleTask(taskInfo.getName());
} catch (TaskException e) {
String msg = "Error occurred while creating the task for tenant " + PrivilegedCarbonContext.
getThreadLocalCarbonContext().getTenantId();
log.error(msg, e);
throw new PolicyMonitoringTaskException(msg, e);
}
}
@Override
public void stopTask() throws PolicyMonitoringTaskException {
try {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
String taskName = PolicyManagementConstants.TASK_NAME + "_" + String.valueOf(tenantId);
TaskService taskService = PolicyManagementDataHolder.getInstance().getTaskService();
TaskManager taskManager = taskService.getTaskManager(PolicyManagementConstants.TASK_TYPE);
taskManager.deleteTask(taskName);
} catch (TaskException e) {
String msg = "Error occurred while deleting the task for tenant " + PrivilegedCarbonContext.
getThreadLocalCarbonContext().getTenantId();
log.error(msg, e);
throw new PolicyMonitoringTaskException(msg, e);
}
}
@Override
public void updateTask(int monitoringFrequency) throws PolicyMonitoringTaskException {
try {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
String taskName = PolicyManagementConstants.TASK_NAME + "_" + String.valueOf(tenantId);
TaskService taskService = PolicyManagementDataHolder.getInstance().getTaskService();
TaskManager taskManager = taskService.getTaskManager(PolicyManagementConstants.TASK_TYPE);
taskManager.deleteTask(taskName);
TriggerInfo triggerInfo = new TriggerInfo();
triggerInfo.setIntervalMillis(monitoringFrequency);
triggerInfo.setRepeatCount(-1);
Map<String, String> properties = new HashMap<>();
properties.put("tenantId", String.valueOf(tenantId));
TaskInfo taskInfo = new TaskInfo(taskName, PolicyManagementConstants.TASK_CLAZZ, properties, triggerInfo);
taskManager.registerTask(taskInfo);
taskManager.rescheduleTask(taskInfo.getName());
} catch (TaskException e) {
String msg = "Error occurred while updating the task for tenant " + PrivilegedCarbonContext.
getThreadLocalCarbonContext().getTenantId();
log.error(msg, e);
throw new PolicyMonitoringTaskException(msg, e);
}
}
}
|
Java
|
# AUTOGENERATED FILE
FROM balenalib/generic-armv7ahf-ubuntu:focal-build
ENV NODE_VERSION 12.21.0
ENV YARN_VERSION 1.22.4
RUN for key in \
6A010C5166006599AA17F08146C2130DFD2497F5 \
; do \
gpg --keyserver pgp.mit.edu --recv-keys "$key" || \
gpg --keyserver keyserver.pgp.com --recv-keys "$key" || \
gpg --keyserver ha.pool.sks-keyservers.net --recv-keys "$key" ; \
done \
&& curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-armv7l.tar.gz" \
&& echo "6edc31a210e47eb72b0a2a150f7fe604539c1b2a45e8c81d378ac9315053a54f node-v$NODE_VERSION-linux-armv7l.tar.gz" | sha256sum -c - \
&& tar -xzf "node-v$NODE_VERSION-linux-armv7l.tar.gz" -C /usr/local --strip-components=1 \
&& rm "node-v$NODE_VERSION-linux-armv7l.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \
&& gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& mkdir -p /opt/yarn \
&& tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \
&& rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& npm config set unsafe-perm true -g --unsafe-perm \
&& rm -rf /tmp/*
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@node.sh" \
&& echo "Running test-stack@node" \
&& chmod +x test-stack@node.sh \
&& bash test-stack@node.sh \
&& rm -rf test-stack@node.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Ubuntu focal \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v12.21.0, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh
|
Java
|
/*
* Copyright 2013 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.api.client.googleapis.testing.json;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.json.Json;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.testing.http.HttpTesting;
import com.google.api.client.testing.http.MockHttpTransport;
import com.google.api.client.testing.http.MockLowLevelHttpResponse;
import com.google.api.client.util.Beta;
import java.io.IOException;
/**
* {@link Beta} <br>
* Factory class that builds {@link GoogleJsonResponseException} instances for testing.
*
* @since 1.18
*/
@Beta
public final class GoogleJsonResponseExceptionFactoryTesting {
/**
* Convenience factory method that builds a {@link GoogleJsonResponseException} from its
* arguments. The method builds a dummy {@link HttpRequest} and {@link HttpResponse}, sets the
* response's status to a user-specified HTTP error code, suppresses exceptions, and executes the
* request. This forces the underlying framework to create, but not throw, a {@link
* GoogleJsonResponseException}, which the method retrieves and returns to the invoker.
*
* @param jsonFactory the JSON factory that will create all JSON required by the underlying
* framework
* @param httpCode the desired HTTP error code. Note: do nut specify any codes that indicate
* successful completion, e.g. 2XX.
* @param reasonPhrase the HTTP reason code that explains the error. For example, if {@code
* httpCode} is {@code 404}, the reason phrase should be {@code NOT FOUND}.
* @return the generated {@link GoogleJsonResponseException}, as specified.
* @throws IOException if request transport fails.
*/
public static GoogleJsonResponseException newMock(
JsonFactory jsonFactory, int httpCode, String reasonPhrase) throws IOException {
MockLowLevelHttpResponse otherServiceUnavaiableLowLevelResponse =
new MockLowLevelHttpResponse()
.setStatusCode(httpCode)
.setReasonPhrase(reasonPhrase)
.setContentType(Json.MEDIA_TYPE)
.setContent(
"{ \"error\": { \"errors\": [ { \"reason\": \""
+ reasonPhrase
+ "\" } ], "
+ "\"code\": "
+ httpCode
+ " } }");
MockHttpTransport otherTransport =
new MockHttpTransport.Builder()
.setLowLevelHttpResponse(otherServiceUnavaiableLowLevelResponse)
.build();
HttpRequest otherRequest =
otherTransport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
otherRequest.setThrowExceptionOnExecuteError(false);
HttpResponse otherServiceUnavailableResponse = otherRequest.execute();
return GoogleJsonResponseException.from(jsonFactory, otherServiceUnavailableResponse);
}
}
|
Java
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_26) on Sun Dec 30 01:26:12 PST 2012 -->
<TITLE>
Uses of Class org.apache.hadoop.fs.s3.S3FileSystem (Hadoop 1.0.4-SNAPSHOT API)
</TITLE>
<META NAME="date" CONTENT="2012-12-30">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.hadoop.fs.s3.S3FileSystem (Hadoop 1.0.4-SNAPSHOT API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/hadoop/fs/s3/S3FileSystem.html" title="class in org.apache.hadoop.fs.s3"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/hadoop/fs/s3//class-useS3FileSystem.html" target="_top"><B>FRAMES</B></A>
<A HREF="S3FileSystem.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.apache.hadoop.fs.s3.S3FileSystem</B></H2>
</CENTER>
No usage of org.apache.hadoop.fs.s3.S3FileSystem
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/hadoop/fs/s3/S3FileSystem.html" title="class in org.apache.hadoop.fs.s3"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/hadoop/fs/s3//class-useS3FileSystem.html" target="_top"><B>FRAMES</B></A>
<A HREF="S3FileSystem.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2009 The Apache Software Foundation
</BODY>
</HTML>
|
Java
|
/* Generic definitions */
#define Custom
#define PACKAGE it.unimi.dsi.fastutil.shorts
#define VALUE_PACKAGE it.unimi.dsi.fastutil.floats
/* Assertions (useful to generate conditional code) */
#unassert keyclass
#assert keyclass(Short)
#unassert keys
#assert keys(primitive)
#unassert valueclass
#assert valueclass(Float)
#unassert values
#assert values(primitive)
/* Current type and class (and size, if applicable) */
#define KEY_TYPE short
#define VALUE_TYPE float
#define KEY_CLASS Short
#define VALUE_CLASS Float
#if #keyclass(Object) || #keyclass(Reference)
#define KEY_GENERIC_CLASS K
#define KEY_GENERIC_TYPE K
#define KEY_GENERIC <K>
#define KEY_GENERIC_WILDCARD <?>
#define KEY_EXTENDS_GENERIC <? extends K>
#define KEY_SUPER_GENERIC <? super K>
#define KEY_GENERIC_CAST (K)
#define KEY_GENERIC_ARRAY_CAST (K[])
#define KEY_GENERIC_BIG_ARRAY_CAST (K[][])
#else
#define KEY_GENERIC_CLASS KEY_CLASS
#define KEY_GENERIC_TYPE KEY_TYPE
#define KEY_GENERIC
#define KEY_GENERIC_WILDCARD
#define KEY_EXTENDS_GENERIC
#define KEY_SUPER_GENERIC
#define KEY_GENERIC_CAST
#define KEY_GENERIC_ARRAY_CAST
#define KEY_GENERIC_BIG_ARRAY_CAST
#endif
#if #valueclass(Object) || #valueclass(Reference)
#define VALUE_GENERIC_CLASS V
#define VALUE_GENERIC_TYPE V
#define VALUE_GENERIC <V>
#define VALUE_EXTENDS_GENERIC <? extends V>
#define VALUE_GENERIC_CAST (V)
#define VALUE_GENERIC_ARRAY_CAST (V[])
#else
#define VALUE_GENERIC_CLASS VALUE_CLASS
#define VALUE_GENERIC_TYPE VALUE_TYPE
#define VALUE_GENERIC
#define VALUE_EXTENDS_GENERIC
#define VALUE_GENERIC_CAST
#define VALUE_GENERIC_ARRAY_CAST
#endif
#if #keyclass(Object) || #keyclass(Reference)
#if #valueclass(Object) || #valueclass(Reference)
#define KEY_VALUE_GENERIC <K,V>
#define KEY_VALUE_EXTENDS_GENERIC <? extends K, ? extends V>
#else
#define KEY_VALUE_GENERIC <K>
#define KEY_VALUE_EXTENDS_GENERIC <? extends K>
#endif
#else
#if #valueclass(Object) || #valueclass(Reference)
#define KEY_VALUE_GENERIC <V>
#define KEY_VALUE_EXTENDS_GENERIC <? extends V>
#else
#define KEY_VALUE_GENERIC
#define KEY_VALUE_EXTENDS_GENERIC
#endif
#endif
/* Value methods */
#define KEY_VALUE shortValue
#define VALUE_VALUE floatValue
/* Interfaces (keys) */
#define COLLECTION ShortCollection
#define SET ShortSet
#define HASH ShortHash
#define SORTED_SET ShortSortedSet
#define STD_SORTED_SET ShortSortedSet
#define FUNCTION Short2FloatFunction
#define MAP Short2FloatMap
#define SORTED_MAP Short2FloatSortedMap
#if #keyclass(Object) || #keyclass(Reference)
#define STD_SORTED_MAP SortedMap
#define STRATEGY Strategy
#else
#define STD_SORTED_MAP Short2FloatSortedMap
#define STRATEGY PACKAGE.ShortHash.Strategy
#endif
#define LIST ShortList
#define BIG_LIST ShortBigList
#define STACK ShortStack
#define PRIORITY_QUEUE ShortPriorityQueue
#define INDIRECT_PRIORITY_QUEUE ShortIndirectPriorityQueue
#define INDIRECT_DOUBLE_PRIORITY_QUEUE ShortIndirectDoublePriorityQueue
#define KEY_ITERATOR ShortIterator
#define KEY_ITERABLE ShortIterable
#define KEY_BIDI_ITERATOR ShortBidirectionalIterator
#define KEY_LIST_ITERATOR ShortListIterator
#define KEY_BIG_LIST_ITERATOR ShortBigListIterator
#define STD_KEY_ITERATOR ShortIterator
#define KEY_COMPARATOR ShortComparator
/* Interfaces (values) */
#define VALUE_COLLECTION FloatCollection
#define VALUE_ARRAY_SET FloatArraySet
#define VALUE_ITERATOR FloatIterator
#define VALUE_LIST_ITERATOR FloatListIterator
/* Abstract implementations (keys) */
#define ABSTRACT_COLLECTION AbstractShortCollection
#define ABSTRACT_SET AbstractShortSet
#define ABSTRACT_SORTED_SET AbstractShortSortedSet
#define ABSTRACT_FUNCTION AbstractShort2FloatFunction
#define ABSTRACT_MAP AbstractShort2FloatMap
#define ABSTRACT_FUNCTION AbstractShort2FloatFunction
#define ABSTRACT_SORTED_MAP AbstractShort2FloatSortedMap
#define ABSTRACT_LIST AbstractShortList
#define ABSTRACT_BIG_LIST AbstractShortBigList
#define SUBLIST ShortSubList
#define ABSTRACT_PRIORITY_QUEUE AbstractShortPriorityQueue
#define ABSTRACT_STACK AbstractShortStack
#define KEY_ABSTRACT_ITERATOR AbstractShortIterator
#define KEY_ABSTRACT_BIDI_ITERATOR AbstractShortBidirectionalIterator
#define KEY_ABSTRACT_LIST_ITERATOR AbstractShortListIterator
#define KEY_ABSTRACT_BIG_LIST_ITERATOR AbstractShortBigListIterator
#if #keyclass(Object)
#define KEY_ABSTRACT_COMPARATOR Comparator
#else
#define KEY_ABSTRACT_COMPARATOR AbstractShortComparator
#endif
/* Abstract implementations (values) */
#define VALUE_ABSTRACT_COLLECTION AbstractFloatCollection
#define VALUE_ABSTRACT_ITERATOR AbstractFloatIterator
#define VALUE_ABSTRACT_BIDI_ITERATOR AbstractFloatBidirectionalIterator
/* Static containers (keys) */
#define COLLECTIONS ShortCollections
#define SETS ShortSets
#define SORTED_SETS ShortSortedSets
#define LISTS ShortLists
#define BIG_LISTS ShortBigLists
#define MAPS Short2FloatMaps
#define FUNCTIONS Short2FloatFunctions
#define SORTED_MAPS Short2FloatSortedMaps
#define PRIORITY_QUEUES ShortPriorityQueues
#define HEAPS ShortHeaps
#define SEMI_INDIRECT_HEAPS ShortSemiIndirectHeaps
#define INDIRECT_HEAPS ShortIndirectHeaps
#define ARRAYS ShortArrays
#define BIG_ARRAYS ShortBigArrays
#define ITERATORS ShortIterators
#define BIG_LIST_ITERATORS ShortBigListIterators
#define COMPARATORS ShortComparators
/* Static containers (values) */
#define VALUE_COLLECTIONS FloatCollections
#define VALUE_SETS FloatSets
#define VALUE_ARRAYS FloatArrays
/* Implementations */
#define OPEN_HASH_SET ShortOpenCustomHashSet
#define OPEN_HASH_BIG_SET ShortOpenCustomHashBigSet
#define OPEN_DOUBLE_HASH_SET ShortOpenCustomDoubleHashSet
#define OPEN_HASH_MAP Short2FloatOpenCustomHashMap
#define STRIPED_OPEN_HASH_MAP StripedShort2FloatOpenCustomHashMap
#define OPEN_DOUBLE_HASH_MAP Short2FloatOpenCustomDoubleHashMap
#define ARRAY_SET ShortArraySet
#define ARRAY_MAP Short2FloatArrayMap
#define LINKED_OPEN_HASH_SET ShortLinkedOpenHashSet
#define AVL_TREE_SET ShortAVLTreeSet
#define RB_TREE_SET ShortRBTreeSet
#define AVL_TREE_MAP Short2FloatAVLTreeMap
#define RB_TREE_MAP Short2FloatRBTreeMap
#define ARRAY_LIST ShortArrayList
#define BIG_ARRAY_BIG_LIST ShortBigArrayBigList
#define ARRAY_FRONT_CODED_LIST ShortArrayFrontCodedList
#define HEAP_PRIORITY_QUEUE ShortHeapPriorityQueue
#define HEAP_SEMI_INDIRECT_PRIORITY_QUEUE ShortHeapSemiIndirectPriorityQueue
#define HEAP_INDIRECT_PRIORITY_QUEUE ShortHeapIndirectPriorityQueue
#define HEAP_SESQUI_INDIRECT_DOUBLE_PRIORITY_QUEUE ShortHeapSesquiIndirectDoublePriorityQueue
#define HEAP_INDIRECT_DOUBLE_PRIORITY_QUEUE ShortHeapIndirectDoublePriorityQueue
#define ARRAY_FIFO_QUEUE ShortArrayFIFOQueue
#define ARRAY_PRIORITY_QUEUE ShortArrayPriorityQueue
#define ARRAY_INDIRECT_PRIORITY_QUEUE ShortArrayIndirectPriorityQueue
#define ARRAY_INDIRECT_DOUBLE_PRIORITY_QUEUE ShortArrayIndirectDoublePriorityQueue
/* Synchronized wrappers */
#define SYNCHRONIZED_COLLECTION SynchronizedShortCollection
#define SYNCHRONIZED_SET SynchronizedShortSet
#define SYNCHRONIZED_SORTED_SET SynchronizedShortSortedSet
#define SYNCHRONIZED_FUNCTION SynchronizedShort2FloatFunction
#define SYNCHRONIZED_MAP SynchronizedShort2FloatMap
#define SYNCHRONIZED_LIST SynchronizedShortList
/* Unmodifiable wrappers */
#define UNMODIFIABLE_COLLECTION UnmodifiableShortCollection
#define UNMODIFIABLE_SET UnmodifiableShortSet
#define UNMODIFIABLE_SORTED_SET UnmodifiableShortSortedSet
#define UNMODIFIABLE_FUNCTION UnmodifiableShort2FloatFunction
#define UNMODIFIABLE_MAP UnmodifiableShort2FloatMap
#define UNMODIFIABLE_LIST UnmodifiableShortList
#define UNMODIFIABLE_KEY_ITERATOR UnmodifiableShortIterator
#define UNMODIFIABLE_KEY_BIDI_ITERATOR UnmodifiableShortBidirectionalIterator
#define UNMODIFIABLE_KEY_LIST_ITERATOR UnmodifiableShortListIterator
/* Other wrappers */
#define KEY_READER_WRAPPER ShortReaderWrapper
#define KEY_DATA_INPUT_WRAPPER ShortDataInputWrapper
/* Methods (keys) */
#define NEXT_KEY nextShort
#define PREV_KEY previousShort
#define FIRST_KEY firstShortKey
#define LAST_KEY lastShortKey
#define GET_KEY getShort
#define REMOVE_KEY removeShort
#define READ_KEY readShort
#define WRITE_KEY writeShort
#define DEQUEUE dequeueShort
#define DEQUEUE_LAST dequeueLastShort
#define SUBLIST_METHOD shortSubList
#define SINGLETON_METHOD shortSingleton
#define FIRST firstShort
#define LAST lastShort
#define TOP topShort
#define PEEK peekShort
#define POP popShort
#define KEY_ITERATOR_METHOD shortIterator
#define KEY_LIST_ITERATOR_METHOD shortListIterator
#define KEY_EMPTY_ITERATOR_METHOD emptyShortIterator
#define AS_KEY_ITERATOR asShortIterator
#define TO_KEY_ARRAY toShortArray
#define ENTRY_GET_KEY getShortKey
#define REMOVE_FIRST_KEY removeFirstShort
#define REMOVE_LAST_KEY removeLastShort
#define PARSE_KEY parseShort
#define LOAD_KEYS loadShorts
#define LOAD_KEYS_BIG loadShortsBig
#define STORE_KEYS storeShorts
/* Methods (values) */
#define NEXT_VALUE nextFloat
#define PREV_VALUE previousFloat
#define READ_VALUE readFloat
#define WRITE_VALUE writeFloat
#define VALUE_ITERATOR_METHOD floatIterator
#define ENTRY_GET_VALUE getFloatValue
#define REMOVE_FIRST_VALUE removeFirstFloat
#define REMOVE_LAST_VALUE removeLastFloat
/* Methods (keys/values) */
#define ENTRYSET short2FloatEntrySet
/* Methods that have special names depending on keys (but the special names depend on values) */
#if #keyclass(Object) || #keyclass(Reference)
#define GET_VALUE getFloat
#define REMOVE_VALUE removeFloat
#else
#define GET_VALUE get
#define REMOVE_VALUE remove
#endif
/* Equality */
#ifdef Custom
#define KEY_EQUALS(x,y) ( strategy.equals( (x), KEY_GENERIC_CAST (y) ) )
#else
#if #keyclass(Object)
#define KEY_EQUALS(x,y) ( (x) == null ? (y) == null : (x).equals(y) )
#define KEY_EQUALS_NOT_NULL(x,y) ( (x).equals(y) )
#else
#define KEY_EQUALS(x,y) ( (x) == (y) )
#define KEY_EQUALS_NOT_NULL(x,y) ( (x) == (y) )
#endif
#endif
#if #valueclass(Object)
#define VALUE_EQUALS(x,y) ( (x) == null ? (y) == null : (x).equals(y) )
#else
#define VALUE_EQUALS(x,y) ( (x) == (y) )
#endif
/* Object/Reference-only definitions (keys) */
#if #keyclass(Object) || #keyclass(Reference)
#define REMOVE remove
#define KEY_OBJ2TYPE(x) (x)
#define KEY_CLASS2TYPE(x) (x)
#define KEY2OBJ(x) (x)
#if #keyclass(Object)
#ifdef Custom
#define KEY2JAVAHASH(x) ( strategy.hashCode( KEY_GENERIC_CAST (x)) )
#define KEY2INTHASH(x) ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( strategy.hashCode( KEY_GENERIC_CAST (x)) ) )
#define KEY2LONGHASH(x) ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( (long)strategy.hashCode( KEY_GENERIC_CAST (x)) ) )
#else
#define KEY2JAVAHASH(x) ( (x) == null ? 0 : (x).hashCode() )
#define KEY2INTHASH(x) ( (x) == null ? 0x87fcd5c : it.unimi.dsi.fastutil.HashCommon.murmurHash3( (x).hashCode() ) )
#define KEY2LONGHASH(x) ( (x) == null ? 0x810879608e4259ccL : it.unimi.dsi.fastutil.HashCommon.murmurHash3( (long)(x).hashCode() ) )
#endif
#else
#define KEY2JAVAHASH(x) ( (x) == null ? 0 : System.identityHashCode(x) )
#define KEY2INTHASH(x) ( (x) == null ? 0x87fcd5c : it.unimi.dsi.fastutil.HashCommon.murmurHash3( System.identityHashCode(x) ) )
#define KEY2LONGHASH(x) ( (x) == null ? 0x810879608e4259ccL : it.unimi.dsi.fastutil.HashCommon.murmurHash3( (long)System.identityHashCode(x) ) )
#endif
#define KEY_CMP(x,y) ( ((Comparable<KEY_GENERIC_CLASS>)(x)).compareTo(y) )
#define KEY_CMP_EQ(x,y) ( ((Comparable<KEY_GENERIC_CLASS>)(x)).compareTo(y) == 0 )
#define KEY_LESS(x,y) ( ((Comparable<KEY_GENERIC_CLASS>)(x)).compareTo(y) < 0 )
#define KEY_LESSEQ(x,y) ( ((Comparable<KEY_GENERIC_CLASS>)(x)).compareTo(y) <= 0 )
#define KEY_NULL (null)
#else
/* Primitive-type-only definitions (keys) */
#define REMOVE rem
#define KEY_CLASS2TYPE(x) ((x).KEY_VALUE())
#define KEY_OBJ2TYPE(x) (KEY_CLASS2TYPE((KEY_CLASS)(x)))
#define KEY2OBJ(x) (KEY_CLASS.valueOf(x))
#if #keyclass(Boolean)
#define KEY_CMP_EQ(x,y) ( (x) == (y) )
#define KEY_NULL (false)
#define KEY_CMP(x,y) ( !(x) && (y) ? -1 : ( (x) == (y) ? 0 : 1 ) )
#define KEY_LESS(x,y) ( !(x) && (y) )
#define KEY_LESSEQ(x,y) ( !(x) || (y) )
#else
#define KEY_NULL ((KEY_TYPE)0)
#if #keyclass(Float) || #keyclass(Double)
#define KEY_CMP_EQ(x,y) ( KEY_CLASS.compare((x),(y)) == 0 )
#define KEY_CMP(x,y) ( KEY_CLASS.compare((x),(y)) )
#define KEY_LESS(x,y) ( KEY_CLASS.compare((x),(y)) < 0 )
#define KEY_LESSEQ(x,y) ( KEY_CLASS.compare((x),(y)) <= 0 )
#else
#define KEY_CMP_EQ(x,y) ( (x) == (y) )
#define KEY_CMP(x,y) ( (x) < (y) ? -1 : ( (x) == (y) ? 0 : 1 ) )
#define KEY_LESS(x,y) ( (x) < (y) )
#define KEY_LESSEQ(x,y) ( (x) <= (y) )
#endif
#if #keyclass(Float)
#define KEY2LEXINT(x) fixFloat(x)
#elif #keyclass(Double)
#define KEY2LEXINT(x) fixDouble(x)
#else
#define KEY2LEXINT(x) (x)
#endif
#endif
#ifdef Custom
#define KEY2JAVAHASH(x) ( strategy.hashCode(x) )
#define KEY2INTHASH(x) ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( strategy.hashCode(x) ) )
#define KEY2LONGHASH(x) ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( (long)strategy.hashCode(x) ) )
#else
#if #keyclass(Float)
#define KEY2JAVAHASH(x) it.unimi.dsi.fastutil.HashCommon.float2int(x)
#define KEY2INTHASH(x) it.unimi.dsi.fastutil.HashCommon.murmurHash3( it.unimi.dsi.fastutil.HashCommon.float2int(x) )
#define KEY2LONGHASH(x) it.unimi.dsi.fastutil.HashCommon.murmurHash3( (long)it.unimi.dsi.fastutil.HashCommon.float2int(x) )
#elif #keyclass(Double)
#define KEY2JAVAHASH(x) it.unimi.dsi.fastutil.HashCommon.double2int(x)
#define KEY2INTHASH(x) (int)it.unimi.dsi.fastutil.HashCommon.murmurHash3(Double.doubleToRawLongBits(x))
#define KEY2LONGHASH(x) it.unimi.dsi.fastutil.HashCommon.murmurHash3(Double.doubleToRawLongBits(x))
#elif #keyclass(Long)
#define KEY2JAVAHASH(x) it.unimi.dsi.fastutil.HashCommon.long2int(x)
#define KEY2INTHASH(x) (int)it.unimi.dsi.fastutil.HashCommon.murmurHash3(x)
#define KEY2LONGHASH(x) it.unimi.dsi.fastutil.HashCommon.murmurHash3(x)
#elif #keyclass(Boolean)
#define KEY2JAVAHASH(x) ((x) ? 1231 : 1237)
#define KEY2INTHASH(x) ((x) ? 0xfab5368 : 0xcba05e7b)
#define KEY2LONGHASH(x) ((x) ? 0x74a19fc8b6428188L : 0xbaeca2031a4fd9ecL)
#else
#define KEY2JAVAHASH(x) (x)
#define KEY2INTHASH(x) ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( (x) ) )
#define KEY2LONGHASH(x) ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( (long)(x) ) )
#endif
#endif
#endif
/* Object/Reference-only definitions (values) */
#if #valueclass(Object) || #valueclass(Reference)
#define VALUE_OBJ2TYPE(x) (x)
#define VALUE_CLASS2TYPE(x) (x)
#define VALUE2OBJ(x) (x)
#if #valueclass(Object)
#define VALUE2JAVAHASH(x) ( (x) == null ? 0 : (x).hashCode() )
#else
#define VALUE2JAVAHASH(x) ( (x) == null ? 0 : System.identityHashCode(x) )
#endif
#define VALUE_NULL (null)
#define OBJECT_DEFAULT_RETURN_VALUE (this.defRetValue)
#else
/* Primitive-type-only definitions (values) */
#define VALUE_CLASS2TYPE(x) ((x).VALUE_VALUE())
#define VALUE_OBJ2TYPE(x) (VALUE_CLASS2TYPE((VALUE_CLASS)(x)))
#define VALUE2OBJ(x) (VALUE_CLASS.valueOf(x))
#if #valueclass(Float) || #valueclass(Double) || #valueclass(Long)
#define VALUE_NULL (0)
#define VALUE2JAVAHASH(x) it.unimi.dsi.fastutil.HashCommon.float2int(x)
#elif #valueclass(Boolean)
#define VALUE_NULL (false)
#define VALUE2JAVAHASH(x) (x ? 1231 : 1237)
#else
#if #valueclass(Integer)
#define VALUE_NULL (0)
#else
#define VALUE_NULL ((VALUE_TYPE)0)
#endif
#define VALUE2JAVAHASH(x) (x)
#endif
#define OBJECT_DEFAULT_RETURN_VALUE (null)
#endif
#include "drv/OpenCustomHashMap.drv"
|
Java
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>
Class: Selenium::Rake::ServerTask
— Documentation by YARD 0.8.3
</title>
<link rel="stylesheet" href="../../css/style.css" type="text/css" media="screen" charset="utf-8" />
<link rel="stylesheet" href="../../css/common.css" type="text/css" media="screen" charset="utf-8" />
<script type="text/javascript" charset="utf-8">
hasFrames = window.top.frames.main ? true : false;
relpath = '../../';
framesUrl = "../../frames.html#!" + escape(window.location.href);
</script>
<script type="text/javascript" charset="utf-8" src="../../js/jquery.js"></script>
<script type="text/javascript" charset="utf-8" src="../../js/app.js"></script>
</head>
<body>
<div id="header">
<div id="menu">
<a href="../../_index.html">Index (S)</a> »
<span class='title'><span class='object_link'><a href="../../Selenium.html" title="Selenium (module)">Selenium</a></span></span> » <span class='title'><span class='object_link'><a href="../Rake.html" title="Selenium::Rake (module)">Rake</a></span></span>
»
<span class="title">ServerTask</span>
<div class="noframes"><span class="title">(</span><a href="." target="_top">no frames</a><span class="title">)</span></div>
</div>
<div id="search">
<a class="full_list_link" id="class_list_link"
href="../../class_list.html">
Class List
</a>
<a class="full_list_link" id="method_list_link"
href="../../method_list.html">
Method List
</a>
<a class="full_list_link" id="file_list_link"
href="../../file_list.html">
File List
</a>
</div>
<div class="clear"></div>
</div>
<iframe id="search_frame"></iframe>
<div id="content"><h1>Class: Selenium::Rake::ServerTask
</h1>
<dl class="box">
<dt class="r1">Inherits:</dt>
<dd class="r1">
<span class="inheritName">Object</span>
<ul class="fullTree">
<li>Object</li>
<li class="next">Selenium::Rake::ServerTask</li>
</ul>
<a href="#" class="inheritanceTree">show all</a>
</dd>
<dt class="r2">Includes:</dt>
<dd class="r2">Rake::DSL</dd>
<dt class="r1 last">Defined in:</dt>
<dd class="r1 last">rb/lib/selenium/rake/server_task.rb</dd>
</dl>
<div class="clear"></div>
<h2>Overview</h2><div class="docstring">
<div class="discussion">
<p>Defines rake tasks for starting, stopping and restarting the Selenium
server.</p>
<p>Usage:</p>
<pre class="code ruby"><code><span class='id identifier rubyid_require'>require</span> <span class='tstring'><span class='tstring_beg'>'</span><span class='tstring_content'>selenium/rake/server_task</span><span class='tstring_end'>'</span></span>
<span class='const'>Selenium</span><span class='op'>::</span><span class='const'>Rake</span><span class='op'>::</span><span class='const'>ServerTask</span><span class='period'>.</span><span class='id identifier rubyid_new'>new</span> <span class='kw'>do</span> <span class='op'>|</span><span class='id identifier rubyid_t'>t</span><span class='op'>|</span>
<span class='id identifier rubyid_t'>t</span><span class='period'>.</span><span class='id identifier rubyid_jar'>jar</span> <span class='op'>=</span> <span class='tstring'><span class='tstring_beg'>"</span><span class='tstring_content'>/path/to/selenium-server-standalone.jar</span><span class='tstring_end'>"</span></span>
<span class='id identifier rubyid_t'>t</span><span class='period'>.</span><span class='id identifier rubyid_port'>port</span> <span class='op'>=</span> <span class='int'>4444</span>
<span class='id identifier rubyid_t'>t</span><span class='period'>.</span><span class='id identifier rubyid_opts'>opts</span> <span class='op'>=</span> <span class='qwords_beg'>%w[</span><span class='tstring_content'>-some</span><span class='words_sep'> </span><span class='tstring_content'>options</span><span class='words_sep'>]</span>
<span class='kw'>end</span></code></pre>
<p>Alternatively, you can have the task download a specific version of the
server:</p>
<pre class="code ruby"><code><span class='const'>Selenium</span><span class='op'>::</span><span class='const'>Rake</span><span class='op'>::</span><span class='const'>ServerTask</span><span class='period'>.</span><span class='id identifier rubyid_new'>new</span><span class='lparen'>(</span><span class='symbol'>:server</span><span class='rparen'>)</span> <span class='kw'>do</span> <span class='op'>|</span><span class='id identifier rubyid_t'>t</span><span class='op'>|</span>
<span class='id identifier rubyid_t'>t</span><span class='period'>.</span><span class='id identifier rubyid_version'>version</span> <span class='op'>=</span> <span class='tstring'><span class='tstring_beg'>'</span><span class='tstring_content'>2.6.0</span><span class='tstring_end'>'</span></span>
<span class='kw'>end</span></code></pre>
<p>or the latest version</p>
<pre class="code ruby"><code><span class='const'>Selenium</span><span class='op'>::</span><span class='const'>Rake</span><span class='op'>::</span><span class='const'>ServerTask</span><span class='period'>.</span><span class='id identifier rubyid_new'>new</span><span class='lparen'>(</span><span class='symbol'>:server</span><span class='rparen'>)</span> <span class='kw'>do</span> <span class='op'>|</span><span class='id identifier rubyid_t'>t</span><span class='op'>|</span>
<span class='id identifier rubyid_t'>t</span><span class='period'>.</span><span class='id identifier rubyid_version'>version</span> <span class='op'>=</span> <span class='symbol'>:latest</span>
<span class='kw'>end</span></code></pre>
<p>Tasks defined:</p>
<pre class="code ruby"><code>rake selenium:server:start
rake selenium:server:stop
rake selenium:server:restart</code></pre>
</div>
</div>
<div class="tags">
</div>
<h2>Instance Attribute Summary <small>(<a href="#" class="summary_toggle">collapse</a>)</small></h2>
<ul class="summary">
<li class="public ">
<span class="summary_signature">
<a href="#background-instance_method" title="#background (instance method)">- (Object) <strong>background</strong> </a>
(also: #background?)
</span>
<span class="summary_desc"><div class='inline'>
<p>Whether we should detach from the server process.</p>
</div></span>
</li>
<li class="public ">
<span class="summary_signature">
<a href="#jar-instance_method" title="#jar (instance method)">- (Object) <strong>jar</strong> </a>
</span>
<span class="summary_desc"><div class='inline'>
<p>Path to the selenium server jar.</p>
</div></span>
</li>
<li class="public ">
<span class="summary_signature">
<a href="#log-instance_method" title="#log (instance method)">- (Object) <strong>log</strong> </a>
</span>
<span class="summary_desc"><div class='inline'>
<p>Configure logging.</p>
</div></span>
</li>
<li class="public ">
<span class="summary_signature">
<a href="#opts-instance_method" title="#opts (instance method)">- (Object) <strong>opts</strong> </a>
</span>
<span class="summary_desc"><div class='inline'>
<p>Add additional options passed to the server jar.</p>
</div></span>
</li>
<li class="public ">
<span class="summary_signature">
<a href="#port-instance_method" title="#port (instance method)">- (Object) <strong>port</strong> </a>
</span>
<span class="summary_desc"><div class='inline'>
<p>Port to use for the server.</p>
</div></span>
</li>
<li class="public ">
<span class="summary_signature">
<a href="#timeout-instance_method" title="#timeout (instance method)">- (Object) <strong>timeout</strong> </a>
</span>
<span class="summary_desc"><div class='inline'>
<p>Timeout in seconds for the server to start/stop.</p>
</div></span>
</li>
<li class="public ">
<span class="summary_signature">
<a href="#version-instance_method" title="#version (instance method)">- (Object) <strong>version</strong> </a>
</span>
<span class="summary_desc"><div class='inline'>
<p>Specify the version of the server jar to download.</p>
</div></span>
</li>
</ul>
<h2>
Instance Method Summary
<small>(<a href="#" class="summary_toggle">collapse</a>)</small>
</h2>
<ul class="summary">
<li class="public ">
<span class="summary_signature">
<a href="#initialize-instance_method" title="#initialize (instance method)">- (ServerTask) <strong>initialize</strong>(prefix = "selenium:server") {|_self| ... }</a>
</span>
<span class="note title constructor">constructor</span>
<span class="summary_desc"><div class='inline'>
<p>A new instance of ServerTask.</p>
</div></span>
</li>
</ul>
<div id="constructor_details" class="method_details_list">
<h2>Constructor Details</h2>
<div class="method_details first">
<h3 class="signature first" id="initialize-instance_method">
- (<tt><span class='object_link'><a href="" title="Selenium::Rake::ServerTask (class)">ServerTask</a></span></tt>) <strong>initialize</strong>(prefix = "selenium:server") {|_self| ... }
</h3><div class="docstring">
<div class="discussion">
<p>A new instance of ServerTask</p>
</div>
</div>
<div class="tags">
<p class="tag_title">Yields:</p>
<ul class="yield">
<li>
<span class='type'>(<tt>_self</tt>)</span>
</li>
</ul>
<p class="tag_title">Yield Parameters:</p>
<ul class="yieldparam">
<li>
<span class='name'>_self</span>
<span class='type'>(<tt><span class='object_link'><a href="" title="Selenium::Rake::ServerTask (class)">Selenium::Rake::ServerTask</a></span></tt>)</span>
—
<div class='inline'>
<p>the object that the method was called on</p>
</div>
</li>
</ul>
</div><table class="source_code">
<tr>
<td>
<pre class="lines">
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129</pre>
</td>
<td>
<pre class="code"><span class="info file"># File 'rb/lib/selenium/rake/server_task.rb', line 99</span>
<span class='kw'>def</span> <span class='id identifier rubyid_initialize'>initialize</span><span class='lparen'>(</span><span class='id identifier rubyid_prefix'>prefix</span> <span class='op'>=</span> <span class='tstring'><span class='tstring_beg'>"</span><span class='tstring_content'>selenium:server</span><span class='tstring_end'>"</span></span><span class='rparen'>)</span>
<span class='ivar'>@jar</span> <span class='op'>=</span> <span class='kw'>nil</span>
<span class='ivar'>@prefix</span> <span class='op'>=</span> <span class='id identifier rubyid_prefix'>prefix</span>
<span class='ivar'>@port</span> <span class='op'>=</span> <span class='int'>4444</span>
<span class='ivar'>@timeout</span> <span class='op'>=</span> <span class='int'>30</span>
<span class='ivar'>@background</span> <span class='op'>=</span> <span class='kw'>true</span>
<span class='ivar'>@log</span> <span class='op'>=</span> <span class='kw'>true</span>
<span class='ivar'>@opts</span> <span class='op'>=</span> <span class='lbracket'>[</span><span class='rbracket'>]</span>
<span class='ivar'>@version</span> <span class='op'>=</span> <span class='kw'>nil</span>
<span class='kw'>yield</span> <span class='kw'>self</span> <span class='kw'>if</span> <span class='id identifier rubyid_block_given?'>block_given?</span>
<span class='kw'>if</span> <span class='ivar'>@version</span>
<span class='ivar'>@jar</span> <span class='op'>=</span> <span class='const'>Selenium</span><span class='op'>::</span><span class='const'>Server</span><span class='period'>.</span><span class='id identifier rubyid_download'>download</span><span class='lparen'>(</span><span class='ivar'>@version</span><span class='rparen'>)</span>
<span class='kw'>end</span>
<span class='kw'>unless</span> <span class='ivar'>@jar</span>
<span class='id identifier rubyid_raise'>raise</span> <span class='const'>MissingJarFileError</span><span class='comma'>,</span> <span class='tstring'><span class='tstring_beg'>"</span><span class='tstring_content'>must provide path to the selenium server jar</span><span class='tstring_end'>"</span></span>
<span class='kw'>end</span>
<span class='ivar'>@server</span> <span class='op'>=</span> <span class='const'>Selenium</span><span class='op'>::</span><span class='const'>Server</span><span class='period'>.</span><span class='id identifier rubyid_new'>new</span><span class='lparen'>(</span><span class='ivar'>@jar</span><span class='comma'>,</span> <span class='symbol'>:port</span> <span class='op'>=></span> <span class='ivar'>@port</span><span class='comma'>,</span>
<span class='symbol'>:timeout</span> <span class='op'>=></span> <span class='ivar'>@timeout</span><span class='comma'>,</span>
<span class='symbol'>:background</span> <span class='op'>=></span> <span class='ivar'>@background</span><span class='comma'>,</span>
<span class='symbol'>:log</span> <span class='op'>=></span> <span class='ivar'>@log</span> <span class='rparen'>)</span>
<span class='ivar'>@server</span> <span class='op'><<</span> <span class='ivar'>@opts</span>
<span class='id identifier rubyid_define_start_task'>define_start_task</span>
<span class='id identifier rubyid_define_stop_task'>define_stop_task</span>
<span class='id identifier rubyid_define_restart_task'>define_restart_task</span>
<span class='kw'>end</span></pre>
</td>
</tr>
</table>
</div>
</div>
<div id="instance_attr_details" class="attr_details">
<h2>Instance Attribute Details</h2>
<span id="background=-instance_method"></span>
<div class="method_details first">
<h3 class="signature first" id="background-instance_method">
- (<tt>Object</tt>) <strong>background</strong>
<span class="aliases">Also known as:
<span class="names"><span id='background?-instance_method'>background?</span></span>
</span>
</h3><div class="docstring">
<div class="discussion">
<p>Whether we should detach from the server process. Default: true</p>
</div>
</div>
<div class="tags">
</div><table class="source_code">
<tr>
<td>
<pre class="lines">
72
73
74</pre>
</td>
<td>
<pre class="code"><span class="info file"># File 'rb/lib/selenium/rake/server_task.rb', line 72</span>
<span class='kw'>def</span> <span class='id identifier rubyid_background'>background</span>
<span class='ivar'>@background</span>
<span class='kw'>end</span></pre>
</td>
</tr>
</table>
</div>
<span id="jar=-instance_method"></span>
<div class="method_details ">
<h3 class="signature " id="jar-instance_method">
- (<tt>Object</tt>) <strong>jar</strong>
</h3><div class="docstring">
<div class="discussion">
<p>Path to the selenium server jar</p>
</div>
</div>
<div class="tags">
</div><table class="source_code">
<tr>
<td>
<pre class="lines">
50
51
52</pre>
</td>
<td>
<pre class="code"><span class="info file"># File 'rb/lib/selenium/rake/server_task.rb', line 50</span>
<span class='kw'>def</span> <span class='id identifier rubyid_jar'>jar</span>
<span class='ivar'>@jar</span>
<span class='kw'>end</span></pre>
</td>
</tr>
</table>
</div>
<span id="log=-instance_method"></span>
<div class="method_details ">
<h3 class="signature " id="log-instance_method">
- (<tt>Object</tt>) <strong>log</strong>
</h3><div class="docstring">
<div class="discussion">
<p>Configure logging. Pass a log file path or a boolean. Default: true</p>
<p>true - log to stdout/stderr false - no logging String - log to the
specified file</p>
</div>
</div>
<div class="tags">
</div><table class="source_code">
<tr>
<td>
<pre class="lines">
84
85
86</pre>
</td>
<td>
<pre class="code"><span class="info file"># File 'rb/lib/selenium/rake/server_task.rb', line 84</span>
<span class='kw'>def</span> <span class='id identifier rubyid_log'>log</span>
<span class='ivar'>@log</span>
<span class='kw'>end</span></pre>
</td>
</tr>
</table>
</div>
<span id="opts=-instance_method"></span>
<div class="method_details ">
<h3 class="signature " id="opts-instance_method">
- (<tt>Object</tt>) <strong>opts</strong>
</h3><div class="docstring">
<div class="discussion">
<p>Add additional options passed to the server jar.</p>
</div>
</div>
<div class="tags">
</div><table class="source_code">
<tr>
<td>
<pre class="lines">
90
91
92</pre>
</td>
<td>
<pre class="code"><span class="info file"># File 'rb/lib/selenium/rake/server_task.rb', line 90</span>
<span class='kw'>def</span> <span class='id identifier rubyid_opts'>opts</span>
<span class='ivar'>@opts</span>
<span class='kw'>end</span></pre>
</td>
</tr>
</table>
</div>
<span id="port=-instance_method"></span>
<div class="method_details ">
<h3 class="signature " id="port-instance_method">
- (<tt>Object</tt>) <strong>port</strong>
</h3><div class="docstring">
<div class="discussion">
<p>Port to use for the server. Default: 4444</p>
</div>
</div>
<div class="tags">
</div><table class="source_code">
<tr>
<td>
<pre class="lines">
58
59
60</pre>
</td>
<td>
<pre class="code"><span class="info file"># File 'rb/lib/selenium/rake/server_task.rb', line 58</span>
<span class='kw'>def</span> <span class='id identifier rubyid_port'>port</span>
<span class='ivar'>@port</span>
<span class='kw'>end</span></pre>
</td>
</tr>
</table>
</div>
<span id="timeout=-instance_method"></span>
<div class="method_details ">
<h3 class="signature " id="timeout-instance_method">
- (<tt>Object</tt>) <strong>timeout</strong>
</h3><div class="docstring">
<div class="discussion">
<p>Timeout in seconds for the server to start/stop. Default: 30</p>
</div>
</div>
<div class="tags">
</div><table class="source_code">
<tr>
<td>
<pre class="lines">
65
66
67</pre>
</td>
<td>
<pre class="code"><span class="info file"># File 'rb/lib/selenium/rake/server_task.rb', line 65</span>
<span class='kw'>def</span> <span class='id identifier rubyid_timeout'>timeout</span>
<span class='ivar'>@timeout</span>
<span class='kw'>end</span></pre>
</td>
</tr>
</table>
</div>
<span id="version=-instance_method"></span>
<div class="method_details ">
<h3 class="signature " id="version-instance_method">
- (<tt>Object</tt>) <strong>version</strong>
</h3><div class="docstring">
<div class="discussion">
<p>Specify the version of the server jar to download</p>
</div>
</div>
<div class="tags">
</div><table class="source_code">
<tr>
<td>
<pre class="lines">
96
97
98</pre>
</td>
<td>
<pre class="code"><span class="info file"># File 'rb/lib/selenium/rake/server_task.rb', line 96</span>
<span class='kw'>def</span> <span class='id identifier rubyid_version'>version</span>
<span class='ivar'>@version</span>
<span class='kw'>end</span></pre>
</td>
</tr>
</table>
</div>
</div>
</div>
<div id="footer">
Generated on Mon Jan 21 19:22:44 2013 by
<a href="http://yardoc.org" title="Yay! A Ruby Documentation Tool" target="_parent">yard</a>
0.8.3 (ruby-1.9.3).
</div>
</body>
</html>
|
Java
|
package pl.mobilization.conference2015.sponsor;
import android.content.Context;
import android.content.Intent;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.ArrayList;
import java.util.List;
import de.greenrobot.event.EventBus;
import lombok.extern.slf4j.Slf4j;
import pl.mobilization.conference2015.sponsor.events.OnSponsorClickEvent;
import pl.mobilization.conference2015.sponsor.events.SponsorUpdatedEvent;
import pl.mobilization.conference2015.sponsor.repository.SponsorRepoModel;
import pl.mobilization.conference2015.sponsor.repository.SponsorRepository;
import pl.mobilization.conference2015.sponsor.rest.SponsorRestService;
import pl.mobilization.conference2015.sponsor.rest.SponsorListRestModel;
import pl.mobilization.conference2015.sponsor.view.SponsorsView;
import pl.mobilization.conference2015.sponsor.view.SponsorsListViewModel;
import rx.Observable;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.mockito.Mockito.*;
/**
* Created by msaramak on 19.08.15.
*/
@Slf4j
public class SponsorRestModelPresenterTest {
@Mock
SponsorRestService sponsorRestService;
@Mock
EventBus eventBus;
@Mock
SponsorsView view;
@Mock
SponsorRepository sponsorRepository;
@Mock
Context context;
private SponsorPresenter testedSp;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
//GIVEN a sponsor presenter..
testedSp = new SponsorPresenter(sponsorRepository, eventBus);
List<SponsorRepoModel> l = new ArrayList<>();
when(sponsorRepository.getSponsors()).thenReturn(Observable.<List<SponsorRepoModel>>just(l));
}
@After
public void tearDown() throws Exception {
}
@SuppressWarnings("ResourceType")
@Test
public void testOnBindView() throws Exception {
//GIVEN a sponsor presenter
verify(eventBus).register(testedSp);
//WHEN bind view
testedSp.onBindView(context, view);
//THEN check if background service is setup
verify(context).bindService(any(Intent.class), any(), eq(Context.BIND_AUTO_CREATE));
}
@Test
public void shouldDisplayDialogWhenOnSponsorClickEventCalled() throws Exception {
//GIVEN a tested sponsor presenter with binded view
testedSp.onBindView(context, view);
//WHEN event come
OnSponsorClickEvent event = new OnSponsorClickEvent(null);
testedSp.onEvent(event);
//THEN
verify(view).showSponsorDialog(event);
}
@Test
public void testOnUpdateSponsorList() throws Exception {
//GIVEN a tested sponsor presenter with binded view
testedSp.onBindView(context, view);
//WHEN sponsors list is updated
SponsorUpdatedEvent event = new SponsorUpdatedEvent();
testedSp.onEvent(event);
//THEN
verify(view).updateSponsors(any(SponsorsListViewModel.class));
}
}
|
Java
|
package org.liveontologies.protege.justification.proof.preferences;
/*-
* #%L
* Protege Proof Justification
* $Id:$
* $HeadURL:$
* %%
* Copyright (C) 2016 - 2017 Live Ontologies Project
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import org.eclipse.core.runtime.IExtension;
import org.protege.editor.core.editorkit.EditorKit;
import org.protege.editor.core.plugin.AbstractPluginLoader;
public class ProofPreferencesPanelPluginLoader extends AbstractPluginLoader<ProofPreferencesPanelPlugin> {
private final EditorKit kit;
private static final String ID = "JustificationProofPreferences";
private static final String KEY = "org.liveontologies.protege.justification.proof";
public ProofPreferencesPanelPluginLoader(EditorKit kit) {
super(KEY, ID);
this.kit = kit;
}
@Override
protected ProofPreferencesPanelPlugin createInstance(IExtension extension) {
return new ProofPreferencesPanelPlugin(kit, extension);
}
}
|
Java
|
# encoding: utf-8
u'''MCL — Publication Folder'''
from ._base import IIngestableFolder, Ingestor, IngestableFolderView
from .interfaces import IPublication
from five import grok
class IPublicationFolder(IIngestableFolder):
u'''Folder containing publications.'''
class PublicationIngestor(Ingestor):
u'''RDF ingestor for publication.'''
grok.context(IPublicationFolder)
def getContainedObjectInterface(self):
return IPublication
class View(IngestableFolderView):
u'''View for an publication folder'''
grok.context(IPublicationFolder)
|
Java
|
export interface SimpleAPIConfig {
}
export interface SimpleAPI {
count: number;
add(n?: number): void;
sub(n?: number): void;
}
|
Java
|
import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.exterior_equipment import ExteriorFuelEquipment
log = logging.getLogger(__name__)
class TestExteriorFuelEquipment(unittest.TestCase):
def setUp(self):
self.fd, self.path = tempfile.mkstemp()
def tearDown(self):
os.remove(self.path)
def test_create_exteriorfuelequipment(self):
pyidf.validation_level = ValidationLevel.error
obj = ExteriorFuelEquipment()
# alpha
var_name = "Name"
obj.name = var_name
# alpha
var_fuel_use_type = "Electricity"
obj.fuel_use_type = var_fuel_use_type
# object-list
var_schedule_name = "object-list|Schedule Name"
obj.schedule_name = var_schedule_name
# real
var_design_level = 0.0
obj.design_level = var_design_level
# alpha
var_enduse_subcategory = "End-Use Subcategory"
obj.enduse_subcategory = var_enduse_subcategory
idf = IDF()
idf.add(obj)
idf.save(self.path, check=False)
with open(self.path, mode='r') as f:
for line in f:
log.debug(line.strip())
idf2 = IDF(self.path)
self.assertEqual(idf2.exteriorfuelequipments[0].name, var_name)
self.assertEqual(idf2.exteriorfuelequipments[0].fuel_use_type, var_fuel_use_type)
self.assertEqual(idf2.exteriorfuelequipments[0].schedule_name, var_schedule_name)
self.assertAlmostEqual(idf2.exteriorfuelequipments[0].design_level, var_design_level)
self.assertEqual(idf2.exteriorfuelequipments[0].enduse_subcategory, var_enduse_subcategory)
|
Java
|
<ul>
<li ng-repeat="item in $ctrl.items">
{{item.quantity}} of {{item.name}}
</li>
</ul>
|
Java
|
/*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.workdocs.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.workdocs.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.protocol.*;
import com.amazonaws.protocol.Protocol;
import com.amazonaws.annotation.SdkInternalApi;
/**
* DeleteFolderRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class DeleteFolderRequestProtocolMarshaller implements Marshaller<Request<DeleteFolderRequest>, DeleteFolderRequest> {
private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.REST_JSON).requestUri("/api/v1/folders/{FolderId}")
.httpMethodName(HttpMethodName.DELETE).hasExplicitPayloadMember(false).hasPayloadMembers(false).serviceName("AmazonWorkDocs").build();
private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory;
public DeleteFolderRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) {
this.protocolFactory = protocolFactory;
}
public Request<DeleteFolderRequest> marshall(DeleteFolderRequest deleteFolderRequest) {
if (deleteFolderRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
final ProtocolRequestMarshaller<DeleteFolderRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING,
deleteFolderRequest);
protocolMarshaller.startMarshalling();
DeleteFolderRequestMarshaller.getInstance().marshall(deleteFolderRequest, protocolMarshaller);
return protocolMarshaller.finishMarshalling();
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
|
Java
|
# Leucopaxillus spinulosus (Kühner & Romagn.) Konrad & Maubl., 1949 SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Encyclop. Mycol. 14: 409 (1949)
#### Original name
Tricholoma spinulosum Kühner & Romagn., 1947
### Remarks
null
|
Java
|
# Didissandra C.B. Clarke GENUS
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
Java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.