lang
stringclasses 1
value | license
stringclasses 13
values | stderr
stringlengths 0
350
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 7
45.1k
| new_contents
stringlengths 0
1.87M
| new_file
stringlengths 6
292
| old_contents
stringlengths 0
1.87M
| message
stringlengths 6
9.26k
| old_file
stringlengths 6
292
| subject
stringlengths 0
4.45k
|
|---|---|---|---|---|---|---|---|---|---|---|---|
Java
|
apache-2.0
|
151da0aa757a3e24f99ea353c368ef60e8d854a2
| 0
|
c0state/udacity-nanodegree-androiddeveloper-sunshine
|
package com.example.android.sunshine.app;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.text.format.Time;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
/**
* A fragment containing the weather forecast.
*/
public class ForecastFragment extends Fragment {
private ArrayAdapter<String> forecastAdapter;
public ForecastFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
setHasOptionsMenu(true);
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_main, container, false);
final FetchWeatherTask weatherTask = new FetchWeatherTask();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.getContext());
weatherTask.execute(prefs.getString(getString(R.string.pref_key), ""));
forecastAdapter = new ArrayAdapter<>(getActivity(),
R.layout.list_item_forecast, R.id.list_item_forecast_textview,
new ArrayList<String>());
ListView forecastListView = (ListView)rootView.findViewById(R.id.listview_forecast);
forecastListView.setAdapter(forecastAdapter);
forecastListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String weatherText = forecastAdapter.getItem(position).toString();
Intent detailForecastIntent = new Intent(
view.getContext(), DetailActivity.class)
.putExtra(DetailActivity.PlaceholderFragment.FORECAST_TEXT,
weatherText);
startActivity(detailForecastIntent);
}
});
return rootView;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.refresh, menu);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_refresh) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.getContext());
new FetchWeatherTask().execute(prefs.getString(getString(R.string.pref_key), ""));
return true;
}
return super.onOptionsItemSelected(item);
}
public class FetchWeatherTask extends AsyncTask<String, Void, String[]> {
@Override
protected String[] doInBackground(String... postalCodes) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String forecastJsonStr = null;
try {
// Construct the URL for the OpenWeatherMap query
// Possible parameters are avaiable at OWM's forecast API page, at
// http://openweathermap.org/API#forecast
Uri.Builder builder = new Uri.Builder();
builder.scheme("http")
.authority("api.openweathermap.org")
.appendPath("data")
.appendPath("2.5")
.appendPath("forecast")
.appendPath("daily")
.appendQueryParameter("appid", BuildConfig.MyOpenWeatherMapApiKey)
.appendQueryParameter("q", postalCodes[0])
.appendQueryParameter("cnt", "7")
.appendQueryParameter("units", "metric")
.appendQueryParameter("mode", "json");
String getWeatherForecastUrl = builder.build().toString();
URL url = new URL(getWeatherForecastUrl);
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
forecastJsonStr = buffer.toString();
return getWeatherDataFromJson(forecastJsonStr, 7);
} catch (IOException e) {
Log.e("ForecastFragment", "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
} catch (JSONException e) {
Log.e("ForecastFragment", "Error ", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("ForecastFragment", "Error closing stream", e);
}
}
}
return null;
}
@Override
protected void onPostExecute(String[] weekForecast) {
forecastAdapter.clear();
forecastAdapter.addAll(weekForecast);
}
/* The date/time conversion code is going to be moved outside the asynctask later,
* so for convenience we're breaking it out into its own method now.
*/
private String getReadableDateString(long time){
// Because the API returns a unix timestamp (measured in seconds),
// it must be converted to milliseconds in order to be converted to valid date.
SimpleDateFormat shortenedDateFormat = new SimpleDateFormat("EEE MMM dd");
return shortenedDateFormat.format(time);
}
/**
* Prepare the weather high/lows for presentation.
*/
private String formatHighLows(double high, double low) {
// For presentation, assume the user doesn't care about tenths of a degree.
long roundedHigh = Math.round(high);
long roundedLow = Math.round(low);
String highLowStr = roundedHigh + "/" + roundedLow;
return highLowStr;
}
/**
* Take the String representing the complete forecast in JSON Format and
* pull out the data we need to construct the Strings needed for the wireframes.
*
* Fortunately parsing is easy: constructor takes the JSON string and converts it
* into an Object hierarchy for us.
*/
private String[] getWeatherDataFromJson(String forecastJsonStr, int numDays)
throws JSONException {
// These are the names of the JSON objects that need to be extracted.
final String OWM_LIST = "list";
final String OWM_WEATHER = "weather";
final String OWM_TEMPERATURE = "temp";
final String OWM_MAX = "max";
final String OWM_MIN = "min";
final String OWM_DESCRIPTION = "main";
JSONObject forecastJson = new JSONObject(forecastJsonStr);
JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);
// OWM returns daily forecasts based upon the local time of the city that is being
// asked for, which means that we need to know the GMT offset to translate this data
// properly.
// Since this data is also sent in-order and the first day is always the
// current day, we're going to take advantage of that to get a nice
// normalized UTC date for all of our weather.
Time dayTime = new Time();
dayTime.setToNow();
// we start at the day returned by local time. Otherwise this is a mess.
int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);
// now we work exclusively in UTC
dayTime = new Time();
String[] resultStrs = new String[numDays];
for(int i = 0; i < weatherArray.length(); i++) {
// For now, using the format "Day, description, hi/low"
String day;
String description;
String highAndLow;
// Get the JSON object representing the day
JSONObject dayForecast = weatherArray.getJSONObject(i);
// The date/time is returned as a long. We need to convert that
// into something human-readable, since most people won't read "1400356800" as
// "this saturday".
long dateTime;
// Cheating to convert this to UTC time, which is what we want anyhow
dateTime = dayTime.setJulianDay(julianStartDay+i);
day = getReadableDateString(dateTime);
// description is in a child array called "weather", which is 1 element long.
JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
description = weatherObject.getString(OWM_DESCRIPTION);
// Temperatures are in a child object called "temp". Try not to name variables
// "temp" when working with temperature. It confuses everybody.
JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
double high = temperatureObject.getDouble(OWM_MAX);
double low = temperatureObject.getDouble(OWM_MIN);
highAndLow = formatHighLows(high, low);
resultStrs[i] = day + " - " + description + " - " + highAndLow;
}
return resultStrs;
}
}
}
|
app/src/main/java/com/example/android/sunshine/app/ForecastFragment.java
|
package com.example.android.sunshine.app;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.format.Time;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
/**
* A fragment containing the weather forecast.
*/
public class ForecastFragment extends Fragment {
private final String LOC_POSTAL_CODE = "10003,us";
private ArrayAdapter<String> forecastAdapter;
public ForecastFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
setHasOptionsMenu(true);
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_main, container, false);
final FetchWeatherTask weatherTask = new FetchWeatherTask();
weatherTask.execute(LOC_POSTAL_CODE);
forecastAdapter = new ArrayAdapter<>(getActivity(),
R.layout.list_item_forecast, R.id.list_item_forecast_textview,
new ArrayList<String>());
ListView forecastListView = (ListView)rootView.findViewById(R.id.listview_forecast);
forecastListView.setAdapter(forecastAdapter);
forecastListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String weatherText = forecastAdapter.getItem(position).toString();
Intent detailForecastIntent = new Intent(
view.getContext(), DetailActivity.class)
.putExtra(DetailActivity.PlaceholderFragment.FORECAST_TEXT,
weatherText);
startActivity(detailForecastIntent);
}
});
return rootView;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.refresh, menu);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_refresh) {
new FetchWeatherTask().execute(LOC_POSTAL_CODE);
return true;
}
return super.onOptionsItemSelected(item);
}
public class FetchWeatherTask extends AsyncTask<String, Void, String[]> {
@Override
protected String[] doInBackground(String... postalCodes) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String forecastJsonStr = null;
try {
// Construct the URL for the OpenWeatherMap query
// Possible parameters are avaiable at OWM's forecast API page, at
// http://openweathermap.org/API#forecast
Uri.Builder builder = new Uri.Builder();
builder.scheme("http")
.authority("api.openweathermap.org")
.appendPath("data")
.appendPath("2.5")
.appendPath("forecast")
.appendPath("daily")
.appendQueryParameter("appid", BuildConfig.MyOpenWeatherMapApiKey)
.appendQueryParameter("q", postalCodes[0])
.appendQueryParameter("cnt", "7")
.appendQueryParameter("units", "metric")
.appendQueryParameter("mode", "json");
String getWeatherForecastUrl = builder.build().toString();
URL url = new URL(getWeatherForecastUrl);
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
forecastJsonStr = buffer.toString();
return getWeatherDataFromJson(forecastJsonStr, 7);
} catch (IOException e) {
Log.e("ForecastFragment", "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
} catch (JSONException e) {
Log.e("ForecastFragment", "Error ", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("ForecastFragment", "Error closing stream", e);
}
}
}
return null;
}
@Override
protected void onPostExecute(String[] weekForecast) {
forecastAdapter.clear();
forecastAdapter.addAll(weekForecast);
}
/* The date/time conversion code is going to be moved outside the asynctask later,
* so for convenience we're breaking it out into its own method now.
*/
private String getReadableDateString(long time){
// Because the API returns a unix timestamp (measured in seconds),
// it must be converted to milliseconds in order to be converted to valid date.
SimpleDateFormat shortenedDateFormat = new SimpleDateFormat("EEE MMM dd");
return shortenedDateFormat.format(time);
}
/**
* Prepare the weather high/lows for presentation.
*/
private String formatHighLows(double high, double low) {
// For presentation, assume the user doesn't care about tenths of a degree.
long roundedHigh = Math.round(high);
long roundedLow = Math.round(low);
String highLowStr = roundedHigh + "/" + roundedLow;
return highLowStr;
}
/**
* Take the String representing the complete forecast in JSON Format and
* pull out the data we need to construct the Strings needed for the wireframes.
*
* Fortunately parsing is easy: constructor takes the JSON string and converts it
* into an Object hierarchy for us.
*/
private String[] getWeatherDataFromJson(String forecastJsonStr, int numDays)
throws JSONException {
// These are the names of the JSON objects that need to be extracted.
final String OWM_LIST = "list";
final String OWM_WEATHER = "weather";
final String OWM_TEMPERATURE = "temp";
final String OWM_MAX = "max";
final String OWM_MIN = "min";
final String OWM_DESCRIPTION = "main";
JSONObject forecastJson = new JSONObject(forecastJsonStr);
JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);
// OWM returns daily forecasts based upon the local time of the city that is being
// asked for, which means that we need to know the GMT offset to translate this data
// properly.
// Since this data is also sent in-order and the first day is always the
// current day, we're going to take advantage of that to get a nice
// normalized UTC date for all of our weather.
Time dayTime = new Time();
dayTime.setToNow();
// we start at the day returned by local time. Otherwise this is a mess.
int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);
// now we work exclusively in UTC
dayTime = new Time();
String[] resultStrs = new String[numDays];
for(int i = 0; i < weatherArray.length(); i++) {
// For now, using the format "Day, description, hi/low"
String day;
String description;
String highAndLow;
// Get the JSON object representing the day
JSONObject dayForecast = weatherArray.getJSONObject(i);
// The date/time is returned as a long. We need to convert that
// into something human-readable, since most people won't read "1400356800" as
// "this saturday".
long dateTime;
// Cheating to convert this to UTC time, which is what we want anyhow
dateTime = dayTime.setJulianDay(julianStartDay+i);
day = getReadableDateString(dateTime);
// description is in a child array called "weather", which is 1 element long.
JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
description = weatherObject.getString(OWM_DESCRIPTION);
// Temperatures are in a child object called "temp". Try not to name variables
// "temp" when working with temperature. It confuses everybody.
JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
double high = temperatureObject.getDouble(OWM_MAX);
double low = temperatureObject.getDouble(OWM_MIN);
highAndLow = formatHighLows(high, low);
resultStrs[i] = day + " - " + description + " - " + highAndLow;
}
return resultStrs;
}
}
}
|
Read location code from preferences
|
app/src/main/java/com/example/android/sunshine/app/ForecastFragment.java
|
Read location code from preferences
|
|
Java
|
apache-2.0
|
3a538faf0f3bae145ec03ead702db0dfb02ea577
| 0
|
apache/accumulo,milleruntime/accumulo,keith-turner/accumulo,milleruntime/accumulo,keith-turner/accumulo,ctubbsii/accumulo,apache/accumulo,phrocker/accumulo-1,keith-turner/accumulo,milleruntime/accumulo,keith-turner/accumulo,ivakegg/accumulo,milleruntime/accumulo,keith-turner/accumulo,keith-turner/accumulo,apache/accumulo,phrocker/accumulo-1,mjwall/accumulo,mjwall/accumulo,mjwall/accumulo,milleruntime/accumulo,ctubbsii/accumulo,apache/accumulo,ivakegg/accumulo,ctubbsii/accumulo,phrocker/accumulo-1,ivakegg/accumulo,ctubbsii/accumulo,apache/accumulo,ctubbsii/accumulo,phrocker/accumulo-1,milleruntime/accumulo,ivakegg/accumulo,ctubbsii/accumulo,mjwall/accumulo,phrocker/accumulo-1,phrocker/accumulo-1,mjwall/accumulo,phrocker/accumulo-1,mjwall/accumulo,ctubbsii/accumulo,ivakegg/accumulo,ivakegg/accumulo,mjwall/accumulo,keith-turner/accumulo,ivakegg/accumulo,apache/accumulo,milleruntime/accumulo,apache/accumulo
|
/*
* 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.accumulo.test;
import static org.junit.Assert.assertEquals;
import org.apache.accumulo.core.client.Connector;
import org.apache.accumulo.core.conf.Property;
import org.apache.accumulo.core.metadata.MetadataTable;
import org.apache.accumulo.core.security.Authorizations;
import org.apache.accumulo.fate.util.UtilWaitThread;
import org.apache.accumulo.minicluster.ServerType;
import org.apache.accumulo.minicluster.impl.MiniAccumuloClusterImpl;
import org.apache.accumulo.minicluster.impl.MiniAccumuloConfigImpl;
import org.apache.accumulo.test.functional.ConfigurableMacBase;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.LocatedFileStatus;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.RawLocalFileSystem;
import org.apache.hadoop.fs.RemoteIterator;
import org.junit.Test;
import com.google.common.collect.Iterators;
public class GarbageCollectWALIT extends ConfigurableMacBase {
@Override
protected void configure(MiniAccumuloConfigImpl cfg, Configuration hadoopCoreSite) {
cfg.setProperty(Property.INSTANCE_ZK_HOST, "5s");
cfg.setProperty(Property.GC_CYCLE_START, "1s");
cfg.setProperty(Property.GC_CYCLE_DELAY, "1s");
cfg.setNumTservers(1);
hadoopCoreSite.set("fs.file.impl", RawLocalFileSystem.class.getName());
}
@Test(timeout = 3 * 60 * 1000)
public void test() throws Exception {
// not yet, please
String tableName = getUniqueNames(1)[0];
cluster.getClusterControl().stop(ServerType.GARBAGE_COLLECTOR);
Connector c = getConnector();
c.tableOperations().create(tableName);
// count the number of WALs in the filesystem
assertEquals(2, countWALsInFS(cluster));
cluster.getClusterControl().stop(ServerType.TABLET_SERVER);
cluster.getClusterControl().start(ServerType.GARBAGE_COLLECTOR);
cluster.getClusterControl().start(ServerType.TABLET_SERVER);
Iterators.size(c.createScanner(MetadataTable.NAME, Authorizations.EMPTY).iterator());
// let GC run
UtilWaitThread.sleep(3 * 5 * 1000);
assertEquals(2, countWALsInFS(cluster));
}
private int countWALsInFS(MiniAccumuloClusterImpl cluster) throws Exception {
FileSystem fs = cluster.getFileSystem();
RemoteIterator<LocatedFileStatus> iterator =
fs.listFiles(new Path(cluster.getConfig().getAccumuloDir() + "/wal"), true);
int result = 0;
while (iterator.hasNext()) {
LocatedFileStatus next = iterator.next();
if (!next.isDirectory()) {
result++;
}
}
return result;
}
}
|
test/src/main/java/org/apache/accumulo/test/GarbageCollectWALIT.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.accumulo.test;
import static org.junit.Assert.assertEquals;
import org.apache.accumulo.core.client.Connector;
import org.apache.accumulo.core.conf.Property;
import org.apache.accumulo.core.metadata.MetadataTable;
import org.apache.accumulo.core.security.Authorizations;
import org.apache.accumulo.fate.util.UtilWaitThread;
import org.apache.accumulo.minicluster.ServerType;
import org.apache.accumulo.minicluster.impl.MiniAccumuloClusterImpl;
import org.apache.accumulo.minicluster.impl.MiniAccumuloConfigImpl;
import org.apache.accumulo.test.functional.ConfigurableMacBase;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.LocatedFileStatus;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.RawLocalFileSystem;
import org.apache.hadoop.fs.RemoteIterator;
import org.junit.Test;
import com.google.common.collect.Iterators;
public class GarbageCollectWALIT extends ConfigurableMacBase {
@Override
protected void configure(MiniAccumuloConfigImpl cfg, Configuration hadoopCoreSite) {
cfg.setProperty(Property.INSTANCE_ZK_HOST, "5s");
cfg.setProperty(Property.GC_CYCLE_START, "1s");
cfg.setProperty(Property.GC_CYCLE_DELAY, "1s");
cfg.setNumTservers(1);
hadoopCoreSite.set("fs.file.impl", RawLocalFileSystem.class.getName());
}
@Test(timeout = 2 * 60 * 1000)
public void test() throws Exception {
// not yet, please
String tableName = getUniqueNames(1)[0];
cluster.getClusterControl().stop(ServerType.GARBAGE_COLLECTOR);
Connector c = getConnector();
c.tableOperations().create(tableName);
// count the number of WALs in the filesystem
assertEquals(2, countWALsInFS(cluster));
cluster.getClusterControl().stop(ServerType.TABLET_SERVER);
cluster.getClusterControl().start(ServerType.GARBAGE_COLLECTOR);
cluster.getClusterControl().start(ServerType.TABLET_SERVER);
Iterators.size(c.createScanner(MetadataTable.NAME, Authorizations.EMPTY).iterator());
// let GC run
UtilWaitThread.sleep(3 * 5 * 1000);
assertEquals(2, countWALsInFS(cluster));
}
private int countWALsInFS(MiniAccumuloClusterImpl cluster) throws Exception {
FileSystem fs = cluster.getFileSystem();
RemoteIterator<LocatedFileStatus> iterator =
fs.listFiles(new Path(cluster.getConfig().getAccumuloDir() + "/wal"), true);
int result = 0;
while (iterator.hasNext()) {
LocatedFileStatus next = iterator.next();
if (!next.isDirectory()) {
result++;
}
}
return result;
}
}
|
Increase timeout for GarbageCollectWALIT to allow recovery
|
test/src/main/java/org/apache/accumulo/test/GarbageCollectWALIT.java
|
Increase timeout for GarbageCollectWALIT to allow recovery
|
|
Java
|
apache-2.0
|
71b39c2b61c6c3544c21e5442de682af7710ab64
| 0
|
rohanoid5/Yaadafy
|
app/java/com/example/user/yaadafy/appIntro/OnBoardScreenActivity.java
|
package com.example.user.yaadafy.appIntro;
import android.content.Intent;
import android.os.Bundle;
import com.example.user.yaadafy.users.Login;
import com.github.paolorotolo.appintro.AppIntro2;
/**
* Created by USER on 2/19/2016.
*/
public class OnBoardScreenActivity extends AppIntro2 {
@Override
public void init(Bundle savedInstanceState) {
ReminderIntro reminderIntro = new ReminderIntro();
AddFriendIntro addFriendIntro = new AddFriendIntro();
ShareReminderIntro shareReminderIntro = new ShareReminderIntro();
addSlide(reminderIntro);
addSlide(addFriendIntro);
addSlide(shareReminderIntro);
showStatusBar(false);
}
@Override
public void onDonePressed() {
loadMainActivity();
}
@Override
public void onNextPressed() {
}
@Override
public void onSlideChanged() {
}
private void loadMainActivity(){
Intent i = new Intent(this, Login.class);
startActivity(i);
}
}
|
Delete OnBoardScreenActivity.java
|
app/java/com/example/user/yaadafy/appIntro/OnBoardScreenActivity.java
|
Delete OnBoardScreenActivity.java
|
||
Java
|
apache-2.0
|
f7c4b2fb9d2604360d4ad6ac96bf48242fd52f82
| 0
|
mrenou/jacksonatic
|
src/main/java/com/fasterxml/jackson/databind/introspect/AnnotatedClassUpdater.java
|
/**
* Copyright (C) 2015 Morgan Renou (mrenou@gmail.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fasterxml.jackson.databind.introspect;
import org.jacksonatic.internal.mapping.ClassBuilderMapping;
import java.util.List;
import java.util.stream.IntStream;
public class AnnotatedClassUpdater {
public static void setConstructors(AnnotatedClass annotatedClass, List<AnnotatedConstructor> annotatedConstructors) {
annotatedClass._constructors = annotatedConstructors;
}
public static void setCreatorMethods(AnnotatedClass annotatedClass, List<AnnotatedMethod> annotatedConstructors) {
annotatedClass._creatorMethods = annotatedConstructors;
}
public static void setCreatorMethods(AnnotatedClass annotatedClass, ClassBuilderMapping classBuilderMapping) {
AnnotatedMethod staticFactoryMethod = annotatedClass.getStaticMethods().stream()
.filter(method -> method.getMember() == classBuilderMapping.getStaticFactory())
.findFirst()
.get();
classBuilderMapping.getAnnotations().values().stream().forEach(annotation -> staticFactoryMethod.addOrOverride(annotation));
IntStream.range(0, classBuilderMapping.getParametersMapping().size())
.forEach(index -> classBuilderMapping.getParametersMapping().get(index).getAnnotations().values().stream()
.forEach(annotation -> staticFactoryMethod.addOrOverrideParam(index, annotation)));
}
public static void setFields(AnnotatedClass annotatedClass, List<AnnotatedField> annotatedFields) {
annotatedClass._fields = annotatedFields;
}
}
|
refactor: remove unused jackson class override
|
src/main/java/com/fasterxml/jackson/databind/introspect/AnnotatedClassUpdater.java
|
refactor: remove unused jackson class override
|
||
Java
|
mit
|
33671f9af0dc8248eb75eb28fbcad0334417ea37
| 0
|
InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service
|
package org.innovateuk.ifs.application.summary.controller;
import org.innovateuk.ifs.application.forms.form.InterviewResponseForm;
import org.innovateuk.ifs.application.resource.ApplicationResource;
import org.innovateuk.ifs.application.service.ApplicationService;
import org.innovateuk.ifs.application.summary.populator.ApplicationSummaryViewModelPopulator;
import org.innovateuk.ifs.async.annotations.AsyncMethod;
import org.innovateuk.ifs.commons.rest.RestResult;
import org.innovateuk.ifs.commons.security.SecuredBySpring;
import org.innovateuk.ifs.competition.resource.CompetitionResource;
import org.innovateuk.ifs.competition.service.CompetitionRestService;
import org.innovateuk.ifs.controller.ValidationHandler;
import org.innovateuk.ifs.granttransfer.service.EuGrantTransferRestService;
import org.innovateuk.ifs.interview.service.InterviewAssignmentRestService;
import org.innovateuk.ifs.interview.service.InterviewResponseRestService;
import org.innovateuk.ifs.user.resource.UserResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.function.Supplier;
import static org.innovateuk.ifs.commons.rest.RestFailure.error;
import static org.innovateuk.ifs.controller.FileUploadControllerUtils.getMultipartFileBytes;
import static org.innovateuk.ifs.file.controller.FileDownloadControllerUtils.getFileResponseEntity;
import static org.innovateuk.ifs.util.CollectionFunctions.removeDuplicates;
/**
* This controller will handle all requests that are related to the application summary.
*/
@Controller
@RequestMapping("/application")
public class ApplicationSummaryController {
@Autowired
private ApplicationService applicationService;
@Autowired
private CompetitionRestService competitionRestService;
@Autowired
private InterviewAssignmentRestService interviewAssignmentRestService;
@Autowired
private InterviewResponseRestService interviewResponseRestService;
@Autowired
private ApplicationSummaryViewModelPopulator applicationSummaryViewModelPopulator;
@Autowired
private EuGrantTransferRestService euGrantTransferRestService;
@SecuredBySpring(value = "READ", description = "Applicants, monitoring officers and kta have permission to view the application summary page")
@PreAuthorize("hasAnyAuthority('applicant', 'assessor', 'monitoring_officer', 'knowledge_transfer_adviser')")
@GetMapping("/{applicationId}/summary")
@AsyncMethod
public String applicationSummary(@ModelAttribute("interviewResponseForm") InterviewResponseForm interviewResponseForm,
BindingResult bindingResult,
ValidationHandler validationHandler,
Model model,
@PathVariable("applicationId") long applicationId,
UserResource user) {
ApplicationResource application = applicationService.getById(applicationId);
CompetitionResource competition = competitionRestService.getCompetitionById(application.getCompetition()).getSuccess();
model.addAttribute("model", applicationSummaryViewModelPopulator.populate(application, competition, user));
return "application-summary";
}
@SecuredBySpring(value = "READ", description = "Applicants, support staff, innovation leads and stakeholders have permission to view the horizon 2020 grant agreement")
@PreAuthorize("hasAnyAuthority('applicant', 'support', 'innovation_lead', 'stakeholder', 'comp_admin', 'project_finance')")
@GetMapping("/{applicationId}/grant-agreement")
public @ResponseBody
ResponseEntity<ByteArrayResource> downloadGrantAgreement(@PathVariable long applicationId) {
return getFileResponseEntity(euGrantTransferRestService.downloadGrantAgreement(applicationId).getSuccess(),
euGrantTransferRestService.findGrantAgreement(applicationId).getSuccess());
}
@SecuredBySpring(value = "READ", description = "Applicants have permission to upload interview feedback.")
@PreAuthorize("hasAuthority('applicant')")
@PostMapping(value = "/{applicationId}/summary",params = "uploadResponse")
public String uploadResponse(@ModelAttribute("interviewResponseForm") InterviewResponseForm form,
BindingResult bindingResult,
ValidationHandler validationHandler,
Model model,
@PathVariable("applicationId") long applicationId,
UserResource user) {
System.out.println("say whaaat?");
Supplier<String> failureAndSuccessView = () -> applicationSummary(form, bindingResult, validationHandler, model, applicationId, user);
MultipartFile file = form.getResponse();
return validationHandler.performFileUpload("response", failureAndSuccessView, () -> interviewResponseRestService
.uploadResponse(applicationId, file.getContentType(), file.getSize(), file.getOriginalFilename(), getMultipartFileBytes(file)));
}
@SecuredBySpring(value = "READ", description = "Applicants have permission to remove interview feedback.")
@PreAuthorize("hasAuthority('applicant')")
@PostMapping(value = "/{applicationId}/summary", params = "removeResponse")
public String removeResponse(@ModelAttribute("interviewResponseForm") InterviewResponseForm interviewResponseForm,
BindingResult bindingResult,
ValidationHandler validationHandler,
Model model,
@PathVariable("applicationId") long applicationId,
UserResource user) {
Supplier<String> failureAndSuccessView = () -> applicationSummary(interviewResponseForm, bindingResult, validationHandler, model, applicationId, user);
RestResult<Void> sendResult = interviewResponseRestService
.deleteResponse(applicationId);
return validationHandler.addAnyErrors(error(removeDuplicates(sendResult.getErrors())))
.failNowOrSucceedWith(failureAndSuccessView, failureAndSuccessView);
}
@GetMapping("/{applicationId}/summary/download-response")
@SecuredBySpring(value = "READ", description = "Applicants, support staff, innovation leads, stakeholders, comp admins and project finance users have permission to view uploaded interview feedback.")
@PreAuthorize("hasAnyAuthority('applicant', 'assessor', 'comp_admin', 'project_finance', 'innovation_lead', 'stakeholder')")
public @ResponseBody
ResponseEntity<ByteArrayResource> downloadResponse(Model model,
@PathVariable("applicationId") long applicationId) {
return getFileResponseEntity(interviewResponseRestService.downloadResponse(applicationId).getSuccess(),
interviewResponseRestService.findResponse(applicationId).getSuccess());
}
@GetMapping("/{applicationId}/summary/download-feedback")
@SecuredBySpring(value = "READ", description = "Applicants, support staff, innovation leads, stakeholders, comp admins and project finance users have permission to view uploaded interview feedback.")
@PreAuthorize("hasAnyAuthority('applicant', 'assessor', 'comp_admin', 'project_finance', 'innovation_lead', 'stakeholder')")
public @ResponseBody
ResponseEntity<ByteArrayResource> downloadFeedback(Model model,
@PathVariable("applicationId") long applicationId) {
return getFileResponseEntity(interviewAssignmentRestService.downloadFeedback(applicationId).getSuccess(),
interviewAssignmentRestService.findFeedback(applicationId).getSuccess());
}
}
|
ifs-web-service/ifs-application-service/src/main/java/org/innovateuk/ifs/application/summary/controller/ApplicationSummaryController.java
|
package org.innovateuk.ifs.application.summary.controller;
import org.innovateuk.ifs.application.forms.form.InterviewResponseForm;
import org.innovateuk.ifs.application.resource.ApplicationResource;
import org.innovateuk.ifs.application.service.ApplicationService;
import org.innovateuk.ifs.application.summary.populator.ApplicationSummaryViewModelPopulator;
import org.innovateuk.ifs.async.annotations.AsyncMethod;
import org.innovateuk.ifs.commons.rest.RestResult;
import org.innovateuk.ifs.commons.security.SecuredBySpring;
import org.innovateuk.ifs.competition.resource.CompetitionResource;
import org.innovateuk.ifs.competition.service.CompetitionRestService;
import org.innovateuk.ifs.controller.ValidationHandler;
import org.innovateuk.ifs.granttransfer.service.EuGrantTransferRestService;
import org.innovateuk.ifs.interview.service.InterviewAssignmentRestService;
import org.innovateuk.ifs.interview.service.InterviewResponseRestService;
import org.innovateuk.ifs.user.resource.UserResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.function.Supplier;
import static org.innovateuk.ifs.commons.rest.RestFailure.error;
import static org.innovateuk.ifs.controller.FileUploadControllerUtils.getMultipartFileBytes;
import static org.innovateuk.ifs.file.controller.FileDownloadControllerUtils.getFileResponseEntity;
import static org.innovateuk.ifs.util.CollectionFunctions.removeDuplicates;
/**
* This controller will handle all requests that are related to the application summary.
*/
@Controller
@RequestMapping("/application")
public class ApplicationSummaryController {
@Autowired
private ApplicationService applicationService;
@Autowired
private CompetitionRestService competitionRestService;
@Autowired
private InterviewAssignmentRestService interviewAssignmentRestService;
@Autowired
private InterviewResponseRestService interviewResponseRestService;
@Autowired
private ApplicationSummaryViewModelPopulator applicationSummaryViewModelPopulator;
@Autowired
private EuGrantTransferRestService euGrantTransferRestService;
@SecuredBySpring(value = "READ", description = "Applicants, monitoring officers and kta have permission to view the application summary page")
@PreAuthorize("hasAnyAuthority('applicant', 'assessor', 'monitoring_officer', 'knowledge_transfer_adviser')")
@GetMapping("/{applicationId}/summary")
@AsyncMethod
public String applicationSummary(@ModelAttribute("interviewResponseForm") InterviewResponseForm interviewResponseForm,
BindingResult bindingResult,
ValidationHandler validationHandler,
Model model,
@PathVariable("applicationId") long applicationId,
UserResource user) {
ApplicationResource application = applicationService.getById(applicationId);
CompetitionResource competition = competitionRestService.getCompetitionById(application.getCompetition()).getSuccess();
model.addAttribute("model", applicationSummaryViewModelPopulator.populate(application, competition, user));
return "application-summary";
}
@SecuredBySpring(value = "READ", description = "Applicants, support staff, innovation leads and stakeholders have permission to view the horizon 2020 grant agreement")
@PreAuthorize("hasAnyAuthority('applicant', 'support', 'innovation_lead', 'stakeholder', 'comp_admin', 'project_finance')")
@GetMapping("/{applicationId}/grant-agreement")
public @ResponseBody
ResponseEntity<ByteArrayResource> downloadGrantAgreement(@PathVariable long applicationId) {
return getFileResponseEntity(euGrantTransferRestService.downloadGrantAgreement(applicationId).getSuccess(),
euGrantTransferRestService.findGrantAgreement(applicationId).getSuccess());
}
@SecuredBySpring(value = "READ", description = "Applicants have permission to upload interview feedback.")
@PreAuthorize("hasAuthority('applicant')")
@PostMapping(value = "/{applicationId}/summary",params = "uploadResponse")
public String uploadResponse(@ModelAttribute("interviewResponseForm") InterviewResponseForm form,
BindingResult bindingResult,
ValidationHandler validationHandler,
Model model,
@PathVariable("applicationId") long applicationId,
UserResource user) {
System.out.println("say whaaat?");
Supplier<String> failureAndSuccessView = () -> applicationSummary(form, bindingResult, validationHandler, model, applicationId, user);
MultipartFile file = form.getResponse();
return validationHandler.performFileUpload("response", failureAndSuccessView, () -> interviewResponseRestService
.uploadResponse(applicationId, file.getContentType(), file.getSize(), file.getOriginalFilename(), getMultipartFileBytes(file)));
}
@SecuredBySpring(value = "READ", description = "Applicants have permission to remove interview feedback.")
@PreAuthorize("hasAuthority('applicant')")
@PostMapping(value = "/{applicationId}/summary", params = "removeResponse")
public String removeResponse(@ModelAttribute("interviewResponseForm") InterviewResponseForm interviewResponseForm,
BindingResult bindingResult,
ValidationHandler validationHandler,
Model model,
@PathVariable("applicationId") long applicationId,
UserResource user) {
Supplier<String> failureAndSuccessView = () -> applicationSummary(interviewResponseForm, bindingResult, validationHandler, model, applicationId, user);
RestResult<Void> sendResult = interviewResponseRestService
.deleteResponse(applicationId);
return validationHandler.addAnyErrors(error(removeDuplicates(sendResult.getErrors())))
.failNowOrSucceedWith(failureAndSuccessView, failureAndSuccessView);
}
@GetMapping("/{applicationId}/summary/download-response")
@SecuredBySpring(value = "READ", description = "Applicants, support staff, innovation leads, stakeholders, comp admins and project finance users have permission to view uploaded interview feedback.")
@PreAuthorize("hasAnyAuthority('applicant', 'assessor', 'comp_admin', 'project_finance', 'innovation_lead', 'stakeholder')")
public @ResponseBody
ResponseEntity<ByteArrayResource> downloadResponse(Model model,
@PathVariable("applicationId") long applicationId) {
System.out.println("try this?");
return getFileResponseEntity(interviewResponseRestService.downloadResponse(applicationId).getSuccess(),
interviewResponseRestService.findResponse(applicationId).getSuccess());
}
@GetMapping("/{applicationId}/summary/download-feedback")
@SecuredBySpring(value = "READ", description = "Applicants, support staff, innovation leads, stakeholders, comp admins and project finance users have permission to view uploaded interview feedback.")
@PreAuthorize("hasAnyAuthority('applicant', 'assessor', 'comp_admin', 'project_finance', 'innovation_lead', 'stakeholder')")
public @ResponseBody
ResponseEntity<ByteArrayResource> downloadFeedback(Model model,
@PathVariable("applicationId") long applicationId) {
return getFileResponseEntity(interviewAssignmentRestService.downloadFeedback(applicationId).getSuccess(),
interviewAssignmentRestService.findFeedback(applicationId).getSuccess());
}
}
|
IFS-8066: removing redundant dev log
|
ifs-web-service/ifs-application-service/src/main/java/org/innovateuk/ifs/application/summary/controller/ApplicationSummaryController.java
|
IFS-8066: removing redundant dev log
|
|
Java
|
mit
|
06a585b4da53751acc86b9133dd758bec8163e93
| 0
|
artem-gabbasov/otus_java_2017_04_L1,artem-gabbasov/otus_java_2017_04_L1,artem-gabbasov/otus_java_2017_04_L1,artem-gabbasov/otus_java_2017_04_L1
|
package ru.otus.cache;
import java.lang.ref.SoftReference;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
/**
* Created by tully.
*/
public class CacheEngineImpl<K, V> implements CacheEngine<K, V> {
private static final int TIME_THRESHOLD_MS = 5;
private final int maxElements;
private final long lifeTimeMs;
private final long idleTimeMs;
private final boolean isEternal;
private final Map<K, SoftReference<MyElement<K, V>>> elements = new LinkedHashMap<>();
private final Timer timer = new Timer();
private int hit = 0;
private int miss = 0;
public CacheEngineImpl(int maxElements, long lifeTimeMs, long idleTimeMs, boolean isEternal) {
this.maxElements = maxElements;
this.lifeTimeMs = lifeTimeMs > 0 ? lifeTimeMs : 0;
this.idleTimeMs = idleTimeMs > 0 ? idleTimeMs : 0;
this.isEternal = lifeTimeMs == 0 && idleTimeMs == 0 || isEternal;
}
public void put(K key, V value) {
if (elements.size() == maxElements) {
K firstKey = elements.keySet().iterator().next();
elements.remove(firstKey);
}
IdleManager idleManager = new EmptyIdleManager();
if (!isEternal) {
if (lifeTimeMs != 0) {
TimerTask lifeTimerTask = getTimerTask(key, lifeElement -> lifeElement.getCreationTime() + lifeTimeMs);
timer.schedule(lifeTimerTask, lifeTimeMs);
}
if (idleTimeMs != 0) {
idleManager = new TimerIdleManager(
timerTask -> timer.schedule(timerTask, idleTimeMs),
() -> getTimerTask(key, idleElement -> idleElement.getCreationTime() + idleTimeMs)
);
}
}
elements.put(key, new SoftReference<>(new MyElement<K, V>(key, value, idleManager)));
}
private MyElement<K, V> getFromMap(K key) {
SoftReference<MyElement<K, V>> ref = elements.get(key);
if (ref != null) return ref.get();
return null;
}
public MyElement<K, V> get(K key) {
MyElement<K, V> element = getFromMap(key);
if (element != null) {
hit++;
element.setAccessed();
} else {
miss++;
}
return element;
}
public int getHitCount() {
return hit;
}
public int getMissCount() {
return miss;
}
@Override
public void dispose() {
timer.cancel();
}
@Override
public void clear() {
elements.clear();
dispose();
}
private TimerTask getTimerTask(final K key, Function<MyElement<K, V>, Long> timeFunction) {
return new TimerTask() {
@Override
public void run() {
MyElement<K, V> checkedElement = getFromMap(key);
if (checkedElement == null ||
isT1BeforeT2(timeFunction.apply(checkedElement), System.currentTimeMillis())) {
elements.remove(key);
}
}
};
}
private boolean isT1BeforeT2(long t1, long t2) {
return t1 < t2 + TIME_THRESHOLD_MS;
}
}
|
L11.1/src/main/java/ru/otus/cache/CacheEngineImpl.java
|
package ru.otus.cache;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
/**
* Created by tully.
*/
public class CacheEngineImpl<K, V> implements CacheEngine<K, V> {
private static final int TIME_THRESHOLD_MS = 5;
private final int maxElements;
private final long lifeTimeMs;
private final long idleTimeMs;
private final boolean isEternal;
private final Map<K, MyElement<K, V>> elements = new LinkedHashMap<>();
private final Timer timer = new Timer();
private int hit = 0;
private int miss = 0;
public CacheEngineImpl(int maxElements, long lifeTimeMs, long idleTimeMs, boolean isEternal) {
this.maxElements = maxElements;
this.lifeTimeMs = lifeTimeMs > 0 ? lifeTimeMs : 0;
this.idleTimeMs = idleTimeMs > 0 ? idleTimeMs : 0;
this.isEternal = lifeTimeMs == 0 && idleTimeMs == 0 || isEternal;
}
public void put(K key, V value) {
if (elements.size() == maxElements) {
K firstKey = elements.keySet().iterator().next();
elements.remove(firstKey);
}
IdleManager idleManager = new EmptyIdleManager();
if (!isEternal) {
if (lifeTimeMs != 0) {
TimerTask lifeTimerTask = getTimerTask(key, lifeElement -> lifeElement.getCreationTime() + lifeTimeMs);
timer.schedule(lifeTimerTask, lifeTimeMs);
}
if (idleTimeMs != 0) {
idleManager = new TimerIdleManager(
timerTask -> timer.schedule(timerTask, idleTimeMs),
() -> getTimerTask(key, idleElement -> idleElement.getCreationTime() + idleTimeMs)
);
}
}
elements.put(key, new MyElement<K, V>(key, value, idleManager));
}
public MyElement<K, V> get(K key) {
MyElement<K, V> element = elements.get(key);
if (element != null) {
hit++;
element.setAccessed();
} else {
miss++;
}
return element;
}
public int getHitCount() {
return hit;
}
public int getMissCount() {
return miss;
}
@Override
public void dispose() {
timer.cancel();
}
@Override
public void clear() {
elements.clear();
dispose();
}
private TimerTask getTimerTask(final K key, Function<MyElement<K, V>, Long> timeFunction) {
return new TimerTask() {
@Override
public void run() {
MyElement<K, V> checkedElement = elements.get(key);
if (checkedElement == null ||
isT1BeforeT2(timeFunction.apply(checkedElement), System.currentTimeMillis())) {
elements.remove(key);
}
}
};
}
private boolean isT1BeforeT2(long t1, long t2) {
return t1 < t2 + TIME_THRESHOLD_MS;
}
}
|
Кеш переделан на использование SoftReference
|
L11.1/src/main/java/ru/otus/cache/CacheEngineImpl.java
|
Кеш переделан на использование SoftReference
|
|
Java
|
mit
|
0f701b5dad54a5608fd19f064ebeb4dd864994c0
| 0
|
sdl/Testy,sdl/Testy,sdl/Testy,sdl/Testy
|
package com.sdl.selenium.extjs6.form;
import com.sdl.selenium.extjs6.button.Button;
import com.sdl.selenium.extjs6.slider.Slider;
import com.sdl.selenium.web.SearchType;
import com.sdl.selenium.web.WebLocator;
import com.sdl.selenium.web.link.WebLink;
import com.sdl.selenium.web.utils.RetryUtils;
import com.sdl.selenium.web.utils.Utils;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.WebDriverException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
@Slf4j
public class DateField extends TextField {
private WebLocator trigger = new WebLocator(this).setRoot("/../../").setClasses("x-form-date-trigger");
private WebLocator calendarLayer = new WebLocator().setClasses("x-datepicker", "x-layer").setAttribute("aria-hidden", "false").setVisibility(true);
private Button monthYearButton = new Button(calendarLayer);
private WebLocator selectOkButton = new WebLocator(calendarLayer).setText("OK").setVisibility(true).setInfoMessage("Ok");
private WebLocator yearAndMonth = new WebLocator(calendarLayer).setClasses("x-monthpicker").setVisibility(true);
private WebLocator nextYears = new WebLocator(yearAndMonth).setClasses("x-monthpicker-yearnav-next").setVisibility(true);
private WebLocator prevYears = new WebLocator(yearAndMonth).setClasses("x-monthpicker-yearnav-prev").setVisibility(true);
private WebLocator yearContainer = new WebLocator(yearAndMonth).setClasses("x-monthpicker-years");
private WebLocator monthContainer = new WebLocator(yearAndMonth).setClasses("x-monthpicker-months");
private WebLocator dayContainer = new WebLocator(calendarLayer).setClasses("x-datepicker-active");
private WebLocator hourLayer = new WebLocator().setClasses("x-panel", "x-layer").setVisibility(true);
private Slider hourSlider = new Slider(hourLayer).setLabel("Hour", SearchType.DEEP_CHILD_NODE_OR_SELF);
private Slider minuteSlider = new Slider(hourLayer).setLabel("Min", SearchType.DEEP_CHILD_NODE_OR_SELF);
private WebLocator tooltip = new WebLocator().setClasses("x-tip").setAttribute("aria-hidden", "false");
public DateField() {
setClassName("DateField");
}
public DateField(WebLocator container) {
this();
setContainer(container);
}
public DateField(WebLocator container, String label, SearchType... searchTypes) {
this(container);
if (searchTypes.length == 0) {
searchTypes = new SearchType[]{SearchType.DEEP_CHILD_NODE_OR_SELF};
} else {
List<SearchType> types = new ArrayList<>(Arrays.asList(searchTypes));
types.add(SearchType.DEEP_CHILD_NODE_OR_SELF);
searchTypes = types.toArray(new SearchType[0]);
}
setLabel(label, searchTypes);
}
/**
* example new DataField().setDate("19", "05", "2013")
*
* @param day String 'dd'
* @param month String 'MMM'
* @param year String 'yyyy'
* @return true if is selected date, false when DataField doesn't exist
*/
private boolean setDate(String day, String month, String year) {
String fullDate = RetryUtils.retry(4, () -> monthYearButton.getText()).trim();
if (!fullDate.contains(month) || !fullDate.contains(year)) {
monthYearButton.click();
if (!yearAndMonth.ready()) {
monthYearButton.click();
}
goToYear(year, fullDate);
WebLink monthEl = new WebLink(monthContainer).setText(month, SearchType.EQUALS).setInfoMessage("month " + month);
monthEl.click();
selectOkButton.click();
}
WebLocator dayEl = new WebLocator(dayContainer).setText(day, SearchType.EQUALS).setVisibility(true).setInfoMessage("day " + day);
Utils.sleep(50);
return dayEl.click();
}
private boolean setHour(String hour, String minute) {
return hourSlider.move(Integer.parseInt(hour)) &&
minuteSlider.move(Integer.parseInt(minute));
}
private void goToYear(String year, String fullDate) {
int currentYear = Integer.parseInt(fullDate.split(" ")[1]);
int yearInt = Integer.parseInt(year);
boolean goNext = yearInt > currentYear;
WebLocator btn = goNext ? nextYears : prevYears;
WebLink yearEl = new WebLink(yearContainer).setText(year, SearchType.EQUALS).setVisibility(true).setInfoMessage("year " + year);
boolean found;
do {
found = yearEl.waitToRender(150L, false);
if (!found) {
btn.click();
}
} while (!found && !foundYear(yearInt, goNext));
try {
yearEl.click();
} catch (WebDriverException e) {
if (tooltip.waitToRender(500L, false)) {
WebLocator monthEl = new WebLocator(monthContainer).setText("Jan", SearchType.EQUALS).setInfoMessage("month Jan");
monthEl.mouseOver();
Utils.sleep(300);
}
yearEl.click();
}
}
private boolean foundYear(int yearInt, boolean goNext) {
WebLink yearEl = new WebLink(yearContainer).setResultIdx(12);
int actualYear = Integer.parseInt(yearEl.getText());
return goNext ? yearInt <= actualYear : yearInt >= actualYear;
}
/**
* example new DataField().select("19/05/2013")
*
* @param date accept only this format: 'dd/MM/yyyy'
* @return true if is selected date, false when DataField doesn't exist
*/
public boolean select(String date) {
return select(date, "dd/MM/yyyy");
}
public boolean select(String date, String format) {
return select(date, format, Locale.ENGLISH);
}
public boolean select(String date, String format, Locale locale) {
SimpleDateFormat inDateFormat = new SimpleDateFormat(format, locale);
SimpleDateFormat outDateForm = new SimpleDateFormat("dd/MMM/yyyy H:m", locale);
Date fromDate;
try {
fromDate = inDateFormat.parse(date);
date = outDateForm.format(fromDate);
} catch (ParseException e) {
log.error("ParseException: {}", e);
}
ready();
log.debug("select: " + date);
String[] dates = date.split("/");
trigger.click();
String[] extraDates = dates[2].split(" ");
String year = extraDates[0];
if (format.contains("H")) {
String[] hours = extraDates[1].split(":");
String hour = hours[0];
String minutes = hours[1];
return setHour(hour, minutes) && setDate(Integer.parseInt(dates[0]) + "", dates[1], year);
} else {
return setDate(Integer.parseInt(dates[0]) + "", dates[1], year);
}
}
public boolean select(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MMM/YYYY");
String dateStr = sdf.format(date);
return select(dateStr);
}
public boolean selectToday() {
return select(new Date());
}
}
|
src/main/java/com/sdl/selenium/extjs6/form/DateField.java
|
package com.sdl.selenium.extjs6.form;
import com.sdl.selenium.extjs6.button.Button;
import com.sdl.selenium.extjs6.slider.Slider;
import com.sdl.selenium.web.SearchType;
import com.sdl.selenium.web.WebLocator;
import com.sdl.selenium.web.link.WebLink;
import com.sdl.selenium.web.utils.RetryUtils;
import com.sdl.selenium.web.utils.Utils;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.WebDriverException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
@Slf4j
public class DateField extends TextField {
private WebLocator trigger = new WebLocator(this).setRoot("/../../").setClasses("x-form-date-trigger");
private WebLocator calendarLayer = new WebLocator().setClasses("x-datepicker", "x-layer").setAttribute("aria-hidden", "false").setVisibility(true);
private Button monthYearButton = new Button(calendarLayer);
private WebLocator selectOkButton = new WebLocator(calendarLayer).setText("OK").setVisibility(true).setInfoMessage("Ok");
private WebLocator yearAndMonth = new WebLocator(calendarLayer).setClasses("x-monthpicker").setVisibility(true);
private WebLocator nextYears = new WebLocator(yearAndMonth).setClasses("x-monthpicker-yearnav-next").setVisibility(true);
private WebLocator prevYears = new WebLocator(yearAndMonth).setClasses("x-monthpicker-yearnav-prev").setVisibility(true);
private WebLocator yearContainer = new WebLocator(yearAndMonth).setClasses("x-monthpicker-years");
private WebLocator monthContainer = new WebLocator(yearAndMonth).setClasses("x-monthpicker-months");
private WebLocator dayContainer = new WebLocator(calendarLayer).setClasses("x-datepicker-active");
private WebLocator hourLayer = new WebLocator().setClasses("x-panel", "x-layer").setVisibility(true);
private Slider hourSlider = new Slider(hourLayer).setLabel("Hour", SearchType.DEEP_CHILD_NODE_OR_SELF);
private Slider minuteSlider = new Slider(hourLayer).setLabel("Min", SearchType.DEEP_CHILD_NODE_OR_SELF);
private WebLocator tooltip = new WebLocator().setClasses("x-tip").setAttribute("aria-hidden", "false");
public DateField() {
setClassName("DateField");
}
public DateField(WebLocator container) {
this();
setContainer(container);
}
public DateField(WebLocator container, String label, SearchType... searchTypes) {
this(container);
if (searchTypes.length == 0) {
searchTypes = new SearchType[]{SearchType.DEEP_CHILD_NODE_OR_SELF};
} else {
List<SearchType> types = new ArrayList<>(Arrays.asList(searchTypes));
types.add(SearchType.DEEP_CHILD_NODE_OR_SELF);
searchTypes = types.toArray(new SearchType[0]);
}
setLabel(label, searchTypes);
}
/**
* example new DataField().setDate("19", "05", "2013")
*
* @param day String 'dd'
* @param month String 'MMM'
* @param year String 'yyyy'
* @return true if is selected date, false when DataField doesn't exist
*/
private boolean setDate(String day, String month, String year) {
String fullDate = RetryUtils.retry(4, () -> monthYearButton.getText()).trim();
if (!fullDate.contains(month) || !fullDate.contains(year)) {
monthYearButton.click();
if (!yearAndMonth.ready()) {
monthYearButton.click();
}
goToYear(year, fullDate);
WebLink monthEl = new WebLink(monthContainer).setText(month, SearchType.EQUALS).setInfoMessage("month " + month);
monthEl.click();
selectOkButton.click();
}
WebLocator dayEl = new WebLocator(dayContainer).setText(day, SearchType.EQUALS).setVisibility(true).setInfoMessage("day " + day);
Utils.sleep(50);
return dayEl.click();
}
private boolean setHour(String hour, String minute) {
return hourSlider.move(Integer.parseInt(hour)) &&
minuteSlider.move(Integer.parseInt(minute));
}
private void goToYear(String year, String fullDate) {
int currentYear = Integer.parseInt(fullDate.split(" ")[1]);
int yearInt = Integer.parseInt(year);
boolean goNext = yearInt > currentYear;
WebLocator btn = goNext ? nextYears : prevYears;
WebLink yearEl = new WebLink(yearContainer).setText(year, SearchType.EQUALS).setVisibility(true).setInfoMessage("year " + year);
boolean found;
do {
found = yearEl.waitToRender(150L, false);
if (!found) {
btn.click();
}
} while (!found && !foundYear(yearInt, goNext));
try {
yearEl.click();
} catch (WebDriverException e) {
if (tooltip.waitToRender(500L, false)) {
WebLocator monthEl = new WebLocator(monthContainer).setText("Jan", SearchType.EQUALS).setInfoMessage("month Jan");
monthEl.mouseOver();
Utils.sleep(300);
}
yearEl.click();
}
}
private boolean foundYear(int yearInt, boolean goNext) {
WebLink yearEl = new WebLink(yearContainer).setResultIdx(12);
int actualYear = Integer.parseInt(yearEl.getText());
return goNext ? yearInt <= actualYear : yearInt >= actualYear;
}
/**
* example new DataField().select("19/05/2013")
*
* @param date accept only this format: 'dd/MM/yyyy'
* @return true if is selected date, false when DataField doesn't exist
*/
public boolean select(String date) {
return select(date, "dd/MM/yyyy");
}
public boolean select(String date, String format) {
return select(date, format, Locale.ENGLISH);
}
public boolean select(String date, String format, Locale locale) {
SimpleDateFormat inDateFormat = new SimpleDateFormat(format, locale);
SimpleDateFormat outDateForm = new SimpleDateFormat("dd/MMM/yyyy H:m", locale);
Date fromDate;
try {
fromDate = inDateFormat.parse(date);
date = outDateForm.format(fromDate);
} catch (ParseException e) {
log.error("ParseException: {}", e);
}
log.debug("select: " + date);
String[] dates = date.split("/");
trigger.click();
String[] extraDates = dates[2].split(" ");
String year = extraDates[0];
if (format.contains("H")) {
String[] hours = extraDates[1].split(":");
String hour = hours[0];
String minutes = hours[1];
return setHour(hour, minutes) && setDate(Integer.parseInt(dates[0]) + "", dates[1], year);
} else {
return setDate(Integer.parseInt(dates[0]) + "", dates[1], year);
}
}
public boolean select(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MMM/YYYY");
String dateStr = sdf.format(date);
return select(dateStr);
}
public boolean selectToday() {
return select(new Date());
}
}
|
improvement DateField
|
src/main/java/com/sdl/selenium/extjs6/form/DateField.java
|
improvement DateField
|
|
Java
|
mit
|
443457fe77b24cc7fcd0201c8ab86020c50b5648
| 0
|
nhydock/revert
|
package com.kgp.level;
// BricksManager.java
// Andrew Davison, April 2005, ad@fivedots.coe.psu.ac.th
/* Loads and manages a wraparound bricks map.
It also deals with various collision detection tests from
JumperSprite.
A 'bricks map' is read in from a configuration file, and used
to make an ArrayList of Brick objects, bricksList.
The collection of bricks defines a bricks map, which is moved
and drawn in the same way as an image ribbon in a Ribbon object.
The bricks map movement step is fixed by moveSize, which
is some fraction of the width of a brick image.
----
JumperSprite uses BricksManager for collision detection.
As it rises/falls it must curtail the movement if it will
enter a brick; checkBrickBase() and checkBrickTop() are used
for testing this.
When JumperSprite moves left/right, it must first check that it will
not move into a brick. It uses insideBrick() for this test.
When JumperSprite does move, it may move off into space -- there
is no brick below it. It tests this using insideBrick() also.
*/
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import revert.util.BrickManager;
import com.kgp.imaging.ImagesLoader;
import com.kgp.util.Vector2;
public class BricksManager extends BrickManager {
private final static String BRICKS_DIR = "Levels/";
private final static int MAX_BRICKS_LINES = 15;
// maximum number of lines (rows) of bricks in the scene
private final static double MOVE_FACTOR = 0.25;
// modifies how fast the bricks map moves; smaller is slower
private int pWidth, pHeight; // dimensions of display panel
private int imWidth, imHeight; // dimensions of a brick image
private int moveSize;
// size of the map move (in pixels) in each tick
// moveSize == the width of a brick image * MOVE_FACTOR
/* The ribbons and 'jack' use the same moveSize value. */
private int xRange;
private int left;
private int right;
private ImagesLoader imsLoader;
private ArrayList<BufferedImage> brickImages = null;
public BricksManager(int w, int h, String fnm, ImagesLoader il) {
pWidth = w;
pHeight = h;
imsLoader = il;
loadBricksFile(fnm);
for (int i = 0; i < bricks.length; i++) {
for (int x = 0; x < bricks[i].length; x++) {
if (bricks[i][x] > 0)
System.out.print(bricks[i][x]);
else
System.out.print(" ");
}
System.out.println();
}
// generate random spawn points because we don't have spawn locations
// defined in classic style maps
spawnPoints = new Point[5];
for (int i = 0; i < 5; i++) {
int x = (int) (Math.random() * this.getWidth());
int y = (int) (Math.random() * this.getHeight());
Point p = new Point(x, y);
spawnPoints[i] = p;
}
yOffset = Math.max(this.getMapHeight(), pHeight) - this.getMapHeight();
moveSize = (int) (imWidth * MOVE_FACTOR);
if (moveSize == 0) {
System.out.println("moveSize cannot be 0, setting it to 1");
moveSize = 1;
}
}
// ----------- load the bricks information -------------------
/**
* Load the bricks map from a configuration file, fnm. The map starts with
* an image strip which contains the images referred to in the map. Format:
* s <fnm> <number>
*
* This means that the map can use images numbered 0 to <number-1>. We
* assume number is less than 10.
*
* The bricks map follows. Each line is processed by storeBricks(). There
* can only be at most MAX_BRICKS_LINES lines.
*
* The configuration file can contain empty lines and comment lines (those
* starting with //), which are ignored.
*/
public void loadBricksFile(String fnm) {
String imsFNm = BRICKS_DIR + fnm;
System.out.println("Reading bricks file: " + imsFNm);
ArrayList<Brick> bricksList = new ArrayList<Brick>();
int numStripImages = -1;
int numBricksLines = 0;
try {
InputStream in = getClass().getClassLoader().getResourceAsStream(
imsFNm);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line;
char ch;
while ((line = br.readLine()) != null) {
if (line.length() == 0) // ignore a blank line
continue;
if (line.startsWith("//")) // ignore a comment line
continue;
ch = Character.toLowerCase(line.charAt(0));
if (ch == 's') // an images strip
{
brickImages = imsLoader.getStripImages(line);
numStripImages = brickImages.size();
imWidth = brickImages.get(0).getWidth();
imHeight = brickImages.get(0).getHeight();
} else { // a bricks map line
if (numBricksLines > MAX_BRICKS_LINES)
System.out.println("Max reached, skipping bricks line: " + line);
else if (numStripImages == -1)
System.out.println("No strip image, skipping bricks line: " + line);
else {
storeBricks(line, numBricksLines, numStripImages, bricksList);
numBricksLines++;
}
}
}
br.close();
} catch (IOException e) {
System.out.println("Error reading file: " + imsFNm);
System.exit(1);
}
numRows = numBricksLines;
bricks = new int[numRows][numCols];
collisionMask = new boolean[numCols][numRows];
for (Brick b : bricksList) {
bricks[b.y][b.x] = b.type;
if (b.type > 0) {
collisionMask[b.x][b.y] = true;
}
}
bricksList = null;
checkForGaps();
}
/**
* Read a single bricks line, and create Brick objects. A line contains
* digits and spaces (which are ignored). Each digit becomes a Brick object.
* The collection of Brick objects are stored in the bricksList ArrayList.
*/
private void storeBricks(String line, int lineNo, int numImages,
ArrayList<Brick> bricksList) {
if (line.length() > numCols) {
numCols = line.length();
}
int imageID;
for (int x = 0; x < line.length(); x++) {
char ch = line.charAt(x);
if (ch == ' ') // ignore a space
continue;
if (Character.isDigit(ch)) {
imageID = ch - '0'; // we assume a digit is 0-9
if (imageID >= numImages)
System.out.println("Image ID " + imageID + " out of range");
else
// make a Brick object
bricksList.add(new Brick(imageID + 1, x, lineNo));
} else
System.out.println("Brick char " + ch + " is not a digit");
}
} // end of storeBricks()
// --------------- initialise bricks data structures -----------------
/*
* Check that the bottom map line (numRows-1) has a brick in every x
* position from 0 to numCols-1. This prevents 'jack' from falling down a
* hole at the bottom of the panel.
*/
private void checkForGaps() {
for (int c = 0; c < bricks[bricks.length - 1].length; c++) {
int i = bricks[bricks.length - 1][c];
boolean gap = false;
if (i == 0) {
gap = true;
for (int r = bricks[bricks.length - 1][c]; r >= 0 && gap; r--) {
if (bricks[r][c] > 0) {
gap = false;
}
}
}
if (gap) {
System.out
.println("Gap found in bricks map bottom line at position "
+ c);
System.exit(-1);
}
}
}
public void update(Vector2 loc) {
xRange = (int) loc.x;
left = (int) ((xRange - pWidth / 2f) / (float) imWidth)-1;
right = (int) Math.ceil((xRange + pWidth / 2f) / (float) imWidth);
// System.out.printf("Vis Range: %d\nLeft/Right: %d %d\n", visCols,
// left, right);
}
// -------------- draw the bricks ----------------------
// ----------------- JumperSprite related methods -------------
// various forms of collision detection with the bricks
@Override
public int getBrickHeight() {
return imHeight;
}
@Override
public int getBrickWidth() {
return imWidth;
}
public int getMoveSize() {
return moveSize;
}
@Override
public void display(Graphics2D g) {
for (int i = left, loc = left, x = loc * imWidth; i <= right; i++, loc++, x += imWidth) {
if (loc < 0) {
loc += numCols;
} else if (loc >= numCols) {
loc %= numCols;
}
for (int j = 0; j < numRows; j++) {
if (bricks[j][loc] - 1 >= 0) {
g.drawImage(brickImages.get(bricks[j][loc] - 1), x, yOffset
+ (j - 1) * imHeight, null);
}
}
}
}
}
|
src/com/kgp/level/BricksManager.java
|
package com.kgp.level;
// BricksManager.java
// Andrew Davison, April 2005, ad@fivedots.coe.psu.ac.th
/* Loads and manages a wraparound bricks map.
It also deals with various collision detection tests from
JumperSprite.
A 'bricks map' is read in from a configuration file, and used
to make an ArrayList of Brick objects, bricksList.
The collection of bricks defines a bricks map, which is moved
and drawn in the same way as an image ribbon in a Ribbon object.
The bricks map movement step is fixed by moveSize, which
is some fraction of the width of a brick image.
----
JumperSprite uses BricksManager for collision detection.
As it rises/falls it must curtail the movement if it will
enter a brick; checkBrickBase() and checkBrickTop() are used
for testing this.
When JumperSprite moves left/right, it must first check that it will
not move into a brick. It uses insideBrick() for this test.
When JumperSprite does move, it may move off into space -- there
is no brick below it. It tests this using insideBrick() also.
*/
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import revert.util.BrickManager;
import com.kgp.imaging.ImagesLoader;
import com.kgp.util.Vector2;
public class BricksManager extends BrickManager {
private final static String BRICKS_DIR = "Levels/";
private final static int MAX_BRICKS_LINES = 15;
// maximum number of lines (rows) of bricks in the scene
private final static double MOVE_FACTOR = 0.25;
// modifies how fast the bricks map moves; smaller is slower
private int pWidth, pHeight; // dimensions of display panel
private int imWidth, imHeight; // dimensions of a brick image
private int moveSize;
// size of the map move (in pixels) in each tick
// moveSize == the width of a brick image * MOVE_FACTOR
/* The ribbons and 'jack' use the same moveSize value. */
private int xRange;
private int left;
private int right;
private ImagesLoader imsLoader;
private ArrayList<BufferedImage> brickImages = null;
public BricksManager(int w, int h, String fnm, ImagesLoader il) {
pWidth = w;
pHeight = h;
imsLoader = il;
loadBricksFile(fnm);
for (int i = 0; i < bricks.length; i++)
{
for (int x = 0; x < bricks[i].length; x++)
{
if (bricks[i][x] > 0)
System.out.print(bricks[i][x]);
else
System.out.print(" ");
}
System.out.println();
}
//generate random spawn points because we don't have spawn locations defined in classic style maps
spawnPoints = new Point[5];
for (int i = 0; i < 5; i++)
{
int x = (int)(Math.random()*this.getWidth());
int y = (int)(Math.random()*this.getHeight());
Point p = new Point(x, y);
spawnPoints[i] = p;
}
yOffset = Math.max(this.getMapHeight(), pHeight) - this.getMapHeight();
moveSize = (int) (imWidth * MOVE_FACTOR);
if (moveSize == 0) {
System.out.println("moveSize cannot be 0, setting it to 1");
moveSize = 1;
}
}
// ----------- load the bricks information -------------------
/**
* Load the bricks map from a configuration file, fnm. The map starts with
* an image strip which contains the images referred to in the map. Format:
* s <fnm> <number>
*
* This means that the map can use images numbered 0 to <number-1>. We
* assume number is less than 10.
*
* The bricks map follows. Each line is processed by storeBricks(). There
* can only be at most MAX_BRICKS_LINES lines.
*
* The configuration file can contain empty lines and comment lines (those
* starting with //), which are ignored.
*/
public void loadBricksFile(String fnm)
{
String imsFNm = BRICKS_DIR + fnm;
System.out.println("Reading bricks file: " + imsFNm);
ArrayList<Brick> bricksList = new ArrayList<Brick>();
int numStripImages = -1;
int numBricksLines = 0;
try {
InputStream in = getClass().getClassLoader().getResourceAsStream(
imsFNm);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line;
char ch;
while ((line = br.readLine()) != null) {
if (line.length() == 0) // ignore a blank line
continue;
if (line.startsWith("//")) // ignore a comment line
continue;
ch = Character.toLowerCase(line.charAt(0));
if (ch == 's') // an images strip
{
brickImages = imsLoader.getStripImages(line);
numStripImages = brickImages.size();
imWidth = brickImages.get(0).getWidth();
imHeight = brickImages.get(0).getHeight();
}
else { // a bricks map line
if (numBricksLines > MAX_BRICKS_LINES)
System.out.println("Max reached, skipping bricks line: " + line);
else if (numStripImages == -1)
System.out.println("No strip image, skipping bricks line: " + line);
else {
storeBricks(line, numBricksLines, numStripImages, bricksList);
numBricksLines++;
}
}
}
br.close();
} catch (IOException e) {
System.out.println("Error reading file: " + imsFNm);
System.exit(1);
}
numRows = numBricksLines;
bricks = new int[numRows][numCols];
collisionMask = new boolean[numCols][numRows];
for (Brick b : bricksList)
{
bricks[b.y][b.x] = b.type;
if (b.type > 0)
{
collisionMask[b.x][b.y] = true;
}
}
bricksList = null;
checkForGaps();
}
private void storeBricks(String line, int lineNo, int numImages, ArrayList<Brick> bricksList)
/*
* Read a single bricks line, and create Brick objects. A line contains
* digits and spaces (which are ignored). Each digit becomes a Brick object.
* The collection of Brick objects are stored in the bricksList ArrayList.
*/
{
if (line.length() > numCols)
{
numCols = line.length();
}
int imageID;
for (int x = 0; x < line.length(); x++) {
char ch = line.charAt(x);
if (ch == ' ') // ignore a space
continue;
if (Character.isDigit(ch)) {
imageID = ch - '0'; // we assume a digit is 0-9
if (imageID >= numImages)
System.out.println("Image ID " + imageID + " out of range");
else
// make a Brick object
bricksList.add(new Brick(imageID+1, x, lineNo));
} else
System.out.println("Brick char " + ch + " is not a digit");
}
} // end of storeBricks()
// --------------- initialise bricks data structures -----------------
/*
* Check that the bottom map line (numRows-1) has a brick in every x
* position from 0 to numCols-1. This prevents 'jack' from falling down a
* hole at the bottom of the panel.
*/
private void checkForGaps()
{
for (int c = 0; c < bricks[bricks.length-1].length; c++)
{
int i = bricks[bricks.length-1][c];
boolean gap = false;
if (i == 0)
{
gap = true;
for (int r = bricks[bricks.length-1][c]; r >= 0 && gap; r--)
{
if (bricks[r][c] > 0)
{
gap = false;
}
}
}
if (gap)
{
System.out.println("Gap found in bricks map bottom line at position " + c);
System.exit(-1);
}
}
}
public void update(Vector2 loc)
{
xRange = (int)loc.x;
left = (int)((xRange - pWidth/2f) / (float)imWidth);
right = (int)Math.ceil((xRange + pWidth/2f) / (float)imWidth);
//System.out.printf("Vis Range: %d\nLeft/Right: %d %d\n", visCols, left, right);
}
// -------------- draw the bricks ----------------------
// ----------------- JumperSprite related methods -------------
// various forms of collision detection with the bricks
@Override
public int getBrickHeight() {
return imHeight;
}
@Override
public int getBrickWidth() {
return imWidth;
}
public int getMoveSize() {
return moveSize;
}
@Override
public void display(Graphics2D g) {
for (int i = left, loc = left, x = left * imWidth + (xRange % imWidth); i <= right; i++, loc++, x += imWidth)
{
if (loc < 0)
{
loc += numCols;
}
else if (loc >= numCols)
{
loc %= numCols;
}
for (int j = 0; j < numRows; j++)
{
if (bricks[j][loc]-1 >= 0)
{
g.drawImage(brickImages.get(bricks[j][loc]-1), x, yOffset + (j-1)*imHeight, null);
}
}
}
}
}
|
Fix brick positioning and rendering
- Much simplier solution to rendering and allows tweening for movement
- There's now some salvage to the left so bricks don't flicker in when at the wrap around point
|
src/com/kgp/level/BricksManager.java
|
Fix brick positioning and rendering - Much simplier solution to rendering and allows tweening for movement - There's now some salvage to the left so bricks don't flicker in when at the wrap around point
|
|
Java
|
mit
|
f36300b6ec9de0ffa026acd425ec5dd1e286510b
| 0
|
yomikaze/OOGASalad,bchao/OOGASalad,DavisTrey/Software-Design-Final-Project,leeweisberger/RPG-Game-Engine,bewallyt/OOGASalad
|
package engine.battle;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.io.IOException;
import java.io.InputStream;
import engine.dialogue.AttackExecutorNode;
import engine.dialogue.BattleExecutorNode;
import engine.dialogue.BattleSelectorNode;
import engine.dialogue.DialogueListeningState;
import engine.dialogue.InteractionBox;
import engine.dialogue.InteractionMatrix;
import engine.dialogue.InteractionMatrix2x2;
import engine.dialogue.MatrixNode;
import engine.gridobject.GridObject;
import engine.gridobject.person.Enemy;
import engine.gridobject.person.Person;
import engine.gridobject.person.Player;
import engine.item.Item;
public class BattleManager implements InteractionBox{
BattleCalculator myBattleCalculate;
private Player myPlayer;
private Enemy myEnemy;
private BattleAI myBattleAI;
private InteractionMatrix myOptions;
private BattleSelectorNode myAttackSelector;
private BattleSelectorNode myBagSelector;
private BattleSelectorNode myWeaponSelector;
private BattleSelectorNode myRunSelector;
private BattleSelectorNode myCurrentBattleSelector;
private BattleExecutorNode myCurrentBattleExecutorNode;
private final static int TOPLEVEL=0;
private final static int BOTTOMLEVEL=1;
private final static int FIRSTATTACKHAPPENED=2;
private final static int SECONDATTACKHAPPENED=3;
private final static int WEAPONSELECTED=4;
private final static int RAN=5;
public final static int ENEMYDEAD=6;
private final static int BATTLEWON=7;
private static int myCurrentState=0;
private Person myCurrentAttacker;
private Person myCurrentVictim;
private static final int SYMBOL_RADIUS = 10;
private static final String TEXT_DISPLAYED_ATTACK=" used ";
private static final String TEXT_DISPLAYED_SECOND_ATTACK_COMPLETED="second attack damaged by: ";
private static final String TEXT_DISPLAYED_WEAPON_SELECTED="weapon selected :: ";
private static final String TEXT_DISPLAYED_RAN="Got away safely!";
private static final String TEXT_DISPLAYED_ENEMY_DEAD = "You defeated ";
private static final String TEXT_DISPLAYED_DROPPED_WEAPON = "Picked dropped weapon!";
private static final String TEXT_DISPLAYED_PLAYER_DEAD="You have been defeated!";
//DialogueListeningState PlayerDead = new DialogueListeningState("You have been defeated!",);
private static final String TEXT_DISPLAYED_ITEM_USED = "Item used!";
public static final int EXITWON = 8;
private static final int PLAYERDEAD = 9;
public static final int EXITLOST=11;
private static final int BATTLELOST = 10;
private final static int ITEMUSED=12;
private String itemUsedName = "";
private String textToBeDisplayed;
private boolean ran=false;
private boolean dropWeapon = false;
public BattleManager(Player player, Enemy enemy){
myPlayer = player;
myEnemy=enemy;
myBattleAI=new BattleAI(enemy);
myOptions = new InteractionMatrix2x2();
setOriginalNodes();
initializeChildrenNodes();
}
private void initializeChildrenNodes() {
setAttackChildrenNodes(myAttackSelector);
setWeaponChildrenNodes(myWeaponSelector);
setBagChildrenNodes(myBagSelector);
setRunChildrenNodes(myRunSelector);
}
private void updateAttackList(){
setAttackChildrenNodes(myAttackSelector);
}
private void setOriginalNodes(){
myAttackSelector = new BattleSelectorNode("Attack");
myBagSelector = new BattleSelectorNode("Bag");
myWeaponSelector = new BattleSelectorNode("Weapon");
myRunSelector = new BattleSelectorNode("Run");
myOptions.setNode(myAttackSelector, 0, 0);
myOptions.setNode(myBagSelector, 1, 0);
myOptions.setNode(myWeaponSelector, 0, 1);
myOptions.setNode(myRunSelector, 1, 1);
myCurrentBattleSelector=(BattleSelectorNode) myOptions.getCurrentNode();
}
private void setAttackChildrenNodes(BattleSelectorNode node){
for(BattleExecutable attack : myPlayer.getCurrentWeapon().getAttackList()){
setNextChild(node, attack);
}
}
private void setNextChild(BattleSelectorNode node, BattleExecutable attack) {
BattleExecutorNode executorNode = new AttackExecutorNode(attack);
node.setChild(executorNode);
}
private void setWeaponChildrenNodes(BattleSelectorNode node){
for(BattleExecutable weapon : myPlayer.getWeaponList()){
setNextChild(node, weapon);
}
}
private void setBagChildrenNodes(BattleSelectorNode node){
for(BattleExecutable item : myPlayer.getItems()){
setNextChild(node, item);
}
}
private void setRunChildrenNodes(BattleSelectorNode node){
BattleExecutable run = new Run();
setNextChild(node, run);
}
@Override
public void paintDisplay(Graphics2D g2d, int xSize, int ySize, int width,int height) {
InputStream is = GridObject.class.getResourceAsStream("PokemonGB.ttf");
Font font=null;
try {
try {
font = Font.createFont(Font.TRUETYPE_FONT, is);
} catch (FontFormatException e) {
e.printStackTrace();
}
Font sizedFont = font.deriveFont(12f);
g2d.setFont(sizedFont);
} catch (IOException e) {
e.printStackTrace();
}
g2d.setColor(Color.white);
g2d.fill(new Rectangle((int) ((int) 0), ySize/2+60, width , height));
g2d.setColor(Color.black);
if(myCurrentState==TOPLEVEL || myCurrentState==BOTTOMLEVEL){
printResponses(g2d, myOptions, xSize, ySize, width, height);
}
else {
g2d.drawString(textToBeDisplayed, (int) xSize/10, ySize/2+120);
}
}
private void printResponses(Graphics2D g2d, InteractionMatrix myResponses2, int xSize, int ySize,
int width, int height) {
int xCornerLoc = xSize/10;
int yCornerLoc = ySize/2 + 120;
for (int i = 0; i < myOptions.getDimension()[0]; i++) {
for (int j = 0; j < myOptions.getDimension()[1]; j++) {
MatrixNode qn = (MatrixNode) myOptions.getNode(j, i);
if(qn!=null)g2d.drawString(qn.toString(), (int) (xCornerLoc + j*(xSize*5/10)), (int)(yCornerLoc + i*(height*3/10)));
}
}
int[] selectedOptionLoc = myOptions.getSelectedNodeLocation();
g2d.fillOval((int) (xCornerLoc-10 + selectedOptionLoc[0]*(xSize-25)*5/10) - SYMBOL_RADIUS,
(int) (yCornerLoc + selectedOptionLoc[1]*(height-15)*3/10) - SYMBOL_RADIUS, SYMBOL_RADIUS, SYMBOL_RADIUS);
}
@Override
public void getNextText() {
((InteractionMatrix2x2) myOptions).resetMatrixPosition();
if(myCurrentState==RAN){
ran=true;
}
else if(myCurrentState==PLAYERDEAD){
setCurrentTextToBeDisplayed();
myCurrentState=BATTLELOST;
}
else if (myCurrentState==ENEMYDEAD){
setCurrentTextToBeDisplayed();
myCurrentState=BATTLEWON;
}
else if(myCurrentState==BATTLEWON){
myCurrentState=EXITWON;
}
else if(myCurrentState==BATTLELOST){
myCurrentState=EXITLOST;
}
else if (myCurrentState==SECONDATTACKHAPPENED || myCurrentState==WEAPONSELECTED || myCurrentState==ITEMUSED){
setOriginalNodes();
initializeChildrenNodes();
myCurrentState=TOPLEVEL;
}
else if(myCurrentState==FIRSTATTACKHAPPENED){
Person tempAttacker=myCurrentAttacker;
myCurrentAttacker=myCurrentVictim;
myCurrentVictim=tempAttacker;
setCurrentTextToBeDisplayed();
myBattleCalculate.attack(myCurrentAttacker,myCurrentVictim,myCurrentAttacker.getCurrentWeapon(),myCurrentAttacker.getCurrentAttack());
myCurrentState=SECONDATTACKHAPPENED;
if(myBattleCalculate.enemyIsDead())
myCurrentState=ENEMYDEAD;
if(myBattleCalculate.playerIsDead()){
myCurrentState=PLAYERDEAD;
}
}
else if(myCurrentState==BOTTOMLEVEL){
BattleExecutable executable = myCurrentBattleExecutorNode.getExecutor();
if(executable instanceof Weapon){
myPlayer.setCurrentWeapon((Weapon) executable);
myCurrentState=WEAPONSELECTED;
updateAttackList();
setCurrentTextToBeDisplayed();
}
else if(executable instanceof Attack){
myBattleCalculate=new BattleCalculator(myPlayer, myEnemy);
Weapon enemyWeapon = myBattleAI.chooseWeapon();
myEnemy.setCurrentWeapon(enemyWeapon);
myEnemy.setCurrentAttack(myBattleAI.chooseAttack(enemyWeapon));
myPlayer.setCurrentAttack((Attack) executable);
myCurrentAttacker = myBattleCalculate.attackFirst(myPlayer, myPlayer.getCurrentWeapon(),
(Attack) executable, myEnemy, enemyWeapon, myEnemy.getCurrentAttack())[0];
myCurrentVictim = myBattleCalculate.attackFirst(myPlayer, myPlayer.getCurrentWeapon(),
(Attack) executable, myEnemy, enemyWeapon, myEnemy.getCurrentAttack())[1];
myCurrentState=FIRSTATTACKHAPPENED;
setCurrentTextToBeDisplayed();
myBattleCalculate.attack(myCurrentAttacker,myCurrentVictim,myCurrentAttacker.getCurrentWeapon(),myCurrentAttacker.getCurrentAttack());
if(myBattleCalculate.enemyIsDead())
myCurrentState=ENEMYDEAD;
if(myBattleCalculate.playerIsDead())
myCurrentState=PLAYERDEAD;
}
else if(executable instanceof Item){
((Item) executable).useItem();
myCurrentState=ITEMUSED;
itemUsedName=((Item) executable).toString();
setCurrentTextToBeDisplayed();
}
else if(executable instanceof Run){
//ran=true;
myCurrentState=RAN;
setCurrentTextToBeDisplayed();
}
}
else if(myCurrentState==TOPLEVEL){
int count=0;
myCurrentBattleSelector.getChildren().size();
for(int i=0; i<myOptions.getDimension()[0]; i++){
for(int j=0; j<myOptions.getDimension()[1]; j++){
if(myCurrentBattleSelector.getChildren().size()>count)
myOptions.setNode(myCurrentBattleSelector.getChildren().get(count), i, j);
else{
myOptions.setNode(null, i, j);
}
count++;
}
}
myCurrentBattleExecutorNode = (BattleExecutorNode) myOptions.getCurrentNode();
myCurrentState=BOTTOMLEVEL;
}
}
public void moveUp() {
myOptions.moveUp();
setCurrentNode();
}
public void moveDown() {
myOptions.moveDown();
setCurrentNode();
}
public void moveLeft() {
myOptions.moveLeft();
setCurrentNode();
}
public void moveRight() {
myOptions.moveRight();
setCurrentNode();
}
private void setCurrentNode() {
if(myCurrentState==TOPLEVEL){
myCurrentBattleSelector=(BattleSelectorNode) myOptions.getCurrentNode();
}
else if(myCurrentState==BOTTOMLEVEL){
myCurrentBattleExecutorNode=(BattleExecutorNode) myOptions.getCurrentNode();
}
}
public Player getPlayer() {
return myPlayer;
}
private void setCurrentTextToBeDisplayed() {
if(myCurrentState==WEAPONSELECTED){
textToBeDisplayed=TEXT_DISPLAYED_WEAPON_SELECTED + myPlayer.getCurrentWeapon().toString();
}
else if(myCurrentState==ITEMUSED){
textToBeDisplayed=TEXT_DISPLAYED_ITEM_USED + itemUsedName;
}
else if (myCurrentState==PLAYERDEAD){
textToBeDisplayed=TEXT_DISPLAYED_PLAYER_DEAD;
}
else if(myCurrentState==FIRSTATTACKHAPPENED || myCurrentState==SECONDATTACKHAPPENED){
textToBeDisplayed=myCurrentAttacker.toString() + TEXT_DISPLAYED_ATTACK + myCurrentAttacker.getCurrentAttack().toString();
}
else if(myCurrentState==RAN){
textToBeDisplayed=TEXT_DISPLAYED_RAN;
}
else if(myCurrentState==ENEMYDEAD){
textToBeDisplayed=TEXT_DISPLAYED_ENEMY_DEAD + myEnemy.toString();
if (dropWeapon) {
textToBeDisplayed=TEXT_DISPLAYED_DROPPED_WEAPON;
}
}
}
public boolean didRun(){
return ran;
}
public int getCurrentState(){
return myCurrentState;
}
public void setCurrentState(int state){
myCurrentState=state;
}
}
|
src/engine/battle/BattleManager.java
|
package engine.battle;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.io.IOException;
import java.io.InputStream;
import engine.dialogue.AttackExecutorNode;
import engine.dialogue.BattleExecutorNode;
import engine.dialogue.BattleSelectorNode;
import engine.dialogue.DialogueListeningState;
import engine.dialogue.InteractionBox;
import engine.dialogue.InteractionMatrix;
import engine.dialogue.InteractionMatrix2x2;
import engine.dialogue.MatrixNode;
import engine.gridobject.GridObject;
import engine.gridobject.person.Enemy;
import engine.gridobject.person.Person;
import engine.gridobject.person.Player;
import engine.item.Item;
public class BattleManager implements InteractionBox{
BattleCalculator myBattleCalculate;
private Player myPlayer;
private Enemy myEnemy;
private BattleAI myBattleAI;
private InteractionMatrix myOptions;
private BattleSelectorNode myAttackSelector;
private BattleSelectorNode myBagSelector;
private BattleSelectorNode myWeaponSelector;
private BattleSelectorNode myRunSelector;
private BattleSelectorNode myCurrentBattleSelector;
private BattleExecutorNode myCurrentBattleExecutorNode;
private final static int TOPLEVEL=0;
private final static int BOTTOMLEVEL=1;
private final static int FIRSTATTACKHAPPENED=2;
private final static int SECONDATTACKHAPPENED=3;
private final static int WEAPONSELECTED=4;
private final static int RAN=5;
public final static int ENEMYDEAD=6;
private final static int BATTLEWON=7;
private static int myCurrentState=0;
private Person myCurrentAttacker;
private Person myCurrentVictim;
private static final int SYMBOL_RADIUS = 10;
private static final String TEXT_DISPLAYED_ATTACK=" used ";
private static final String TEXT_DISPLAYED_SECOND_ATTACK_COMPLETED="second attack damaged by: ";
private static final String TEXT_DISPLAYED_WEAPON_SELECTED="weapon selected :: ";
private static final String TEXT_DISPLAYED_RAN="Got away safely!";
private static final String TEXT_DISPLAYED_ENEMY_DEAD = "You defeated ";
private static final String TEXT_DISPLAYED_DROPPED_WEAPON = "Picked dropped weapon!";
private static final String TEXT_DISPLAYED_PLAYER_DEAD="You have been defeated!";
//DialogueListeningState PlayerDead = new DialogueListeningState("You have been defeated!",);
private static final String TEXT_DISPLAYED_ITEM_USED = "Item used!";
public static final int EXITWON = 8;
private static final int PLAYERDEAD = 9;
public static final int EXITLOST=11;
private static final int BATTLELOST = 10;
private final static int ITEMUSED=12;
private String itemUsedName = "";
private String textToBeDisplayed;
private boolean ran=false;
private boolean dropWeapon = false;
public BattleManager(Player player, Enemy enemy){
myPlayer = player;
myEnemy=enemy;
myBattleAI=new BattleAI(enemy);
myOptions = new InteractionMatrix2x2();
setOriginalNodes();
initializeChildrenNodes();
}
private void initializeChildrenNodes() {
setAttackChildrenNodes(myAttackSelector);
setWeaponChildrenNodes(myWeaponSelector);
setBagChildrenNodes(myBagSelector);
setRunChildrenNodes(myRunSelector);
}
private void updateAttackList(){
setAttackChildrenNodes(myAttackSelector);
}
private void setOriginalNodes(){
myAttackSelector = new BattleSelectorNode("Attack");
myBagSelector = new BattleSelectorNode("Bag");
myWeaponSelector = new BattleSelectorNode("Weapon");
myRunSelector = new BattleSelectorNode("Run");
myOptions.setNode(myAttackSelector, 0, 0);
myOptions.setNode(myBagSelector, 1, 0);
myOptions.setNode(myWeaponSelector, 0, 1);
myOptions.setNode(myRunSelector, 1, 1);
myCurrentBattleSelector=(BattleSelectorNode) myOptions.getCurrentNode();
}
private void setAttackChildrenNodes(BattleSelectorNode node){
for(BattleExecutable attack : myPlayer.getCurrentWeapon().getAttackList()){
setNextChild(node, attack);
}
}
private void setNextChild(BattleSelectorNode node, BattleExecutable attack) {
BattleExecutorNode executorNode = new AttackExecutorNode(attack);
node.setChild(executorNode);
}
private void setWeaponChildrenNodes(BattleSelectorNode node){
for(BattleExecutable weapon : myPlayer.getWeaponList()){
setNextChild(node, weapon);
}
}
private void setBagChildrenNodes(BattleSelectorNode node){
for(BattleExecutable item : myPlayer.getItems()){
setNextChild(node, item);
}
}
private void setRunChildrenNodes(BattleSelectorNode node){
BattleExecutable run = new Run();
setNextChild(node, run);
}
@Override
public void paintDisplay(Graphics2D g2d, int xSize, int ySize, int width,int height) {
InputStream is = GridObject.class.getResourceAsStream("PokemonGB.ttf");
Font font=null;
try {
try {
font = Font.createFont(Font.TRUETYPE_FONT, is);
} catch (FontFormatException e) {
e.printStackTrace();
}
Font sizedFont = font.deriveFont(12f);
g2d.setFont(sizedFont);
} catch (IOException e) {
e.printStackTrace();
}
g2d.setColor(Color.white);
g2d.fill(new Rectangle((int) ((int) 0), ySize/2+60, width , height));
g2d.setColor(Color.black);
if(myCurrentState==TOPLEVEL || myCurrentState==BOTTOMLEVEL){
printResponses(g2d, myOptions, xSize, ySize, width, height);
}
else {
g2d.drawString(textToBeDisplayed, (int) xSize/10, ySize/2+120);
}
}
private void printResponses(Graphics2D g2d, InteractionMatrix myResponses2, int xSize, int ySize,
int width, int height) {
int xCornerLoc = xSize/10;
int yCornerLoc = ySize/2 + 120;
for (int i = 0; i < myOptions.getDimension()[0]; i++) {
for (int j = 0; j < myOptions.getDimension()[1]; j++) {
MatrixNode qn = (MatrixNode) myOptions.getNode(j, i);
if(qn!=null)g2d.drawString(qn.toString(), (int) (xCornerLoc + j*(xSize*5/10)), (int)(yCornerLoc + i*(height*3/10)));
}
}
int[] selectedOptionLoc = myOptions.getSelectedNodeLocation();
g2d.fillOval((int) (xCornerLoc-10 + selectedOptionLoc[0]*(xSize-25)*5/10) - SYMBOL_RADIUS,
(int) (yCornerLoc + selectedOptionLoc[1]*(height-15)*3/10) - SYMBOL_RADIUS, SYMBOL_RADIUS, SYMBOL_RADIUS);
}
@Override
public void getNextText() {
((InteractionMatrix2x2) myOptions).resetMatrixPosition();
if(myCurrentState==RAN){
ran=true;
}
else if(myCurrentState==PLAYERDEAD){
setCurrentTextToBeDisplayed();
myCurrentState=BATTLELOST;
}
else if (myCurrentState==ENEMYDEAD){
setCurrentTextToBeDisplayed();
myCurrentState=BATTLEWON;
}
else if(myCurrentState==BATTLEWON){
myCurrentState=EXITWON;
}
else if(myCurrentState==BATTLELOST){
myCurrentState=EXITLOST;
}
else if (myCurrentState==SECONDATTACKHAPPENED || myCurrentState==WEAPONSELECTED || myCurrentState==ITEMUSED){
setOriginalNodes();
initializeChildrenNodes();
myCurrentState=TOPLEVEL;
}
else if(myCurrentState==FIRSTATTACKHAPPENED){
Person tempAttacker=myCurrentAttacker;
myCurrentAttacker=myCurrentVictim;
myCurrentVictim=tempAttacker;
setCurrentTextToBeDisplayed();
myBattleCalculate.attack(myCurrentAttacker,myCurrentVictim,myCurrentAttacker.getCurrentWeapon(),myCurrentAttacker.getCurrentAttack());
myCurrentState=SECONDATTACKHAPPENED;
if(myBattleCalculate.enemyIsDead())
myCurrentState=ENEMYDEAD;
if(myBattleCalculate.playerIsDead()){
myCurrentState=PLAYERDEAD;
}
}
else if(myCurrentState==BOTTOMLEVEL){
BattleExecutable executable = myCurrentBattleExecutorNode.getExecutor();
if(executable instanceof Weapon){
myPlayer.setCurrentWeapon((Weapon) executable);
myCurrentState=WEAPONSELECTED;
updateAttackList();
setCurrentTextToBeDisplayed();
}
else if(executable instanceof Attack){
myBattleCalculate=new BattleCalculator(myPlayer, myEnemy);
Weapon enemyWeapon = myBattleAI.chooseWeapon();
myEnemy.setCurrentWeapon(enemyWeapon);
myEnemy.setCurrentAttack(myBattleAI.chooseAttack(enemyWeapon));
myPlayer.setCurrentAttack((Attack) executable);
myCurrentAttacker = myBattleCalculate.attackFirst(myPlayer, myPlayer.getCurrentWeapon(),
(Attack) executable, myEnemy, enemyWeapon, myEnemy.getCurrentAttack())[0];
myCurrentVictim = myBattleCalculate.attackFirst(myPlayer, myPlayer.getCurrentWeapon(),
(Attack) executable, myEnemy, enemyWeapon, myEnemy.getCurrentAttack())[1];
myCurrentState=FIRSTATTACKHAPPENED;
setCurrentTextToBeDisplayed();
myBattleCalculate.attack(myCurrentAttacker,myCurrentVictim,myCurrentAttacker.getCurrentWeapon(),myCurrentAttacker.getCurrentAttack());
if(myBattleCalculate.enemyIsDead())
myCurrentState=ENEMYDEAD;
if(myBattleCalculate.playerIsDead())
myCurrentState=PLAYERDEAD;
}
else if(executable instanceof Item){
((Item) executable).useItem();
myCurrentState=ITEMUSED;
itemUsedName=((Item) executable).getName();
setCurrentTextToBeDisplayed();
}
else if(executable instanceof Run){
//ran=true;
myCurrentState=RAN;
setCurrentTextToBeDisplayed();
}
}
else if(myCurrentState==TOPLEVEL){
int count=0;
myCurrentBattleSelector.getChildren().size();
for(int i=0; i<myOptions.getDimension()[0]; i++){
for(int j=0; j<myOptions.getDimension()[1]; j++){
if(myCurrentBattleSelector.getChildren().size()>count)
myOptions.setNode(myCurrentBattleSelector.getChildren().get(count), i, j);
else{
myOptions.setNode(null, i, j);
}
count++;
}
}
myCurrentBattleExecutorNode = (BattleExecutorNode) myOptions.getCurrentNode();
myCurrentState=BOTTOMLEVEL;
}
}
public void moveUp() {
myOptions.moveUp();
setCurrentNode();
}
public void moveDown() {
myOptions.moveDown();
setCurrentNode();
}
public void moveLeft() {
myOptions.moveLeft();
setCurrentNode();
}
public void moveRight() {
myOptions.moveRight();
setCurrentNode();
}
private void setCurrentNode() {
if(myCurrentState==TOPLEVEL){
myCurrentBattleSelector=(BattleSelectorNode) myOptions.getCurrentNode();
}
else if(myCurrentState==BOTTOMLEVEL){
myCurrentBattleExecutorNode=(BattleExecutorNode) myOptions.getCurrentNode();
}
}
public Player getPlayer() {
return myPlayer;
}
private void setCurrentTextToBeDisplayed() {
if(myCurrentState==WEAPONSELECTED){
textToBeDisplayed=TEXT_DISPLAYED_WEAPON_SELECTED + myPlayer.getCurrentWeapon().toString();
}
else if(myCurrentState==ITEMUSED){
textToBeDisplayed=TEXT_DISPLAYED_ITEM_USED + itemUsedName;
}
else if (myCurrentState==PLAYERDEAD){
textToBeDisplayed=TEXT_DISPLAYED_PLAYER_DEAD;
}
else if(myCurrentState==FIRSTATTACKHAPPENED || myCurrentState==SECONDATTACKHAPPENED){
textToBeDisplayed=myCurrentAttacker.toString() + TEXT_DISPLAYED_ATTACK + myCurrentAttacker.getCurrentAttack().toString();
}
else if(myCurrentState==RAN){
textToBeDisplayed=TEXT_DISPLAYED_RAN;
}
else if(myCurrentState==ENEMYDEAD){
textToBeDisplayed=TEXT_DISPLAYED_ENEMY_DEAD + myEnemy.toString();
if (dropWeapon) {
textToBeDisplayed=TEXT_DISPLAYED_DROPPED_WEAPON;
}
}
}
public boolean didRun(){
return ran;
}
public int getCurrentState(){
return myCurrentState;
}
public void setCurrentState(int state){
myCurrentState=state;
}
}
|
stuff
|
src/engine/battle/BattleManager.java
|
stuff
|
|
Java
|
mit
|
17c326a066a68231c2256c2a2453216da2854535
| 0
|
aterai/java-swing-tips,aterai/java-swing-tips,aterai/java-swing-tips,aterai/java-swing-tips
|
// -*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
// @homepage@
package example;
import java.awt.*;
import java.util.Objects;
import java.util.Optional;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableModel;
public final class MainPanel extends JPanel {
private MainPanel() {
super(new BorderLayout());
String[] columnNames = {"String-String/String", "Integer", "Boolean"};
Object[][] data = {
{"1234567890123456789012345678901234567890", 12, true},
{"BBB", 2, true}, {"EEE", 3, false},
{"CCC", 4, true}, {"FFF", 5, false},
{"DDD", 6, true}, {"GGG", 7, false}
};
TableModel model = new DefaultTableModel(data, columnNames) {
@Override public Class<?> getColumnClass(int column) {
return getValueAt(0, column).getClass();
}
};
JTable table = new JTable(model) {
@Override public Component prepareRenderer(TableCellRenderer tcr, int row, int column) {
Component c = super.prepareRenderer(tcr, row, column);
if (c instanceof JComponent) {
JComponent l = (JComponent) c;
Insets i = l.getInsets();
Rectangle rect = getCellRect(row, column, false);
rect.width -= i.left + i.right;
FontMetrics fm = l.getFontMetrics(l.getFont());
String str = Objects.toString(getValueAt(row, column), "");
int cellTextWidth = fm.stringWidth(str);
l.setToolTipText(cellTextWidth > rect.width ? str : null);
}
return c;
}
@Override public void updateUI() {
super.updateUI();
TableCellRenderer r = new ToolTipHeaderRenderer();
for (int i = 0; i < getColumnModel().getColumnCount(); i++) {
getColumnModel().getColumn(i).setHeaderRenderer(r);
}
// JTableHeader h = getTableHeader();
// h.setDefaultRenderer(new ToolTipHeaderRenderer(h.getDefaultRenderer()));
}
};
table.setAutoCreateRowSorter(true);
add(new JScrollPane(table));
setPreferredSize(new Dimension(320, 240));
}
public static void main(String[] args) {
EventQueue.invokeLater(MainPanel::createAndShowGui);
}
private static void createAndShowGui() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
Toolkit.getDefaultToolkit().beep();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class ToolTipHeaderRenderer implements TableCellRenderer {
// private final Icon icon = UIManager.getIcon("Table.ascendingSortIcon");
@Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
TableCellRenderer renderer = table.getTableHeader().getDefaultRenderer();
JLabel l = (JLabel) renderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
Insets i = l.getInsets();
Rectangle rect = table.getCellRect(row, column, false);
rect.width -= i.left + i.right;
// RowSorter<? extends TableModel> sorter = table.getRowSorter();
// if (sorter != null && !sorter.getSortKeys().isEmpty() && sorter.getSortKeys().get(0).getColumn() == column) {
// rect.width -= icon.getIconWidth() + l.getIconTextGap();
// }
// Optional.ofNullable(table.getRowSorter())
// .filter(sorter -> !sorter.getSortKeys().isEmpty() && sorter.getSortKeys().get(0).getColumn() == column)
// .filter(sorter -> Objects.nonNull(l.getIcon()))
// .ifPresent(sorter -> rect.width -= icon.getIconWidth() + l.getIconTextGap());
Optional.ofNullable(l.getIcon())
.ifPresent(icon -> rect.width -= icon.getIconWidth() + l.getIconTextGap());
FontMetrics fm = l.getFontMetrics(l.getFont());
String str = Objects.toString(value, "");
int cellTextWidth = fm.stringWidth(str);
l.setToolTipText(cellTextWidth > rect.width ? str : null);
return l;
}
}
|
ClippedCellTooltips/src/java/example/MainPanel.java
|
// -*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
// @homepage@
package example;
import java.awt.*;
import java.util.Objects;
import java.util.Optional;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableModel;
public final class MainPanel extends JPanel {
private final String[] columnNames = {"String-String/String", "Integer", "Boolean"};
private final Object[][] data = {
{"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", 12, true},
{"BBB", 2, true}, {"EEE", 3, false},
{"CCC", 4, true}, {"FFF", 5, false},
{"DDD", 6, true}, {"GGG", 7, false}
};
private final TableModel model = new DefaultTableModel(data, columnNames) {
@Override public Class<?> getColumnClass(int column) {
return getValueAt(0, column).getClass();
}
};
private final JTable table = new JTable(model) {
@Override public Component prepareRenderer(TableCellRenderer tcr, int row, int column) {
Component c = super.prepareRenderer(tcr, row, column);
if (c instanceof JComponent) {
JComponent l = (JComponent) c;
Insets i = l.getInsets();
Rectangle rect = getCellRect(row, column, false);
rect.width -= i.left + i.right;
FontMetrics fm = l.getFontMetrics(l.getFont());
String str = Objects.toString(getValueAt(row, column), "");
int cellTextWidth = fm.stringWidth(str);
l.setToolTipText(cellTextWidth > rect.width ? str : null);
}
return c;
}
@Override public void updateUI() {
super.updateUI();
TableCellRenderer r = new ToolTipHeaderRenderer();
for (int i = 0; i < getColumnModel().getColumnCount(); i++) {
getColumnModel().getColumn(i).setHeaderRenderer(r);
}
// JTableHeader h = getTableHeader();
// h.setDefaultRenderer(new ToolTipHeaderRenderer(h.getDefaultRenderer()));
}
};
private MainPanel() {
super(new BorderLayout());
table.setAutoCreateRowSorter(true);
add(new JScrollPane(table));
setPreferredSize(new Dimension(320, 240));
}
public static void main(String[] args) {
EventQueue.invokeLater(MainPanel::createAndShowGui);
}
private static void createAndShowGui() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
Toolkit.getDefaultToolkit().beep();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class ToolTipHeaderRenderer implements TableCellRenderer {
// private final Icon icon = UIManager.getIcon("Table.ascendingSortIcon");
@Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
TableCellRenderer renderer = table.getTableHeader().getDefaultRenderer();
JLabel l = (JLabel) renderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
Insets i = l.getInsets();
Rectangle rect = table.getCellRect(row, column, false);
rect.width -= i.left + i.right;
// RowSorter<? extends TableModel> sorter = table.getRowSorter();
// if (sorter != null && !sorter.getSortKeys().isEmpty() && sorter.getSortKeys().get(0).getColumn() == column) {
// rect.width -= icon.getIconWidth() + l.getIconTextGap();
// }
// Optional.ofNullable(table.getRowSorter())
// .filter(sorter -> !sorter.getSortKeys().isEmpty() && sorter.getSortKeys().get(0).getColumn() == column)
// .filter(sorter -> Objects.nonNull(l.getIcon()))
// .ifPresent(sorter -> rect.width -= icon.getIconWidth() + l.getIconTextGap());
Optional.ofNullable(l.getIcon())
.ifPresent(icon -> rect.width -= icon.getIconWidth() + l.getIconTextGap());
FontMetrics fm = l.getFontMetrics(l.getFont());
String str = Objects.toString(value, "");
int cellTextWidth = fm.stringWidth(str);
l.setToolTipText(cellTextWidth > rect.width ? str : null);
return l;
}
}
|
refactor: field can be converted to a local variable
|
ClippedCellTooltips/src/java/example/MainPanel.java
|
refactor: field can be converted to a local variable
|
|
Java
|
mit
|
60df0e89eccf9785a93b5bcce4972a5fdcefaad9
| 0
|
B-Stefan/Risiko
|
package main.java.logic.data;
import main.java.logic.data.Continent;
import main.java.logic.data.Country;
import main.java.logic.data.Player;
import java.awt.*;
import java.util.*;
/**
* @author Jennifer Theloy, Thu Nguyen, Stefan Bieliauskas
*
* Dient zur Verwaltung der Karte für ein Spiel
*/
public class Map {
/**
* Beinhaltet alle Länder, für die Karte
*/
private final ArrayList<Country> countries = new ArrayList<Country>();
/**
* Beinhaltet alle Kontinente für die Karte
*/
private final ArrayList<Continent> continents = new ArrayList<Continent>();
/**
* Erstellt eine neue Standard-Karte
*/
public Map() {
//Kontinente erzeugen
Continent northAmerica = new Continent("Nord Amerika", 5);
Continent southAmerica = new Continent("Süd Amerika", 2);
Continent europe = new Continent("Europa", 5);
Continent asia = new Continent("Asien", 7);
Continent afrika = new Continent("Afrika", 3);
Continent australia = new Continent("Australien", 2);
this.continents.add(northAmerica);
this.continents.add(southAmerica);
this.continents.add(asia);
this.continents.add(afrika);
this.continents.add(australia);
//Länder zuweisen
this.countries.add(new Country("Alaska", northAmerica, new Color(255,55,0)));
this.countries.add(new Country("Nordwest-Territorium", northAmerica, new Color(255,222,111)));
this.countries.add(new Country("Alberta", northAmerica, new Color(150,0,222)));
this.countries.add(new Country("Ontario", northAmerica, new Color(0,222,150)));
this.countries.add(new Country("Quebec", northAmerica, new Color(222,111,150)));
this.countries.add(new Country("Weststaaten", northAmerica, new Color(222,0,222)));
this.countries.add(new Country("Oststaaten", northAmerica, new Color(222,111,222)));
this.countries.add(new Country("Mittelamerika", northAmerica, new Color(222,111,111)));
this.countries.add(new Country("Hawaii", northAmerica, new Color(255,222,22)));
this.countries.add(new Country("Nunavut", northAmerica, new Color(222,40,111)));
this.countries.add(new Country("Venezuela", southAmerica, new Color(111,111,222)));
this.countries.add(new Country("Brasilien", southAmerica, new Color(50,150,50)));
this.countries.add(new Country("Peru", southAmerica, new Color(222,0,111)));
this.countries.add(new Country("Falkland-Inseln", southAmerica, new Color(50,150,150)));
this.countries.add(new Country("Argentinien", southAmerica, new Color(50,150,100)));
this.countries.add(new Country("Grönland", europe, new Color(0,255,0)));
this.countries.add(new Country("Island", europe, new Color(22,255,123)));
this.countries.add(new Country("Großbritannien", europe, new Color(22,111,222)));
this.countries.add(new Country("Skandinavien", europe, new Color(50,120,120)));
this.countries.add(new Country("Mitteleuropa", europe, new Color(255,111,137)));
this.countries.add(new Country("Westeuropa", europe, new Color(0,255,199)));
this.countries.add(new Country("Südeuropa", europe, new Color(30,99,255)));
this.countries.add(new Country("Ukraine", europe, new Color(255,255,0)));
this.countries.add(new Country("Svalbard", europe, new Color(50,60,120)));
this.countries.add(new Country("Afghanistan", asia, new Color(255,200,0)));
this.countries.add(new Country("Ural", asia, new Color(105,8,90)));
this.countries.add(new Country("Sibirien", asia, new Color(100,0,0)));
this.countries.add(new Country("Irrutsk", asia, new Color(0,0,100)));
this.countries.add(new Country("Jakutsk", asia, new Color(0,100,0)));
this.countries.add(new Country("Kamtschatka", asia, new Color(0,158,224)));
this.countries.add(new Country("Mongolei", asia, new Color(234,105,160)));
this.countries.add(new Country("Japan", asia, new Color(226,0,122)));
this.countries.add(new Country("China", asia, new Color(255,0,0)));
this.countries.add(new Country("Indien", asia, new Color(171,140,188)));
this.countries.add(new Country("Siam", asia, new Color(151,191,13)));
this.countries.add(new Country("Mittlerer-Osten", asia, new Color(0,255,255)));
this.countries.add(new Country("Ägypten", afrika, new Color(200,100,100)));
this.countries.add(new Country("Ostafrika", afrika, new Color(100,200,100)));
this.countries.add(new Country("Nordwestafrika", afrika, new Color(50,150,200)));
this.countries.add(new Country("Südafrika", afrika, new Color(0,200,200)));
this.countries.add(new Country("Madagaskar", afrika, new Color(0,200,0)));
this.countries.add(new Country("Kongo", afrika, new Color(50,100,200)));
this.countries.add(new Country("Indonesien", australia, new Color(122,0,122)));
this.countries.add(new Country("Neu-Guinea", australia, new Color(100,0,200)));
this.countries.add(new Country("Ostaustralien", australia, new Color(200,100,0)));
this.countries.add(new Country("Westaustralien", australia, new Color(255,255,100)));
this.countries.add(new Country("Neuseeland", australia, new Color(200,0,100)));
this.countries.add(new Country("Philippinen", australia, new Color(255,147,0)));
//Hinzufügen der Verbindungen
//Australien
Country ostaustralien = this.getCountry("Ostaustralien");
ostaustralien.connectTo(this.getCountry("Westaustralien"));
ostaustralien.connectTo(this.getCountry("Neu-Guinea"));
Country indonesien = this.getCountry("Indonesien");
indonesien.connectTo(this.getCountry("Siam"));
indonesien.connectTo(this.getCountry("Westaustralien"));
indonesien.connectTo(this.getCountry("Philippinen"));
Country Neuguinea = this.getCountry("Neu-Guinea");
Neuguinea.connectTo(this.getCountry("Westaustralien"));
Country neuseeland = this.getCountry("Neuseeland");
neuseeland.connectTo(this.getCountry("Ostaustralien"));
//Asien
Country China = this.getCountry("China");
China.connectTo(this.getCountry("Siam"));
China.connectTo(this.getCountry("Indien"));
China.connectTo(this.getCountry("Mongolei"));
China.connectTo(this.getCountry("Afghanistan"));
China.connectTo(this.getCountry("Sibirien"));
China.connectTo(this.getCountry("Ural"));
Country mongolei = this.getCountry("Mongolei");
mongolei.connectTo(this.getCountry("Japan"));
mongolei.connectTo(this.getCountry("Irrutsk"));
mongolei.connectTo(this.getCountry("Sibirien"));
Country jakutsk = this.getCountry("Jakutsk");
jakutsk.connectTo(this.getCountry("Kamtschatka"));
jakutsk.connectTo(this.getCountry("Sibirien"));
jakutsk.connectTo(this.getCountry("Irrutsk"));
Country japan = this.getCountry("Japan");
japan.connectTo(this.getCountry("Hawaii"));
japan.connectTo(this.getCountry("Philippinen"));
japan.connectTo(this.getCountry("Kamtschatka"));
Country irrutsk = this.getCountry("Irrutsk");
irrutsk.connectTo(this.getCountry("Kamtschatka"));
irrutsk.connectTo(this.getCountry("Sibirien"));
Country Indien = this.getCountry("Indien");
Indien.connectTo(this.getCountry("Siam"));
Indien.connectTo(this.getCountry("Mittlerer-Osten"));
Indien.connectTo(this.getCountry("Afghanistan"));
Country ural = this.getCountry("Ural");
ural.connectTo(this.getCountry("Sibirien"));
ural.connectTo(this.getCountry("Afghanistan"));
ural.connectTo(this.getCountry("Ukraine"));
Country mittlererOsten = this.getCountry("Mittlerer-Osten");
mittlererOsten.connectTo(this.getCountry("Afghanistan"));
mittlererOsten.connectTo(this.getCountry("Ukraine"));
mittlererOsten.connectTo(this.getCountry("Ägypten"));
mittlererOsten.connectTo(this.getCountry("Südeuropa"));
//Europa
Country ukraine = this.getCountry("Ukraine");
ukraine.connectTo(this.getCountry("Afghanistan"));
ukraine.connectTo(this.getCountry("Südeuropa"));
ukraine.connectTo(this.getCountry("Skandinavien"));
ukraine.connectTo(this.getCountry("Mitteleuropa"));
Country Skandinavien = this.getCountry("Skandinavien");
Skandinavien.connectTo(this.getCountry("Svalbard"));
Skandinavien.connectTo(this.getCountry("Island"));
Skandinavien.connectTo(this.getCountry("Großbritannien"));
Skandinavien.connectTo(this.getCountry("Mitteleuropa"));
Country gb = this.getCountry("Großbritannien");
gb.connectTo(this.getCountry("Island"));
gb.connectTo(this.getCountry("Mitteleuropa"));
gb.connectTo(this.getCountry("Westeuropa"));
Country westEu = this.getCountry("Westeuropa");
westEu.connectTo(this.getCountry("Nordwestafrika"));
westEu.connectTo(this.getCountry("Südeuropa"));
westEu.connectTo(this.getCountry("Mitteleuropa"));
Country southEu = this.getCountry("Südeuropa");
southEu.connectTo(this.getCountry("Ägypten"));
southEu.connectTo(this.getCountry("Nordwestafrika"));
//Afrika
Country noWeAfrika = this.getCountry("Nordwestafrika");
noWeAfrika.connectTo(this.getCountry("Ägypten"));
noWeAfrika.connectTo(this.getCountry("Ostafrika"));
noWeAfrika.connectTo(this.getCountry("Kongo"));
Country ostAfrika = this.getCountry("Ostafrika");
ostAfrika.connectTo(this.getCountry("Ägypten"));
ostAfrika.connectTo(this.getCountry("Kongo"));
ostAfrika.connectTo(this.getCountry("Südafrika"));
ostAfrika.connectTo(this.getCountry("Madagaskar"));
Country southAfrika = this.getCountry("Südafrika");
southAfrika.connectTo(this.getCountry("Madagaskar"));
southAfrika.connectTo(this.getCountry("Kongo"));
southAfrika.connectTo(this.getCountry("Falkland-Inseln"));
//Süd-Amerika
Country brasil = this.getCountry("Brasilien");
brasil.connectTo(this.getCountry("Nordwestafrika"));
brasil.connectTo(this.getCountry("Venezuela"));
brasil.connectTo(this.getCountry("Peru"));
brasil.connectTo(this.getCountry("Argentinien"));
Country venezuela = this.getCountry("Venezuela");
venezuela.connectTo(this.getCountry("Peru"));
venezuela.connectTo(this.getCountry("Mittelamerika"));
Country Argentinien = this.getCountry("Argentinien");
Argentinien.connectTo(this.getCountry("Peru"));
Argentinien.connectTo(this.getCountry("Falkland-Inseln"));
Argentinien.connectTo(this.getCountry("Neuseeland"));
//Nord-Amerika
Country mittelamerika = this.getCountry("Mittelamerika");
mittelamerika.connectTo(this.getCountry("Oststaaten"));
mittelamerika.connectTo(this.getCountry("Weststaaten"));
Country Weststaaten = this.getCountry("Weststaaten");
Weststaaten.connectTo(this.getCountry("Oststaaten"));
Weststaaten.connectTo(this.getCountry("Hawaii"));
Weststaaten.connectTo(this.getCountry("Alberta"));
Weststaaten.connectTo(this.getCountry("Ontario"));
Country Ontario = this.getCountry("Ontario");
Ontario.connectTo(this.getCountry("Quebec"));
Weststaaten.connectTo(this.getCountry("Oststaaten"));
Weststaaten.connectTo(this.getCountry("Nunavut"));
Weststaaten.connectTo(this.getCountry("Nordwest-Territorium"));
Weststaaten.connectTo(this.getCountry("Alberta"));
Country alaska = this.getCountry("Alaska");
alaska.connectTo(this.getCountry("Kamtschatka"));
alaska.connectTo(this.getCountry("Nordwest-Territorium"));
alaska.connectTo(this.getCountry("Alberta"));
Country Nordwest = this.getCountry("Nordwest-Territorium");
Nordwest.connectTo(this.getCountry("Alberta"));
Nordwest.connectTo(this.getCountry("Nunavut"));
Country Nunavut = this.getCountry("Nunavut");
Nunavut.connectTo(this.getCountry("Quebec"));
Nunavut.connectTo(this.getCountry("Grönland"));
Country groenland = this.getCountry("Grönland");
groenland.connectTo(this.getCountry("Quebec"));
groenland.connectTo(this.getCountry("Svalbard"));
groenland.connectTo(this.getCountry("Island"));
}
public ArrayList<Country> getCountries() {
return this.countries;
}
/**
* Berechnet den Benous, den ein Spieler an Einheiten bekommt f�r die komplette Einnahme des jeweilligen Kontinents
* @param p der aktuelle Spieler
* @return die Anzahl der Bonus Einheiten
*/
public int getBonus(Player p){
int bonus = 0;
for (Continent c : this.continents){
if(c.getCurrentOwner()==p){bonus += c.getBonus();}
}
return bonus;
}
/**
* Vergleicht die Namen der L�nder mit �bergebenem String
* @param n String (name des zu suchenden Landes)
* @return das zu suchende Land
*/
public Country getCountry(String n){
for (Country c : countries){
if(c.getName().equals(n)){
return c;
}
}
return null;
}
/**
* Vergleicht die Farbe mit der übergebenen Farbe
* @param col Color (Farbe des zu suchenden Landes)
* @return das zu suchende Land
*/
public Country getCountry(Color col){
for (Country c : countries){
if(c.getColor().equals(col)){
return c;
}
}
return null;
}
/**
*
* @return Alle Kontinente dieser Karte
*/
public ArrayList<Continent> getContinents() {
return continents;
}
}
|
Client/src/main/java/logic/data/Map.java
|
package main.java.logic.data;
import main.java.logic.data.Continent;
import main.java.logic.data.Country;
import main.java.logic.data.Player;
import java.awt.*;
import java.util.*;
/**
* @author Jennifer Theloy, Thu Nguyen, Stefan Bieliauskas
*
* Dient zur Verwaltung der Karte für ein Spiel
*/
public class Map {
/**
* Beinhaltet alle Länder, für die Karte
*/
private final ArrayList<Country> countries = new ArrayList<Country>();
/**
* Beinhaltet alle Kontinente für die Karte
*/
private final ArrayList<Continent> continents = new ArrayList<Continent>();
/**
* Erstellt eine neue Standard-Karte
*/
public Map() {
//Kontinente erzeugen
Continent northAmerica = new Continent("Nord Amerika", 5);
Continent southAmerica = new Continent("Süd Amerika", 2);
Continent europe = new Continent("Europa", 5);
Continent asia = new Continent("Asien", 7);
Continent afrika = new Continent("Afrika", 3);
Continent australia = new Continent("Australien", 2);
this.continents.add(northAmerica);
this.continents.add(southAmerica);
this.continents.add(asia);
this.continents.add(afrika);
this.continents.add(australia);
//Länder zuweisen
this.countries.add(new Country("Alaska", northAmerica, new Color(255,55,0)));
this.countries.add(new Country("Nordwest-Territorium", northAmerica, new Color(255,222,111)));
this.countries.add(new Country("Alberta", northAmerica, new Color(150,0,222)));
this.countries.add(new Country("Ontario", northAmerica, new Color(0,222,150)));
this.countries.add(new Country("Quebec", northAmerica, new Color(222,111,150)));
this.countries.add(new Country("Weststaaten", northAmerica, new Color(222,0,222)));
this.countries.add(new Country("Oststaaten", northAmerica, new Color(222,111,222)));
this.countries.add(new Country("Mittelamerika", northAmerica, new Color(222,111,111)));
this.countries.add(new Country("Hawaii", northAmerica, new Color(255,222,22)));
this.countries.add(new Country("Nunavut", northAmerica, new Color(222,40,111)));
this.countries.add(new Country("Venezuela", southAmerica, new Color(111,111,222)));
this.countries.add(new Country("Brasilien", southAmerica, new Color(50,150,50)));
this.countries.add(new Country("Peru", southAmerica, new Color(222,0,111)));
this.countries.add(new Country("Falkland-Inseln", southAmerica, new Color(50,150,150)));
this.countries.add(new Country("Argentinien", southAmerica, new Color(50,150,100)));
this.countries.add(new Country("Grönland", europe, new Color(0,255,0)));
this.countries.add(new Country("Island", europe, new Color(22,255,123)));
this.countries.add(new Country("Großbritannien", europe, new Color(22,111,222)));
this.countries.add(new Country("Skandinavien", europe, new Color(50,120,120)));
this.countries.add(new Country("Mitteleuropa", europe, new Color(255,111,137)));
this.countries.add(new Country("Westeuropa", europe, new Color(0,255,199)));
this.countries.add(new Country("Südeuropa", europe, new Color(0,0,0)));
this.countries.add(new Country("Ukraine", europe, new Color(255,255,0)));
this.countries.add(new Country("Svalbard", europe, new Color(50,60,120)));
this.countries.add(new Country("Afghanistan", asia, new Color(255,200,0)));
this.countries.add(new Country("Ural", asia, new Color(105,8,90)));
this.countries.add(new Country("Sibirien", asia, new Color(100,0,0)));
this.countries.add(new Country("Irrutsk", asia, new Color(0,0,100)));
this.countries.add(new Country("Jakutsk", asia, new Color(0,100,0)));
this.countries.add(new Country("Kamtschatka", asia, new Color(0,158,224)));
this.countries.add(new Country("Mongolei", asia, new Color(234,105,160)));
this.countries.add(new Country("Japan", asia, new Color(226,0,122)));
this.countries.add(new Country("China", asia, new Color(255,0,0)));
this.countries.add(new Country("Indien", asia, new Color(171,140,188)));
this.countries.add(new Country("Siam", asia, new Color(151,191,13)));
this.countries.add(new Country("Mittlerer-Osten", asia, new Color(0,255,255)));
this.countries.add(new Country("Ägypten", afrika, new Color(200,100,100)));
this.countries.add(new Country("Ostafrika", afrika, new Color(100,200,100)));
this.countries.add(new Country("Nordwestafrika", afrika, new Color(50,150,200)));
this.countries.add(new Country("Südafrika", afrika, new Color(0,200,200)));
this.countries.add(new Country("Madagaskar", afrika, new Color(0,200,0)));
this.countries.add(new Country("Kongo", afrika, new Color(50,100,200)));
this.countries.add(new Country("Indonesien", australia, new Color(122,0,122)));
this.countries.add(new Country("Neu-Guinea", australia, new Color(100,0,200)));
this.countries.add(new Country("Ostaustralien", australia, new Color(200,100,0)));
this.countries.add(new Country("Westaustralien", australia, new Color(255,255,100)));
this.countries.add(new Country("Neuseeland", australia, new Color(200,0,100)));
this.countries.add(new Country("Philippinen", australia, new Color(255,147,0)));
//Hinzufügen der Verbindungen
//Australien
Country ostaustralien = this.getCountry("Ostaustralien");
ostaustralien.connectTo(this.getCountry("Westaustralien"));
ostaustralien.connectTo(this.getCountry("Neu-Guinea"));
Country indonesien = this.getCountry("Indonesien");
indonesien.connectTo(this.getCountry("Siam"));
indonesien.connectTo(this.getCountry("Westaustralien"));
indonesien.connectTo(this.getCountry("Philippinen"));
Country Neuguinea = this.getCountry("Neu-Guinea");
Neuguinea.connectTo(this.getCountry("Westaustralien"));
Country neuseeland = this.getCountry("Neuseeland");
neuseeland.connectTo(this.getCountry("Ostaustralien"));
//Asien
Country China = this.getCountry("China");
China.connectTo(this.getCountry("Siam"));
China.connectTo(this.getCountry("Indien"));
China.connectTo(this.getCountry("Mongolei"));
China.connectTo(this.getCountry("Afghanistan"));
China.connectTo(this.getCountry("Sibirien"));
China.connectTo(this.getCountry("Ural"));
Country mongolei = this.getCountry("Mongolei");
mongolei.connectTo(this.getCountry("Japan"));
mongolei.connectTo(this.getCountry("Irrutsk"));
mongolei.connectTo(this.getCountry("Sibirien"));
Country jakutsk = this.getCountry("Jakutsk");
jakutsk.connectTo(this.getCountry("Kamtschatka"));
jakutsk.connectTo(this.getCountry("Sibirien"));
jakutsk.connectTo(this.getCountry("Irrutsk"));
Country japan = this.getCountry("Japan");
japan.connectTo(this.getCountry("Hawaii"));
japan.connectTo(this.getCountry("Philippinen"));
japan.connectTo(this.getCountry("Kamtschatka"));
Country irrutsk = this.getCountry("Irrutsk");
irrutsk.connectTo(this.getCountry("Kamtschatka"));
irrutsk.connectTo(this.getCountry("Sibirien"));
Country Indien = this.getCountry("Indien");
Indien.connectTo(this.getCountry("Siam"));
Indien.connectTo(this.getCountry("Mittlerer-Osten"));
Indien.connectTo(this.getCountry("Afghanistan"));
Country ural = this.getCountry("Ural");
ural.connectTo(this.getCountry("Sibirien"));
ural.connectTo(this.getCountry("Afghanistan"));
ural.connectTo(this.getCountry("Ukraine"));
Country mittlererOsten = this.getCountry("Mittlerer-Osten");
mittlererOsten.connectTo(this.getCountry("Afghanistan"));
mittlererOsten.connectTo(this.getCountry("Ukraine"));
mittlererOsten.connectTo(this.getCountry("Ägypten"));
mittlererOsten.connectTo(this.getCountry("Südeuropa"));
//Europa
Country ukraine = this.getCountry("Ukraine");
ukraine.connectTo(this.getCountry("Afghanistan"));
ukraine.connectTo(this.getCountry("Südeuropa"));
ukraine.connectTo(this.getCountry("Skandinavien"));
ukraine.connectTo(this.getCountry("Mitteleuropa"));
Country Skandinavien = this.getCountry("Skandinavien");
Skandinavien.connectTo(this.getCountry("Svalbard"));
Skandinavien.connectTo(this.getCountry("Island"));
Skandinavien.connectTo(this.getCountry("Großbritannien"));
Skandinavien.connectTo(this.getCountry("Mitteleuropa"));
Country gb = this.getCountry("Großbritannien");
gb.connectTo(this.getCountry("Island"));
gb.connectTo(this.getCountry("Mitteleuropa"));
gb.connectTo(this.getCountry("Westeuropa"));
Country westEu = this.getCountry("Westeuropa");
westEu.connectTo(this.getCountry("Nordwestafrika"));
westEu.connectTo(this.getCountry("Südeuropa"));
westEu.connectTo(this.getCountry("Mitteleuropa"));
Country southEu = this.getCountry("Südeuropa");
southEu.connectTo(this.getCountry("Ägypten"));
southEu.connectTo(this.getCountry("Nordwestafrika"));
//Afrika
Country noWeAfrika = this.getCountry("Nordwestafrika");
noWeAfrika.connectTo(this.getCountry("Ägypten"));
noWeAfrika.connectTo(this.getCountry("Ostafrika"));
noWeAfrika.connectTo(this.getCountry("Kongo"));
Country ostAfrika = this.getCountry("Ostafrika");
ostAfrika.connectTo(this.getCountry("Ägypten"));
ostAfrika.connectTo(this.getCountry("Kongo"));
ostAfrika.connectTo(this.getCountry("Südafrika"));
ostAfrika.connectTo(this.getCountry("Madagaskar"));
Country southAfrika = this.getCountry("Südafrika");
southAfrika.connectTo(this.getCountry("Madagaskar"));
southAfrika.connectTo(this.getCountry("Kongo"));
southAfrika.connectTo(this.getCountry("Falkland-Inseln"));
//Süd-Amerika
Country brasil = this.getCountry("Brasilien");
brasil.connectTo(this.getCountry("Nordwestafrika"));
brasil.connectTo(this.getCountry("Venezuela"));
brasil.connectTo(this.getCountry("Peru"));
brasil.connectTo(this.getCountry("Argentinien"));
Country venezuela = this.getCountry("Venezuela");
venezuela.connectTo(this.getCountry("Peru"));
venezuela.connectTo(this.getCountry("Mittelamerika"));
Country Argentinien = this.getCountry("Argentinien");
Argentinien.connectTo(this.getCountry("Peru"));
Argentinien.connectTo(this.getCountry("Falkland-Inseln"));
Argentinien.connectTo(this.getCountry("Neuseeland"));
//Nord-Amerika
Country mittelamerika = this.getCountry("Mittelamerika");
mittelamerika.connectTo(this.getCountry("Oststaaten"));
mittelamerika.connectTo(this.getCountry("Weststaaten"));
Country Weststaaten = this.getCountry("Weststaaten");
Weststaaten.connectTo(this.getCountry("Oststaaten"));
Weststaaten.connectTo(this.getCountry("Hawaii"));
Weststaaten.connectTo(this.getCountry("Alberta"));
Weststaaten.connectTo(this.getCountry("Ontario"));
Country Ontario = this.getCountry("Ontario");
Ontario.connectTo(this.getCountry("Quebec"));
Weststaaten.connectTo(this.getCountry("Oststaaten"));
Weststaaten.connectTo(this.getCountry("Nunavut"));
Weststaaten.connectTo(this.getCountry("Nordwest-Territorium"));
Weststaaten.connectTo(this.getCountry("Alberta"));
Country alaska = this.getCountry("Alaska");
alaska.connectTo(this.getCountry("Kamtschatka"));
alaska.connectTo(this.getCountry("Nordwest-Territorium"));
alaska.connectTo(this.getCountry("Alberta"));
Country Nordwest = this.getCountry("Nordwest-Territorium");
Nordwest.connectTo(this.getCountry("Alberta"));
Nordwest.connectTo(this.getCountry("Nunavut"));
Country Nunavut = this.getCountry("Nunavut");
Nunavut.connectTo(this.getCountry("Quebec"));
Nunavut.connectTo(this.getCountry("Grönland"));
Country groenland = this.getCountry("Grönland");
groenland.connectTo(this.getCountry("Quebec"));
groenland.connectTo(this.getCountry("Svalbard"));
groenland.connectTo(this.getCountry("Island"));
}
public ArrayList<Country> getCountries() {
return this.countries;
}
/**
* Berechnet den Benous, den ein Spieler an Einheiten bekommt f�r die komplette Einnahme des jeweilligen Kontinents
* @param p der aktuelle Spieler
* @return die Anzahl der Bonus Einheiten
*/
public int getBonus(Player p){
int bonus = 0;
for (Continent c : this.continents){
if(c.getCurrentOwner()==p){bonus += c.getBonus();}
}
return bonus;
}
/**
* Vergleicht die Namen der L�nder mit �bergebenem String
* @param n String (name des zu suchenden Landes)
* @return das zu suchende Land
*/
public Country getCountry(String n){
for (Country c : countries){
if(c.getName().equals(n)){
return c;
}
}
return null;
}
/**
* Vergleicht die Farbe mit der übergebenen Farbe
* @param col Color (Farbe des zu suchenden Landes)
* @return das zu suchende Land
*/
public Country getCountry(Color col){
for (Country c : countries){
if(c.getColor().equals(col)){
return c;
}
}
return null;
}
/**
*
* @return Alle Kontinente dieser Karte
*/
public ArrayList<Continent> getContinents() {
return continents;
}
}
|
Farbcode Südeuropa hinzugefügt
|
Client/src/main/java/logic/data/Map.java
|
Farbcode Südeuropa hinzugefügt
|
|
Java
|
mit
|
6c3d3d299ba56df253e7874e167073987ca4d2f5
| 0
|
stachon/XChange,andre77/XChange,timmolter/XChange,douggie/XChange,TSavo/XChange
|
package org.knowm.xchange.binance.dto.account;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
public final class AssetDividendResponse
extends SapiResponse<List<AssetDividendResponse.AssetDividend>> {
private final AssetDividend[] rows;
private final BigDecimal total;
public AssetDividendResponse(@JsonProperty("rows") AssetDividend[] rows, @JsonProperty("total") BigDecimal total) {
this.rows = rows;
this.total = total;
}
@Override
public List<AssetDividend> getData() {
return Arrays.asList(rows);
}
public BigDecimal getTotal() {
return total;
}
@Override
public String toString() {
return "assetDividendRow [rows=" + Arrays.toString(rows) + "]";
}
@Data
public static final class AssetDividend {
private BigDecimal amount;
private String asset;
private long divTime;
private String enInfo;
private long tranId;
}
}
|
xchange-binance/src/main/java/org/knowm/xchange/binance/dto/account/AssetDividendResponse.java
|
package org.knowm.xchange.binance.dto.account;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
public final class AssetDividendResponse
extends SapiResponse<List<AssetDividendResponse.AssetDividend>> {
private final AssetDividend[] rows;
private BigDecimal total;
public AssetDividendResponse(@JsonProperty("rows") AssetDividend[] rows) {
this.rows = rows;
}
@Override
public List<AssetDividend> getData() {
return Arrays.asList(rows);
}
@Override
public String toString() {
return "assetDividendRow [rows=" + Arrays.toString(rows) + "]";
}
@Data
public static final class AssetDividend {
private BigDecimal amount;
private String asset;
private long divTime;
private String enInfo;
private long tranId;
}
}
|
added total from AssetDividendResponse
|
xchange-binance/src/main/java/org/knowm/xchange/binance/dto/account/AssetDividendResponse.java
|
added total from AssetDividendResponse
|
|
Java
|
mit
|
9cfaa21cdf3e5a4175724e59bebde015d7541a13
| 0
|
davidfialho14/bgp-simulator
|
package v2.core.protocols;
import v2.core.*;
import v2.core.exporters.Exporter;
import static v2.core.InvalidAttribute.invalidAttr;
import static v2.core.InvalidRoute.invalidRoute;
/**
* Implementation of the SS-BGP Protocol. The protocol can be configured to use any detection implementation.
* Singleton Class!
*/
public class SSBGPProtocol implements Protocol {
private static final SSBGPProtocol PROTOCOL = new SSBGPProtocol();
private SSBGPProtocol() { } // use factory method!
/**
* Returns an SS-BGP protocol instance.
*
* @return an SS-BGP protocol instance.
*/
public static SSBGPProtocol ssBGPProtocol() {
return PROTOCOL;
}
/**
* Processes a message that arrives at the given router.
*
* @param message message to process.
* @param exporter exporter used to export a route.
*/
@Override
public final void process(Message message, Exporter exporter) {
Link link = message.getTraversedLink();
Route importedRoute = importRoute(message.getRoute(), link);
Route learnedRoute = learn(importedRoute, link);
Router learningRouter = link.getSource();
learningRouter.getTable().setRoute(link.getTarget(), learnedRoute);
if (learningRouter.getTable().selectedNewRoute()) { // checks if the selected route changed
exporter.export(learningRouter, learningRouter.getTable().getSelectedRoute(),
message.getArrivalTime());
}
}
/**
* Imports the route received from the given link. This is the first step in the 'process' execution.
*
* @return the imported route.
*/
public Route importRoute(Route route, Link link) {
if (link.isTurnedOff()) {
return invalidRoute();
}
Attribute attribute = link.getLabel().extend(link, route.getAttribute());
if (attribute == invalidAttr()) {
return invalidRoute();
}
Path path = Path.copy(route.getPath());
path.add(link.getTarget());
// return a new route instance to avoid changing a route of the sending router
return new Route(attribute, path);
}
/**
* Takes a route and checks if the route constitutes a loop and if so, it considers the route to be
* invalid and checks and using the pre-configured detection method checks if there is a policy dispute.
* If so, then it turns the link off. If the route does not constitute a loop then it returns the same
* route as the imported route.
*
* @param importedRoute imported route.
* @param link link from which the route was received.
* @return an invalid route if detected a loop or the imported route if did not detect a loop.
*/
public Route learn(Route importedRoute, Link link) {
Router learningRouter = link.getSource();
Route learnedRoute = importedRoute;
if (importedRoute.getPath().contains(learningRouter)) {
// detected a loop
// select the best route learned from all out-neighbours except the exporting neighbors
Route alternativeRoute = learningRouter.getTable().getAlternativeRoute(link.getTarget());
if (learningRouter.getDetection().isPolicyConflict(link, importedRoute, alternativeRoute)) {
link.setTurnedOff(true);
}
learnedRoute = invalidRoute();
}
return learnedRoute;
}
}
|
src/v2/core/protocols/SSBGPProtocol.java
|
package v2.core.protocols;
import v2.core.*;
import v2.core.exporters.Exporter;
import static v2.core.InvalidAttribute.invalidAttr;
import static v2.core.InvalidRoute.invalidRoute;
/**
* Implementation of the SS-BGP Protocol. The protocol can be configured to use any detection implementation.
*/
public class SSBGPProtocol implements Protocol {
/**
* Processes a message that arrives at the given router.
*
* @param message message to process.
* @param exporter exporter used to export a route.
*/
@Override
public final void process(Message message, Exporter exporter) {
Link link = message.getTraversedLink();
Route importedRoute = importRoute(message.getRoute(), link);
Route learnedRoute = learn(importedRoute, link);
Router learningRouter = link.getSource();
learningRouter.getTable().setRoute(link.getTarget(), learnedRoute);
if (learningRouter.getTable().selectedNewRoute()) { // checks if the selected route changed
exporter.export(learningRouter, learningRouter.getTable().getSelectedRoute(),
message.getArrivalTime());
}
}
/**
* Imports the route received from the given link. This is the first step in the 'process' execution.
*
* @return the imported route.
*/
public Route importRoute(Route route, Link link) {
if (link.isTurnedOff()) {
return invalidRoute();
}
Attribute attribute = link.getLabel().extend(link, route.getAttribute());
if (attribute == invalidAttr()) {
return invalidRoute();
}
Path path = Path.copy(route.getPath());
path.add(link.getTarget());
// return a new route instance to avoid changing a route of the sending router
return new Route(attribute, path);
}
/**
* Takes a route and checks if the route constitutes a loop and if so, it considers the route to be
* invalid and checks and using the pre-configured detection method checks if there is a policy dispute.
* If so, then it turns the link off. If the route does not constitute a loop then it returns the same
* route as the imported route.
*
* @param importedRoute imported route.
* @param link link from which the route was received.
* @return an invalid route if detected a loop or the imported route if did not detect a loop.
*/
public Route learn(Route importedRoute, Link link) {
Router learningRouter = link.getSource();
Route learnedRoute = importedRoute;
if (importedRoute.getPath().contains(learningRouter)) {
// detected a loop
// select the best route learned from all out-neighbours except the exporting neighbors
Route alternativeRoute = learningRouter.getTable().getAlternativeRoute(link.getTarget());
if (learningRouter.getDetection().isPolicyConflict(link, importedRoute, alternativeRoute)) {
link.setTurnedOff(true);
}
learnedRoute = invalidRoute();
}
return learnedRoute;
}
}
|
"SS-BGP protocol" is now a singleton
|
src/v2/core/protocols/SSBGPProtocol.java
|
"SS-BGP protocol" is now a singleton
|
|
Java
|
agpl-3.0
|
c6eafb96d534d7324004dbbd7a5d032d43399b7e
| 0
|
avram/zandy,avram/zandy
|
/*******************************************************************************
* This file is part of Zandy.
*
* Zandy is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Zandy is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Zandy. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package com.gimranov.zandy.app;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Authenticator;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.apache.http.util.ByteArrayBuffer;
import org.json.JSONException;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.MimeTypeMap;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.BufferType;
import android.widget.Toast;
import com.gimranov.zandy.app.data.Attachment;
import com.gimranov.zandy.app.data.Database;
import com.gimranov.zandy.app.data.Item;
import com.gimranov.zandy.app.task.APIRequest;
import com.gimranov.zandy.app.task.ZoteroAPITask;
/**
* This Activity handles displaying and editing attachments. It works almost the same as
* ItemDataActivity and TagActivity, using a simple ArrayAdapter on Bundles with the creator info.
*
* This currently operates by showing the attachments for a given item
*
* @author ajlyon
*
*/
public class AttachmentActivity extends ListActivity {
private static final String TAG = "com.gimranov.zandy.app.AttachmentActivity";
static final int DIALOG_CONFIRM_NAVIGATE = 4;
static final int DIALOG_FILE_PROGRESS = 6;
static final int DIALOG_CONFIRM_DELETE = 5;
static final int DIALOG_NOTE = 3;
static final int DIALOG_NEW = 1;
public Item item;
private ProgressDialog mProgressDialog;
private ProgressThread progressThread;
private Database db;
/**
* For <= Android 2.1 (API 7), we can't pass bundles to showDialog(), so set this instead
*/
private Bundle b = new Bundle();
private ArrayList<File> tmpFiles;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tmpFiles = new ArrayList<File>();
db = new Database(this);
/* Get the incoming data from the calling activity */
final String itemKey = getIntent().getStringExtra("com.gimranov.zandy.app.itemKey");
Item item = Item.load(itemKey, db);
this.item = item;
if (item == null) {
Log.e(TAG, "AttachmentActivity started without itemKey; finishing.");
finish();
return;
}
this.setTitle(getResources().getString(R.string.attachments_for_item,item.getTitle()));
ArrayList<Attachment> rows = Attachment.forItem(item, db);
/*
* We use the standard ArrayAdapter, passing in our data as a Attachment.
* Since it's no longer a simple TextView, we need to override getView, but
* we can do that anonymously.
*/
setListAdapter(new ArrayAdapter<Attachment>(this, R.layout.list_attach, rows) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
// We are reusing views, but we need to initialize it if null
if (null == convertView) {
LayoutInflater inflater = getLayoutInflater();
row = inflater.inflate(R.layout.list_attach, null);
} else {
row = convertView;
}
ImageView tvType = (ImageView)row.findViewById(R.id.attachment_type);
TextView tvSummary = (TextView)row.findViewById(R.id.attachment_summary);
Attachment att = getItem(position);
Log.d(TAG, "Have an attachment: "+att.title + " fn:"+att.filename + " status:" + att.status);
tvType.setImageResource(Item.resourceForType(att.getType()));
try {
Log.d(TAG, att.content.toString(4));
} catch (JSONException e) {
Log.e(TAG, "JSON parse exception when reading attachment content", e);
}
if (att.getType().equals("note")) {
String note = att.content.optString("note","");
if (note.length() > 40) {
note = note.substring(0,40);
}
tvSummary.setText(note);
} else {
StringBuffer status = new StringBuffer(getResources().getString(R.string.status));
if (att.status == Attachment.AVAILABLE)
status.append(getResources().getString(R.string.attachment_zfs_available));
else if (att.status == Attachment.LOCAL)
status.append(getResources().getString(R.string.attachment_zfs_local));
else
status.append(getResources().getString(R.string.attachment_unknown));
tvSummary.setText(att.title + " " + status.toString());
}
return row;
}
});
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
// Warning here because Eclipse can't tell whether my ArrayAdapter is
// being used with the correct parametrization.
@SuppressWarnings("unchecked")
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// If we have a click on an entry, show its note
ArrayAdapter<Attachment> adapter = (ArrayAdapter<Attachment>) parent.getAdapter();
Attachment row = adapter.getItem(position);
if (row.content.has("note")) {
Log.d(TAG, "Trying to start note view activity for: "+row.key);
Intent i = new Intent(getBaseContext(), NoteActivity.class);
i.putExtra("com.gimranov.zandy.app.attKey", row.key);//row.content.optString("note", ""));
startActivity(i);
}
}
});
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
// Warning here because Eclipse can't tell whether my ArrayAdapter is
// being used with the correct parametrization.
@SuppressWarnings("unchecked")
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
// If we have a long click on an entry, do something...
ArrayAdapter<Attachment> adapter = (ArrayAdapter<Attachment>) parent.getAdapter();
Attachment row = adapter.getItem(position);
String url = (row.url != null && !row.url.equals("")) ?
row.url : row.content.optString("url");
if (!row.getType().equals("note")) {
Bundle b = new Bundle();
b.putString("title", row.title);
b.putString("attachmentKey", row.key);
b.putString("content", url);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
int linkMode = row.content.optInt("linkMode", Attachment.MODE_LINKED_URL);
if (settings.getBoolean("webdav_enabled", false))
b.putString("mode", "webdav");
else
b.putString("mode", "zfs");
if (linkMode == Attachment.MODE_IMPORTED_FILE
|| linkMode == Attachment.MODE_IMPORTED_URL) {
loadFileAttachment(b);
} else {
AttachmentActivity.this.b = b;
showDialog(DIALOG_CONFIRM_NAVIGATE);
}
}
if (row.getType().equals("note")) {
Bundle b = new Bundle();
b.putString("attachmentKey", row.key);
b.putString("itemKey", itemKey);
b.putString("content", row.content.optString("note", ""));
removeDialog(DIALOG_NOTE);
AttachmentActivity.this.b = b;
showDialog(DIALOG_NOTE);
}
return true;
}
});
}
@Override
public void onDestroy() {
if (db != null) db.close();
if (tmpFiles != null) {
for (File f : tmpFiles) {
if (!f.delete()) {
Log.e(TAG, "Failed to delete temporary file on activity close.");
}
}
tmpFiles.clear();
}
super.onDestroy();
}
@Override
public void onResume() {
if (db == null) db = new Database(this);
super.onResume();
}
protected Dialog onCreateDialog(int id) {
final String attachmentKey = b.getString("attachmentKey");
final String itemKey = b.getString("itemKey");
final String content = b.getString("content");
final String mode = b.getString("mode");
AlertDialog dialog;
switch (id) {
case DIALOG_CONFIRM_NAVIGATE:
dialog = new AlertDialog.Builder(this)
.setTitle(getResources().getString(R.string.view_online_warning))
.setPositiveButton(getResources().getString(R.string.view), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// The behavior for invalid URIs might be nasty, but
// we'll cross that bridge if we come to it.
try {
Uri uri = Uri.parse(content);
startActivity(new Intent(Intent.ACTION_VIEW)
.setData(uri));
} catch (ActivityNotFoundException e) {
// There can be exceptions here; not sure what would prompt us to have
// URIs that the browser can't load, but it apparently happens.
Toast.makeText(getApplicationContext(),
getResources().getString(R.string.attachment_intent_failed_for_uri, content),
Toast.LENGTH_SHORT).show();
}
}
}).setNeutralButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// do nothing
}
}).create();
return dialog;
case DIALOG_CONFIRM_DELETE:
dialog = new AlertDialog.Builder(this)
.setTitle(getResources().getString(R.string.attachment_delete_confirm))
.setPositiveButton(getResources().getString(R.string.menu_delete), new DialogInterface.OnClickListener() {
@SuppressWarnings("unchecked")
public void onClick(DialogInterface dialog, int whichButton) {
Attachment a = Attachment.load(attachmentKey, db);
a.delete(db);
ArrayAdapter<Attachment> la = (ArrayAdapter<Attachment>) getListAdapter();
la.clear();
for (Attachment at : Attachment.forItem(Item.load(itemKey, db), db)) {
la.add(at);
}
}
}).setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// do nothing
}
}).create();
return dialog;
case DIALOG_NOTE:
final EditText input = new EditText(this);
input.setText(content, BufferType.EDITABLE);
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setTitle(getResources().getString(R.string.note))
.setView(input)
.setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
@SuppressWarnings("unchecked")
public void onClick(DialogInterface dialog, int whichButton) {
Editable value = input.getText();
String fixed = value.toString().replaceAll("\n\n", "\n<br>");
if (mode != null && mode.equals("new")) {
Log.d(TAG, "Attachment created with parent key: "+itemKey);
Attachment att = new Attachment(getBaseContext(), "note", itemKey);
att.setNoteText(fixed);
att.dirty = APIRequest.API_NEW;
att.save(db);
} else {
Attachment att = Attachment.load(attachmentKey, db);
att.setNoteText(fixed);
att.dirty = APIRequest.API_DIRTY;
att.save(db);
}
ArrayAdapter<Attachment> la = (ArrayAdapter<Attachment>) getListAdapter();
la.clear();
for (Attachment a : Attachment.forItem(Item.load(itemKey, db), db)) {
la.add(a);
}
la.notifyDataSetChanged();
}
}).setNeutralButton(getResources().getString(R.string.cancel),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// do nothing
}
});
// We only want the delete option when this isn't a new note
if (mode == null || !"new".equals(mode)) {
builder = builder.setNegativeButton(getResources().getString(R.string.menu_delete), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Bundle b = new Bundle();
b.putString("attachmentKey", attachmentKey);
b.putString("itemKey", itemKey);
removeDialog(DIALOG_CONFIRM_DELETE);
AttachmentActivity.this.b = b;
showDialog(DIALOG_CONFIRM_DELETE);
}
});
}
dialog = builder.create();
return dialog;
case DIALOG_FILE_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setMessage(getResources().getString(R.string.attachment_downloading, b.getString("title")));
mProgressDialog.setIndeterminate(true);
return mProgressDialog;
default:
Log.e(TAG, "Invalid dialog requested");
return null;
}
}
protected void onPrepareDialog(int id, Dialog dialog) {
switch(id) {
case DIALOG_FILE_PROGRESS:
mProgressDialog.setMessage(getResources().getString(R.string.attachment_downloading, b.getString("title")));
progressThread = new ProgressThread(handler, b);
progressThread.start();
}
}
private void showAttachment(Attachment att) {
if (att.status == Attachment.LOCAL) {
Log.d(TAG,"Starting to display local attachment");
Uri uri = Uri.fromFile(new File(att.filename));
String mimeType = att.content.optString("mimeType",null);
try {
startActivity(new Intent(Intent.ACTION_VIEW)
.setDataAndType(uri,mimeType));
} catch (ActivityNotFoundException e) {
Log.e(TAG, "No activity for intent", e);
Toast.makeText(getApplicationContext(),
getResources().getString(R.string.attachment_intent_failed, mimeType),
Toast.LENGTH_SHORT).show();
}
}
}
/**
* This mainly is to move the logic out of the onClick callback above
* Decides whether to download or view, and launches the appropriate action
* @param b
*/
private void loadFileAttachment(Bundle b) {
Attachment att = Attachment.load(b.getString("attachmentKey"), db);
if (!ServerCredentials.sBaseStorageDir.exists())
ServerCredentials.sBaseStorageDir.mkdir();
if (!ServerCredentials.sDocumentStorageDir.exists())
ServerCredentials.sDocumentStorageDir.mkdir();
File attFile = new File(att.filename);
if (att.status == Attachment.AVAILABLE
// Zero-length or nonexistent gives length == 0
|| (attFile != null && attFile.length() == 0)) {
Log.d(TAG,"Starting to try and download attachment (status: "+att.status+", fn: "+att.filename+")");
this.b = b;
showDialog(DIALOG_FILE_PROGRESS);
} else showAttachment(att);
}
/**
* Refreshes the current list adapter
*/
@SuppressWarnings("unchecked")
private void refreshView() {
ArrayAdapter<Attachment> la = (ArrayAdapter<Attachment>) getListAdapter();
la.clear();
for (Attachment at : Attachment.forItem(item, db)) {
la.add(at);
}
}
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.arg2) {
case ProgressThread.STATE_DONE:
if(mProgressDialog.isShowing())
dismissDialog(DIALOG_FILE_PROGRESS);
refreshView();
if (null != msg.obj)
showAttachment((Attachment)msg.obj);
break;
case ProgressThread.STATE_FAILED:
// Notify that we failed to get anything
Toast.makeText(getApplicationContext(),
getResources().getString(R.string.attachment_no_download_url),
Toast.LENGTH_SHORT).show();
if(mProgressDialog.isShowing())
dismissDialog(DIALOG_FILE_PROGRESS);
// Let's try to fall back on an online version
AttachmentActivity.this.b = msg.getData();
showDialog(DIALOG_CONFIRM_NAVIGATE);
refreshView();
break;
case ProgressThread.STATE_UNZIPPING:
mProgressDialog.setMax(msg.arg1);
mProgressDialog.setProgress(0);
mProgressDialog.setMessage(getResources().getString(R.string.attachment_unzipping));
break;
case ProgressThread.STATE_RUNNING:
mProgressDialog.setMax(msg.arg1);
mProgressDialog.setProgress(0);
mProgressDialog.setIndeterminate(false);
break;
default:
mProgressDialog.setProgress(msg.arg1);
break;
}
}
};
private class ProgressThread extends Thread {
Handler mHandler;
Bundle arguments;
final static int STATE_DONE = 5;
final static int STATE_FAILED = 3;
final static int STATE_RUNNING = 1;
final static int STATE_UNZIPPING = 6;
ProgressThread(Handler h, Bundle b) {
mHandler = h;
arguments = b;
}
@SuppressWarnings("unchecked")
public void run() {
// Setup
final String attachmentKey = arguments.getString("attachmentKey");
final String mode = arguments.getString("mode");
URL url;
File file;
String urlstring;
Attachment att = Attachment.load(attachmentKey, db);
String sanitized = att.title.replace(' ', '_');
// If no 1-6-character extension, try to add one using MIME type
if (!sanitized.matches(".*\\.[a-zA-Z0-9]{1,6}$")) {
String extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(att.getType());
if (extension != null) sanitized = sanitized + "." + extension;
}
sanitized = sanitized.replaceFirst("^(.*?)(\\.?[^.]*)$", "$1"+"_"+att.key+"$2");
file = new File(ServerCredentials.sDocumentStorageDir,sanitized);
if (!ServerCredentials.sBaseStorageDir.exists())
ServerCredentials.sBaseStorageDir.mkdir();
if (!ServerCredentials.sDocumentStorageDir.exists())
ServerCredentials.sDocumentStorageDir.mkdir();
final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
if ("webdav".equals(mode)) {
//urlstring = "https://dfs.humnet.ucla.edu/home/ajlyon/zotero/223RMC7C.zip";
//urlstring = "http://www.gimranov.com/research/zotero/223RMC7C.zip";
urlstring = settings.getString("webdav_path", "")+"/"+att.key+".zip";
Authenticator.setDefault (new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication (settings.getString("webdav_username", ""),
settings.getString("webdav_password", "").toCharArray());
}
});
} else {
urlstring = att.url+"?key="+settings.getString("user_key","");
}
try {
try {
url = new URL(urlstring);
} catch (MalformedURLException e) {
// Alert that we don't have a valid download URL and return
Message msg = mHandler.obtainMessage();
msg.arg2 = STATE_FAILED;
msg.setData(arguments);
mHandler.sendMessage(msg);
Log.e(TAG, "Download URL not valid: "+urlstring, e);
return;
}
//this is the downloader method
long startTime = System.currentTimeMillis();
Log.d(TAG, "download beginning");
Log.d(TAG, "download url:" + url.toString());
Log.d(TAG, "downloaded file name:" + file.getPath());
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
ucon.setRequestProperty("User-Agent","Mozilla/5.0 ( compatible ) ");
ucon.setRequestProperty("Accept","*/*");
Message msg = mHandler.obtainMessage();
msg.arg1 = ucon.getContentLength();
msg.arg2 = STATE_RUNNING;
mHandler.sendMessage(msg);
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is, 16000);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
* TODO read in chunks instead of byte by byte
*/
while ((current = bis.read()) != -1) {
baf.append((byte) current);
if (baf.length() % 2048 == 0) {
msg = mHandler.obtainMessage();
msg.arg1 = baf.length();
mHandler.sendMessage(msg);
}
}
/* Save to temporary directory for WebDAV */
if ("webdav".equals(mode)) {
File tmpFile = File.createTempFile("zandy", ".zip");
// Keep track of temp files that we've created.
if (tmpFiles == null) tmpFiles = new ArrayList<File>();
tmpFiles.add(tmpFile);
FileOutputStream fos = new FileOutputStream(tmpFile);
fos.write(baf.toByteArray());
fos.close();
ZipFile zf = new ZipFile(tmpFile);
Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zf.entries();
do {
ZipEntry entry = entries.nextElement();
// Change the message to reflect that we're unzipping now
msg = mHandler.obtainMessage();
msg.arg1 = (int) entry.getSize();
msg.arg2 = STATE_UNZIPPING;
mHandler.sendMessage(msg);
String name64 = entry.getName();
byte[] byteName = Base64.decode(name64.getBytes(), 0, name64.length() - 5, Base64.DEFAULT);
String name = new String(byteName);
Log.d(TAG, "Found file "+name+" from encoded "+name64);
// If the linkMode is not an imported URL (snapshot) and the MIME type isn't text/html,
// then we unzip it and we're happy. If either of the preceding is true, we skip the file
// unless the filename includes .htm (covering .html automatically)
if ( (!att.getType().equals("text/html")) || name.contains(".htm")) {
FileOutputStream fos2 = new FileOutputStream(file);
InputStream entryStream = zf.getInputStream(entry);
ByteArrayBuffer baf2 = new ByteArrayBuffer(100);
while ((current = entryStream.read()) != -1) {
baf2.append((byte) current);
if (baf2.length() % 2048 == 0) {
msg = mHandler.obtainMessage();
msg.arg1 = baf2.length();
mHandler.sendMessage(msg);
}
}
fos2.write(baf2.toByteArray());
fos2.close();
Log.d(TAG, "Finished reading file");
} else {
Log.d(TAG, "Skipping file: "+name);
}
} while (entries.hasMoreElements());
zf.close();
// We remove the file from the ArrayList if deletion succeeded;
// otherwise deletion is put off until the activity exits.
if (tmpFile.delete()) {
tmpFiles.remove(tmpFile);
}
} else {
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
}
Log.d(TAG, "download ready in "
+ ((System.currentTimeMillis() - startTime) / 1000)
+ " sec");
} catch (IOException e) {
Log.e(TAG, "Error: ",e);
}
att.filename = file.getPath();
File newFile = new File(att.filename);
Message msg = mHandler.obtainMessage();
if (newFile.length() > 0) {
att.status = Attachment.LOCAL;
Log.d(TAG,"File downloaded: "+att.filename);
msg.obj = att;
} else {
Log.d(TAG, "File not downloaded: "+att.filename);
att.status = Attachment.AVAILABLE;
msg.obj = null;
}
att.save(db);
msg.arg2 = STATE_DONE;
mHandler.sendMessage(msg);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.zotero_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Bundle b = new Bundle();
// Handle item selection
switch (item.getItemId()) {
case R.id.do_sync:
if (!ServerCredentials.check(getApplicationContext())) {
Toast.makeText(getApplicationContext(), getResources().getString(R.string.sync_log_in_first),
Toast.LENGTH_SHORT).show();
return true;
}
Log.d(TAG, "Preparing sync requests, starting with present item");
new ZoteroAPITask(getBaseContext()).execute(APIRequest.update(this.item));
Toast.makeText(getApplicationContext(), getResources().getString(R.string.sync_started),
Toast.LENGTH_SHORT).show();
return true;
case R.id.do_new:
b.putString("itemKey", this.item.getKey());
b.putString("mode", "new");
removeDialog(DIALOG_NOTE);
this.b = b;
showDialog(DIALOG_NOTE);
return true;
case R.id.do_prefs:
startActivity(new Intent(this, SettingsActivity.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
|
app/src/com/gimranov/zandy/app/AttachmentActivity.java
|
/*******************************************************************************
* This file is part of Zandy.
*
* Zandy is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Zandy is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Zandy. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package com.gimranov.zandy.app;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Authenticator;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.apache.http.util.ByteArrayBuffer;
import org.json.JSONException;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.MimeTypeMap;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.BufferType;
import android.widget.Toast;
import com.gimranov.zandy.app.data.Attachment;
import com.gimranov.zandy.app.data.Database;
import com.gimranov.zandy.app.data.Item;
import com.gimranov.zandy.app.task.APIRequest;
import com.gimranov.zandy.app.task.ZoteroAPITask;
/**
* This Activity handles displaying and editing attachments. It works almost the same as
* ItemDataActivity and TagActivity, using a simple ArrayAdapter on Bundles with the creator info.
*
* This currently operates by showing the attachments for a given item
*
* @author ajlyon
*
*/
public class AttachmentActivity extends ListActivity {
private static final String TAG = "com.gimranov.zandy.app.AttachmentActivity";
static final int DIALOG_CONFIRM_NAVIGATE = 4;
static final int DIALOG_FILE_PROGRESS = 6;
static final int DIALOG_CONFIRM_DELETE = 5;
static final int DIALOG_NOTE = 3;
static final int DIALOG_NEW = 1;
public Item item;
private ProgressDialog mProgressDialog;
private ProgressThread progressThread;
private Database db;
/**
* For <= Android 2.1 (API 7), we can't pass bundles to showDialog(), so set this instead
*/
private Bundle b = new Bundle();
private ArrayList<File> tmpFiles;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tmpFiles = new ArrayList<File>();
db = new Database(this);
/* Get the incoming data from the calling activity */
final String itemKey = getIntent().getStringExtra("com.gimranov.zandy.app.itemKey");
Item item = Item.load(itemKey, db);
this.item = item;
if (item == null) {
Log.e(TAG, "AttachmentActivity started without itemKey; finishing.");
finish();
return;
}
this.setTitle(getResources().getString(R.string.attachments_for_item,item.getTitle()));
ArrayList<Attachment> rows = Attachment.forItem(item, db);
/*
* We use the standard ArrayAdapter, passing in our data as a Attachment.
* Since it's no longer a simple TextView, we need to override getView, but
* we can do that anonymously.
*/
setListAdapter(new ArrayAdapter<Attachment>(this, R.layout.list_attach, rows) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
// We are reusing views, but we need to initialize it if null
if (null == convertView) {
LayoutInflater inflater = getLayoutInflater();
row = inflater.inflate(R.layout.list_attach, null);
} else {
row = convertView;
}
ImageView tvType = (ImageView)row.findViewById(R.id.attachment_type);
TextView tvSummary = (TextView)row.findViewById(R.id.attachment_summary);
Attachment att = getItem(position);
Log.d(TAG, "Have an attachment: "+att.title + " fn:"+att.filename + " status:" + att.status);
tvType.setImageResource(Item.resourceForType(att.getType()));
try {
Log.d(TAG, att.content.toString(4));
} catch (JSONException e) {
Log.e(TAG, "JSON parse exception when reading attachment content", e);
}
if (att.getType().equals("note")) {
String note = att.content.optString("note","");
if (note.length() > 40) {
note = note.substring(0,40);
}
tvSummary.setText(note);
} else {
StringBuffer status = new StringBuffer(getResources().getString(R.string.status));
if (att.status == Attachment.AVAILABLE)
status.append(getResources().getString(R.string.attachment_zfs_available));
else if (att.status == Attachment.LOCAL)
status.append(getResources().getString(R.string.attachment_zfs_local));
else
status.append(getResources().getString(R.string.attachment_unknown));
tvSummary.setText(att.title + " " + status.toString());
}
return row;
}
});
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
// Warning here because Eclipse can't tell whether my ArrayAdapter is
// being used with the correct parametrization.
@SuppressWarnings("unchecked")
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// If we have a click on an entry, show its note
ArrayAdapter<Attachment> adapter = (ArrayAdapter<Attachment>) parent.getAdapter();
Attachment row = adapter.getItem(position);
if (row.content.has("note")) {
Log.d(TAG, "Trying to start note view activity for: "+row.key);
Intent i = new Intent(getBaseContext(), NoteActivity.class);
i.putExtra("com.gimranov.zandy.app.attKey", row.key);//row.content.optString("note", ""));
startActivity(i);
}
}
});
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
// Warning here because Eclipse can't tell whether my ArrayAdapter is
// being used with the correct parametrization.
@SuppressWarnings("unchecked")
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
// If we have a long click on an entry, do something...
ArrayAdapter<Attachment> adapter = (ArrayAdapter<Attachment>) parent.getAdapter();
Attachment row = adapter.getItem(position);
String url = (row.url != null && !row.url.equals("")) ?
row.url : row.content.optString("url");
if (!row.getType().equals("note")) {
Bundle b = new Bundle();
b.putString("title", row.title);
b.putString("attachmentKey", row.key);
b.putString("content", url);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
int linkMode = row.content.optInt("linkMode", Attachment.MODE_LINKED_URL);
if (settings.getBoolean("webdav_enabled", false))
b.putString("mode", "webdav");
else
b.putString("mode", "zfs");
if (linkMode == Attachment.MODE_IMPORTED_FILE
|| linkMode == Attachment.MODE_IMPORTED_URL) {
loadFileAttachment(b);
} else {
AttachmentActivity.this.b = b;
showDialog(DIALOG_CONFIRM_NAVIGATE);
}
}
if (row.getType().equals("note")) {
Bundle b = new Bundle();
b.putString("attachmentKey", row.key);
b.putString("itemKey", itemKey);
b.putString("content", row.content.optString("note", ""));
removeDialog(DIALOG_NOTE);
AttachmentActivity.this.b = b;
showDialog(DIALOG_NOTE);
}
return true;
}
});
}
@Override
public void onDestroy() {
if (db != null) db.close();
if (tmpFiles != null) {
for (File f : tmpFiles) {
if (!f.delete()) {
Log.e(TAG, "Failed to delete temporary file on activity close.");
}
}
tmpFiles.clear();
}
super.onDestroy();
}
@Override
public void onResume() {
if (db == null) db = new Database(this);
super.onResume();
}
protected Dialog onCreateDialog(int id) {
final String attachmentKey = b.getString("attachmentKey");
final String itemKey = b.getString("itemKey");
final String content = b.getString("content");
final String mode = b.getString("mode");
AlertDialog dialog;
switch (id) {
case DIALOG_CONFIRM_NAVIGATE:
dialog = new AlertDialog.Builder(this)
.setTitle(getResources().getString(R.string.view_online_warning))
.setPositiveButton(getResources().getString(R.string.view), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// The behavior for invalid URIs might be nasty, but
// we'll cross that bridge if we come to it.
try {
Uri uri = Uri.parse(content);
startActivity(new Intent(Intent.ACTION_VIEW)
.setData(uri));
} catch (ActivityNotFoundException e) {
// There can be exceptions here; not sure what would prompt us to have
// URIs that the browser can't load, but it apparently happens.
Toast.makeText(getApplicationContext(),
getResources().getString(R.string.attachment_intent_failed_for_uri, content),
Toast.LENGTH_SHORT).show();
}
}
}).setNeutralButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// do nothing
}
}).create();
return dialog;
case DIALOG_CONFIRM_DELETE:
dialog = new AlertDialog.Builder(this)
.setTitle(getResources().getString(R.string.attachment_delete_confirm))
.setPositiveButton(getResources().getString(R.string.menu_delete), new DialogInterface.OnClickListener() {
@SuppressWarnings("unchecked")
public void onClick(DialogInterface dialog, int whichButton) {
Attachment a = Attachment.load(attachmentKey, db);
a.delete(db);
ArrayAdapter<Attachment> la = (ArrayAdapter<Attachment>) getListAdapter();
la.clear();
for (Attachment at : Attachment.forItem(Item.load(itemKey, db), db)) {
la.add(at);
}
}
}).setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// do nothing
}
}).create();
return dialog;
case DIALOG_NOTE:
final EditText input = new EditText(this);
input.setText(content, BufferType.EDITABLE);
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setTitle(getResources().getString(R.string.note))
.setView(input)
.setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
@SuppressWarnings("unchecked")
public void onClick(DialogInterface dialog, int whichButton) {
Editable value = input.getText();
String fixed = value.toString().replaceAll("\n\n", "\n<br>");
if (mode != null && mode.equals("new")) {
Log.d(TAG, "Attachment created with parent key: "+itemKey);
Attachment att = new Attachment(getBaseContext(), "note", itemKey);
att.setNoteText(fixed);
att.dirty = APIRequest.API_NEW;
att.save(db);
} else {
Attachment att = Attachment.load(attachmentKey, db);
att.setNoteText(fixed);
att.dirty = APIRequest.API_DIRTY;
att.save(db);
}
ArrayAdapter<Attachment> la = (ArrayAdapter<Attachment>) getListAdapter();
la.clear();
for (Attachment a : Attachment.forItem(Item.load(itemKey, db), db)) {
la.add(a);
}
la.notifyDataSetChanged();
}
}).setNeutralButton(getResources().getString(R.string.cancel),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// do nothing
}
});
// We only want the delete option when this isn't a new note
if (mode == null || !"new".equals(mode)) {
builder = builder.setNegativeButton(getResources().getString(R.string.menu_delete), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Bundle b = new Bundle();
b.putString("attachmentKey", attachmentKey);
b.putString("itemKey", itemKey);
removeDialog(DIALOG_CONFIRM_DELETE);
AttachmentActivity.this.b = b;
showDialog(DIALOG_CONFIRM_DELETE);
}
});
}
dialog = builder.create();
return dialog;
case DIALOG_FILE_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setMessage(getResources().getString(R.string.attachment_downloading, b.getString("title")));
mProgressDialog.setIndeterminate(true);
return mProgressDialog;
default:
Log.e(TAG, "Invalid dialog requested");
return null;
}
}
protected void onPrepareDialog(int id, Dialog dialog) {
switch(id) {
case DIALOG_FILE_PROGRESS:
mProgressDialog.setMessage(getResources().getString(R.string.attachment_downloading, b.getString("title")));
progressThread = new ProgressThread(handler, b);
progressThread.start();
}
}
private void showAttachment(Attachment att) {
if (att.status == Attachment.LOCAL) {
Log.d(TAG,"Starting to display local attachment");
Uri uri = Uri.fromFile(new File(att.filename));
String mimeType = att.content.optString("mimeType",null);
try {
startActivity(new Intent(Intent.ACTION_VIEW)
.setDataAndType(uri,mimeType));
} catch (ActivityNotFoundException e) {
Log.e(TAG, "No activity for intent", e);
Toast.makeText(getApplicationContext(),
getResources().getString(R.string.attachment_intent_failed, mimeType),
Toast.LENGTH_SHORT).show();
}
}
}
/**
* This mainly is to move the logic out of the onClick callback above
* Decides whether to download or view, and launches the appropriate action
* @param b
*/
private void loadFileAttachment(Bundle b) {
Attachment att = Attachment.load(b.getString("attachmentKey"), db);
if (!ServerCredentials.sBaseStorageDir.exists())
ServerCredentials.sBaseStorageDir.mkdir();
if (!ServerCredentials.sDocumentStorageDir.exists())
ServerCredentials.sDocumentStorageDir.mkdir();
File attFile = new File(att.filename);
if (att.status == Attachment.AVAILABLE
// Zero-length or nonexistent gives length == 0
|| (attFile != null && attFile.length() == 0)) {
Log.d(TAG,"Starting to try and download attachment (status: "+att.status+", fn: "+att.filename+")");
this.b = b;
showDialog(DIALOG_FILE_PROGRESS);
} else showAttachment(att);
}
/**
* Refreshes the current list adapter
*/
@SuppressWarnings("unchecked")
private void refreshView() {
ArrayAdapter<Attachment> la = (ArrayAdapter<Attachment>) getListAdapter();
la.clear();
for (Attachment at : Attachment.forItem(item, db)) {
la.add(at);
}
}
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.arg2) {
case ProgressThread.STATE_DONE:
if(mProgressDialog.isShowing())
dismissDialog(DIALOG_FILE_PROGRESS);
refreshView();
if (null != msg.obj)
showAttachment((Attachment)msg.obj);
case ProgressThread.STATE_FAILED:
// Notify that we failed to get anything
Toast.makeText(getApplicationContext(),
getResources().getString(R.string.attachment_no_download_url),
Toast.LENGTH_SHORT).show();
if(mProgressDialog.isShowing())
dismissDialog(DIALOG_FILE_PROGRESS);
// Let's try to fall back on an online version
AttachmentActivity.this.b = msg.getData();
showDialog(DIALOG_CONFIRM_NAVIGATE);
refreshView();
break;
case ProgressThread.STATE_UNZIPPING:
mProgressDialog.setMax(msg.arg1);
mProgressDialog.setProgress(0);
mProgressDialog.setMessage(getResources().getString(R.string.attachment_unzipping));
break;
case ProgressThread.STATE_RUNNING:
mProgressDialog.setMax(msg.arg1);
mProgressDialog.setProgress(0);
mProgressDialog.setIndeterminate(false);
break;
default:
mProgressDialog.setProgress(msg.arg1);
break;
}
}
};
private class ProgressThread extends Thread {
Handler mHandler;
Bundle arguments;
final static int STATE_DONE = 5;
final static int STATE_FAILED = 3;
final static int STATE_RUNNING = 1;
final static int STATE_UNZIPPING = 6;
ProgressThread(Handler h, Bundle b) {
mHandler = h;
arguments = b;
}
@SuppressWarnings("unchecked")
public void run() {
// Setup
final String attachmentKey = arguments.getString("attachmentKey");
final String mode = arguments.getString("mode");
URL url;
File file;
String urlstring;
Attachment att = Attachment.load(attachmentKey, db);
String sanitized = att.title.replace(' ', '_');
// If no 1-6-character extension, try to add one using MIME type
if (!sanitized.matches(".*\\.[a-zA-Z0-9]{1,6}$")) {
String extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(att.getType());
if (extension != null) sanitized = sanitized + "." + extension;
}
sanitized = sanitized.replaceFirst("^(.*?)(\\.?[^.]*)$", "$1"+"_"+att.key+"$2");
file = new File(ServerCredentials.sDocumentStorageDir,sanitized);
if (!ServerCredentials.sBaseStorageDir.exists())
ServerCredentials.sBaseStorageDir.mkdir();
if (!ServerCredentials.sDocumentStorageDir.exists())
ServerCredentials.sDocumentStorageDir.mkdir();
final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
if ("webdav".equals(mode)) {
//urlstring = "https://dfs.humnet.ucla.edu/home/ajlyon/zotero/223RMC7C.zip";
//urlstring = "http://www.gimranov.com/research/zotero/223RMC7C.zip";
urlstring = settings.getString("webdav_path", "")+"/"+att.key+".zip";
Authenticator.setDefault (new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication (settings.getString("webdav_username", ""),
settings.getString("webdav_password", "").toCharArray());
}
});
} else {
urlstring = att.url+"?key="+settings.getString("user_key","");
}
try {
try {
url = new URL(urlstring);
} catch (MalformedURLException e) {
// Alert that we don't have a valid download URL and return
Message msg = mHandler.obtainMessage();
msg.arg2 = STATE_FAILED;
msg.setData(arguments);
mHandler.sendMessage(msg);
Log.e(TAG, "Download URL not valid: "+urlstring, e);
return;
}
//this is the downloader method
long startTime = System.currentTimeMillis();
Log.d(TAG, "download beginning");
Log.d(TAG, "download url:" + url.toString());
Log.d(TAG, "downloaded file name:" + file.getPath());
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
ucon.setRequestProperty("User-Agent","Mozilla/5.0 ( compatible ) ");
ucon.setRequestProperty("Accept","*/*");
Message msg = mHandler.obtainMessage();
msg.arg1 = ucon.getContentLength();
msg.arg2 = STATE_RUNNING;
mHandler.sendMessage(msg);
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is, 16000);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
* TODO read in chunks instead of byte by byte
*/
while ((current = bis.read()) != -1) {
baf.append((byte) current);
if (baf.length() % 2048 == 0) {
msg = mHandler.obtainMessage();
msg.arg1 = baf.length();
mHandler.sendMessage(msg);
}
}
/* Save to temporary directory for WebDAV */
if ("webdav".equals(mode)) {
File tmpFile = File.createTempFile("zandy", ".zip");
// Keep track of temp files that we've created.
if (tmpFiles == null) tmpFiles = new ArrayList<File>();
tmpFiles.add(tmpFile);
FileOutputStream fos = new FileOutputStream(tmpFile);
fos.write(baf.toByteArray());
fos.close();
ZipFile zf = new ZipFile(tmpFile);
Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zf.entries();
do {
ZipEntry entry = entries.nextElement();
// Change the message to reflect that we're unzipping now
msg = mHandler.obtainMessage();
msg.arg1 = (int) entry.getSize();
msg.arg2 = STATE_UNZIPPING;
mHandler.sendMessage(msg);
String name64 = entry.getName();
byte[] byteName = Base64.decode(name64.getBytes(), 0, name64.length() - 5, Base64.DEFAULT);
String name = new String(byteName);
Log.d(TAG, "Found file "+name+" from encoded "+name64);
// If the linkMode is not an imported URL (snapshot) and the MIME type isn't text/html,
// then we unzip it and we're happy. If either of the preceding is true, we skip the file
// unless the filename includes .htm (covering .html automatically)
if ( (!att.getType().equals("text/html")) || name.contains(".htm")) {
FileOutputStream fos2 = new FileOutputStream(file);
InputStream entryStream = zf.getInputStream(entry);
ByteArrayBuffer baf2 = new ByteArrayBuffer(100);
while ((current = entryStream.read()) != -1) {
baf2.append((byte) current);
if (baf2.length() % 2048 == 0) {
msg = mHandler.obtainMessage();
msg.arg1 = baf2.length();
mHandler.sendMessage(msg);
}
}
fos2.write(baf2.toByteArray());
fos2.close();
Log.d(TAG, "Finished reading file");
} else {
Log.d(TAG, "Skipping file: "+name);
}
} while (entries.hasMoreElements());
zf.close();
// We remove the file from the ArrayList if deletion succeeded;
// otherwise deletion is put off until the activity exits.
if (tmpFile.delete()) {
tmpFiles.remove(tmpFile);
}
} else {
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
}
Log.d(TAG, "download ready in "
+ ((System.currentTimeMillis() - startTime) / 1000)
+ " sec");
} catch (IOException e) {
Log.e(TAG, "Error: ",e);
}
att.filename = file.getPath();
File newFile = new File(att.filename);
Message msg = mHandler.obtainMessage();
if (newFile.length() > 0) {
att.status = Attachment.LOCAL;
Log.d(TAG,"File downloaded: "+att.filename);
msg.obj = att;
} else {
Log.d(TAG, "File not downloaded: "+att.filename);
att.status = Attachment.AVAILABLE;
msg.obj = null;
}
att.save(db);
msg.arg2 = STATE_DONE;
mHandler.sendMessage(msg);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.zotero_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Bundle b = new Bundle();
// Handle item selection
switch (item.getItemId()) {
case R.id.do_sync:
if (!ServerCredentials.check(getApplicationContext())) {
Toast.makeText(getApplicationContext(), getResources().getString(R.string.sync_log_in_first),
Toast.LENGTH_SHORT).show();
return true;
}
Log.d(TAG, "Preparing sync requests, starting with present item");
new ZoteroAPITask(getBaseContext()).execute(APIRequest.update(this.item));
Toast.makeText(getApplicationContext(), getResources().getString(R.string.sync_started),
Toast.LENGTH_SHORT).show();
return true;
case R.id.do_new:
b.putString("itemKey", this.item.getKey());
b.putString("mode", "new");
removeDialog(DIALOG_NOTE);
this.b = b;
showDialog(DIALOG_NOTE);
return true;
case R.id.do_prefs:
startActivity(new Intent(this, SettingsActivity.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
|
add missing break; fixes crash after attachment view
|
app/src/com/gimranov/zandy/app/AttachmentActivity.java
|
add missing break; fixes crash after attachment view
|
|
Java
|
lgpl-2.1
|
fa0ccdebc3efd98ce325da7835405e1118f3ba4c
| 0
|
andyflury/opentsdb,OpenTSDB/opentsdb,sidhhu/opentsdb,kidaa/opentsdb,eswdd/opentsdb,OpenTSDB/opentsdb,MadDogTechnology/opentsdb,eswdd/opentsdb,MadDogTechnology/opentsdb,MadDogTechnology/opentsdb,sidhhu/opentsdb,andyflury/opentsdb,OpenTSDB/opentsdb,johann8384/opentsdb,alienth/opentsdb,kidaa/opentsdb,ShefronYudy/opentsdb,alienth/opentsdb,johann8384/opentsdb,ShefronYudy/opentsdb
|
// This file is part of OpenTSDB.
// Copyright (C) 2010 StumbleUpon, Inc.
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or (at your
// option) any later version. 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 GNU Lesser
// General Public License for more details. You should have received a copy
// of the GNU Lesser General Public License along with this program. If not,
// see <http://www.gnu.org/licenses/>.
package net.opentsdb.tsd;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.opentsdb.core.Aggregator;
import net.opentsdb.core.Aggregators;
import net.opentsdb.core.Const;
import net.opentsdb.core.DataPoint;
import net.opentsdb.core.DataPoints;
import net.opentsdb.core.Query;
import net.opentsdb.core.TSDB;
import net.opentsdb.core.Tags;
import net.opentsdb.graph.Plot;
import net.opentsdb.stats.Histogram;
import net.opentsdb.stats.StatsCollector;
import net.opentsdb.uid.NoSuchUniqueName;
/**
* Stateless handler of HTTP graph requests (the {@code /q} endpoint).
*/
final class GraphHandler implements HttpRpc {
private static final Logger LOG =
LoggerFactory.getLogger(GraphHandler.class);
/** Number of times we had to do all the work up to running Gnuplot. */
private static final AtomicInteger graphs_generated
= new AtomicInteger();
/** Number of times a graph request was served from disk, no work needed. */
private static final AtomicInteger graphs_diskcache_hit
= new AtomicInteger();
/** Keep track of the latency of graphing requests. */
private static final Histogram graphlatency =
new Histogram(16000, (short) 2, 100);
/** Keep track of the latency (in ms) introduced by running Gnuplot. */
private static final Histogram gnuplotlatency =
new Histogram(16000, (short) 2, 100);
/** Executor to run Gnuplot in separate bounded thread pool. */
private final ThreadPoolExecutor gnuplot;
/** Directory where to cache query results. */
private final String cachedir;
/**
* Constructor.
* @param tsdb The TSDB to use.
*/
public GraphHandler() {
// Gnuplot is mostly CPU bound and does only a little bit of IO at the
// beginning to read the input data and at the end to write its output.
// We don't want to avoid running too many Gnuplot instances concurrently
// as it can steal a significant number of CPU cycles from us. Instead,
// we allow only one per core, and we nice it (the nicing is done in the
// shell script we use to start Gnuplot). Similarly, the queue we use
// is sized so as to have a fixed backlog per core.
final int ncores = Runtime.getRuntime().availableProcessors();
gnuplot = new ThreadPoolExecutor(
ncores, ncores, // Thread pool of a fixed size.
/* 5m = */ 300000, MILLISECONDS, // How long to keep idle threads.
new ArrayBlockingQueue<Runnable>(20 * ncores), // XXX Don't hardcode?
thread_factory);
// ArrayBlockingQueue does not scale as much as LinkedBlockingQueue in terms
// of throughput but we don't need high throughput here. We use ABQ instead
// of LBQ because it creates far fewer references.
cachedir = RpcHandler.getDirectoryFromSystemProp("tsd.http.cachedir");
}
public void execute(final TSDB tsdb, final HttpQuery query) {
try {
doGraph(tsdb, query);
} catch (IOException e) {
query.internalError(e);
}
}
private void doGraph(final TSDB tsdb, final HttpQuery query)
throws IOException {
final String basepath = getGnuplotBasePath(query);
final long start_time = getQueryStringDate(query, "start");
if (start_time == -1) {
throw BadRequestException.missingParameter("start");
}
long end_time = getQueryStringDate(query, "end");
final long now = System.currentTimeMillis() / 1000;
if (end_time == -1) {
end_time = now;
}
// If the end time is in the future (1), make the graph uncacheable.
// Otherwise, if the end time is far enough in the past (2) such that
// no TSD can still be writing to rows for that time span, make the graph
// cacheable for a day since it's very unlikely that any data will change
// for this time span.
// Otherwise (3), allow the client to cache the graph for ~0.1% of the
// time span covered by the request e.g., for 1h of data, it's OK to
// serve something 3s stale, for 1d of data, 84s stale.
final int max_age = (end_time > now ? 0 // (1)
: (end_time < now - Const.MAX_TIMESPAN ? 86400 // (2)
: (int) (end_time - start_time) >> 10)); // (3)
if (isDiskCacheHit(query, max_age, basepath)) {
return;
}
Query[] tsdbqueries;
List<String> options;
tsdbqueries = parseQuery(tsdb, query);
options = query.getQueryStringParams("o");
if (options == null) {
options = new ArrayList<String>(tsdbqueries.length);
for (int i = 0; i < tsdbqueries.length; i++) {
options.add("");
}
} else if (options.size() != tsdbqueries.length) {
throw new BadRequestException(options.size() + " `o' parameters, but "
+ tsdbqueries.length + " `m' parameters.");
}
for (final Query tsdbquery : tsdbqueries) {
try {
tsdbquery.setStartTime(start_time);
} catch (IllegalArgumentException e) {
throw new BadRequestException("start time: " + e.getMessage());
}
try {
tsdbquery.setEndTime(end_time);
} catch (IllegalArgumentException e) {
throw new BadRequestException("end time: " + e.getMessage());
}
}
final Plot plot = new Plot(start_time, end_time);
setPlotDimensions(query, plot);
setPlotParams(query, plot);
final int nqueries = tsdbqueries.length;
@SuppressWarnings("unchecked")
final HashSet<String>[] aggregated_tags = new HashSet[nqueries];
int npoints = 0;
for (int i = 0; i < nqueries; i++) {
try { // execute the TSDB query!
// XXX This is slow and will block Netty. TODO(tsuna): Don't block.
// TODO(tsuna): Optimization: run each query in parallel.
final DataPoints[] series = tsdbqueries[i].run();
for (final DataPoints datapoints : series) {
plot.add(datapoints, options.get(i));
aggregated_tags[i] = new HashSet<String>();
aggregated_tags[i].addAll(datapoints.getAggregatedTags());
npoints += datapoints.aggregatedSize();
}
} catch (RuntimeException e) {
logInfo(query, "Query failed (stack trace coming): "
+ tsdbqueries[i]);
throw e;
}
tsdbqueries[i] = null; // free()
}
tsdbqueries = null; // free()
if (query.hasQueryStringParam("ascii")) {
respondAsciiQuery(query, max_age, basepath, plot);
return;
}
try {
gnuplot.execute(new RunGnuplot(query, max_age, plot, basepath,
aggregated_tags, npoints));
} catch (RejectedExecutionException e) {
query.internalError(new Exception("Too many requests pending,"
+ " please try again later", e));
}
}
// Runs Gnuplot in a subprocess to generate the graph.
private static final class RunGnuplot implements Runnable {
private final HttpQuery query;
private final int max_age;
private final Plot plot;
private final String basepath;
private final HashSet<String>[] aggregated_tags;
private final int npoints;
public RunGnuplot(final HttpQuery query,
final int max_age,
final Plot plot,
final String basepath,
final HashSet<String>[] aggregated_tags,
final int npoints) {
this.query = query;
this.max_age = max_age;
this.plot = plot;
this.basepath = basepath;
this.aggregated_tags = aggregated_tags;
this.npoints = npoints;
}
public void run() {
try {
execute();
} catch (BadRequestException e) {
query.badRequest(e.getMessage());
} catch (GnuplotException e) {
query.badRequest("<pre>" + e.getMessage() + "</pre>");
} catch (RuntimeException e) {
query.internalError(e);
} catch (IOException e) {
query.internalError(e);
}
}
private void execute() throws IOException {
final int nplotted = runGnuplot(query, basepath, plot);
if (query.hasQueryStringParam("json")) {
final StringBuilder buf = new StringBuilder(64);
buf.append("{\"plotted\":").append(nplotted)
.append(",\"points\":").append(npoints)
.append(",\"etags\":[");
for (final HashSet<String> tags : aggregated_tags) {
if (tags == null || tags.isEmpty()) {
buf.append("[]");
} else {
query.toJsonArray(tags, buf);
}
buf.append(',');
}
buf.setCharAt(buf.length() - 1, ']');
// The "timing" field must remain last, loadCachedJson relies this.
buf.append(",\"timing\":").append(query.processingTimeMillis())
.append('}');
query.sendReply(buf);
writeFile(query, basepath + ".json", buf.toString().getBytes());
} else {
if (query.hasQueryStringParam("png")) {
query.sendFile(basepath + ".png", max_age);
} else {
if (nplotted > 0) {
query.sendReply(query.makePage("TSDB Query", "Your graph is ready",
"<img src=\"" + query.request().getUri() + "&png\"/><br/>"
+ "<small>(" + nplotted + " points plotted in "
+ query.processingTimeMillis() + "ms)</small>"));
} else {
query.sendReply(query.makePage("TSDB Query", "No results found",
"<blockquote><h1>No results</h1>Your query didn't return"
+ " anything. Try changing some parameters.</blockquote>"));
}
}
}
// TODO(tsuna): Expire old files from the on-disk cache.
graphlatency.add(query.processingTimeMillis());
graphs_generated.incrementAndGet();
}
}
/** Shuts down the thread pool used to run Gnuplot. */
public void shutdown() {
gnuplot.shutdown();
}
/**
* Collects the stats and metrics tracked by this instance.
* @param collector The collector to use.
*/
public static void collectStats(final StatsCollector collector) {
collector.record("http.latency", graphlatency, "type=graph");
collector.record("http.latency", gnuplotlatency, "type=gnuplot");
collector.record("http.graph.requests", graphs_diskcache_hit, "cache=disk");
collector.record("http.graph.requests", graphs_generated, "cache=miss");
}
/** Returns the base path to use for the Gnuplot files. */
private String getGnuplotBasePath(final HttpQuery query) {
final Map<String, List<String>> q = query.getQueryString();
q.remove("ignore");
// Super cheap caching mechanism: hash the query string.
final HashMap<String, List<String>> qs =
new HashMap<String, List<String>>(q);
// But first remove the parameters that don't influence the output.
qs.remove("png");
qs.remove("json");
qs.remove("ascii");
return cachedir + Integer.toHexString(qs.hashCode());
}
/**
* Checks whether or not it's possible to re-serve this query from disk.
* @param query The query to serve.
* @param max_age The maximum time (in seconds) we wanna allow clients to
* cache the result in case of a cache hit.
* @param basepath The base path used for the Gnuplot files.
* @return {@code true} if this request was served from disk (in which
* case processing can stop here), {@code false} otherwise (in which case
* the query needs to be processed).
*/
private boolean isDiskCacheHit(final HttpQuery query,
final int max_age,
final String basepath) throws IOException {
final String cachepath = basepath + (query.hasQueryStringParam("ascii")
? ".txt" : ".png");
final File cachedfile = new File(cachepath);
if (cachedfile.exists()) {
final long bytes = cachedfile.length();
if (bytes < 21) { // Minimum possible size for a PNG: 21 bytes.
// For .txt files, <21 bytes is almost impossible.
logWarn(query, "Cached " + cachepath + " is too small ("
+ bytes + " bytes) to be valid. Ignoring it.");
return false;
}
if (staleCacheFile(query, max_age, cachedfile)) {
return false;
}
if (query.hasQueryStringParam("json")) {
StringBuilder json = loadCachedJson(query, max_age, basepath);
if (json == null) {
json = new StringBuilder(32);
json.append("{\"timing\":");
}
json.append(query.processingTimeMillis())
.append(",\"cachehit\":\"disk\"}");
query.sendReply(json);
} else if (query.hasQueryStringParam("png")
|| query.hasQueryStringParam("ascii")) {
query.sendFile(cachepath, max_age);
} else {
query.sendReply(query.makePage("TSDB Query", "Your graph is ready",
"<img src=\"" + query.request().getUri() + "&png\"/><br/>"
+ "<small>(served from disk cache)</small>"));
}
graphs_diskcache_hit.incrementAndGet();
return true;
}
// We didn't find an image. Do a negative cache check. If we've seen
// this query before but there was no result, we at least wrote the JSON.
final StringBuilder json = loadCachedJson(query, max_age, basepath);
// If we don't have a JSON file it's a complete cache miss. If we have
// one, and it says 0 data points were plotted, it's a negative cache hit.
if (json == null || !json.toString().contains("\"plotted\":0")) {
return false;
}
if (query.hasQueryStringParam("json")) {
json.append(query.processingTimeMillis())
.append(",\"cachehit\":\"disk\"}");
query.sendReply(json);
} else if (query.hasQueryStringParam("png")) {
query.sendReply(" "); // Send back an empty response...
} else {
query.sendReply(query.makePage("TSDB Query", "No results",
"Sorry, your query didn't return anything.<br/>"
+ "<small>(served from disk cache)</small>"));
}
graphs_diskcache_hit.incrementAndGet();
return true;
}
/**
* Returns whether or not the given cache file can be used or is stale.
* @param query The query to serve.
* @param max_age The maximum time (in seconds) we wanna allow clients to
* cache the result in case of a cache hit.
* @param cachedfile The file to check for staleness.
*/
private boolean staleCacheFile(final HttpQuery query,
final long max_age,
final File cachedfile) {
final long mtime = cachedfile.lastModified() / 1000;
if (mtime <= 0) {
return true; // File doesn't exist, or can't be read.
}
// Queries that don't specify an end-time must be handled carefully,
// since time passes and we may need to regenerate the results in case
// new data points have arrived in the mean time.
final String end = query.getQueryStringParam("end");
if (end == null || end.endsWith("ago")) {
// How many seconds stale?
final long staleness = System.currentTimeMillis() / 1000 - mtime;
if (staleness < 0) { // Can happen if the mtime is "in the future".
logWarn(query, "Not using file @ " + cachedfile + " with weird"
+ " mtime in the future: " + mtime);
return true;
}
// If our graph is older than 0.1% of the duration of the request,
// let's regenerate it in order to avoid service data that's too
// stale, e.g., for 1h of data, it's OK to serve something 3s stale.
if (staleness > max_age) {
logInfo(query, "Cached file @ " + cachedfile.getPath() + " is "
+ staleness + "s stale, which is more than its limit of "
+ max_age + "s, and needs to be regenerated.");
return true;
}
}
return false;
}
/**
* Writes the given byte array into a file.
* This function logs an error but doesn't throw if it fails.
* @param query The query being handled (for logging purposes).
* @param path The path to write to.
* @param contents The contents to write into the file.
*/
private static void writeFile(final HttpQuery query,
final String path,
final byte[] contents) {
try {
final FileOutputStream out = new FileOutputStream(path);
try {
out.write(contents);
} finally {
out.close();
}
} catch (FileNotFoundException e) {
logError(query, "Failed to create file " + path, e);
} catch (IOException e) {
logError(query, "Failed to write file " + path, e);
}
}
/**
* Reads a file into a byte array.
* @param query The query being handled (for logging purposes).
* @param file The file to read.
* @param max_length The maximum number of bytes to read from the file.
* @return {@code null} if the file doesn't exist or is empty or couldn't be
* read, otherwise a byte array of up to {@code max_length} bytes.
*/
private static byte[] readFile(final HttpQuery query,
final File file,
final int max_length) {
final int length = (int) file.length();
if (length <= 0) {
return null;
}
FileInputStream in;
try {
in = new FileInputStream(file.getPath());
} catch (FileNotFoundException e) {
return null;
}
try {
final byte[] buf = new byte[Math.min(length, max_length)];
final int read = in.read(buf);
if (read != buf.length) {
logError(query, "When reading " + file + ": read only "
+ read + " bytes instead of " + buf.length);
return null;
}
return buf;
} catch (IOException e) {
logError(query, "Error while reading " + file, e);
return null;
} finally {
try {
in.close();
} catch (IOException e) {
logError(query, "Error while closing " + file, e);
}
}
}
/**
* Attempts to read the cached {@code .json} file for this query.
* @param query The query to serve.
* @param max_age The maximum time (in seconds) we wanna allow clients to
* cache the result in case of a cache hit.
* @param basepath The base path used for the Gnuplot files.
* @return {@code null} in case no file was found, or the contents of the
* file if it was found. In case some contents was found, it is truncated
* after the position of the last `:' in order to allow the caller to add
* the time taken to serve by the request and other JSON elements if wanted.
*/
private StringBuilder loadCachedJson(final HttpQuery query,
final long max_age,
final String basepath) {
final String json_path = basepath + ".json";
File json_cache = new File(json_path);
if (staleCacheFile(query, max_age, json_cache)) {
return null;
}
final byte[] json = readFile(query, json_cache, 4096);
if (json == null) {
return null;
}
json_cache = null;
final StringBuilder buf = new StringBuilder(20 + json.length);
// The json file is always expected to end in: {...,"timing":N}
// We remove everything past the last `:' so we can send the new
// timing for this request. This doesn't work if there's a tag name
// with a `:' in it, which is not allowed right now.
int colon = 0; // 0 isn't a valid value.
for (int i = 0; i < json.length; i++) {
buf.append((char) json[i]);
if (json[i] == ':') {
colon = i;
}
}
if (colon != 0) {
buf.setLength(colon + 1);
return buf;
} else {
logError(query, "No `:' found in " + json_path + " (" + json.length
+ " bytes) = " + new String(json));
}
return null;
}
/** Parses the {@code wxh} query parameter to set the graph dimension. */
static void setPlotDimensions(final HttpQuery query, final Plot plot) {
final String wxh = query.getQueryStringParam("wxh");
if (wxh != null && !wxh.isEmpty()) {
final int wxhlength = wxh.length();
if (wxhlength < 7) { // 100x100 minimum.
throw new BadRequestException("Parameter wxh too short: " + wxh);
}
final int x = wxh.indexOf('x', 3); // Start at 2 as min size is 100x100
if (x < 0) {
throw new BadRequestException("Invalid wxh parameter: " + wxh);
}
try {
final short width = Short.parseShort(wxh.substring(0, x));
final short height = Short.parseShort(wxh.substring(x + 1, wxhlength));
try {
plot.setDimensions(width, height);
} catch (IllegalArgumentException e) {
throw new BadRequestException("Invalid wxh parameter: " + wxh + ", "
+ e.getMessage());
}
} catch (NumberFormatException e) {
throw new BadRequestException("Can't parse wxh '" + wxh + "': "
+ e.getMessage());
}
}
}
/**
* Formats and quotes the given string so it's a suitable Gnuplot string.
* @param s The string to stringify.
* @return A string suitable for use as a literal string in Gnuplot.
*/
private static String stringify(final String s) {
final StringBuilder buf = new StringBuilder(1 + s.length() + 1);
buf.append('"');
HttpQuery.escapeJson(s, buf); // Abusing this function gets the job done.
buf.append('"');
return buf.toString();
}
/**
* Pops out of the query string the given parameter.
* @param querystring The query string.
* @param param The name of the parameter to pop out.
* @return {@code null} if the parameter wasn't passed, otherwise the
* value of the last occurrence of the parameter.
*/
private static String popParam(final Map<String, List<String>> querystring,
final String param) {
final List<String> params = querystring.remove(param);
if (params == null) {
return null;
}
return params.get(params.size() - 1);
}
/**
* Applies the plot parameters from the query to the given plot.
* @param query The query from which to get the query string.
* @param plot The plot on which to apply the parameters.
*/
static void setPlotParams(final HttpQuery query, final Plot plot) {
final HashMap<String, String> params = new HashMap<String, String>();
final Map<String, List<String>> querystring = query.getQueryString();
String value;
if ((value = popParam(querystring, "yrange")) != null) {
params.put("yrange", value);
}
if ((value = popParam(querystring, "y2range")) != null) {
params.put("y2range", value);
}
if ((value = popParam(querystring, "ylabel")) != null) {
params.put("ylabel", stringify(value));
}
if ((value = popParam(querystring, "y2label")) != null) {
params.put("y2label", stringify(value));
}
if ((value = popParam(querystring, "yformat")) != null) {
params.put("format y", stringify(value));
}
if ((value = popParam(querystring, "y2format")) != null) {
params.put("format y2", stringify(value));
}
if ((value = popParam(querystring, "ylog")) != null) {
params.put("logscale", "y");
}
if ((value = popParam(querystring, "y2log")) != null) {
params.put("logscale", "y2");
}
if ((value = popParam(querystring, "key")) != null) {
params.put("key", value);
}
// This must remain after the previous `if' in order to properly override
// any previous `key' parameter if a `nokey' parameter is given.
if ((value = popParam(querystring, "nokey")) != null) {
params.put("key", null);
}
plot.setParams(params);
}
/**
* Runs Gnuplot in a subprocess to generate the graph.
* <strong>This function will block</strong> while Gnuplot is running.
* @param query The query being handled (for logging purposes).
* @param basepath The base path used for the Gnuplot files.
* @param plot The plot object to generate Gnuplot's input files.
* @return The number of points plotted by Gnuplot (0 or more).
* @throws IOException if the Gnuplot files can't be written, or
* the Gnuplot subprocess fails to start, or we can't read the
* graph from the file it produces, or if we have been interrupted.
* @throws GnuplotException if Gnuplot returns non-zero.
*/
static int runGnuplot(final HttpQuery query,
final String basepath,
final Plot plot) throws IOException {
final int nplotted = plot.dumpToFiles(basepath);
final long start_time = System.nanoTime();
final Process gnuplot = new ProcessBuilder(
// XXX Java Kludge XXX
"./src/graph/mygnuplot.sh", basepath + ".out", basepath + ".err",
basepath + ".gnuplot").start();
int rv;
try {
rv = gnuplot.waitFor(); // Couldn't find how to do this asynchronously.
} catch (InterruptedException e) {
gnuplot.destroy();
Thread.currentThread().interrupt(); // Restore the interrupted status.
throw new IOException("interrupted", e); // I hate checked exceptions.
}
gnuplotlatency.add((int) ((System.nanoTime() - start_time) / 1000000));
if (rv != 0) {
final byte[] stderr = readFile(query, new File(basepath + ".err"),
4096);
// Sometimes Gnuplot will error out but still create the file.
new File(basepath + ".png").delete();
if (stderr == null) {
throw new GnuplotException(rv);
}
throw new GnuplotException(new String(stderr));
}
// Remove the files for stderr/stdout if they're empty.
deleteFileIfEmpty(basepath + ".out");
deleteFileIfEmpty(basepath + ".err");
return nplotted;
}
private static void deleteFileIfEmpty(final String path) {
final File file = new File(path);
if (file.length() <= 0) {
file.delete();
}
}
/**
* Respond to a query that wants the output in ASCII.
* <p>
* When a query specifies the "ascii" query string parameter, we send the
* data points back to the client in plain text instead of sending a PNG.
* @param query The query we're currently serving.
* @param max_age The maximum time (in seconds) we wanna allow clients to
* cache the result in case of a cache hit.
* @param basepath The base path used for the Gnuplot files.
* @param plot The plot object to generate Gnuplot's input files.
*/
private static void respondAsciiQuery(final HttpQuery query,
final int max_age,
final String basepath,
final Plot plot) {
final String path = basepath + ".txt";
PrintWriter asciifile;
try {
asciifile = new PrintWriter(path);
} catch (IOException e) {
query.internalError(e);
return;
}
try {
final StringBuilder tagbuf = new StringBuilder();
for (final DataPoints dp : plot.getDataPoints()) {
final String metric = dp.metricName();
tagbuf.setLength(0);
for (final Map.Entry<String, String> tag : dp.getTags().entrySet()) {
tagbuf.append(' ').append(tag.getKey())
.append('=').append(tag.getValue());
}
for (final DataPoint d : dp) {
asciifile.print(metric);
asciifile.print(' ');
asciifile.print(d.timestamp());
asciifile.print(' ');
if (d.isInteger()) {
asciifile.print(d.longValue());
} else {
final double value = d.doubleValue();
if (value != value || Double.isInfinite(value)) {
throw new IllegalStateException("NaN or Infinity:" + value
+ " d=" + d + ", query=" + query);
}
asciifile.print(value);
}
asciifile.print(tagbuf);
asciifile.print('\n');
}
}
} finally {
asciifile.close();
}
try {
query.sendFile(path, max_age);
} catch (IOException e) {
query.internalError(e);
}
}
/**
* Parses the {@code /q} query in a list of {@link Query} objects.
* @param tsdb The TSDB to use.
* @param query The HTTP query for {@code /q}.
* @return The corresponding {@link Query} objects.
* @throws BadRequestException if the query was malformed.
*/
private static Query[] parseQuery(final TSDB tsdb, final HttpQuery query) {
final List<String> ms = query.getQueryStringParams("m");
if (ms == null) {
throw BadRequestException.missingParameter("m");
}
final Query[] tsdbqueries = new Query[ms.size()];
int nqueries = 0;
for (final String m : ms) {
// m is of the following forms:
// agg:[interval-agg:][rate:]metric[{tag=value,...}]
// Where the parts in square brackets `[' .. `]' are optional.
final String[] parts = Tags.splitString(m, ':');
int i = parts.length;
if (i < 2 || i > 4) {
throw new BadRequestException("Invalid parameter m=" + m + " ("
+ (i < 2 ? "not enough" : "too many") + " :-separated parts)");
}
final Aggregator agg = getAggregator(parts[0]);
i--; // Move to the last part (the metric name).
final HashMap<String, String> parsedtags = new HashMap<String, String>();
final String metric = parseMetricAndTags(parts[i], parsedtags);
final boolean rate = "rate".equals(parts[--i]);
if (rate) {
i--; // Move to the next part.
}
final Query tsdbquery = tsdb.newQuery();
try {
tsdbquery.setTimeSeries(metric, parsedtags, agg, rate);
} catch (NoSuchUniqueName e) {
throw new BadRequestException(e.getMessage());
}
// downsampling function & interval.
if (i > 0) {
final int dash = parts[1].indexOf('-', 1); // 1st char can't be `-'.
if (dash < 0) {
throw new BadRequestException("Invalid downsampling specifier '"
+ parts[1] + "' in m=" + m);
}
Aggregator downsampler;
try {
downsampler = Aggregators.get(parts[1].substring(dash + 1));
} catch (NoSuchElementException e) {
throw new BadRequestException("No such downsampling function: "
+ parts[1].substring(dash + 1));
}
final int interval = parseDuration(parts[1].substring(0, dash));
tsdbquery.downsample(interval, downsampler);
}
tsdbqueries[nqueries++] = tsdbquery;
}
return tsdbqueries;
}
/**
* Parses the metric and tags out of the given string.
* @param metric A string of the form "metric" or "metric{tag=value,...}".
* @param tags The map to populate with the tags parsed out of the first
* argument.
* @return The name of the metric.
* @throws BadRequestException if the metric is malformed.
*/
private static String parseMetricAndTags(final String metric,
final HashMap<String, String> tags) {
final int curly = metric.indexOf('{');
if (curly < 0) {
return metric;
}
final int len = metric.length();
if (metric.charAt(len - 1) != '}') { // "foo{"
throw new BadRequestException("Missing '}' at the end of: " + metric);
} else if (curly == len - 1) { // "foo{}"
return metric.substring(0, len - 2);
}
// substring the tags out of "foo{a=b,...,x=y}" and parse them.
for (final String tag
: Tags.splitString(metric.substring(curly + 1, len - 1), ',')) {
try {
Tags.parse(tags, tag);
} catch (IllegalArgumentException e) {
throw new BadRequestException("When parsing tag '" + tag
+ "': " + e.getMessage());
}
}
// Return the "foo" part of "foo{a=b,...,x=y}"
return metric.substring(0, curly);
}
/**
* Returns the aggregator with the given name.
* @param name Name of the aggregator to get.
* @throws BadRequestException if there's no aggregator with this name.
*/
private static final Aggregator getAggregator(final String name) {
try {
return Aggregators.get(name);
} catch (NoSuchElementException e) {
throw new BadRequestException("No such aggregation function: " + name);
}
}
/**
* Parses a human-readable duration (e.g, "10m", "3h", "14d") into seconds.
* <p>
* Formats supported: {@code s}: seconds, {@code m}: minutes,
* {@code h}: hours, {@code d}: days, {@code w}: weeks, {@code y}: years.
* @param duration The human-readable duration to parse.
* @return A strictly positive number of seconds.
* @throws BadRequestException if the interval was malformed.
*/
private static final int parseDuration(final String duration) {
int interval;
final int lastchar = duration.length() - 1;
try {
interval = Integer.parseInt(duration.substring(0, lastchar));
} catch (NumberFormatException e) {
throw new BadRequestException("Invalid duration (number): " + duration);
}
if (interval <= 0) {
throw new BadRequestException("Zero or negative duration: " + duration);
}
switch (duration.charAt(lastchar)) {
case 's': return interval; // seconds
case 'm': return interval * 60; // minutes
case 'h': return interval * 3600; // hours
case 'd': return interval * 3600 * 24; // days
case 'w': return interval * 3600 * 24 * 7; // weeks
case 'y': return interval * 3600 * 24 * 365; // years (screw leap years)
}
throw new BadRequestException("Invalid duration (suffix): " + duration);
}
/**
* Returns a timestamp from a date specified in a query string parameter.
* @param query The HTTP query from which to get the query string parameter.
* @param paramname The name of the query string parameter.
* @return A UNIX timestamp in seconds (strictly positive 32-bit "unsigned")
* or -1 if there was no query string parameter named {@code paramname}.
* @throws BadRequestException if the date is invalid.
*/
private static long getQueryStringDate(final HttpQuery query,
final String paramname) {
final String date = query.getQueryStringParam(paramname);
if (date == null) {
return -1;
} else if (date.endsWith("-ago")) {
return (System.currentTimeMillis() / 1000
- parseDuration(date.substring(0, date.length() - 4)));
}
try {
final SimpleDateFormat fmt = new SimpleDateFormat("yyyy/MM/dd-HH:mm:ss");
final long timestamp = fmt.parse(date).getTime() / 1000;
if (timestamp <= 0) {
throw new BadRequestException("Bad " + paramname + " date: " + date);
}
return timestamp;
} catch (ParseException e) {
throw new BadRequestException("Invalid " + paramname + " date: " + date
+ ". " + e.getMessage());
} catch (NumberFormatException e) {
throw new BadRequestException("Invalid " + paramname + " date: " + date
+ ". " + e.getMessage());
}
}
private static final PlotThdFactory thread_factory = new PlotThdFactory();
private static final class PlotThdFactory implements ThreadFactory {
private final AtomicInteger id = new AtomicInteger(0);
public Thread newThread(final Runnable r) {
return new Thread(r, "Gnuplot #" + id.incrementAndGet());
}
}
// ---------------- //
// Logging helpers. //
// ---------------- //
static void logInfo(final HttpQuery query, final String msg) {
LOG.info(query.channel().toString() + ' ' + msg);
}
static void logWarn(final HttpQuery query, final String msg) {
LOG.warn(query.channel().toString() + ' ' + msg);
}
static void logError(final HttpQuery query, final String msg) {
LOG.error(query.channel().toString() + ' ' + msg);
}
static void logError(final HttpQuery query, final String msg,
final Throwable e) {
LOG.error(query.channel().toString() + ' ' + msg, e);
}
}
|
src/tsd/GraphHandler.java
|
// This file is part of OpenTSDB.
// Copyright (C) 2010 StumbleUpon, Inc.
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or (at your
// option) any later version. 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 GNU Lesser
// General Public License for more details. You should have received a copy
// of the GNU Lesser General Public License along with this program. If not,
// see <http://www.gnu.org/licenses/>.
package net.opentsdb.tsd;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.opentsdb.core.Aggregator;
import net.opentsdb.core.Aggregators;
import net.opentsdb.core.Const;
import net.opentsdb.core.DataPoint;
import net.opentsdb.core.DataPoints;
import net.opentsdb.core.Query;
import net.opentsdb.core.TSDB;
import net.opentsdb.core.Tags;
import net.opentsdb.graph.Plot;
import net.opentsdb.stats.Histogram;
import net.opentsdb.stats.StatsCollector;
import net.opentsdb.uid.NoSuchUniqueName;
/**
* Stateless handler of HTTP graph requests (the {@code /q} endpoint).
*/
final class GraphHandler implements HttpRpc {
private static final Logger LOG =
LoggerFactory.getLogger(GraphHandler.class);
/** Number of times we had to do all the work up to running Gnuplot. */
private static final AtomicInteger graphs_generated
= new AtomicInteger();
/** Number of times a graph request was served from disk, no work needed. */
private static final AtomicInteger graphs_diskcache_hit
= new AtomicInteger();
/** Keep track of the latency of graphing requests. */
private static final Histogram graphlatency =
new Histogram(16000, (short) 2, 100);
/** Keep track of the latency (in ms) introduced by running Gnuplot. */
private static final Histogram gnuplotlatency =
new Histogram(16000, (short) 2, 100);
/** Executor to run Gnuplot in separate bounded thread pool. */
private final ThreadPoolExecutor gnuplot;
/** Directory where to cache query results. */
private final String cachedir;
/**
* Constructor.
* @param tsdb The TSDB to use.
*/
public GraphHandler() {
// Gnuplot is mostly CPU bound and does only a little bit of IO at the
// beginning to read the input data and at the end to write its output.
// We don't want to avoid running too many Gnuplot instances concurrently
// as it can steal a significant number of CPU cycles from us. Instead,
// we allow only one per core, and we nice it (the nicing is done in the
// shell script we use to start Gnuplot). Similarly, the queue we use
// is sized so as to have a fixed backlog per core.
final int ncores = Runtime.getRuntime().availableProcessors();
gnuplot = new ThreadPoolExecutor(
ncores, ncores, // Thread pool of a fixed size.
/* 5m = */ 300000, MILLISECONDS, // How long to keep idle threads.
new ArrayBlockingQueue<Runnable>(20 * ncores), // XXX Don't hardcode?
thread_factory);
// ArrayBlockingQueue does not scale as much as LinkedBlockingQueue in terms
// of throughput but we don't need high throughput here. We use ABQ instead
// of LBQ because it creates far fewer references.
cachedir = RpcHandler.getDirectoryFromSystemProp("tsd.http.cachedir");
}
public void execute(final TSDB tsdb, final HttpQuery query) {
try {
doGraph(tsdb, query);
} catch (IOException e) {
query.internalError(e);
}
}
private void doGraph(final TSDB tsdb, final HttpQuery query)
throws IOException {
final String basepath = getGnuplotBasePath(query);
final long start_time = getQueryStringDate(query, "start");
if (start_time == -1) {
throw BadRequestException.missingParameter("start");
}
long end_time = getQueryStringDate(query, "end");
final long now = System.currentTimeMillis() / 1000;
if (end_time == -1) {
end_time = now;
}
// If the end time is in the future (1), make the graph uncacheable.
// Otherwise, if the end time is far enough in the past (2) such that
// no TSD can still be writing to rows for that time span, make the graph
// cacheable for a day since it's very unlikely that any data will change
// for this time span.
// Otherwise (3), allow the client to cache the graph for ~0.1% of the
// time span covered by the request e.g., for 1h of data, it's OK to
// serve something 3s stale, for 1d of data, 84s stale.
final int max_age = (end_time > now ? 0 // (1)
: (end_time < now - Const.MAX_TIMESPAN ? 86400 // (2)
: (int) (end_time - start_time) >> 10)); // (3)
if (isDiskCacheHit(query, max_age, basepath)) {
return;
}
Query[] tsdbqueries;
List<String> options;
tsdbqueries = parseQuery(tsdb, query);
options = query.getQueryStringParams("o");
if (options == null) {
options = new ArrayList<String>(tsdbqueries.length);
for (int i = 0; i < tsdbqueries.length; i++) {
options.add("");
}
} else if (options.size() != tsdbqueries.length) {
throw new BadRequestException(options.size() + " `o' parameters, but "
+ tsdbqueries.length + " `m' parameters.");
}
for (final Query tsdbquery : tsdbqueries) {
try {
tsdbquery.setStartTime(start_time);
} catch (IllegalArgumentException e) {
throw new BadRequestException("start time: " + e.getMessage());
}
try {
tsdbquery.setEndTime(end_time);
} catch (IllegalArgumentException e) {
throw new BadRequestException("end time: " + e.getMessage());
}
}
final Plot plot = new Plot(start_time, end_time);
setPlotDimensions(query, plot);
setPlotParams(query, plot);
final int nqueries = tsdbqueries.length;
@SuppressWarnings("unchecked")
final HashSet<String>[] aggregated_tags = new HashSet[nqueries];
int npoints = 0;
for (int i = 0; i < nqueries; i++) {
try { // execute the TSDB query!
// XXX This is slow and will block Netty. TODO(tsuna): Don't block.
// TODO(tsuna): Optimization: run each query in parallel.
final DataPoints[] series = tsdbqueries[i].run();
for (final DataPoints datapoints : series) {
plot.add(datapoints, options.get(i));
aggregated_tags[i] = new HashSet<String>();
aggregated_tags[i].addAll(datapoints.getAggregatedTags());
npoints += datapoints.aggregatedSize();
}
} catch (RuntimeException e) {
logInfo(query, "Query failed (stack trace coming): "
+ tsdbqueries[i]);
throw e;
}
tsdbqueries[i] = null; // free()
}
tsdbqueries = null; // free()
if (query.hasQueryStringParam("ascii")) {
respondAsciiQuery(query, max_age, basepath, plot);
return;
}
try {
gnuplot.execute(new RunGnuplot(query, max_age, plot, basepath,
aggregated_tags, npoints));
} catch (RejectedExecutionException e) {
query.internalError(new Exception("Too many requests pending,"
+ " please try again later", e));
}
}
// Runs Gnuplot in a subprocess to generate the graph.
private static final class RunGnuplot implements Runnable {
private final HttpQuery query;
private final int max_age;
private final Plot plot;
private final String basepath;
private final HashSet<String>[] aggregated_tags;
private final int npoints;
public RunGnuplot(final HttpQuery query,
final int max_age,
final Plot plot,
final String basepath,
final HashSet<String>[] aggregated_tags,
final int npoints) {
this.query = query;
this.max_age = max_age;
this.plot = plot;
this.basepath = basepath;
this.aggregated_tags = aggregated_tags;
this.npoints = npoints;
}
public void run() {
try {
execute();
} catch (BadRequestException e) {
query.badRequest(e.getMessage());
} catch (GnuplotException e) {
query.badRequest("<pre>" + e.getMessage() + "</pre>");
} catch (RuntimeException e) {
query.internalError(e);
} catch (IOException e) {
query.internalError(e);
}
}
private void execute() throws IOException {
final int nplotted = runGnuplot(query, basepath, plot);
if (query.hasQueryStringParam("json")) {
final StringBuilder buf = new StringBuilder(64);
buf.append("{\"plotted\":").append(nplotted)
.append(",\"points\":").append(npoints)
.append(",\"etags\":[");
for (final HashSet<String> tags : aggregated_tags) {
if (tags == null || tags.isEmpty()) {
buf.append("[]");
} else {
query.toJsonArray(tags, buf);
}
buf.append(',');
}
buf.setCharAt(buf.length() - 1, ']');
// The "timing" field must remain last, loadCachedJson relies this.
buf.append(",\"timing\":").append(query.processingTimeMillis())
.append('}');
query.sendReply(buf);
writeFile(query, basepath + ".json", buf.toString().getBytes());
} else {
if (query.hasQueryStringParam("png")) {
query.sendFile(basepath + ".png", max_age);
} else {
if (nplotted > 0) {
query.sendReply(query.makePage("TSDB Query", "Your graph is ready",
"<img src=\"" + query.request().getUri() + "&png\"/><br/>"
+ "<small>(" + nplotted + " points plotted in "
+ query.processingTimeMillis() + "ms)</small>"));
} else {
query.sendReply(query.makePage("TSDB Query", "No results found",
"<blockquote><h1>No results</h1>Your query didn't return"
+ " anything. Try changing some parameters.</blockquote>"));
}
}
}
// TODO(tsuna): Expire old files from the on-disk cache.
graphlatency.add(query.processingTimeMillis());
graphs_generated.incrementAndGet();
}
}
/** Shuts down the thread pool used to run Gnuplot. */
public void shutdown() {
gnuplot.shutdown();
}
/**
* Collects the stats and metrics tracked by this instance.
* @param collector The collector to use.
*/
public static void collectStats(final StatsCollector collector) {
collector.record("http.latency", graphlatency, "type=graph");
collector.record("http.latency", gnuplotlatency, "type=gnuplot");
collector.record("http.graph.requests", graphs_diskcache_hit, "cache=disk");
collector.record("http.graph.requests", graphs_generated, "cache=miss");
}
/** Returns the base path to use for the Gnuplot files. */
private String getGnuplotBasePath(final HttpQuery query) {
final Map<String, List<String>> q = query.getQueryString();
q.remove("ignore");
// Super cheap caching mechanism: hash the query string.
final HashMap<String, List<String>> qs =
new HashMap<String, List<String>>(q);
// But first remove the parameters that don't influence the output.
qs.remove("png");
qs.remove("json");
qs.remove("ascii");
return cachedir + Integer.toHexString(qs.hashCode());
}
/**
* Checks whether or not it's possible to re-serve this query from disk.
* @param query The query to serve.
* @param max_age The maximum time (in seconds) we wanna allow clients to
* cache the result in case of a cache hit.
* @param basepath The base path used for the Gnuplot files.
* @return {@code true} if this request was served from disk (in which
* case processing can stop here), {@code false} otherwise (in which case
* the query needs to be processed).
*/
private boolean isDiskCacheHit(final HttpQuery query,
final int max_age,
final String basepath) throws IOException {
final String cachepath = basepath + (query.hasQueryStringParam("ascii")
? ".txt" : ".png");
final File cachedfile = new File(cachepath);
if (cachedfile.exists()) {
final long bytes = cachedfile.length();
if (bytes < 21) { // Minimum possible size for a PNG: 21 bytes.
// For .txt files, <21 bytes is almost impossible.
logWarn(query, "Cached " + cachepath + " is too small ("
+ bytes + " bytes) to be valid. Ignoring it.");
return false;
}
if (staleCacheFile(query, max_age, cachedfile)) {
return false;
}
if (query.hasQueryStringParam("json")) {
StringBuilder json = loadCachedJson(query, max_age, basepath);
if (json == null) {
json = new StringBuilder(32);
json.append("{\"timing\":");
}
json.append(query.processingTimeMillis())
.append(",\"cachehit\":\"disk\"}");
query.sendReply(json);
} else if (query.hasQueryStringParam("png")
|| query.hasQueryStringParam("ascii")) {
query.sendFile(cachepath, max_age);
} else {
query.sendReply(query.makePage("TSDB Query", "Your graph is ready",
"<img src=\"" + query.request().getUri() + "&png\"/><br/>"
+ "<small>(served from disk cache)</small>"));
}
graphs_diskcache_hit.incrementAndGet();
return true;
}
// We didn't find an image. Do a negative cache check. If we've seen
// this query before but there was no result, we at least wrote the JSON.
final StringBuilder json = loadCachedJson(query, max_age, basepath);
// If we don't have a JSON file it's a complete cache miss. If we have
// one, and it says 0 data points were plotted, it's a negative cache hit.
if (json == null || !json.toString().contains("\"plotted\":0")) {
return false;
}
if (query.hasQueryStringParam("json")) {
json.append(query.processingTimeMillis())
.append(",\"cachehit\":\"disk\"}");
query.sendReply(json);
} else if (query.hasQueryStringParam("png")) {
query.sendReply(" "); // Send back an empty response...
} else {
query.sendReply(query.makePage("TSDB Query", "No results",
"Sorry, your query didn't return anything.<br/>"
+ "<small>(served from disk cache)</small>"));
}
graphs_diskcache_hit.incrementAndGet();
return true;
}
/**
* Returns whether or not the given cache file can be used or is stale.
* @param query The query to serve.
* @param max_age The maximum time (in seconds) we wanna allow clients to
* cache the result in case of a cache hit.
* @param cachedfile The file to check for staleness.
*/
private boolean staleCacheFile(final HttpQuery query,
final long max_age,
final File cachedfile) {
// Queries that don't specify an end-time must be handled carefully,
// since time passes and we may need to regenerate the results in case
// new data points have arrived in the mean time.
final String end = query.getQueryStringParam("end");
if (end == null || end.endsWith("ago")) {
// How many seconds stale?
final long mtime = cachedfile.lastModified() / 1000;
final long staleness = System.currentTimeMillis() / 1000 - mtime;
if (staleness < 0) { // Can happen if the mtime is "in the future".
logWarn(query, "Not using file @ " + cachedfile + " with weird"
+ " mtime in the future: " + mtime);
return true;
}
// If our graph is older than 0.1% of the duration of the request,
// let's regenerate it in order to avoid service data that's too
// stale, e.g., for 1h of data, it's OK to serve something 3s stale.
if (staleness > max_age) {
logInfo(query, "Cached file @ " + cachedfile.getPath() + " is "
+ staleness + "s stale, which is more than its limit of "
+ max_age + "s, and needs to be regenerated.");
return true;
}
}
return false;
}
/**
* Writes the given byte array into a file.
* This function logs an error but doesn't throw if it fails.
* @param query The query being handled (for logging purposes).
* @param path The path to write to.
* @param contents The contents to write into the file.
*/
private static void writeFile(final HttpQuery query,
final String path,
final byte[] contents) {
try {
final FileOutputStream out = new FileOutputStream(path);
try {
out.write(contents);
} finally {
out.close();
}
} catch (FileNotFoundException e) {
logError(query, "Failed to create file " + path, e);
} catch (IOException e) {
logError(query, "Failed to write file " + path, e);
}
}
/**
* Reads a file into a byte array.
* @param query The query being handled (for logging purposes).
* @param file The file to read.
* @param max_length The maximum number of bytes to read from the file.
* @return {@code null} if the file doesn't exist or is empty or couldn't be
* read, otherwise a byte array of up to {@code max_length} bytes.
*/
private static byte[] readFile(final HttpQuery query,
final File file,
final int max_length) {
final int length = (int) file.length();
if (length <= 0) {
return null;
}
FileInputStream in;
try {
in = new FileInputStream(file.getPath());
} catch (FileNotFoundException e) {
return null;
}
try {
final byte[] buf = new byte[Math.min(length, max_length)];
final int read = in.read(buf);
if (read != buf.length) {
logError(query, "When reading " + file + ": read only "
+ read + " bytes instead of " + buf.length);
return null;
}
return buf;
} catch (IOException e) {
logError(query, "Error while reading " + file, e);
return null;
} finally {
try {
in.close();
} catch (IOException e) {
logError(query, "Error while closing " + file, e);
}
}
}
/**
* Attempts to read the cached {@code .json} file for this query.
* @param query The query to serve.
* @param max_age The maximum time (in seconds) we wanna allow clients to
* cache the result in case of a cache hit.
* @param basepath The base path used for the Gnuplot files.
* @return {@code null} in case no file was found, or the contents of the
* file if it was found. In case some contents was found, it is truncated
* after the position of the last `:' in order to allow the caller to add
* the time taken to serve by the request and other JSON elements if wanted.
*/
private StringBuilder loadCachedJson(final HttpQuery query,
final long max_age,
final String basepath) {
final String json_path = basepath + ".json";
File json_cache = new File(json_path);
if (!json_cache.exists() || staleCacheFile(query, max_age, json_cache)) {
return null;
}
final byte[] json = readFile(query, json_cache, 4096);
if (json == null) {
return null;
}
json_cache = null;
final StringBuilder buf = new StringBuilder(20 + json.length);
// The json file is always expected to end in: {...,"timing":N}
// We remove everything past the last `:' so we can send the new
// timing for this request. This doesn't work if there's a tag name
// with a `:' in it, which is not allowed right now.
int colon = 0; // 0 isn't a valid value.
for (int i = 0; i < json.length; i++) {
buf.append((char) json[i]);
if (json[i] == ':') {
colon = i;
}
}
if (colon != 0) {
buf.setLength(colon + 1);
return buf;
} else {
logError(query, "No `:' found in " + json_path + " (" + json.length
+ " bytes) = " + new String(json));
}
return null;
}
/** Parses the {@code wxh} query parameter to set the graph dimension. */
static void setPlotDimensions(final HttpQuery query, final Plot plot) {
final String wxh = query.getQueryStringParam("wxh");
if (wxh != null && !wxh.isEmpty()) {
final int wxhlength = wxh.length();
if (wxhlength < 7) { // 100x100 minimum.
throw new BadRequestException("Parameter wxh too short: " + wxh);
}
final int x = wxh.indexOf('x', 3); // Start at 2 as min size is 100x100
if (x < 0) {
throw new BadRequestException("Invalid wxh parameter: " + wxh);
}
try {
final short width = Short.parseShort(wxh.substring(0, x));
final short height = Short.parseShort(wxh.substring(x + 1, wxhlength));
try {
plot.setDimensions(width, height);
} catch (IllegalArgumentException e) {
throw new BadRequestException("Invalid wxh parameter: " + wxh + ", "
+ e.getMessage());
}
} catch (NumberFormatException e) {
throw new BadRequestException("Can't parse wxh '" + wxh + "': "
+ e.getMessage());
}
}
}
/**
* Formats and quotes the given string so it's a suitable Gnuplot string.
* @param s The string to stringify.
* @return A string suitable for use as a literal string in Gnuplot.
*/
private static String stringify(final String s) {
final StringBuilder buf = new StringBuilder(1 + s.length() + 1);
buf.append('"');
HttpQuery.escapeJson(s, buf); // Abusing this function gets the job done.
buf.append('"');
return buf.toString();
}
/**
* Pops out of the query string the given parameter.
* @param querystring The query string.
* @param param The name of the parameter to pop out.
* @return {@code null} if the parameter wasn't passed, otherwise the
* value of the last occurrence of the parameter.
*/
private static String popParam(final Map<String, List<String>> querystring,
final String param) {
final List<String> params = querystring.remove(param);
if (params == null) {
return null;
}
return params.get(params.size() - 1);
}
/**
* Applies the plot parameters from the query to the given plot.
* @param query The query from which to get the query string.
* @param plot The plot on which to apply the parameters.
*/
static void setPlotParams(final HttpQuery query, final Plot plot) {
final HashMap<String, String> params = new HashMap<String, String>();
final Map<String, List<String>> querystring = query.getQueryString();
String value;
if ((value = popParam(querystring, "yrange")) != null) {
params.put("yrange", value);
}
if ((value = popParam(querystring, "y2range")) != null) {
params.put("y2range", value);
}
if ((value = popParam(querystring, "ylabel")) != null) {
params.put("ylabel", stringify(value));
}
if ((value = popParam(querystring, "y2label")) != null) {
params.put("y2label", stringify(value));
}
if ((value = popParam(querystring, "yformat")) != null) {
params.put("format y", stringify(value));
}
if ((value = popParam(querystring, "y2format")) != null) {
params.put("format y2", stringify(value));
}
if ((value = popParam(querystring, "ylog")) != null) {
params.put("logscale", "y");
}
if ((value = popParam(querystring, "y2log")) != null) {
params.put("logscale", "y2");
}
if ((value = popParam(querystring, "key")) != null) {
params.put("key", value);
}
// This must remain after the previous `if' in order to properly override
// any previous `key' parameter if a `nokey' parameter is given.
if ((value = popParam(querystring, "nokey")) != null) {
params.put("key", null);
}
plot.setParams(params);
}
/**
* Runs Gnuplot in a subprocess to generate the graph.
* <strong>This function will block</strong> while Gnuplot is running.
* @param query The query being handled (for logging purposes).
* @param basepath The base path used for the Gnuplot files.
* @param plot The plot object to generate Gnuplot's input files.
* @return The number of points plotted by Gnuplot (0 or more).
* @throws IOException if the Gnuplot files can't be written, or
* the Gnuplot subprocess fails to start, or we can't read the
* graph from the file it produces, or if we have been interrupted.
* @throws GnuplotException if Gnuplot returns non-zero.
*/
static int runGnuplot(final HttpQuery query,
final String basepath,
final Plot plot) throws IOException {
final int nplotted = plot.dumpToFiles(basepath);
final long start_time = System.nanoTime();
final Process gnuplot = new ProcessBuilder(
// XXX Java Kludge XXX
"./src/graph/mygnuplot.sh", basepath + ".out", basepath + ".err",
basepath + ".gnuplot").start();
int rv;
try {
rv = gnuplot.waitFor(); // Couldn't find how to do this asynchronously.
} catch (InterruptedException e) {
gnuplot.destroy();
Thread.currentThread().interrupt(); // Restore the interrupted status.
throw new IOException("interrupted", e); // I hate checked exceptions.
}
gnuplotlatency.add((int) ((System.nanoTime() - start_time) / 1000000));
if (rv != 0) {
final byte[] stderr = readFile(query, new File(basepath + ".err"),
4096);
// Sometimes Gnuplot will error out but still create the file.
new File(basepath + ".png").delete();
if (stderr == null) {
throw new GnuplotException(rv);
}
throw new GnuplotException(new String(stderr));
}
// Remove the files for stderr/stdout if they're empty.
deleteFileIfEmpty(basepath + ".out");
deleteFileIfEmpty(basepath + ".err");
return nplotted;
}
private static void deleteFileIfEmpty(final String path) {
final File file = new File(path);
if (file.length() <= 0) {
file.delete();
}
}
/**
* Respond to a query that wants the output in ASCII.
* <p>
* When a query specifies the "ascii" query string parameter, we send the
* data points back to the client in plain text instead of sending a PNG.
* @param query The query we're currently serving.
* @param max_age The maximum time (in seconds) we wanna allow clients to
* cache the result in case of a cache hit.
* @param basepath The base path used for the Gnuplot files.
* @param plot The plot object to generate Gnuplot's input files.
*/
private static void respondAsciiQuery(final HttpQuery query,
final int max_age,
final String basepath,
final Plot plot) {
final String path = basepath + ".txt";
PrintWriter asciifile;
try {
asciifile = new PrintWriter(path);
} catch (IOException e) {
query.internalError(e);
return;
}
try {
final StringBuilder tagbuf = new StringBuilder();
for (final DataPoints dp : plot.getDataPoints()) {
final String metric = dp.metricName();
tagbuf.setLength(0);
for (final Map.Entry<String, String> tag : dp.getTags().entrySet()) {
tagbuf.append(' ').append(tag.getKey())
.append('=').append(tag.getValue());
}
for (final DataPoint d : dp) {
asciifile.print(metric);
asciifile.print(' ');
asciifile.print(d.timestamp());
asciifile.print(' ');
if (d.isInteger()) {
asciifile.print(d.longValue());
} else {
final double value = d.doubleValue();
if (value != value || Double.isInfinite(value)) {
throw new IllegalStateException("NaN or Infinity:" + value
+ " d=" + d + ", query=" + query);
}
asciifile.print(value);
}
asciifile.print(tagbuf);
asciifile.print('\n');
}
}
} finally {
asciifile.close();
}
try {
query.sendFile(path, max_age);
} catch (IOException e) {
query.internalError(e);
}
}
/**
* Parses the {@code /q} query in a list of {@link Query} objects.
* @param tsdb The TSDB to use.
* @param query The HTTP query for {@code /q}.
* @return The corresponding {@link Query} objects.
* @throws BadRequestException if the query was malformed.
*/
private static Query[] parseQuery(final TSDB tsdb, final HttpQuery query) {
final List<String> ms = query.getQueryStringParams("m");
if (ms == null) {
throw BadRequestException.missingParameter("m");
}
final Query[] tsdbqueries = new Query[ms.size()];
int nqueries = 0;
for (final String m : ms) {
// m is of the following forms:
// agg:[interval-agg:][rate:]metric[{tag=value,...}]
// Where the parts in square brackets `[' .. `]' are optional.
final String[] parts = Tags.splitString(m, ':');
int i = parts.length;
if (i < 2 || i > 4) {
throw new BadRequestException("Invalid parameter m=" + m + " ("
+ (i < 2 ? "not enough" : "too many") + " :-separated parts)");
}
final Aggregator agg = getAggregator(parts[0]);
i--; // Move to the last part (the metric name).
final HashMap<String, String> parsedtags = new HashMap<String, String>();
final String metric = parseMetricAndTags(parts[i], parsedtags);
final boolean rate = "rate".equals(parts[--i]);
if (rate) {
i--; // Move to the next part.
}
final Query tsdbquery = tsdb.newQuery();
try {
tsdbquery.setTimeSeries(metric, parsedtags, agg, rate);
} catch (NoSuchUniqueName e) {
throw new BadRequestException(e.getMessage());
}
// downsampling function & interval.
if (i > 0) {
final int dash = parts[1].indexOf('-', 1); // 1st char can't be `-'.
if (dash < 0) {
throw new BadRequestException("Invalid downsampling specifier '"
+ parts[1] + "' in m=" + m);
}
Aggregator downsampler;
try {
downsampler = Aggregators.get(parts[1].substring(dash + 1));
} catch (NoSuchElementException e) {
throw new BadRequestException("No such downsampling function: "
+ parts[1].substring(dash + 1));
}
final int interval = parseDuration(parts[1].substring(0, dash));
tsdbquery.downsample(interval, downsampler);
}
tsdbqueries[nqueries++] = tsdbquery;
}
return tsdbqueries;
}
/**
* Parses the metric and tags out of the given string.
* @param metric A string of the form "metric" or "metric{tag=value,...}".
* @param tags The map to populate with the tags parsed out of the first
* argument.
* @return The name of the metric.
* @throws BadRequestException if the metric is malformed.
*/
private static String parseMetricAndTags(final String metric,
final HashMap<String, String> tags) {
final int curly = metric.indexOf('{');
if (curly < 0) {
return metric;
}
final int len = metric.length();
if (metric.charAt(len - 1) != '}') { // "foo{"
throw new BadRequestException("Missing '}' at the end of: " + metric);
} else if (curly == len - 1) { // "foo{}"
return metric.substring(0, len - 2);
}
// substring the tags out of "foo{a=b,...,x=y}" and parse them.
for (final String tag
: Tags.splitString(metric.substring(curly + 1, len - 1), ',')) {
try {
Tags.parse(tags, tag);
} catch (IllegalArgumentException e) {
throw new BadRequestException("When parsing tag '" + tag
+ "': " + e.getMessage());
}
}
// Return the "foo" part of "foo{a=b,...,x=y}"
return metric.substring(0, curly);
}
/**
* Returns the aggregator with the given name.
* @param name Name of the aggregator to get.
* @throws BadRequestException if there's no aggregator with this name.
*/
private static final Aggregator getAggregator(final String name) {
try {
return Aggregators.get(name);
} catch (NoSuchElementException e) {
throw new BadRequestException("No such aggregation function: " + name);
}
}
/**
* Parses a human-readable duration (e.g, "10m", "3h", "14d") into seconds.
* <p>
* Formats supported: {@code s}: seconds, {@code m}: minutes,
* {@code h}: hours, {@code d}: days, {@code w}: weeks, {@code y}: years.
* @param duration The human-readable duration to parse.
* @return A strictly positive number of seconds.
* @throws BadRequestException if the interval was malformed.
*/
private static final int parseDuration(final String duration) {
int interval;
final int lastchar = duration.length() - 1;
try {
interval = Integer.parseInt(duration.substring(0, lastchar));
} catch (NumberFormatException e) {
throw new BadRequestException("Invalid duration (number): " + duration);
}
if (interval <= 0) {
throw new BadRequestException("Zero or negative duration: " + duration);
}
switch (duration.charAt(lastchar)) {
case 's': return interval; // seconds
case 'm': return interval * 60; // minutes
case 'h': return interval * 3600; // hours
case 'd': return interval * 3600 * 24; // days
case 'w': return interval * 3600 * 24 * 7; // weeks
case 'y': return interval * 3600 * 24 * 365; // years (screw leap years)
}
throw new BadRequestException("Invalid duration (suffix): " + duration);
}
/**
* Returns a timestamp from a date specified in a query string parameter.
* @param query The HTTP query from which to get the query string parameter.
* @param paramname The name of the query string parameter.
* @return A UNIX timestamp in seconds (strictly positive 32-bit "unsigned")
* or -1 if there was no query string parameter named {@code paramname}.
* @throws BadRequestException if the date is invalid.
*/
private static long getQueryStringDate(final HttpQuery query,
final String paramname) {
final String date = query.getQueryStringParam(paramname);
if (date == null) {
return -1;
} else if (date.endsWith("-ago")) {
return (System.currentTimeMillis() / 1000
- parseDuration(date.substring(0, date.length() - 4)));
}
try {
final SimpleDateFormat fmt = new SimpleDateFormat("yyyy/MM/dd-HH:mm:ss");
final long timestamp = fmt.parse(date).getTime() / 1000;
if (timestamp <= 0) {
throw new BadRequestException("Bad " + paramname + " date: " + date);
}
return timestamp;
} catch (ParseException e) {
throw new BadRequestException("Invalid " + paramname + " date: " + date
+ ". " + e.getMessage());
} catch (NumberFormatException e) {
throw new BadRequestException("Invalid " + paramname + " date: " + date
+ ". " + e.getMessage());
}
}
private static final PlotThdFactory thread_factory = new PlotThdFactory();
private static final class PlotThdFactory implements ThreadFactory {
private final AtomicInteger id = new AtomicInteger(0);
public Thread newThread(final Runnable r) {
return new Thread(r, "Gnuplot #" + id.incrementAndGet());
}
}
// ---------------- //
// Logging helpers. //
// ---------------- //
static void logInfo(final HttpQuery query, final String msg) {
LOG.info(query.channel().toString() + ' ' + msg);
}
static void logWarn(final HttpQuery query, final String msg) {
LOG.warn(query.channel().toString() + ' ' + msg);
}
static void logError(final HttpQuery query, final String msg) {
LOG.error(query.channel().toString() + ' ' + msg);
}
static void logError(final HttpQuery query, final String msg,
final Throwable e) {
LOG.error(query.channel().toString() + ' ' + msg, e);
}
}
|
Minor improvement in the code checking cache staleness.
This removes one indirect syscall to `stat'.
Change-Id: If0fa32c698c6dbf51a0ea57f8c3177bde84cc1a4
|
src/tsd/GraphHandler.java
|
Minor improvement in the code checking cache staleness.
|
|
Java
|
lgpl-2.1
|
285a39b3478561e69796b305b9dcbe256eea34a0
| 0
|
wsnavely/soot-infoflow-android,jgarci40/soot-infoflow,matedealer/soot-infoflow,wangxiayang/soot-infoflow,xph906/FlowDroidInfoflowNew,lilicoding/soot-infoflow,johspaeth/soot-infoflow,kaunder/soot-infoflow,secure-software-engineering/soot-infoflow
|
/*******************************************************************************
* Copyright (c) 2012 Eric Bodden.
* Copyright (c) 2013 Tata Consultancy Services & Ecole Polytechnique de Montreal
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* Eric Bodden - initial API and implementation
* Marc-Andre Laverdiere-Papineau - Fixed race condition
******************************************************************************/
package soot.jimple.infoflow.solver.fastSolver;
import heros.DontSynchronize;
import heros.FlowFunction;
import heros.FlowFunctionCache;
import heros.FlowFunctions;
import heros.IFDSTabulationProblem;
import heros.SynchronizedBy;
import heros.ZeroedFlowFunctions;
import heros.solver.CountingThreadPoolExecutor;
import heros.solver.LinkedNode;
import heros.solver.Pair;
import heros.solver.PathEdge;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.SootMethod;
import soot.Unit;
import soot.jimple.infoflow.util.ConcurrentHashSet;
import soot.jimple.infoflow.util.MyConcurrentHashMap;
import soot.jimple.toolkits.ide.icfg.BiDiInterproceduralCFG;
import com.google.common.cache.CacheBuilder;
/**
* A solver for an {@link IFDSTabulationProblem}. This solver is not based on the IDESolver
* implementation in Heros for performance reasons.
*
* @param <N> The type of nodes in the interprocedural control-flow graph. Typically {@link Unit}.
* @param <D> The type of data-flow facts to be computed by the tabulation problem.
* @param <M> The type of objects used to represent methods. Typically {@link SootMethod}.
* @param <I> The type of inter-procedural control-flow graph being used.
* @see IFDSTabulationProblem
*/
public class IFDSSolver<N,D extends LinkedNode<D>,M,I extends BiDiInterproceduralCFG<N, M>> {
public static CacheBuilder<Object, Object> DEFAULT_CACHE_BUILDER = CacheBuilder.newBuilder().concurrencyLevel
(Runtime.getRuntime().availableProcessors()).initialCapacity(10000).softValues();
protected static final Logger logger = LoggerFactory.getLogger(IFDSSolver.class);
//enable with -Dorg.slf4j.simpleLogger.defaultLogLevel=trace
public static final boolean DEBUG = logger.isDebugEnabled();
protected CountingThreadPoolExecutor executor;
@DontSynchronize("only used by single thread")
protected int numThreads;
@SynchronizedBy("thread safe data structure, consistent locking when used")
protected final JumpFunctions<N,D> jumpFn;
@SynchronizedBy("thread safe data structure, only modified internally")
protected final I icfg;
//stores summaries that were queried before they were computed
//see CC 2010 paper by Naeem, Lhotak and Rodriguez
@SynchronizedBy("consistent lock on 'incoming'")
protected final MyConcurrentHashMap<Pair<M,D>,Set<Pair<N,D>>> endSummary =
new MyConcurrentHashMap<Pair<M,D>, Set<Pair<N,D>>>();
//edges going along calls
//see CC 2010 paper by Naeem, Lhotak and Rodriguez
@SynchronizedBy("consistent lock on field")
protected final MyConcurrentHashMap<Pair<M,D>,MyConcurrentHashMap<N,Set<D>>> incoming =
new MyConcurrentHashMap<Pair<M,D>,MyConcurrentHashMap<N,Set<D>>>();
@DontSynchronize("stateless")
protected final FlowFunctions<N, D, M> flowFunctions;
@DontSynchronize("only used by single thread")
protected final Map<N,Set<D>> initialSeeds;
@DontSynchronize("benign races")
public long propagationCount;
@DontSynchronize("stateless")
protected final D zeroValue;
@DontSynchronize("readOnly")
protected final FlowFunctionCache<N,D,M> ffCache;
@DontSynchronize("readOnly")
protected final boolean followReturnsPastSeeds;
/**
* Creates a solver for the given problem, which caches flow functions and edge functions.
* The solver must then be started by calling {@link #solve()}.
*/
public IFDSSolver(IFDSTabulationProblem<N,D,M,I> tabulationProblem) {
this(tabulationProblem, DEFAULT_CACHE_BUILDER);
}
/**
* Creates a solver for the given problem, constructing caches with the given {@link CacheBuilder}. The solver must then be started by calling
* {@link #solve()}.
* @param flowFunctionCacheBuilder A valid {@link CacheBuilder} or <code>null</code> if no caching is to be used for flow functions.
* @param edgeFunctionCacheBuilder A valid {@link CacheBuilder} or <code>null</code> if no caching is to be used for edge functions.
*/
public IFDSSolver(IFDSTabulationProblem<N,D,M,I> tabulationProblem, @SuppressWarnings("rawtypes") CacheBuilder flowFunctionCacheBuilder) {
if(logger.isDebugEnabled())
flowFunctionCacheBuilder = flowFunctionCacheBuilder.recordStats();
this.zeroValue = tabulationProblem.zeroValue();
this.icfg = tabulationProblem.interproceduralCFG();
FlowFunctions<N, D, M> flowFunctions = tabulationProblem.autoAddZero() ?
new ZeroedFlowFunctions<N,D,M>(tabulationProblem.flowFunctions(), tabulationProblem.zeroValue()) : tabulationProblem.flowFunctions();
if(flowFunctionCacheBuilder!=null) {
ffCache = new FlowFunctionCache<N,D,M>(flowFunctions, flowFunctionCacheBuilder);
flowFunctions = ffCache;
} else {
ffCache = null;
}
this.flowFunctions = flowFunctions;
this.initialSeeds = tabulationProblem.initialSeeds();
this.jumpFn = new JumpFunctions<N,D>();
this.followReturnsPastSeeds = tabulationProblem.followReturnsPastSeeds();
this.numThreads = Math.max(1,tabulationProblem.numThreads());
this.executor = getExecutor();
}
/**
* Runs the solver on the configured problem. This can take some time.
*/
public void solve() {
submitInitialSeeds();
awaitCompletionComputeValuesAndShutdown();
}
/**
* Schedules the processing of initial seeds, initiating the analysis.
* Clients should only call this methods if performing synchronization on
* their own. Normally, {@link #solve()} should be called instead.
*/
protected void submitInitialSeeds() {
for(Entry<N, Set<D>> seed: initialSeeds.entrySet()) {
N startPoint = seed.getKey();
for(D val: seed.getValue())
propagate(zeroValue, startPoint, val, null, false);
jumpFn.addFunction(new WeakPathEdge<N, D>(zeroValue, startPoint, zeroValue));
}
}
/**
* Awaits the completion of the exploded super graph. When complete, computes result values,
* shuts down the executor and returns.
*/
protected void awaitCompletionComputeValuesAndShutdown() {
{
//run executor and await termination of tasks
runExecutorAndAwaitCompletion();
}
if(logger.isDebugEnabled())
printStats();
//ask executor to shut down;
//this will cause new submissions to the executor to be rejected,
//but at this point all tasks should have completed anyway
executor.shutdown();
//similarly here: we await termination, but this should happen instantaneously,
//as all tasks should have completed
runExecutorAndAwaitCompletion();
}
/**
* Runs execution, re-throwing exceptions that might be thrown during its execution.
*/
private void runExecutorAndAwaitCompletion() {
try {
executor.awaitCompletion();
} catch (InterruptedException e) {
e.printStackTrace();
}
Throwable exception = executor.getException();
if(exception!=null) {
throw new RuntimeException("There were exceptions during IDE analysis. Exiting.",exception);
}
}
/**
* Dispatch the processing of a given edge. It may be executed in a different thread.
* @param edge the edge to process
*/
protected void scheduleEdgeProcessing(PathEdge<N,D> edge){
// If the executor has been killed, there is little point
// in submitting new tasks
if (executor.isTerminating())
return;
executor.execute(new PathEdgeProcessingTask(edge));
propagationCount++;
}
/**
* Lines 13-20 of the algorithm; processing a call site in the caller's context.
*
* For each possible callee, registers incoming call edges.
* Also propagates call-to-return flows and summarized callee flows within the caller.
*
* @param edge an edge whose target node resembles a method call
*/
private void processCall(PathEdge<N,D> edge) {
final D d1 = edge.factAtSource();
final N n = edge.getTarget(); // a call node; line 14...
logger.trace("Processing call to {}", n);
final D d2 = edge.factAtTarget();
assert d2 != null;
Collection<N> returnSiteNs = icfg.getReturnSitesOfCallAt(n);
//for each possible callee
Set<M> callees = icfg.getCalleesOfCallAt(n);
for(M sCalledProcN: callees) { //still line 14
//compute the call-flow function
FlowFunction<D> function = flowFunctions.getCallFlowFunction(n, sCalledProcN);
Set<D> res = computeCallFlowFunction(function, d1, d2);
Collection<N> startPointsOf = icfg.getStartPointsOf(sCalledProcN);
//for each result node of the call-flow function
for(D d3: res) {
//for each callee's start point(s)
for(N sP: startPointsOf) {
//create initial self-loop
propagate(d3, sP, d3, n, false); //line 15
}
//register the fact that <sp,d3> has an incoming edge from <n,d2>
//line 15.1 of Naeem/Lhotak/Rodriguez
if (!addIncoming(sCalledProcN,d3,n,d1))
continue;
//line 15.2
Set<Pair<N, D>> endSumm = endSummary(sCalledProcN, d3);
//still line 15.2 of Naeem/Lhotak/Rodriguez
//for each already-queried exit value <eP,d4> reachable from <sP,d3>,
//create new caller-side jump functions to the return sites
//because we have observed a potentially new incoming edge into <sP,d3>
if (endSumm != null)
for(Pair<N, D> entry: endSumm) {
N eP = entry.getO1();
D d4 = entry.getO2();
//for each return site
for(N retSiteN: returnSiteNs) {
//compute return-flow function
FlowFunction<D> retFunction = flowFunctions.getReturnFlowFunction(n, sCalledProcN, eP, retSiteN);
//for each target value of the function
for(D d5: computeReturnFlowFunction(retFunction, d4, n, Collections.singleton(d2)))
propagate(d1, retSiteN, d5, n, false);
}
}
}
}
//line 17-19 of Naeem/Lhotak/Rodriguez
//process intra-procedural flows along call-to-return flow functions
for (N returnSiteN : returnSiteNs) {
FlowFunction<D> callToReturnFlowFunction = flowFunctions.getCallToReturnFlowFunction(n, returnSiteN);
for(D d3: computeCallToReturnFlowFunction(callToReturnFlowFunction, d1, d2))
propagate(d1, returnSiteN, d3, n, false);
}
}
/**
* Computes the call flow function for the given call-site abstraction
* @param callFlowFunction The call flow function to compute
* @param d1 The abstraction at the current method's start node.
* @param d2 The abstraction at the call site
* @return The set of caller-side abstractions at the callee's start node
*/
protected Set<D> computeCallFlowFunction
(FlowFunction<D> callFlowFunction, D d1, D d2) {
return callFlowFunction.computeTargets(d2);
}
/**
* Computes the call-to-return flow function for the given call-site
* abstraction
* @param callToReturnFlowFunction The call-to-return flow function to
* compute
* @param d1 The abstraction at the current method's start node.
* @param d2 The abstraction at the call site
* @return The set of caller-side abstractions at the return site
*/
protected Set<D> computeCallToReturnFlowFunction
(FlowFunction<D> callToReturnFlowFunction, D d1, D d2) {
return callToReturnFlowFunction.computeTargets(d2);
}
/**
* Lines 21-32 of the algorithm.
*
* Stores callee-side summaries.
* Also, at the side of the caller, propagates intra-procedural flows to return sites
* using those newly computed summaries.
*
* @param edge an edge whose target node resembles a method exits
*/
protected void processExit(PathEdge<N,D> edge) {
final N n = edge.getTarget(); // an exit node; line 21...
M methodThatNeedsSummary = icfg.getMethodOf(n);
final D d1 = edge.factAtSource();
final D d2 = edge.factAtTarget();
//for each of the method's start points, determine incoming calls
//line 21.1 of Naeem/Lhotak/Rodriguez
//register end-summary
if (!addEndSummary(methodThatNeedsSummary, d1, n, d2))
return;
Map<N,Set<D>> inc = incoming(d1, methodThatNeedsSummary);
//for each incoming call edge already processed
//(see processCall(..))
if (inc != null)
for (Entry<N,Set<D>> entry: inc.entrySet()) {
//line 22
N c = entry.getKey();
//for each return site
for(N retSiteC: icfg.getReturnSitesOfCallAt(c)) {
//compute return-flow function
FlowFunction<D> retFunction = flowFunctions.getReturnFlowFunction(c, methodThatNeedsSummary,n,retSiteC);
Set<D> targets = computeReturnFlowFunction(retFunction, d2, c, entry.getValue());
//for each incoming-call value
for(D d4: entry.getValue())
for(D d5: targets)
propagate(d4, retSiteC, d5, c, false);
}
}
//handling for unbalanced problems where we return out of a method with a fact for which we have no incoming flow
//note: we propagate that way only values that originate from ZERO, as conditionally generated values should only
//be propagated into callers that have an incoming edge for this condition
if(followReturnsPastSeeds && (inc == null || inc.isEmpty()) && d1.equals(zeroValue)) {
Set<N> callers = icfg.getCallersOf(methodThatNeedsSummary);
for(N c: callers) {
for(N retSiteC: icfg.getReturnSitesOfCallAt(c)) {
FlowFunction<D> retFunction = flowFunctions.getReturnFlowFunction(c, methodThatNeedsSummary,n,retSiteC);
Set<D> targets = computeReturnFlowFunction(retFunction, d2, c, Collections.singleton(zeroValue));
for(D d5: targets)
propagate(zeroValue, retSiteC, d5, c, true);
}
}
//in cases where there are no callers, the return statement would normally not be processed at all;
//this might be undesirable if the flow function has a side effect such as registering a taint;
//instead we thus call the return flow function will a null caller
if(callers.isEmpty()) {
FlowFunction<D> retFunction = flowFunctions.getReturnFlowFunction(null, methodThatNeedsSummary,n,null);
retFunction.computeTargets(d2);
}
}
}
/**
* Computes the return flow function for the given set of caller-side
* abstractions.
* @param retFunction The return flow function to compute
* @param d2 The abstraction at the exit node in the callee
* @param callSite The call site
* @param callerSideDs The abstractions at the call site
* @return The set of caller-side abstractions at the return site
*/
protected Set<D> computeReturnFlowFunction
(FlowFunction<D> retFunction, D d2, N callSite, Collection<D> callerSideDs) {
return retFunction.computeTargets(d2);
}
/**
* Lines 33-37 of the algorithm.
* Simply propagate normal, intra-procedural flows.
* @param edge
*/
private void processNormalFlow(PathEdge<N,D> edge) {
final D d1 = edge.factAtSource();
final N n = edge.getTarget();
final D d2 = edge.factAtTarget();
for (N m : icfg.getSuccsOf(n)) {
FlowFunction<D> flowFunction = flowFunctions.getNormalFlowFunction(n,m);
Set<D> res = computeNormalFlowFunction(flowFunction, d1, d2);
for (D d3 : res)
propagate(d1, m, d3, null, false);
}
}
/**
* Computes the normal flow function for the given set of start and end
* abstractions.
* @param flowFunction The normal flow function to compute
* @param d1 The abstraction at the method's start node
* @param d1 The abstraction at the current node
* @return The set of abstractions at the successor node
*/
protected Set<D> computeNormalFlowFunction
(FlowFunction<D> flowFunction, D d1, D d2) {
return flowFunction.computeTargets(d2);
}
/**
* Propagates the flow further down the exploded super graph.
* @param sourceVal the source value of the propagated summary edge
* @param target the target statement
* @param targetVal the target value at the target statement
* @param relatedCallSite for call and return flows the related call statement, <code>null</code> otherwise
* (this value is not used within this implementation but may be useful for subclasses of {@link IFDSSolver})
* @param isUnbalancedReturn <code>true</code> if this edge is propagating an unbalanced return
* (this value is not used within this implementation but may be useful for subclasses of {@link IFDSSolver})
*/
protected void propagate(D sourceVal, N target, D targetVal,
/* deliberately exposed to clients */ N relatedCallSite,
/* deliberately exposed to clients */ boolean isUnbalancedReturn) {
final PathEdge<N,D> edge = new PathEdge<N,D>(sourceVal, target, targetVal);
final D existingVal = isMergePoint(target) ?
jumpFn.addFunction(new WeakPathEdge<N, D>(sourceVal, target, targetVal)) : null;
if (existingVal != null) {
if (existingVal != targetVal)
existingVal.addNeighbor(targetVal);
}
else {
scheduleEdgeProcessing(edge);
if(targetVal!=zeroValue)
logger.trace("EDGE: <{},{}> -> <{},{}>", icfg.getMethodOf(target), sourceVal, target, targetVal);
}
}
/**
* Gets whether the given unit is a merge point in the ICFG
* @param target The unit to check
* @return True if the given unit is a merge point in the ICFG, otherwise
* false
*/
private boolean isMergePoint(N target) {
if (icfg.isStartPoint(target))
return true;
if (icfg.getPredsOf(target).size() > 1)
return true;
return false;
}
private Set<Pair<N, D>> endSummary(M m, D d3) {
Set<Pair<N, D>> map = endSummary.get(new Pair<M, D>(m, d3));
return map;
}
private boolean addEndSummary(M m, D d1, N eP, D d2) {
Set<Pair<N, D>> summaries = endSummary.putIfAbsentElseGet
(new Pair<M, D>(m, d1), new ConcurrentHashSet<Pair<N, D>>());
return summaries.add(new Pair<N, D>(eP, d2));
}
protected Map<N, Set<D>> incoming(D d1, M m) {
Map<N, Set<D>> map = incoming.get(new Pair<M, D>(m, d1));
return map;
}
protected boolean addIncoming(M m, D d3, N n, D d2) {
MyConcurrentHashMap<N, Set<D>> summaries = incoming.putIfAbsentElseGet
(new Pair<M, D>(m, d3), new MyConcurrentHashMap<N, Set<D>>());
Set<D> set = summaries.putIfAbsentElseGet(n, new ConcurrentHashSet<D>());
return set.add(d2);
}
/**
* Factory method for this solver's thread-pool executor.
*/
protected CountingThreadPoolExecutor getExecutor() {
return new CountingThreadPoolExecutor(1, this.numThreads, 30, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
}
/**
* Returns a String used to identify the output of this solver in debug mode.
* Subclasses can overwrite this string to distinguish the output from different solvers.
*/
protected String getDebugName() {
return "FAST IFDS SOLVER";
}
public void printStats() {
if(logger.isDebugEnabled()) {
if(ffCache!=null)
ffCache.printStats();
} else {
logger.info("No statistics were collected, as DEBUG is disabled.");
}
}
private class PathEdgeProcessingTask implements Runnable {
private final PathEdge<N,D> edge;
public PathEdgeProcessingTask(PathEdge<N,D> edge) {
this.edge = edge;
}
public void run() {
if(icfg.isCallStmt(edge.getTarget())) {
processCall(edge);
} else {
//note that some statements, such as "throw" may be
//both an exit statement and a "normal" statement
if(icfg.isExitStmt(edge.getTarget())) {
processExit(edge);
}
if(!icfg.getSuccsOf(edge.getTarget()).isEmpty()) {
processNormalFlow(edge);
}
}
}
}
}
|
src/soot/jimple/infoflow/solver/fastSolver/IFDSSolver.java
|
/*******************************************************************************
* Copyright (c) 2012 Eric Bodden.
* Copyright (c) 2013 Tata Consultancy Services & Ecole Polytechnique de Montreal
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* Eric Bodden - initial API and implementation
* Marc-Andre Laverdiere-Papineau - Fixed race condition
******************************************************************************/
package soot.jimple.infoflow.solver.fastSolver;
import heros.DontSynchronize;
import heros.FlowFunction;
import heros.FlowFunctionCache;
import heros.FlowFunctions;
import heros.IFDSTabulationProblem;
import heros.InterproceduralCFG;
import heros.SynchronizedBy;
import heros.ZeroedFlowFunctions;
import heros.solver.CountingThreadPoolExecutor;
import heros.solver.LinkedNode;
import heros.solver.Pair;
import heros.solver.PathEdge;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.SootMethod;
import soot.Unit;
import soot.jimple.infoflow.util.ConcurrentHashSet;
import soot.jimple.infoflow.util.MyConcurrentHashMap;
import com.google.common.cache.CacheBuilder;
/**
* A solver for an {@link IFDSTabulationProblem}. This solver is not based on the IDESolver
* implementation in Heros for performance reasons.
*
* @param <N> The type of nodes in the interprocedural control-flow graph. Typically {@link Unit}.
* @param <D> The type of data-flow facts to be computed by the tabulation problem.
* @param <M> The type of objects used to represent methods. Typically {@link SootMethod}.
* @param <I> The type of inter-procedural control-flow graph being used.
* @see IFDSTabulationProblem
*/
public class IFDSSolver<N,D extends LinkedNode<D>,M,I extends InterproceduralCFG<N, M>> {
public static CacheBuilder<Object, Object> DEFAULT_CACHE_BUILDER = CacheBuilder.newBuilder().concurrencyLevel
(Runtime.getRuntime().availableProcessors()).initialCapacity(10000).softValues();
protected static final Logger logger = LoggerFactory.getLogger(IFDSSolver.class);
//enable with -Dorg.slf4j.simpleLogger.defaultLogLevel=trace
public static final boolean DEBUG = logger.isDebugEnabled();
protected CountingThreadPoolExecutor executor;
@DontSynchronize("only used by single thread")
protected int numThreads;
@SynchronizedBy("thread safe data structure, consistent locking when used")
protected final JumpFunctions<N,D> jumpFn;
@SynchronizedBy("thread safe data structure, only modified internally")
protected final I icfg;
//stores summaries that were queried before they were computed
//see CC 2010 paper by Naeem, Lhotak and Rodriguez
@SynchronizedBy("consistent lock on 'incoming'")
protected final MyConcurrentHashMap<Pair<M,D>,Set<Pair<N,D>>> endSummary =
new MyConcurrentHashMap<Pair<M,D>, Set<Pair<N,D>>>();
//edges going along calls
//see CC 2010 paper by Naeem, Lhotak and Rodriguez
@SynchronizedBy("consistent lock on field")
protected final MyConcurrentHashMap<Pair<M,D>,MyConcurrentHashMap<N,Set<D>>> incoming =
new MyConcurrentHashMap<Pair<M,D>,MyConcurrentHashMap<N,Set<D>>>();
@DontSynchronize("stateless")
protected final FlowFunctions<N, D, M> flowFunctions;
@DontSynchronize("only used by single thread")
protected final Map<N,Set<D>> initialSeeds;
@DontSynchronize("benign races")
public long propagationCount;
@DontSynchronize("stateless")
protected final D zeroValue;
@DontSynchronize("readOnly")
protected final FlowFunctionCache<N,D,M> ffCache;
@DontSynchronize("readOnly")
protected final boolean followReturnsPastSeeds;
/**
* Creates a solver for the given problem, which caches flow functions and edge functions.
* The solver must then be started by calling {@link #solve()}.
*/
public IFDSSolver(IFDSTabulationProblem<N,D,M,I> tabulationProblem) {
this(tabulationProblem, DEFAULT_CACHE_BUILDER);
}
/**
* Creates a solver for the given problem, constructing caches with the given {@link CacheBuilder}. The solver must then be started by calling
* {@link #solve()}.
* @param flowFunctionCacheBuilder A valid {@link CacheBuilder} or <code>null</code> if no caching is to be used for flow functions.
* @param edgeFunctionCacheBuilder A valid {@link CacheBuilder} or <code>null</code> if no caching is to be used for edge functions.
*/
public IFDSSolver(IFDSTabulationProblem<N,D,M,I> tabulationProblem, @SuppressWarnings("rawtypes") CacheBuilder flowFunctionCacheBuilder) {
if(logger.isDebugEnabled())
flowFunctionCacheBuilder = flowFunctionCacheBuilder.recordStats();
this.zeroValue = tabulationProblem.zeroValue();
this.icfg = tabulationProblem.interproceduralCFG();
FlowFunctions<N, D, M> flowFunctions = tabulationProblem.autoAddZero() ?
new ZeroedFlowFunctions<N,D,M>(tabulationProblem.flowFunctions(), tabulationProblem.zeroValue()) : tabulationProblem.flowFunctions();
if(flowFunctionCacheBuilder!=null) {
ffCache = new FlowFunctionCache<N,D,M>(flowFunctions, flowFunctionCacheBuilder);
flowFunctions = ffCache;
} else {
ffCache = null;
}
this.flowFunctions = flowFunctions;
this.initialSeeds = tabulationProblem.initialSeeds();
this.jumpFn = new JumpFunctions<N,D>();
this.followReturnsPastSeeds = tabulationProblem.followReturnsPastSeeds();
this.numThreads = Math.max(1,tabulationProblem.numThreads());
this.executor = getExecutor();
}
/**
* Runs the solver on the configured problem. This can take some time.
*/
public void solve() {
submitInitialSeeds();
awaitCompletionComputeValuesAndShutdown();
}
/**
* Schedules the processing of initial seeds, initiating the analysis.
* Clients should only call this methods if performing synchronization on
* their own. Normally, {@link #solve()} should be called instead.
*/
protected void submitInitialSeeds() {
for(Entry<N, Set<D>> seed: initialSeeds.entrySet()) {
N startPoint = seed.getKey();
for(D val: seed.getValue())
propagate(zeroValue, startPoint, val, null, false);
jumpFn.addFunction(new WeakPathEdge<N, D>(zeroValue, startPoint, zeroValue));
}
}
/**
* Awaits the completion of the exploded super graph. When complete, computes result values,
* shuts down the executor and returns.
*/
protected void awaitCompletionComputeValuesAndShutdown() {
{
//run executor and await termination of tasks
runExecutorAndAwaitCompletion();
}
if(logger.isDebugEnabled())
printStats();
//ask executor to shut down;
//this will cause new submissions to the executor to be rejected,
//but at this point all tasks should have completed anyway
executor.shutdown();
//similarly here: we await termination, but this should happen instantaneously,
//as all tasks should have completed
runExecutorAndAwaitCompletion();
}
/**
* Runs execution, re-throwing exceptions that might be thrown during its execution.
*/
private void runExecutorAndAwaitCompletion() {
try {
executor.awaitCompletion();
} catch (InterruptedException e) {
e.printStackTrace();
}
Throwable exception = executor.getException();
if(exception!=null) {
throw new RuntimeException("There were exceptions during IDE analysis. Exiting.",exception);
}
}
/**
* Dispatch the processing of a given edge. It may be executed in a different thread.
* @param edge the edge to process
*/
protected void scheduleEdgeProcessing(PathEdge<N,D> edge){
// If the executor has been killed, there is little point
// in submitting new tasks
if (executor.isTerminating())
return;
executor.execute(new PathEdgeProcessingTask(edge));
propagationCount++;
}
/**
* Lines 13-20 of the algorithm; processing a call site in the caller's context.
*
* For each possible callee, registers incoming call edges.
* Also propagates call-to-return flows and summarized callee flows within the caller.
*
* @param edge an edge whose target node resembles a method call
*/
private void processCall(PathEdge<N,D> edge) {
final D d1 = edge.factAtSource();
final N n = edge.getTarget(); // a call node; line 14...
logger.trace("Processing call to {}", n);
final D d2 = edge.factAtTarget();
assert d2 != null;
Collection<N> returnSiteNs = icfg.getReturnSitesOfCallAt(n);
//for each possible callee
Set<M> callees = icfg.getCalleesOfCallAt(n);
for(M sCalledProcN: callees) { //still line 14
//compute the call-flow function
FlowFunction<D> function = flowFunctions.getCallFlowFunction(n, sCalledProcN);
Set<D> res = computeCallFlowFunction(function, d1, d2);
Collection<N> startPointsOf = icfg.getStartPointsOf(sCalledProcN);
//for each result node of the call-flow function
for(D d3: res) {
//for each callee's start point(s)
for(N sP: startPointsOf) {
//create initial self-loop
propagate(d3, sP, d3, n, false); //line 15
}
//register the fact that <sp,d3> has an incoming edge from <n,d2>
//line 15.1 of Naeem/Lhotak/Rodriguez
if (!addIncoming(sCalledProcN,d3,n,d1))
continue;
//line 15.2
Set<Pair<N, D>> endSumm = endSummary(sCalledProcN, d3);
//still line 15.2 of Naeem/Lhotak/Rodriguez
//for each already-queried exit value <eP,d4> reachable from <sP,d3>,
//create new caller-side jump functions to the return sites
//because we have observed a potentially new incoming edge into <sP,d3>
if (endSumm != null)
for(Pair<N, D> entry: endSumm) {
N eP = entry.getO1();
D d4 = entry.getO2();
//for each return site
for(N retSiteN: returnSiteNs) {
//compute return-flow function
FlowFunction<D> retFunction = flowFunctions.getReturnFlowFunction(n, sCalledProcN, eP, retSiteN);
//for each target value of the function
for(D d5: computeReturnFlowFunction(retFunction, d4, n, Collections.singleton(d2)))
propagate(d1, retSiteN, d5, n, false);
}
}
}
}
//line 17-19 of Naeem/Lhotak/Rodriguez
//process intra-procedural flows along call-to-return flow functions
for (N returnSiteN : returnSiteNs) {
FlowFunction<D> callToReturnFlowFunction = flowFunctions.getCallToReturnFlowFunction(n, returnSiteN);
for(D d3: computeCallToReturnFlowFunction(callToReturnFlowFunction, d1, d2))
propagate(d1, returnSiteN, d3, n, false);
}
}
/**
* Computes the call flow function for the given call-site abstraction
* @param callFlowFunction The call flow function to compute
* @param d1 The abstraction at the current method's start node.
* @param d2 The abstraction at the call site
* @return The set of caller-side abstractions at the callee's start node
*/
protected Set<D> computeCallFlowFunction
(FlowFunction<D> callFlowFunction, D d1, D d2) {
return callFlowFunction.computeTargets(d2);
}
/**
* Computes the call-to-return flow function for the given call-site
* abstraction
* @param callToReturnFlowFunction The call-to-return flow function to
* compute
* @param d1 The abstraction at the current method's start node.
* @param d2 The abstraction at the call site
* @return The set of caller-side abstractions at the return site
*/
protected Set<D> computeCallToReturnFlowFunction
(FlowFunction<D> callToReturnFlowFunction, D d1, D d2) {
return callToReturnFlowFunction.computeTargets(d2);
}
/**
* Lines 21-32 of the algorithm.
*
* Stores callee-side summaries.
* Also, at the side of the caller, propagates intra-procedural flows to return sites
* using those newly computed summaries.
*
* @param edge an edge whose target node resembles a method exits
*/
protected void processExit(PathEdge<N,D> edge) {
final N n = edge.getTarget(); // an exit node; line 21...
M methodThatNeedsSummary = icfg.getMethodOf(n);
final D d1 = edge.factAtSource();
final D d2 = edge.factAtTarget();
//for each of the method's start points, determine incoming calls
//line 21.1 of Naeem/Lhotak/Rodriguez
//register end-summary
if (!addEndSummary(methodThatNeedsSummary, d1, n, d2))
return;
Map<N,Set<D>> inc = incoming(d1, methodThatNeedsSummary);
//for each incoming call edge already processed
//(see processCall(..))
if (inc != null)
for (Entry<N,Set<D>> entry: inc.entrySet()) {
//line 22
N c = entry.getKey();
//for each return site
for(N retSiteC: icfg.getReturnSitesOfCallAt(c)) {
//compute return-flow function
FlowFunction<D> retFunction = flowFunctions.getReturnFlowFunction(c, methodThatNeedsSummary,n,retSiteC);
Set<D> targets = computeReturnFlowFunction(retFunction, d2, c, entry.getValue());
//for each incoming-call value
for(D d4: entry.getValue())
for(D d5: targets)
propagate(d4, retSiteC, d5, c, false);
}
}
//handling for unbalanced problems where we return out of a method with a fact for which we have no incoming flow
//note: we propagate that way only values that originate from ZERO, as conditionally generated values should only
//be propagated into callers that have an incoming edge for this condition
if(followReturnsPastSeeds && (inc == null || inc.isEmpty()) && d1.equals(zeroValue)) {
Set<N> callers = icfg.getCallersOf(methodThatNeedsSummary);
for(N c: callers) {
for(N retSiteC: icfg.getReturnSitesOfCallAt(c)) {
FlowFunction<D> retFunction = flowFunctions.getReturnFlowFunction(c, methodThatNeedsSummary,n,retSiteC);
Set<D> targets = computeReturnFlowFunction(retFunction, d2, c, Collections.singleton(zeroValue));
for(D d5: targets)
propagate(zeroValue, retSiteC, d5, c, true);
}
}
//in cases where there are no callers, the return statement would normally not be processed at all;
//this might be undesirable if the flow function has a side effect such as registering a taint;
//instead we thus call the return flow function will a null caller
if(callers.isEmpty()) {
FlowFunction<D> retFunction = flowFunctions.getReturnFlowFunction(null, methodThatNeedsSummary,n,null);
retFunction.computeTargets(d2);
}
}
}
/**
* Computes the return flow function for the given set of caller-side
* abstractions.
* @param retFunction The return flow function to compute
* @param d2 The abstraction at the exit node in the callee
* @param callSite The call site
* @param callerSideDs The abstractions at the call site
* @return The set of caller-side abstractions at the return site
*/
protected Set<D> computeReturnFlowFunction
(FlowFunction<D> retFunction, D d2, N callSite, Collection<D> callerSideDs) {
return retFunction.computeTargets(d2);
}
/**
* Lines 33-37 of the algorithm.
* Simply propagate normal, intra-procedural flows.
* @param edge
*/
private void processNormalFlow(PathEdge<N,D> edge) {
final D d1 = edge.factAtSource();
final N n = edge.getTarget();
final D d2 = edge.factAtTarget();
for (N m : icfg.getSuccsOf(n)) {
FlowFunction<D> flowFunction = flowFunctions.getNormalFlowFunction(n,m);
Set<D> res = computeNormalFlowFunction(flowFunction, d1, d2);
for (D d3 : res)
propagate(d1, m, d3, null, false);
}
}
/**
* Computes the normal flow function for the given set of start and end
* abstractions.
* @param flowFunction The normal flow function to compute
* @param d1 The abstraction at the method's start node
* @param d1 The abstraction at the current node
* @return The set of abstractions at the successor node
*/
protected Set<D> computeNormalFlowFunction
(FlowFunction<D> flowFunction, D d1, D d2) {
return flowFunction.computeTargets(d2);
}
/**
* Propagates the flow further down the exploded super graph.
* @param sourceVal the source value of the propagated summary edge
* @param target the target statement
* @param targetVal the target value at the target statement
* @param relatedCallSite for call and return flows the related call statement, <code>null</code> otherwise
* (this value is not used within this implementation but may be useful for subclasses of {@link IFDSSolver})
* @param isUnbalancedReturn <code>true</code> if this edge is propagating an unbalanced return
* (this value is not used within this implementation but may be useful for subclasses of {@link IFDSSolver})
*/
protected void propagate(D sourceVal, N target, D targetVal,
/* deliberately exposed to clients */ N relatedCallSite,
/* deliberately exposed to clients */ boolean isUnbalancedReturn) {
final PathEdge<N,D> edge = new PathEdge<N,D>(sourceVal, target, targetVal);
final D existingVal = jumpFn.addFunction(new WeakPathEdge<N, D>(sourceVal, target, targetVal));
if (existingVal != null) {
if (existingVal != targetVal)
existingVal.addNeighbor(targetVal);
}
else {
scheduleEdgeProcessing(edge);
if(targetVal!=zeroValue)
logger.trace("EDGE: <{},{}> -> <{},{}>", icfg.getMethodOf(target), sourceVal, target, targetVal);
}
}
private Set<Pair<N, D>> endSummary(M m, D d3) {
Set<Pair<N, D>> map = endSummary.get(new Pair<M, D>(m, d3));
return map;
}
private boolean addEndSummary(M m, D d1, N eP, D d2) {
Set<Pair<N, D>> summaries = endSummary.putIfAbsentElseGet
(new Pair<M, D>(m, d1), new ConcurrentHashSet<Pair<N, D>>());
return summaries.add(new Pair<N, D>(eP, d2));
}
protected Map<N, Set<D>> incoming(D d1, M m) {
Map<N, Set<D>> map = incoming.get(new Pair<M, D>(m, d1));
return map;
}
protected boolean addIncoming(M m, D d3, N n, D d2) {
MyConcurrentHashMap<N, Set<D>> summaries = incoming.putIfAbsentElseGet
(new Pair<M, D>(m, d3), new MyConcurrentHashMap<N, Set<D>>());
Set<D> set = summaries.putIfAbsentElseGet(n, new ConcurrentHashSet<D>());
return set.add(d2);
}
/**
* Factory method for this solver's thread-pool executor.
*/
protected CountingThreadPoolExecutor getExecutor() {
return new CountingThreadPoolExecutor(1, this.numThreads, 30, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
}
/**
* Returns a String used to identify the output of this solver in debug mode.
* Subclasses can overwrite this string to distinguish the output from different solvers.
*/
protected String getDebugName() {
return "FAST IFDS SOLVER";
}
public void printStats() {
if(logger.isDebugEnabled()) {
if(ffCache!=null)
ffCache.printStats();
} else {
logger.info("No statistics were collected, as DEBUG is disabled.");
}
}
private class PathEdgeProcessingTask implements Runnable {
private final PathEdge<N,D> edge;
public PathEdgeProcessingTask(PathEdge<N,D> edge) {
this.edge = edge;
}
public void run() {
if(icfg.isCallStmt(edge.getTarget())) {
processCall(edge);
} else {
//note that some statements, such as "throw" may be
//both an exit statement and a "normal" statement
if(icfg.isExitStmt(edge.getTarget())) {
processExit(edge);
}
if(!icfg.getSuccsOf(edge.getTarget()).isEmpty()) {
processNormalFlow(edge);
}
}
}
}
}
|
not saving non-merge points to jumpFn any more
|
src/soot/jimple/infoflow/solver/fastSolver/IFDSSolver.java
|
not saving non-merge points to jumpFn any more
|
|
Java
|
apache-2.0
|
8b127135775d5ced980655b048e14b720a76ff08
| 0
|
statsbiblioteket/doms-bitstorage,statsbiblioteket/doms-bitstorage,statsbiblioteket/doms-bitstorage
|
/*
* $Id$
* $Revision$
* $Date$
* $Author$
*
* The DOMS project.
* Copyright (C) 2007-2010 The State and University Library
*
* 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 dk.statsbiblioteket.doms.bitstorage.lowlevel.frontend;
import com.sun.xml.ws.developer.StreamingDataHandler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import dk.statsbiblioteket.doms.bitstorage.lowlevel.backend.Bitstorage;
import dk.statsbiblioteket.doms.bitstorage.lowlevel.backend.BitstorageFactory;
import dk.statsbiblioteket.doms.bitstorage.lowlevel.backend.exceptions.BitstorageException;
import dk.statsbiblioteket.doms.bitstorage.lowlevel.*;
import dk.statsbiblioteket.util.qa.QAInfo;
import javax.activation.DataHandler;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.xml.ws.WebServiceException;
import javax.xml.ws.soap.MTOM;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Web service that exposes a low level bitstorage.
* This class handles communication with SOAP and delegating calls to the
* underlying bitstorage. Exceptions are logged and delegated as SOAP faults.
*/
@MTOM
@WebService(
endpointInterface = "dk.statsbiblioteket.doms.bitstorage.lowlevel.LowlevelBitstorageSoapWebservice")
@QAInfo(author = "abr",
reviewers = "kfc",
level = QAInfo.Level.NORMAL,
state = QAInfo.State.QA_OK)
public class LowlevelBitstorageSoapWebserviceImpl
implements LowlevelBitstorageSoapWebservice {
/**
* An exception mapper that maps exceptions from the underlying bitstorage
* to SOAP faults.
*/
private BitstorageToLowlevelExceptionMapper bitstorageMapper
= new BitstorageToLowlevelExceptionMapper();
/**
* The logger for this class.
*/
private static final Log LOG
= LogFactory.getLog(LowlevelBitstorageSoapWebserviceImpl.class);
/**
* Upload the provided file for later approval, for details, see
* {@link Bitstorage#upload(String, InputStream, String, long)}.
* <p/>
* The data for the file should be streamed to the underlying service.
* <p/>
* This method works as a fault barrier, handling exceptions by converting
* them to relecant SOAP faults.
*
* @param filename The name to give the file to upload.
* @param filedata The data for the file.
* @param md5String MD5 checksum of the data.
* @param filelength Size of the data.
* @return The checksum calculated by the server.
* @throws ChecksumFailedException If the server calculated a different
* checksum than the given checksum
* @throws CommunicationException On generic trouble communicating with the
* underlying script.
* @throws NotEnoughFreeSpaceException If there is not enough space to store
* the file.
* @throws FileIsLockedException If the file is locked by another operation.
* @throws LowlevelSoapException On internal errors that are not correctly
* mapped to SOAP faults. Should never happen.
* @throws WebServiceException On other unclassified errors. Should never
* happen.
*/
@WebMethod
public String uploadFile(@WebParam(name = "filename",
targetNamespace = "")
String filename,
@WebParam(name = "filedata",
targetNamespace = "")
DataHandler filedata,
@WebParam(name = "md5string",
targetNamespace = "")
String md5String,
@WebParam(name = "filelength",
targetNamespace = "")
long filelength)
throws ChecksumFailedException, CommunicationException,
NotEnoughFreeSpaceException, FileIsLockedException,
LowlevelSoapException, WebServiceException {
LOG.trace("Enter uploadFile('" + filename + "','" + filedata + "','"
+ md5String + "','" + filelength + "')");
String errorMessage = "Trouble while uploading file '" + filename + "'";
try {
Bitstorage bs = BitstorageFactory.getInstance();
InputStream data;
if (filedata instanceof StreamingDataHandler) {
LOG.trace("Reading data for file '" + filedata
+ "' as streaming data");
data = ((StreamingDataHandler) filedata).readOnce();
} else {
LOG.trace("Reading data for file '" + filedata
+ "' as non-streaming data");
data = filedata.getInputStream();
}
try {
return bs.upload(filename, data, md5String, filelength)
.toString();
} finally {
LOG.trace("Function over, returning");
data.close();
LOG.trace("data stream closed");
}
} catch (BitstorageException e) {
LOG.error(errorMessage, e);
throw bitstorageMapper.convertMostApplicable(e);
} catch (Exception e) {
LOG.error(errorMessage, e);
throw new WebServiceException(errorMessage + ": " + e, e);
}
}
/**
* Remove a file that has not yet been approved, for details see
* {@link Bitstorage#disapprove(URL)}.
* <p/>
* This method works as a fault barrier, handling exceptions by converting
* them to relecant SOAP faults.
*
* @param fileurl The url of the file to disapprove.
* @throws CommunicationException On generic trouble communicating with the
* underlying script.
* @throws FileIsLockedException If the file is locked by another operation.
* @throws LowlevelSoapException On internal errors that are not correctly
* mapped to SOAP faults. Should never happen.
* @throws WebServiceException On other unclassified errors. Should never
* happen.
*/
@WebMethod
public void disapprove(@WebParam(name = "fileurl",
targetNamespace = "") String fileurl)
throws FileIsLockedException,
CommunicationException,
LowlevelSoapException,
WebServiceException {
LOG.trace("Enter disapprove('" + fileurl + "')");
String errorMessage = "Trouble while disapproving file '" + fileurl
+ "'";
try {
Bitstorage bs = BitstorageFactory.getInstance();
bs.disapprove(new URL(fileurl));
} catch (BitstorageException e) {
LOG.error(errorMessage, e);
throw bitstorageMapper.convertMostApplicable(e);
} catch (Exception e) {
LOG.error(errorMessage, e);
throw new WebServiceException(errorMessage + ": " + e, e);
}
}
/**
* Approve a file for permanent storage, for details see
* {@link Bitstorage#approve(URL, String)}.
* <p/>
* This method works as a fault barrier, handling exceptions by converting
* them to relecant SOAP faults.
*
* @param fileurl The url of the file to approve.
* @param md5String The md5 checksum of files.
* @throws FileNotFoundException If the file does not exist in any storage.
* @throws CommunicationException On generic trouble communicating with the
* underlying script.
* @throws NotEnoughFreeSpaceException If there is not enough space to store
* the file.
* @throws ChecksumFailedException If the file on server has a different
* checksum than the given checksum
* @throws FileIsLockedException If the file is locked by another operation.
* @throws LowlevelSoapException On internal errors that are not correctly
* mapped to SOAP faults. Should never happen.
* @throws WebServiceException On other unclassified errors. Should never
* happen.
*/
@WebMethod
public void approve(@WebParam(name = "fileurl",
targetNamespace = "") String fileurl,
@WebParam(name = "md5string",
targetNamespace = "") String md5String)
throws FileNotFoundException, CommunicationException,
NotEnoughFreeSpaceException, ChecksumFailedException,
FileIsLockedException,
LowlevelSoapException, WebServiceException {
LOG.trace("Enter approve('" + fileurl + "', '" + md5String + "')");
String errorMessage = "Trouble while approving file '" + fileurl + "'";
try {
Bitstorage bs = BitstorageFactory.getInstance();
bs.approve(new URL(fileurl), md5String);
} catch (BitstorageException e) {
LOG.error(errorMessage, e);
throw bitstorageMapper.convertMostApplicable(e);
} catch (Exception e) {
LOG.error(errorMessage, e);
throw new WebServiceException(errorMessage + ": " + e, e);
}
}
/**
* Get amount of free space in bitstorage, for details see
* {@link Bitstorage#spaceLeft()}.
* <p/>
* This method works as a fault barrier, handling exceptions by converting
* them to relecant SOAP faults.
*
* @return Amount of free space in bytes.
* @throws CommunicationException On generic trouble communicating with the
* underlying script.
* @throws LowlevelSoapException On internal errors that are not correctly
* mapped to SOAP faults. Should never happen.
* @throws WebServiceException On other unclassified errors. Should never
* happen.
*/
@WebMethod
public long spaceLeft() throws CommunicationException,
LowlevelSoapException, WebServiceException {
LOG.trace("Enter spaceLeft()");
String errorMessage = "Trouble while checking free space";
try {
Bitstorage bs = BitstorageFactory.getInstance();
return bs.spaceLeft();
} catch (BitstorageException e) {
LOG.error(errorMessage, e);
throw bitstorageMapper.convertMostApplicable(e);
} catch (Exception e) {
LOG.error(errorMessage, e);
throw new WebServiceException(errorMessage + ": " + e, e);
}
}
/**
* Get amount of free space in bitstorage for a single file, for details see
* {@link Bitstorage#getMaxFileSize()}.
* <p/>
* This method works as a fault barrier, handling exceptions by converting
* them to relecant SOAP faults.
*
* @return Amount of free space in bytes for one single file.
* @throws CommunicationException On generic trouble communicating with the
* underlying script.
* @throws LowlevelSoapException On internal errors that are not correctly
* mapped to SOAP faults. Should never happen.
* @throws WebServiceException On other unclassified errors. Should never
* happen.
*/
@WebMethod
public long getMaxFileSize() throws CommunicationException,
LowlevelSoapException,
WebServiceException {
LOG.trace("Enter getMaxFileSize()");
String errorMessage = "Trouble while checking free space";
try {
Bitstorage bs = BitstorageFactory.getInstance();
return bs.getMaxFileSize();
} catch (BitstorageException e) {
LOG.error(errorMessage, e);
throw bitstorageMapper.convertMostApplicable(e);
} catch (Exception e) {
LOG.error(errorMessage, e);
throw new WebServiceException(errorMessage + ": " + e, e);
}
}
/**
* Get checksum for a file, for details see
* {@link Bitstorage#getMd5(URL)}.
* <p/>
* This method works as a fault barrier, handling exceptions by converting
* them to relecant SOAP faults.
*
* @param fileurl The url of the file to get checksum for.
* @return Checksum for file.
* @throws FileNotFoundException If the file does not exist in any storage.
* @throws CommunicationException On generic trouble communicating with the
* underlying script.
* @throws FileIsLockedException If the file is locked by another operation.
* @throws LowlevelSoapException On internal errors that are not correctly
* mapped to SOAP faults. Should never happen.
* @throws WebServiceException On other unclassified errors. Should never
* happen.
*/
@WebMethod
public String getMd5(@WebParam(name = "fileurl",
targetNamespace = "")
String fileurl)
throws FileNotFoundException, CommunicationException,
FileIsLockedException,
LowlevelSoapException, WebServiceException {
LOG.trace("Enter getMd5('" + fileurl + "')");
String errorMessage = "Trouble while getting checksum for fileurl '"
+ fileurl + "'";
try {
Bitstorage bs = BitstorageFactory.getInstance();
return bs.getMd5(new URL(fileurl));
} catch (BitstorageException e) {
LOG.error(errorMessage, e);
throw bitstorageMapper.convertMostApplicable(e);
} catch (Exception e) {
LOG.error(errorMessage, e);
throw new WebServiceException(errorMessage + ": " + e, e);
}
}
/**
* Check whether a file is approved, for details see
* {@link Bitstorage#isApproved(URL)}.
* <p/>
* This method works as a fault barrier, handling exceptions by converting
* them to relecant SOAP faults.
*
* @param fileurl The url of the file to check whether is approved.
* @return true if exists and is approved, false if exists but is not yet
* approved.
* @throws FileNotFoundException If the file does not exist in any storage.
* @throws CommunicationException On generic trouble communicating with the
* underlying script.
* @throws FileIsLockedException If the file is locked by another operation.
* @throws LowlevelSoapException On internal errors that are not correctly
* mapped to SOAP faults. Should never happen.
* @throws WebServiceException On other unclassified errors. Should never
* happen.
*/
@WebMethod
public boolean isApproved(@WebParam(name = "fileurl",
targetNamespace = "")
String fileurl)
throws FileNotFoundException, CommunicationException,
FileIsLockedException,
LowlevelSoapException, WebServiceException {
LOG.trace("Enter getMd5('" + fileurl + "')");
String errorMessage = "Trouble while checking if fileurl '"
+ fileurl + "' is approved";
try {
Bitstorage bs = BitstorageFactory.getInstance();
return bs.isApproved(new URL(fileurl));
} catch (BitstorageException e) {
LOG.error(errorMessage, e);
throw bitstorageMapper.convertMostApplicable(e);
} catch (Exception e) {
LOG.error(errorMessage, e);
throw new WebServiceException(errorMessage + ": " + e, e);
}
}
}
|
modules/lowlevel/lowlevel_impl/src/dk/statsbiblioteket/doms/bitstorage/lowlevel/frontend/LowlevelBitstorageSoapWebserviceImpl.java
|
/*
* $Id$
* $Revision$
* $Date$
* $Author$
*
* The DOMS project.
* Copyright (C) 2007-2010 The State and University Library
*
* 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 dk.statsbiblioteket.doms.bitstorage.lowlevel.frontend;
import com.sun.xml.ws.developer.StreamingDataHandler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import dk.statsbiblioteket.doms.bitstorage.lowlevel.backend.Bitstorage;
import dk.statsbiblioteket.doms.bitstorage.lowlevel.backend.BitstorageFactory;
import dk.statsbiblioteket.doms.bitstorage.lowlevel.backend.exceptions.BitstorageException;
import dk.statsbiblioteket.doms.bitstorage.lowlevel.*;
import dk.statsbiblioteket.util.qa.QAInfo;
import javax.activation.DataHandler;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.xml.ws.WebServiceException;
import javax.xml.ws.soap.MTOM;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Web service that exposes a low level bitstorage.
* This class handles communication with SOAP and delegating calls to the
* underlying bitstorage. Exceptions are logged and delegated as SOAP faults.
*/
@MTOM
@WebService(
endpointInterface = "dk.statsbiblioteket.doms.bitstorage.lowlevel.LowlevelBitstorageSoapWebservice")
@QAInfo(author = "abr",
reviewers = "kfc",
level = QAInfo.Level.NORMAL,
state = QAInfo.State.QA_OK)
public class LowlevelBitstorageSoapWebserviceImpl
implements LowlevelBitstorageSoapWebservice {
/**
* An exception mapper that maps exceptions from the underlying bitstorage
* to SOAP faults.
*/
private BitstorageToLowlevelExceptionMapper bitstorageMapper
= new BitstorageToLowlevelExceptionMapper();
/**
* The logger for this class.
*/
private static final Log LOG
= LogFactory.getLog(LowlevelBitstorageSoapWebserviceImpl.class);
/**
* Upload the provided file for later approval, for details, see
* {@link Bitstorage#upload(String, InputStream, String, long)}.
* <p/>
* The data for the file should be streamed to the underlying service.
* <p/>
* This method works as a fault barrier, handling exceptions by converting
* them to relecant SOAP faults.
*
* @param filename The name to give the file to upload.
* @param filedata The data for the file.
* @param md5String MD5 checksum of the data.
* @param filelength Size of the data.
* @return The checksum calculated by the server.
* @throws ChecksumFailedException If the server calculated a different
* checksum than the given checksum
* @throws CommunicationException On generic trouble communicating with the
* underlying script.
* @throws NotEnoughFreeSpaceException If there is not enough space to store
* the file.
* @throws FileIsLockedException If the file is locked by another operation.
* @throws LowlevelSoapException On internal errors that are not correctly
* mapped to SOAP faults. Should never happen.
* @throws WebServiceException On other unclassified errors. Should never
* happen.
*/
@WebMethod
public String uploadFile(@WebParam(name = "filename",
targetNamespace = "")
String filename,
@WebParam(name = "filedata",
targetNamespace = "")
DataHandler filedata,
@WebParam(name = "md5string",
targetNamespace = "")
String md5String,
@WebParam(name = "filelength",
targetNamespace = "")
long filelength)
throws ChecksumFailedException, CommunicationException,
NotEnoughFreeSpaceException, FileIsLockedException,
LowlevelSoapException, WebServiceException {
LOG.trace("Enter uploadFile('" + filename + "','" + filedata + "','"
+ md5String + "','" + filelength + "')");
String errorMessage = "Trouble while uploading file '" + filename + "'";
try {
Bitstorage bs = BitstorageFactory.getInstance();
InputStream data;
if (filedata instanceof StreamingDataHandler) {
LOG.trace("Reading data for file '" + filedata
+ "' as streaming data");
data = ((StreamingDataHandler) filedata).readOnce();
} else {
LOG.trace("Reading data for file '" + filedata
+ "' as non-streaming data");
data = filedata.getInputStream();
}
try {
return bs.upload(filename, data, md5String, filelength)
.toString();
} finally {
LOG.trace("Function over, returning");
data.close();
}
} catch (BitstorageException e) {
LOG.error(errorMessage, e);
throw bitstorageMapper.convertMostApplicable(e);
} catch (Exception e) {
LOG.error(errorMessage, e);
throw new WebServiceException(errorMessage + ": " + e, e);
}
}
/**
* Remove a file that has not yet been approved, for details see
* {@link Bitstorage#disapprove(URL)}.
* <p/>
* This method works as a fault barrier, handling exceptions by converting
* them to relecant SOAP faults.
*
* @param fileurl The url of the file to disapprove.
* @throws CommunicationException On generic trouble communicating with the
* underlying script.
* @throws FileIsLockedException If the file is locked by another operation.
* @throws LowlevelSoapException On internal errors that are not correctly
* mapped to SOAP faults. Should never happen.
* @throws WebServiceException On other unclassified errors. Should never
* happen.
*/
@WebMethod
public void disapprove(@WebParam(name = "fileurl",
targetNamespace = "") String fileurl)
throws FileIsLockedException,
CommunicationException,
LowlevelSoapException,
WebServiceException {
LOG.trace("Enter disapprove('" + fileurl + "')");
String errorMessage = "Trouble while disapproving file '" + fileurl
+ "'";
try {
Bitstorage bs = BitstorageFactory.getInstance();
bs.disapprove(new URL(fileurl));
} catch (BitstorageException e) {
LOG.error(errorMessage, e);
throw bitstorageMapper.convertMostApplicable(e);
} catch (Exception e) {
LOG.error(errorMessage, e);
throw new WebServiceException(errorMessage + ": " + e, e);
}
}
/**
* Approve a file for permanent storage, for details see
* {@link Bitstorage#approve(URL, String)}.
* <p/>
* This method works as a fault barrier, handling exceptions by converting
* them to relecant SOAP faults.
*
* @param fileurl The url of the file to approve.
* @param md5String The md5 checksum of files.
* @throws FileNotFoundException If the file does not exist in any storage.
* @throws CommunicationException On generic trouble communicating with the
* underlying script.
* @throws NotEnoughFreeSpaceException If there is not enough space to store
* the file.
* @throws ChecksumFailedException If the file on server has a different
* checksum than the given checksum
* @throws FileIsLockedException If the file is locked by another operation.
* @throws LowlevelSoapException On internal errors that are not correctly
* mapped to SOAP faults. Should never happen.
* @throws WebServiceException On other unclassified errors. Should never
* happen.
*/
@WebMethod
public void approve(@WebParam(name = "fileurl",
targetNamespace = "") String fileurl,
@WebParam(name = "md5string",
targetNamespace = "") String md5String)
throws FileNotFoundException, CommunicationException,
NotEnoughFreeSpaceException, ChecksumFailedException,
FileIsLockedException,
LowlevelSoapException, WebServiceException {
LOG.trace("Enter approve('" + fileurl + "', '" + md5String + "')");
String errorMessage = "Trouble while approving file '" + fileurl + "'";
try {
Bitstorage bs = BitstorageFactory.getInstance();
bs.approve(new URL(fileurl), md5String);
} catch (BitstorageException e) {
LOG.error(errorMessage, e);
throw bitstorageMapper.convertMostApplicable(e);
} catch (Exception e) {
LOG.error(errorMessage, e);
throw new WebServiceException(errorMessage + ": " + e, e);
}
}
/**
* Get amount of free space in bitstorage, for details see
* {@link Bitstorage#spaceLeft()}.
* <p/>
* This method works as a fault barrier, handling exceptions by converting
* them to relecant SOAP faults.
*
* @return Amount of free space in bytes.
* @throws CommunicationException On generic trouble communicating with the
* underlying script.
* @throws LowlevelSoapException On internal errors that are not correctly
* mapped to SOAP faults. Should never happen.
* @throws WebServiceException On other unclassified errors. Should never
* happen.
*/
@WebMethod
public long spaceLeft() throws CommunicationException,
LowlevelSoapException, WebServiceException {
LOG.trace("Enter spaceLeft()");
String errorMessage = "Trouble while checking free space";
try {
Bitstorage bs = BitstorageFactory.getInstance();
return bs.spaceLeft();
} catch (BitstorageException e) {
LOG.error(errorMessage, e);
throw bitstorageMapper.convertMostApplicable(e);
} catch (Exception e) {
LOG.error(errorMessage, e);
throw new WebServiceException(errorMessage + ": " + e, e);
}
}
/**
* Get amount of free space in bitstorage for a single file, for details see
* {@link Bitstorage#getMaxFileSize()}.
* <p/>
* This method works as a fault barrier, handling exceptions by converting
* them to relecant SOAP faults.
*
* @return Amount of free space in bytes for one single file.
* @throws CommunicationException On generic trouble communicating with the
* underlying script.
* @throws LowlevelSoapException On internal errors that are not correctly
* mapped to SOAP faults. Should never happen.
* @throws WebServiceException On other unclassified errors. Should never
* happen.
*/
@WebMethod
public long getMaxFileSize() throws CommunicationException,
LowlevelSoapException,
WebServiceException {
LOG.trace("Enter getMaxFileSize()");
String errorMessage = "Trouble while checking free space";
try {
Bitstorage bs = BitstorageFactory.getInstance();
return bs.getMaxFileSize();
} catch (BitstorageException e) {
LOG.error(errorMessage, e);
throw bitstorageMapper.convertMostApplicable(e);
} catch (Exception e) {
LOG.error(errorMessage, e);
throw new WebServiceException(errorMessage + ": " + e, e);
}
}
/**
* Get checksum for a file, for details see
* {@link Bitstorage#getMd5(URL)}.
* <p/>
* This method works as a fault barrier, handling exceptions by converting
* them to relecant SOAP faults.
*
* @param fileurl The url of the file to get checksum for.
* @return Checksum for file.
* @throws FileNotFoundException If the file does not exist in any storage.
* @throws CommunicationException On generic trouble communicating with the
* underlying script.
* @throws FileIsLockedException If the file is locked by another operation.
* @throws LowlevelSoapException On internal errors that are not correctly
* mapped to SOAP faults. Should never happen.
* @throws WebServiceException On other unclassified errors. Should never
* happen.
*/
@WebMethod
public String getMd5(@WebParam(name = "fileurl",
targetNamespace = "")
String fileurl)
throws FileNotFoundException, CommunicationException,
FileIsLockedException,
LowlevelSoapException, WebServiceException {
LOG.trace("Enter getMd5('" + fileurl + "')");
String errorMessage = "Trouble while getting checksum for fileurl '"
+ fileurl + "'";
try {
Bitstorage bs = BitstorageFactory.getInstance();
return bs.getMd5(new URL(fileurl));
} catch (BitstorageException e) {
LOG.error(errorMessage, e);
throw bitstorageMapper.convertMostApplicable(e);
} catch (Exception e) {
LOG.error(errorMessage, e);
throw new WebServiceException(errorMessage + ": " + e, e);
}
}
/**
* Check whether a file is approved, for details see
* {@link Bitstorage#isApproved(URL)}.
* <p/>
* This method works as a fault barrier, handling exceptions by converting
* them to relecant SOAP faults.
*
* @param fileurl The url of the file to check whether is approved.
* @return true if exists and is approved, false if exists but is not yet
* approved.
* @throws FileNotFoundException If the file does not exist in any storage.
* @throws CommunicationException On generic trouble communicating with the
* underlying script.
* @throws FileIsLockedException If the file is locked by another operation.
* @throws LowlevelSoapException On internal errors that are not correctly
* mapped to SOAP faults. Should never happen.
* @throws WebServiceException On other unclassified errors. Should never
* happen.
*/
@WebMethod
public boolean isApproved(@WebParam(name = "fileurl",
targetNamespace = "")
String fileurl)
throws FileNotFoundException, CommunicationException,
FileIsLockedException,
LowlevelSoapException, WebServiceException {
LOG.trace("Enter getMd5('" + fileurl + "')");
String errorMessage = "Trouble while checking if fileurl '"
+ fileurl + "' is approved";
try {
Bitstorage bs = BitstorageFactory.getInstance();
return bs.isApproved(new URL(fileurl));
} catch (BitstorageException e) {
LOG.error(errorMessage, e);
throw bitstorageMapper.convertMostApplicable(e);
} catch (Exception e) {
LOG.error(errorMessage, e);
throw new WebServiceException(errorMessage + ": " + e, e);
}
}
}
|
Just another log statement
|
modules/lowlevel/lowlevel_impl/src/dk/statsbiblioteket/doms/bitstorage/lowlevel/frontend/LowlevelBitstorageSoapWebserviceImpl.java
|
Just another log statement
|
|
Java
|
apache-2.0
|
90f9b57e784ca04596e258941eb03ffe0a571c86
| 0
|
omindu/carbon-identity-framework,wso2/carbon-identity-framework,omindu/carbon-identity-framework,wso2/carbon-identity-framework,omindu/carbon-identity-framework,wso2/carbon-identity-framework,wso2/carbon-identity-framework,omindu/carbon-identity-framework
|
/*
* Copyright (c) 2021, 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.identity.application.authentication.framework.cache;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.identity.core.cache.AbstractCacheListener;
import org.wso2.carbon.identity.core.cache.BaseCache;
import org.wso2.carbon.identity.core.util.IdentityTenantUtil;
import java.io.Serializable;
import java.util.List;
import static org.wso2.carbon.utils.multitenancy.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
/**
* Base cache for authentication flow related caches. The difference from the Base cache is,
* AuthenticationBaseCache will maintain the caches in the tenant space if the Tenant Qualified Urls enabled.
* Else the caches will be maintained in the super tenant.
*
* This is because when the Tenant Qualified Urls disabled, all the authentication flow requests will be received
* in the common endpoints. So the tenant domain will not be resolved until the session data or application data
* retrieved using the session identifier or application identifier. In this case tenanted caching will not help.
* So the the caches will be maintained in the super tenant when the Tenant Qualified Urls.
*
* @param <K> cache key type.
* @param <V> cache value type.
*/
public class AuthenticationBaseCache<K extends Serializable, V extends Serializable> extends BaseCache<K,V> {
private static final Log log = LogFactory.getLog(AuthenticationBaseCache.class);
public AuthenticationBaseCache(String cacheName) {
super(cacheName);
}
public AuthenticationBaseCache(String cacheName, boolean isTemp) {
super(cacheName, isTemp);
}
public AuthenticationBaseCache(String cacheName, List<AbstractCacheListener<K, V>> cacheListeners) {
super(cacheName, cacheListeners);
}
public AuthenticationBaseCache(String cacheName, boolean isTemp, List<AbstractCacheListener<K, V>> cacheListeners) {
super(cacheName, isTemp, cacheListeners);
}
/**
* Add a cache entry. If TenantQualifiedUrls enabled, add to the cache of tenant from Context
* else add to the super tenant.
*
* @param key Key which cache entry is indexed.
* @param entry Actual object where cache entry is placed.
*/
public void addToCache(K key, V entry) {
addToCache(key, entry, getTenantDomainFromContext());
}
/**
* Retrieves a cache entry. If TenantQualifiedUrls enabled, retrieve from the cache of tenant from Context
* else retrieve from the cache of super tenant.
*
* @param key CacheKey
* @return Cached entry.
*/
public V getValueFromCache(K key) {
return getValueFromCache(key, getTenantDomainFromContext());
}
/**
* Clears a cache entry. If TenantQualifiedUrls enabled, clears from the cache of tenant from Context
* else clear from the cache of super tenant.
*
* @param key CacheKey
*/
public void clearCacheEntry(K key) {
clearCacheEntry(key, getTenantDomainFromContext());
}
private static String getTenantDomainFromContext() {
// Due to the SaaS application use cases, we are reverting this.
// We use the tenant domain set in context only in tenant qualified URL mode.
// if (IdentityTenantUtil.isTenantQualifiedUrlsEnabled()) {
// String tenantDomain = IdentityTenantUtil.getTenantDomainFromContext();
// if (StringUtils.isNotBlank(tenantDomain)) {
// return tenantDomain;
// } else {
// if (log.isDebugEnabled()) {
// log.debug("TenantQualifiedUrlsEnabled is enabled, but the tenant domain is not set to the" +
// " context. Hence using the tenant domain from the carbon context.");
// }
// return PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
// }
// }
return SUPER_TENANT_DOMAIN_NAME;
}
}
|
components/authentication-framework/org.wso2.carbon.identity.application.authentication.framework/src/main/java/org/wso2/carbon/identity/application/authentication/framework/cache/AuthenticationBaseCache.java
|
/*
* Copyright (c) 2021, 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.identity.application.authentication.framework.cache;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.identity.core.cache.AbstractCacheListener;
import org.wso2.carbon.identity.core.cache.BaseCache;
import org.wso2.carbon.identity.core.util.IdentityTenantUtil;
import java.io.Serializable;
import java.util.List;
import static org.wso2.carbon.utils.multitenancy.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
/**
* Base cache for authentication flow related caches. The difference from the Base cache is,
* AuthenticationBaseCache will maintain the caches in the tenant space if the Tenant Qualified Urls enabled.
* Else the caches will be maintained in the super tenant.
*
* This is because when the Tenant Qualified Urls disabled, all the authentication flow requests will be received
* in the common endpoints. So the tenant domain will not be resolved until the session data or application data
* retrieved using the session identifier or application identifier. In this case tenanted caching will not help.
* So the the caches will be maintained in the super tenant when the Tenant Qualified Urls.
*
* @param <K> cache key type.
* @param <V> cache value type.
*/
public class AuthenticationBaseCache<K extends Serializable, V extends Serializable> extends BaseCache<K,V> {
private static final Log log = LogFactory.getLog(AuthenticationBaseCache.class);
public AuthenticationBaseCache(String cacheName) {
super(cacheName);
}
public AuthenticationBaseCache(String cacheName, boolean isTemp) {
super(cacheName, isTemp);
}
public AuthenticationBaseCache(String cacheName, List<AbstractCacheListener<K, V>> cacheListeners) {
super(cacheName, cacheListeners);
}
public AuthenticationBaseCache(String cacheName, boolean isTemp, List<AbstractCacheListener<K, V>> cacheListeners) {
super(cacheName, isTemp, cacheListeners);
}
/**
* Add a cache entry. If TenantQualifiedUrls enabled, add to the cache of tenant from Context
* else add to the super tenant.
*
* @param key Key which cache entry is indexed.
* @param entry Actual object where cache entry is placed.
*/
public void addToCache(K key, V entry) {
addToCache(key, entry, getTenantDomainFromContext());
}
/**
* Retrieves a cache entry. If TenantQualifiedUrls enabled, retrieve from the cache of tenant from Context
* else retrieve from the cache of super tenant.
*
* @param key CacheKey
* @return Cached entry.
*/
public V getValueFromCache(K key) {
return getValueFromCache(key, getTenantDomainFromContext());
}
/**
* Clears a cache entry. If TenantQualifiedUrls enabled, clears from the cache of tenant from Context
* else clear from the cache of super tenant.
*
* @param key CacheKey
*/
public void clearCacheEntry(K key) {
clearCacheEntry(key, getTenantDomainFromContext());
}
private static String getTenantDomainFromContext() {
// We use the tenant domain set in context only in tenant qualified URL mode.
if (IdentityTenantUtil.isTenantQualifiedUrlsEnabled()) {
String tenantDomain = IdentityTenantUtil.getTenantDomainFromContext();
if (StringUtils.isNotBlank(tenantDomain)) {
return tenantDomain;
} else {
if (log.isDebugEnabled()) {
log.debug("TenantQualifiedUrlsEnabled is enabled, but the tenant domain is not set to the" +
" context. Hence using the tenant domain from the carbon context.");
}
return PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
}
}
return SUPER_TENANT_DOMAIN_NAME;
}
}
|
Always use the super tenant cache for the authentication flow.
|
components/authentication-framework/org.wso2.carbon.identity.application.authentication.framework/src/main/java/org/wso2/carbon/identity/application/authentication/framework/cache/AuthenticationBaseCache.java
|
Always use the super tenant cache for the authentication flow.
|
|
Java
|
apache-2.0
|
b50ce98eb20b653245d2278c99013f375325bc94
| 0
|
palava/palava-ipc-session-store
|
/**
* Copyright 2010 CosmoCode GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.cosmocode.palava.ipc.session.store;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import de.cosmocode.palava.ipc.AbstractIpcSession;
import de.cosmocode.palava.ipc.IpcSession;
import de.cosmocode.palava.store.Store;
/**
* Storable implementation of the {@link IpcSession} interface.
*
* @author Willi Schoenborn
* @author Tobias Sarnowski
*/
class Session extends AbstractIpcSession implements Serializable {
private static final long serialVersionUID = 6746261643974379263L;
private static final Logger LOG = LoggerFactory.getLogger(Session.class);
private transient Store store;
private final String sessionId;
private final String identifier;
// the data storage
private Map<Object, Object> data = Maps.newHashMap();
protected Session(String sessionId, String identifier, Store store) {
this.sessionId = sessionId;
this.identifier = identifier;
this.store = store;
}
@Override
public String getSessionId() {
return sessionId;
}
@Override
public String getIdentifier() {
return identifier;
}
@Override
protected Map<Object, Object> context() {
if (!isHydrated()) hydrate();
return data;
}
protected void setStore(Store store) {
this.store = store;
}
public boolean isHydrated() {
return data != null;
}
/**
* Dehydrates this session.
*
* @since 1.0
* @throws IllegalStateException if this session is already dehydrated
* @throws IOException if storing session data failed
*/
public void dehydrate() throws IOException {
Preconditions.checkState(isHydrated(), "session %s already dehydrated", this);
LOG.trace("Dehydrating {}", this);
final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
final ObjectOutputStream stream = new ObjectOutputStream(buffer);
stream.writeObject(data);
stream.close();
store.create(new ByteArrayInputStream(buffer.toByteArray()), sessionId);
this.data = null;
}
private void hydrate() {
Preconditions.checkState(!isHydrated(), "session %s is already hydrated", this);
LOG.trace("Hydrating {}", this);
try {
final ObjectInputStream stream = new ObjectInputStream(store.read(sessionId));
@SuppressWarnings("unchecked")
final Map<Object, Object> map = (Map<Object, Object>) stream.readObject();
this.data = map;
stream.close();
store.delete(sessionId);
} catch (IOException e) {
LOG.error("IO exception on loading session data for " + this, e);
this.data = null;
} catch (ClassNotFoundException e) {
LOG.error("Incompatible session data found for " + this, e);
this.data = null;
} catch (IllegalStateException e) {
LOG.error("Session data not found for " + this, e);
this.data = null;
} finally {
if (this.data == null) {
LOG.warn("Hydrating failed, continuing with a vanilla session.");
this.data = Maps.newHashMap();
}
}
}
/**
* <p>
* "+" symbolizes the in-memory session, "-" means, the session is in the storage.
* </p>
*
* {@inheritDoc}
*/
@Override
public String toString() {
return String.format("Session{%s:%s/%s}", isHydrated() ? "+" : "-", getSessionId(), getIdentifier());
}
}
|
src/main/java/de/cosmocode/palava/ipc/session/store/Session.java
|
/**
* Copyright 2010 CosmoCode GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.cosmocode.palava.ipc.session.store;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import de.cosmocode.palava.ipc.AbstractIpcSession;
import de.cosmocode.palava.ipc.IpcSession;
import de.cosmocode.palava.store.Store;
/**
* Storable implementation of the {@link IpcSession} interface.
*
* @author Willi Schoenborn
* @author Tobias Sarnowski
*/
class Session extends AbstractIpcSession implements Serializable {
private static final long serialVersionUID = 6746261643974379263L;
private static final Logger LOG = LoggerFactory.getLogger(Session.class);
private transient Store store;
private final String sessionId;
private final String identifier;
// the data storage
private Map<Object, Object> data = Maps.newHashMap();
protected Session(String sessionId, String identifier, Store store) {
this.sessionId = sessionId;
this.identifier = identifier;
this.store = store;
}
@Override
public String getSessionId() {
return sessionId;
}
@Override
public String getIdentifier() {
return identifier;
}
@Override
protected Map<Object, Object> context() {
if (!isHydrated()) hydrate();
return data;
}
protected void setStore(Store store) {
this.store = store;
}
public boolean isHydrated() {
return data != null;
}
/**
* Dehydrates this session.
*
* @since 1.0
* @throws IllegalStateException if this session is already dehydrated
* @throws IOException if storing session data failed
*/
public void dehydrate() throws IOException {
Preconditions.checkState(isHydrated(), "session %s already dehydrated", this);
LOG.trace("Dehydrating {}", this);
final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
final ObjectOutputStream stream = new ObjectOutputStream(buffer);
stream.writeObject(data);
stream.close();
store.create(new ByteArrayInputStream(buffer.toByteArray()), sessionId);
this.data = null;
}
private void hydrate() {
Preconditions.checkState(!isHydrated(), "session %s is already hydrated", this);
LOG.trace("Hydrating {}", this);
try {
final ObjectInputStream stream = new ObjectInputStream(store.read(sessionId));
@SuppressWarnings("unchecked")
final Map<Object, Object> map = (Map<Object, Object>) stream.readObject();
this.data = map;
stream.close();
store.delete(sessionId);
} catch (IOException e) {
LOG.error("IO exception on loading session data for " + this, e);
this.data = null;
} catch (ClassNotFoundException e) {
LOG.error("Incompatible session data found for " + this, e);
this.data = null;
} catch (IllegalStateException e) {
LOG.error("Session data not found for " + this, e);
this.data = null;
} finally {
if (this.data == null) {
LOG.warn("Hydrating failed, continuing with a vanilla session.");
this.data = Maps.newHashMap();
}
}
}
/**
* <p>
* "+" symbolizes the in-memory session, "-" means, the session is in the storage.
* </p>
*
* {@inheritDoc}
*/
@Override
public String toString() {
return String.format("Session %s:%s/%s", isHydrated() ? "+" : "-", getSessionId(), getIdentifier());
}
}
|
unified session toString
|
src/main/java/de/cosmocode/palava/ipc/session/store/Session.java
|
unified session toString
|
|
Java
|
apache-2.0
|
7a8b264505b53f14e8063beb6e8e8e69266b9f22
| 0
|
bozimmerman/CoffeeMud,bozimmerman/CoffeeMud,bozimmerman/CoffeeMud,bozimmerman/CoffeeMud
|
package com.planet_ink.coffee_mud.Abilities.Common;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2016-2021 Bo Zimmerman
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
public class Salvaging extends CommonSkill
{
@Override
public String ID()
{
return "Salvaging";
}
private final static String localizedName = CMLib.lang().L("Salvaging");
@Override
public String name()
{
return localizedName;
}
private static final String[] triggerStrings = I(new String[] { "SALVAGE", "SALVAGING" });
@Override
public String[] triggerStrings()
{
return triggerStrings;
}
@Override
protected ExpertiseLibrary.SkillCostDefinition getRawTrainingCost()
{
return CMProps.getNormalSkillGainCost(ID());
}
@Override
public int classificationCode()
{
return Ability.ACODE_COMMON_SKILL | Ability.DOMAIN_NATURELORE;
}
protected Item found = null;
protected int amount = 0;
protected String oldItemName = "";
protected boolean messedUp = false;
public Salvaging()
{
super();
displayText = L("You are salvaging...");
verb = L("salvaging");
}
@Override
public boolean tick(final Tickable ticking, final int tickID)
{
if((affected!=null)
&&(affected instanceof MOB)
&&(tickID==Tickable.TICKID_MOB))
{
if(found==null)
{
messedUp=true;
unInvoke();
}
}
return super.tick(ticking,tickID);
}
protected void finishSalvage(final MOB mob, final Item found, int amount)
{
final CMMsg msg=CMClass.getMsg(mob,found,this,getCompletedActivityMessageType(),null);
msg.setValue(amount);
if(mob.location().okMessage(mob, msg))
{
final String foundShortName=RawMaterial.CODES.NAME(found.material()).toLowerCase();
if(msg.value()<2)
msg.modify(L("<S-NAME> manage(s) to salvage @x1.",found.name()));
else
msg.modify(L("<S-NAME> manage(s) to salvage @x1 pounds of @x2.",""+msg.value(),foundShortName));
mob.location().send(mob, msg);
amount=msg.value();
int extra=0;
int weight=1;
if((amount>=20)
&&(found instanceof RawMaterial))
{
weight=amount/10;
extra=amount-(weight*10);
amount=10;
}
for(int i=0;i<amount;i++)
{
final Item newFound=(Item)found.copyOf();
if(newFound.basePhyStats().weight()<weight)
{
newFound.basePhyStats().setWeight(weight);
newFound.phyStats().setWeight(weight);
CMLib.materials().adjustResourceName(newFound);
}
if(!dropAWinner(mob,newFound))
break;
}
for(int i=0;i<extra;i++)
{
final Item newFound=(Item)found.copyOf();
if(newFound.basePhyStats().weight()<extra)
{
newFound.basePhyStats().setWeight(extra);
newFound.phyStats().setWeight(extra);
CMLib.materials().adjustResourceName(newFound);
}
if(!dropAWinner(mob,newFound))
break;
}
}
}
@Override
public void unInvoke()
{
if(canBeUninvoked())
{
if(affected instanceof MOB)
{
final MOB mob=(MOB)affected;
if((found!=null)&&(!aborted)&&(mob.location()!=null))
{
if(messedUp)
commonTell(mob,L("You've messed up salvaging @x1!",oldItemName));
else
{
final Item baseShip=found;
final int finalAmount=amount*(baseYield()+abilityCode());
finishSalvage(mob,baseShip, finalAmount);
if((baseShip.material()&RawMaterial.MATERIAL_MASK)!=RawMaterial.MATERIAL_METAL)
{
final Item metalFound=CMLib.materials().makeItemResource(RawMaterial.RESOURCE_IRON);
final int metalAmount = Math.round(CMath.sqrt(finalAmount));
finishSalvage(mob,metalFound, metalAmount);
}
if((baseShip.material()&RawMaterial.MATERIAL_MASK)!=RawMaterial.MATERIAL_CLOTH)
{
final Item clothFound=CMLib.materials().makeItemResource(RawMaterial.RESOURCE_COTTON);
final int metalAmount = Math.round(CMath.sqrt(finalAmount));
final int clothAmount = Math.round(CMath.sqrt(metalAmount));
finishSalvage(mob,clothFound, clothAmount);
}
}
}
}
}
super.unInvoke();
}
@Override
public boolean invoke(final MOB mob, final List<String> commands, final Physical givenTarget, final boolean auto, final int asLevel)
{
if(super.checkStop(mob, commands))
return true;
verb=L("salvaging");
final String str=CMParms.combine(commands,0);
final Item I=mob.location().findItem(null,str);
if((I==null)||(!CMLib.flags().canBeSeenBy(I,mob)))
{
commonTell(mob,L("You don't see anything called '@x1' here.",str));
return false;
}
boolean okMaterial=true;
oldItemName=I.Name();
switch(I.material()&RawMaterial.MATERIAL_MASK)
{
case RawMaterial.MATERIAL_FLESH:
case RawMaterial.MATERIAL_LIQUID:
case RawMaterial.MATERIAL_PAPER:
case RawMaterial.MATERIAL_ENERGY:
case RawMaterial.MATERIAL_GAS:
case RawMaterial.MATERIAL_VEGETATION:
{
okMaterial = false;
break;
}
}
if(!okMaterial)
{
commonTell(mob,L("You don't know how to salvage @x1.",I.name(mob)));
return false;
}
if(I instanceof RawMaterial)
{
commonTell(mob,L("@x1 already looks like salvage.",I.name(mob)));
return false;
}
if(CMLib.flags().isEnchanted(I))
{
commonTell(mob,L("@x1 is enchanted, and can't be salvaged.",I.name(mob)));
return false;
}
final LandTitle t=CMLib.law().getLandTitle(mob.location());
if((t!=null)&&(!CMLib.law().doesHavePriviledgesHere(mob,mob.location())))
{
mob.tell(L("You are not allowed to salvage anything here."));
return false;
}
if((!(I instanceof SailingShip))
||((((SailingShip)I).subjectToWearAndTear())&&(((SailingShip)I).usesRemaining()>0))
||(((SailingShip)I).getShipArea()==null))
{
mob.tell(L("You can only salvage large sunk sailing ships, which @x1 is not.",I.Name()));
return false;
}
final SailingShip ship=(SailingShip)I;
final Area shipArea=ship.getShipArea();
final int totalWeight=I.phyStats().weight();
final List<Item> itemsToMove=new ArrayList<Item>();
for(final Enumeration<Room> r=shipArea.getProperMap();r.hasMoreElements();)
{
final Room R=r.nextElement();
if(R!=null)
{
if(R.numInhabitants()>0)
{
mob.tell(L("There are still people aboard!"));
return false;
}
for(final Enumeration<Item> i=R.items();i.hasMoreElements();)
{
final Item I2=i.nextElement();
if((I2!=null)&&(CMLib.flags().isGettable(I2))&&(I2.container()==null))
itemsToMove.add(I2);
}
}
}
found=null;
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
int duration=getDuration(45,mob,1,10);
amount=I.phyStats().weight();
messedUp=!proficiencyCheck(mob,0,auto);
found=CMLib.materials().makeItemResource(I.material());
playSound="ripping.wav";
final CMMsg msg=CMClass.getMsg(mob,I,this,getActivityMessageType(),L("<S-NAME> start(s) salvaging @x1.",I.name()));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
for(final Item I2 : itemsToMove)
mob.location().moveItemTo(I2);
I.destroy();
mob.location().recoverPhyStats();
duration += CMath.sqrt(totalWeight/5);
beneficialAffect(mob,mob,asLevel,duration);
}
return true;
}
}
|
com/planet_ink/coffee_mud/Abilities/Common/Salvaging.java
|
package com.planet_ink.coffee_mud.Abilities.Common;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2016-2021 Bo Zimmerman
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
public class Salvaging extends CommonSkill
{
@Override
public String ID()
{
return "Salvaging";
}
private final static String localizedName = CMLib.lang().L("Salvaging");
@Override
public String name()
{
return localizedName;
}
private static final String[] triggerStrings = I(new String[] { "SALVAGE", "SALVAGING" });
@Override
public String[] triggerStrings()
{
return triggerStrings;
}
@Override
protected ExpertiseLibrary.SkillCostDefinition getRawTrainingCost()
{
return CMProps.getNormalSkillGainCost(ID());
}
@Override
public int classificationCode()
{
return Ability.ACODE_COMMON_SKILL | Ability.DOMAIN_NATURELORE;
}
protected Item found = null;
protected int amount = 0;
protected String oldItemName = "";
protected boolean messedUp = false;
public Salvaging()
{
super();
displayText = L("You are salvaging...");
verb = L("salvaging");
}
@Override
public boolean tick(final Tickable ticking, final int tickID)
{
if((affected!=null)
&&(affected instanceof MOB)
&&(tickID==Tickable.TICKID_MOB))
{
if(found==null)
{
messedUp=true;
unInvoke();
}
}
return super.tick(ticking,tickID);
}
protected void finishSalvage(final MOB mob, final Item found, final int amount)
{
final CMMsg msg=CMClass.getMsg(mob,found,this,getCompletedActivityMessageType(),null);
msg.setValue(amount);
if(mob.location().okMessage(mob, msg))
{
final String foundShortName=RawMaterial.CODES.NAME(found.material()).toLowerCase();
if(msg.value()<2)
msg.modify(L("<S-NAME> manage(s) to salvage @x1.",found.name()));
else
msg.modify(L("<S-NAME> manage(s) to salvage @x1 pounds of @x2.",""+msg.value(),foundShortName));
mob.location().send(mob, msg);
for(int i=0;i<msg.value();i++)
{
final Item newFound=(Item)found.copyOf();
if(!dropAWinner(mob,newFound))
break;
}
}
}
@Override
public void unInvoke()
{
if(canBeUninvoked())
{
if(affected instanceof MOB)
{
final MOB mob=(MOB)affected;
if((found!=null)&&(!aborted)&&(mob.location()!=null))
{
if(messedUp)
commonTell(mob,L("You've messed up salvaging @x1!",oldItemName));
else
{
final Item baseShip=found;
final int finalAmount=amount*(baseYield()+abilityCode());
finishSalvage(mob,baseShip, finalAmount);
if((baseShip.material()&RawMaterial.MATERIAL_MASK)!=RawMaterial.MATERIAL_METAL)
{
final Item metalFound=CMLib.materials().makeItemResource(RawMaterial.RESOURCE_IRON);
final int metalAmount = Math.round(CMath.sqrt(finalAmount));
finishSalvage(mob,metalFound, metalAmount);
}
if((baseShip.material()&RawMaterial.MATERIAL_MASK)!=RawMaterial.MATERIAL_CLOTH)
{
final Item clothFound=CMLib.materials().makeItemResource(RawMaterial.RESOURCE_COTTON);
final int metalAmount = Math.round(CMath.sqrt(finalAmount));
final int clothAmount = Math.round(CMath.sqrt(metalAmount));
finishSalvage(mob,clothFound, clothAmount);
}
}
}
}
}
super.unInvoke();
}
@Override
public boolean invoke(final MOB mob, final List<String> commands, final Physical givenTarget, final boolean auto, final int asLevel)
{
if(super.checkStop(mob, commands))
return true;
verb=L("salvaging");
final String str=CMParms.combine(commands,0);
final Item I=mob.location().findItem(null,str);
if((I==null)||(!CMLib.flags().canBeSeenBy(I,mob)))
{
commonTell(mob,L("You don't see anything called '@x1' here.",str));
return false;
}
boolean okMaterial=true;
oldItemName=I.Name();
switch(I.material()&RawMaterial.MATERIAL_MASK)
{
case RawMaterial.MATERIAL_FLESH:
case RawMaterial.MATERIAL_LIQUID:
case RawMaterial.MATERIAL_PAPER:
case RawMaterial.MATERIAL_ENERGY:
case RawMaterial.MATERIAL_GAS:
case RawMaterial.MATERIAL_VEGETATION:
{
okMaterial = false;
break;
}
}
if(!okMaterial)
{
commonTell(mob,L("You don't know how to salvage @x1.",I.name(mob)));
return false;
}
if(I instanceof RawMaterial)
{
commonTell(mob,L("@x1 already looks like salvage.",I.name(mob)));
return false;
}
if(CMLib.flags().isEnchanted(I))
{
commonTell(mob,L("@x1 is enchanted, and can't be salvaged.",I.name(mob)));
return false;
}
final LandTitle t=CMLib.law().getLandTitle(mob.location());
if((t!=null)&&(!CMLib.law().doesHavePriviledgesHere(mob,mob.location())))
{
mob.tell(L("You are not allowed to salvage anything here."));
return false;
}
if((!(I instanceof SailingShip))
||((((SailingShip)I).subjectToWearAndTear())&&(((SailingShip)I).usesRemaining()>0))
||(((SailingShip)I).getShipArea()==null))
{
mob.tell(L("You can only salvage large sunk sailing ships, which @x1 is not.",I.Name()));
return false;
}
final SailingShip ship=(SailingShip)I;
final Area shipArea=ship.getShipArea();
final int totalWeight=I.phyStats().weight();
final List<Item> itemsToMove=new ArrayList<Item>();
for(final Enumeration<Room> r=shipArea.getProperMap();r.hasMoreElements();)
{
final Room R=r.nextElement();
if(R!=null)
{
if(R.numInhabitants()>0)
{
mob.tell(L("There are still people aboard!"));
return false;
}
for(final Enumeration<Item> i=R.items();i.hasMoreElements();)
{
final Item I2=i.nextElement();
if((I2!=null)&&(CMLib.flags().isGettable(I2))&&(I2.container()==null))
itemsToMove.add(I2);
}
}
}
found=null;
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
int duration=getDuration(45,mob,1,10);
amount=I.phyStats().weight();
messedUp=!proficiencyCheck(mob,0,auto);
found=CMLib.materials().makeItemResource(I.material());
playSound="ripping.wav";
final CMMsg msg=CMClass.getMsg(mob,I,this,getActivityMessageType(),L("<S-NAME> start(s) salvaging @x1.",I.name()));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
for(final Item I2 : itemsToMove)
mob.location().moveItemTo(I2);
I.destroy();
mob.location().recoverPhyStats();
duration += CMath.sqrt(totalWeight/5);
beneficialAffect(mob,mob,asLevel,duration);
}
return true;
}
}
|
Salvage will drop in larger chunks for speedier delivery.
git-svn-id: 0cdf8356e41b2d8ccbb41bb76c82068fe80b2514@20366 0d6f1817-ed0e-0410-87c9-987e46238f29
|
com/planet_ink/coffee_mud/Abilities/Common/Salvaging.java
|
Salvage will drop in larger chunks for speedier delivery.
|
|
Java
|
apache-2.0
|
ade687afc2ad8d9b130cafd6bdeddff6768777d7
| 0
|
BackupTheBerlios/gavrog,BackupTheBerlios/gavrog,BackupTheBerlios/gavrog,BackupTheBerlios/gavrog,BackupTheBerlios/gavrog
|
/*
Copyright 2005 Olaf Delgado-Friedrichs
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.gavrog.joss.dsyms.basic;
import java.util.ArrayList;
import java.util.Iterator;
/**
* Convenience class to represent lists of Delaney symbol indices.
* @author Olaf Delgado
* @version $Id: IndexList.java,v 1.2 2007/04/19 23:07:42 odf Exp $
*/
public class IndexList extends ArrayList {
public IndexList(final DelaneySymbol ds) {
this(ds.indices());
}
public IndexList(final Iterator iter) {
while (iter.hasNext()) {
add(iter.next());
}
}
public IndexList(final int i) {
add(new Integer(i));
}
public IndexList(final int i, final int j) {
add(new Integer(i));
add(new Integer(j));
}
public IndexList(final int i, final int j, final int k) {
add(new Integer(i));
add(new Integer(j));
add(new Integer(k));
}
public static IndexList except(final DelaneySymbol ds, final int i) {
final IndexList res = new IndexList(ds);
res.remove(new Integer(i));
return res;
}
public static IndexList except(final DelaneySymbol ds, final int i,
final int j) {
final IndexList res = new IndexList(ds);
res.remove(new Integer(i));
res.remove(new Integer(j));
return res;
}
}
|
src/org/gavrog/joss/dsyms/basic/IndexList.java
|
/*
Copyright 2005 Olaf Delgado-Friedrichs
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.gavrog.joss.dsyms.basic;
import java.util.ArrayList;
import java.util.Iterator;
/**
* Convenience class to represent lists of Delaney symbol indices.
* @author Olaf Delgado
* @version $Id: IndexList.java,v 1.1.1.1 2005/07/15 21:58:38 odf Exp $
*/
public class IndexList extends ArrayList {
public IndexList(DelaneySymbol ds) {
this(ds.indices());
}
public IndexList(Iterator iter) {
while (iter.hasNext()) {
add(iter.next());
}
}
public IndexList(final int i) {
add(new Integer(i));
}
public IndexList(final int i, final int j) {
add(new Integer(i));
add(new Integer(j));
}
public IndexList(final int i, final int j, final int k) {
add(new Integer(i));
add(new Integer(j));
add(new Integer(k));
}
}
|
Added the except() factory methods.
|
src/org/gavrog/joss/dsyms/basic/IndexList.java
|
Added the except() factory methods.
|
|
Java
|
apache-2.0
|
2919c96da0af9b55fb2d62b350cbf5e997916fd9
| 0
|
EcoleKeine/pentaho-kettle,rmansoor/pentaho-kettle,pavel-sakun/pentaho-kettle,emartin-pentaho/pentaho-kettle,pedrofvteixeira/pentaho-kettle,GauravAshara/pentaho-kettle,stevewillcock/pentaho-kettle,ViswesvarSekar/pentaho-kettle,rmansoor/pentaho-kettle,pentaho/pentaho-kettle,ViswesvarSekar/pentaho-kettle,GauravAshara/pentaho-kettle,nantunes/pentaho-kettle,birdtsai/pentaho-kettle,tkafalas/pentaho-kettle,DFieldFL/pentaho-kettle,birdtsai/pentaho-kettle,SergeyTravin/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,pminutillo/pentaho-kettle,ma459006574/pentaho-kettle,ViswesvarSekar/pentaho-kettle,pentaho/pentaho-kettle,eayoungs/pentaho-kettle,pminutillo/pentaho-kettle,nicoben/pentaho-kettle,hudak/pentaho-kettle,tkafalas/pentaho-kettle,flbrino/pentaho-kettle,matrix-stone/pentaho-kettle,emartin-pentaho/pentaho-kettle,alina-ipatina/pentaho-kettle,mbatchelor/pentaho-kettle,nanata1115/pentaho-kettle,YuryBY/pentaho-kettle,CapeSepias/pentaho-kettle,bmorrise/pentaho-kettle,nanata1115/pentaho-kettle,matrix-stone/pentaho-kettle,ma459006574/pentaho-kettle,rfellows/pentaho-kettle,cjsonger/pentaho-kettle,SergeyTravin/pentaho-kettle,stepanovdg/pentaho-kettle,CapeSepias/pentaho-kettle,stevewillcock/pentaho-kettle,mattyb149/pentaho-kettle,nicoben/pentaho-kettle,pymjer/pentaho-kettle,nantunes/pentaho-kettle,CapeSepias/pentaho-kettle,denisprotopopov/pentaho-kettle,cjsonger/pentaho-kettle,yshakhau/pentaho-kettle,e-cuellar/pentaho-kettle,zlcnju/kettle,lgrill-pentaho/pentaho-kettle,airy-ict/pentaho-kettle,pavel-sakun/pentaho-kettle,zlcnju/kettle,zlcnju/kettle,mdamour1976/pentaho-kettle,aminmkhan/pentaho-kettle,jbrant/pentaho-kettle,airy-ict/pentaho-kettle,GauravAshara/pentaho-kettle,ccaspanello/pentaho-kettle,roboguy/pentaho-kettle,aminmkhan/pentaho-kettle,birdtsai/pentaho-kettle,rfellows/pentaho-kettle,gretchiemoran/pentaho-kettle,tmcsantos/pentaho-kettle,roboguy/pentaho-kettle,YuryBY/pentaho-kettle,dkincade/pentaho-kettle,aminmkhan/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,yshakhau/pentaho-kettle,ccaspanello/pentaho-kettle,nicoben/pentaho-kettle,mdamour1976/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,brosander/pentaho-kettle,HiromuHota/pentaho-kettle,skofra0/pentaho-kettle,mbatchelor/pentaho-kettle,ddiroma/pentaho-kettle,akhayrutdinov/pentaho-kettle,ivanpogodin/pentaho-kettle,ivanpogodin/pentaho-kettle,stepanovdg/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,HiromuHota/pentaho-kettle,wseyler/pentaho-kettle,EcoleKeine/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,bmorrise/pentaho-kettle,alina-ipatina/pentaho-kettle,pavel-sakun/pentaho-kettle,pavel-sakun/pentaho-kettle,nantunes/pentaho-kettle,drndos/pentaho-kettle,e-cuellar/pentaho-kettle,ddiroma/pentaho-kettle,mdamour1976/pentaho-kettle,roboguy/pentaho-kettle,kurtwalker/pentaho-kettle,mattyb149/pentaho-kettle,kurtwalker/pentaho-kettle,andrei-viaryshka/pentaho-kettle,Advent51/pentaho-kettle,matthewtckr/pentaho-kettle,bmorrise/pentaho-kettle,marcoslarsen/pentaho-kettle,akhayrutdinov/pentaho-kettle,graimundo/pentaho-kettle,sajeetharan/pentaho-kettle,bmorrise/pentaho-kettle,HiromuHota/pentaho-kettle,pymjer/pentaho-kettle,drndos/pentaho-kettle,alina-ipatina/pentaho-kettle,DFieldFL/pentaho-kettle,ViswesvarSekar/pentaho-kettle,codek/pentaho-kettle,flbrino/pentaho-kettle,nicoben/pentaho-kettle,ccaspanello/pentaho-kettle,pminutillo/pentaho-kettle,lgrill-pentaho/pentaho-kettle,mkambol/pentaho-kettle,hudak/pentaho-kettle,lgrill-pentaho/pentaho-kettle,MikhailHubanau/pentaho-kettle,marcoslarsen/pentaho-kettle,pentaho/pentaho-kettle,wseyler/pentaho-kettle,eayoungs/pentaho-kettle,tmcsantos/pentaho-kettle,brosander/pentaho-kettle,sajeetharan/pentaho-kettle,GauravAshara/pentaho-kettle,emartin-pentaho/pentaho-kettle,gretchiemoran/pentaho-kettle,emartin-pentaho/pentaho-kettle,andrei-viaryshka/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,jbrant/pentaho-kettle,matthewtckr/pentaho-kettle,stepanovdg/pentaho-kettle,yshakhau/pentaho-kettle,EcoleKeine/pentaho-kettle,airy-ict/pentaho-kettle,ddiroma/pentaho-kettle,tmcsantos/pentaho-kettle,denisprotopopov/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,matthewtckr/pentaho-kettle,mbatchelor/pentaho-kettle,codek/pentaho-kettle,yshakhau/pentaho-kettle,pedrofvteixeira/pentaho-kettle,dkincade/pentaho-kettle,aminmkhan/pentaho-kettle,nanata1115/pentaho-kettle,mbatchelor/pentaho-kettle,gretchiemoran/pentaho-kettle,kurtwalker/pentaho-kettle,wseyler/pentaho-kettle,mkambol/pentaho-kettle,mdamour1976/pentaho-kettle,pedrofvteixeira/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,flbrino/pentaho-kettle,MikhailHubanau/pentaho-kettle,matrix-stone/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,skofra0/pentaho-kettle,ccaspanello/pentaho-kettle,stepanovdg/pentaho-kettle,ma459006574/pentaho-kettle,denisprotopopov/pentaho-kettle,nanata1115/pentaho-kettle,rmansoor/pentaho-kettle,andrei-viaryshka/pentaho-kettle,graimundo/pentaho-kettle,gretchiemoran/pentaho-kettle,roboguy/pentaho-kettle,codek/pentaho-kettle,pentaho/pentaho-kettle,graimundo/pentaho-kettle,sajeetharan/pentaho-kettle,akhayrutdinov/pentaho-kettle,birdtsai/pentaho-kettle,mattyb149/pentaho-kettle,EcoleKeine/pentaho-kettle,tkafalas/pentaho-kettle,cjsonger/pentaho-kettle,brosander/pentaho-kettle,dkincade/pentaho-kettle,Advent51/pentaho-kettle,mattyb149/pentaho-kettle,jbrant/pentaho-kettle,drndos/pentaho-kettle,tmcsantos/pentaho-kettle,YuryBY/pentaho-kettle,Advent51/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,jbrant/pentaho-kettle,rfellows/pentaho-kettle,SergeyTravin/pentaho-kettle,denisprotopopov/pentaho-kettle,pymjer/pentaho-kettle,matrix-stone/pentaho-kettle,nantunes/pentaho-kettle,eayoungs/pentaho-kettle,cjsonger/pentaho-kettle,pminutillo/pentaho-kettle,MikhailHubanau/pentaho-kettle,SergeyTravin/pentaho-kettle,ddiroma/pentaho-kettle,DFieldFL/pentaho-kettle,hudak/pentaho-kettle,rmansoor/pentaho-kettle,CapeSepias/pentaho-kettle,sajeetharan/pentaho-kettle,mkambol/pentaho-kettle,hudak/pentaho-kettle,ma459006574/pentaho-kettle,eayoungs/pentaho-kettle,pymjer/pentaho-kettle,dkincade/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,drndos/pentaho-kettle,tkafalas/pentaho-kettle,e-cuellar/pentaho-kettle,akhayrutdinov/pentaho-kettle,marcoslarsen/pentaho-kettle,stevewillcock/pentaho-kettle,wseyler/pentaho-kettle,YuryBY/pentaho-kettle,pedrofvteixeira/pentaho-kettle,Advent51/pentaho-kettle,ivanpogodin/pentaho-kettle,alina-ipatina/pentaho-kettle,flbrino/pentaho-kettle,e-cuellar/pentaho-kettle,lgrill-pentaho/pentaho-kettle,marcoslarsen/pentaho-kettle,HiromuHota/pentaho-kettle,ivanpogodin/pentaho-kettle,skofra0/pentaho-kettle,mkambol/pentaho-kettle,matthewtckr/pentaho-kettle,zlcnju/kettle,AlexanderBuloichik/pentaho-kettle,graimundo/pentaho-kettle,airy-ict/pentaho-kettle,DFieldFL/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,codek/pentaho-kettle,kurtwalker/pentaho-kettle,skofra0/pentaho-kettle,brosander/pentaho-kettle,stevewillcock/pentaho-kettle
|
/*
* Copyright (c) 2007 Pentaho Corporation. All rights reserved.
* This software was developed by Pentaho Corporation and is provided under the terms
* of the GNU Lesser General Public License, Version 2.1. You may not use
* this file except in compliance with the license. If you need a copy of the license,
* please go to http://www.gnu.org/licenses/lgpl-2.1.txt. The Original Code is Pentaho
* Data Integration. The Initial Developer is Pentaho Corporation.
*
* Software distributed under the GNU Lesser Public License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to
* the license for the specific language governing your rights and limitations.
*/
/**********************************************************************
** **
** **
** Kettle, from version 2.2 on, is released into the public domain **
** under the Lesser GNU Public License (LGPL). **
** **
** For more details, please read the document LICENSE.txt, included **
** in this project **
** **
** http://www.kettle.be **
** info@kettle.be **
** **
**********************************************************************/
package org.pentaho.di.core.database;
import java.io.StringReader;
import java.sql.BatchUpdateException;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.sql.DataSource;
import org.eclipse.core.runtime.IProgressMonitor;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.Counter;
import org.pentaho.di.core.DBCache;
import org.pentaho.di.core.DBCacheEntry;
import org.pentaho.di.core.Result;
import org.pentaho.di.core.RowMetaAndData;
import org.pentaho.di.core.database.map.DatabaseConnectionMap;
import org.pentaho.di.core.database.util.DatabaseUtil;
import org.pentaho.di.core.exception.KettleDatabaseBatchException;
import org.pentaho.di.core.exception.KettleDatabaseException;
import org.pentaho.di.core.exception.KettleValueException;
import org.pentaho.di.core.logging.LogWriter;
import org.pentaho.di.core.row.RowDataUtil;
import org.pentaho.di.core.row.RowMeta;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMeta;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.core.variables.Variables;
/**
* Database handles the process of connecting to, reading from, writing to and updating databases.
* The database specific parameters are defined in DatabaseInfo.
*
* @author Matt
* @since 05-04-2003
*
*/
public class Database implements VariableSpace
{
private DatabaseMeta databaseMeta;
private int rowlimit;
private int commitsize;
private Connection connection;
private Statement sel_stmt;
private PreparedStatement pstmt;
private PreparedStatement prepStatementLookup;
private PreparedStatement prepStatementUpdate;
private PreparedStatement prepStatementInsert;
private PreparedStatement pstmt_seq;
private CallableStatement cstmt;
// private ResultSetMetaData rsmd;
private DatabaseMetaData dbmd;
private RowMetaInterface rowMeta;
private int written;
private LogWriter log;
/**
* Counts the number of rows written to a batch for a certain PreparedStatement.
*/
private Map<PreparedStatement, Integer> batchCounterMap;
/**
* Number of times a connection was opened using this object.
* Only used in the context of a database connection map
*/
private int opened;
/**
* The copy is equal to opened at the time of creation.
*/
private int copy;
private String connectionGroup;
private boolean performRollbackAtLastDisconnect; // Only used in the context of a database connection map
private String partitionId;
private VariableSpace variables = new Variables();
/**
* Construct a new Database Connection
* @param inf The Database Connection Info to construct the connection with.
*/
public Database(DatabaseMeta inf)
{
log=LogWriter.getInstance();
databaseMeta = inf;
shareVariablesWith(inf);
batchCounterMap = new HashMap<PreparedStatement, Integer>();
pstmt = null;
rowMeta = null;
dbmd = null;
rowlimit=0;
written=0;
performRollbackAtLastDisconnect=false;
log.logDetailed(toString(), "New database connection defined");
}
public boolean equals(Object obj)
{
Database other = (Database) obj;
return other.databaseMeta.equals(other.databaseMeta);
}
/**
* Allows for the injection of a "life" connection, generated by a piece of software outside of Kettle.
* @param connection
*/
public void setConnection(Connection connection) {
this.connection = connection;
}
/**
* @return Returns the connection.
*/
public Connection getConnection()
{
return connection;
}
/**
* Set the maximum number of records to retrieve from a query.
* @param rows
*/
public void setQueryLimit(int rows)
{
rowlimit = rows;
}
/**
* @return Returns the prepStatementInsert.
*/
public PreparedStatement getPrepStatementInsert()
{
return prepStatementInsert;
}
/**
* @return Returns the prepStatementLookup.
*/
public PreparedStatement getPrepStatementLookup()
{
return prepStatementLookup;
}
/**
* @return Returns the prepStatementUpdate.
*/
public PreparedStatement getPrepStatementUpdate()
{
return prepStatementUpdate;
}
/**
* Open the database connection.
* @throws KettleDatabaseException if something went wrong.
*/
public void connect() throws KettleDatabaseException
{
connect(null);
}
/**
* Open the database connection.
* @param partitionId the partition ID in the cluster to connect to.
* @throws KettleDatabaseException if something went wrong.
*/
public void connect(String partitionId) throws KettleDatabaseException
{
connect(null, partitionId);
}
public synchronized void connect(String group, String partitionId) throws KettleDatabaseException
{
// Before anything else, let's see if we already have a connection defined for this group/partition!
// The group is called after the thread-name of the transformation or job that is running
// The name of that threadname is expected to be unique (it is in Kettle)
// So the deal is that if there is another thread using that, we go for it.
//
if (!Const.isEmpty(group))
{
this.connectionGroup = group;
this.partitionId = partitionId;
DatabaseConnectionMap map = DatabaseConnectionMap.getInstance();
// Try to find the conection for the group
Database lookup = map.getDatabase(group, partitionId, this);
if (lookup==null) // We already opened this connection for the partition & database in this group
{
// Do a normal connect and then store this database object for later re-use.
normalConnect(partitionId);
opened++;
copy = opened;
map.storeDatabase(group, partitionId, this);
}
else
{
connection = lookup.getConnection();
lookup.setOpened(lookup.getOpened()+1); // if this counter hits 0 again, close the connection.
copy = lookup.getOpened();
}
}
else
{
// Proceed with a normal connect
normalConnect(partitionId);
}
}
/**
* Open the database connection.
* @param partitionId the partition ID in the cluster to connect to.
* @throws KettleDatabaseException if something went wrong.
*/
public void normalConnect(String partitionId) throws KettleDatabaseException
{
if (databaseMeta==null)
{
throw new KettleDatabaseException("No valid database connection defined!");
}
try
{
// First see if we use connection pooling...
//
if ( databaseMeta.isUsingConnectionPool() && // default = false for backward compatibility
databaseMeta.getAccessType()!=DatabaseMeta.TYPE_ACCESS_JNDI // JNDI does pooling on it's own.
)
{
try
{
this.connection = ConnectionPoolUtil.getConnection(databaseMeta, partitionId);
}
catch (Exception e)
{
throw new KettleDatabaseException("Error occured while trying to connect to the database", e);
}
}
else
{
connectUsingClass(databaseMeta.getDriverClass(), partitionId );
log.logDetailed(toString(), "Connected to database.");
// See if we need to execute extra SQL statemtent...
String sql = environmentSubstitute( databaseMeta.getConnectSQL() );
// only execute if the SQL is not empty, null and is not just a bunch of spaces, tabs, CR etc.
if (!Const.isEmpty(sql) && !Const.onlySpaces(sql))
{
execStatements(sql);
log.logDetailed(toString(), "Executed connect time SQL statements:"+Const.CR+sql);
}
}
}
catch(Exception e)
{
throw new KettleDatabaseException("Error occured while trying to connect to the database", e);
}
}
private void initWithJNDI(String jndiName) throws KettleDatabaseException {
connection = null;
try {
DataSource dataSource = DatabaseUtil.getDataSourceFromJndi(jndiName);
if (dataSource != null) {
connection = dataSource.getConnection();
if (connection == null) {
throw new KettleDatabaseException( "Invalid JNDI connection "+ jndiName); //$NON-NLS-1$
}
} else {
throw new KettleDatabaseException( "Invalid JNDI connection "+ jndiName); //$NON-NLS-1$
}
} catch (Exception e) {
throw new KettleDatabaseException( "Invalid JNDI connection "+ jndiName + " : " + e.getMessage()); //$NON-NLS-1$
}
}
/**
* Connect using the correct classname
* @param classname for example "org.gjt.mm.mysql.Driver"
* @return true if the connect was succesfull, false if something went wrong.
*/
private void connectUsingClass(String classname, String partitionId) throws KettleDatabaseException
{
// Install and load the jdbc Driver
// first see if this is a JNDI connection
if( databaseMeta.getAccessType() == DatabaseMeta.TYPE_ACCESS_JNDI ) {
initWithJNDI( environmentSubstitute(databaseMeta.getDatabaseName()) );
return;
}
try
{
Class.forName(classname);
}
catch(NoClassDefFoundError e)
{
throw new KettleDatabaseException("Exception while loading class", e);
}
catch(ClassNotFoundException e)
{
throw new KettleDatabaseException("Exception while loading class", e);
}
catch(Exception e)
{
throw new KettleDatabaseException("Exception while loading class", e);
}
try
{
String url;
if (databaseMeta.isPartitioned() && !Const.isEmpty(partitionId))
{
url = environmentSubstitute(databaseMeta.getURL(partitionId));
}
else
{
url = environmentSubstitute(databaseMeta.getURL());
}
String clusterUsername=null;
String clusterPassword=null;
if (databaseMeta.isPartitioned() && !Const.isEmpty(partitionId))
{
// Get the cluster information...
PartitionDatabaseMeta partition = databaseMeta.getPartitionMeta(partitionId);
if (partition!=null)
{
clusterUsername = partition.getUsername();
clusterPassword = partition.getPassword();
}
}
String username;
String password;
if (!Const.isEmpty(clusterUsername))
{
username = clusterUsername;
password = clusterPassword;
}
else
{
username = environmentSubstitute(databaseMeta.getUsername());
password = environmentSubstitute(databaseMeta.getPassword());
}
if (databaseMeta.supportsOptionsInURL())
{
if (!Const.isEmpty(username) || !Const.isEmpty(password))
{
// also allow for empty username with given password, in this case username must be given with one space
connection = DriverManager.getConnection(url, Const.NVL(username, " "), Const.NVL(password, ""));
}
else
{
// Perhaps the username is in the URL or no username is required...
connection = DriverManager.getConnection(url);
}
}
else
{
Properties properties = databaseMeta.getConnectionProperties();
if (!Const.isEmpty(username)) properties.put("user", username);
if (!Const.isEmpty(password)) properties.put("password", password);
connection = DriverManager.getConnection(url, properties);
}
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error connecting to database: (using class "+classname+")", e);
}
catch(Throwable e)
{
throw new KettleDatabaseException("Error connecting to database: (using class "+classname+")", e);
}
}
/**
* Disconnect from the database and close all open prepared statements.
*/
public synchronized void disconnect()
{
try
{
if (connection==null)
{
return ; // Nothing to do...
}
if (connection.isClosed())
{
return ; // Nothing to do...
}
if (pstmt !=null)
{
pstmt.close();
pstmt=null;
}
if (prepStatementLookup!=null)
{
prepStatementLookup.close();
prepStatementLookup=null;
}
if (prepStatementInsert!=null)
{
prepStatementInsert.close();
prepStatementInsert=null;
}
if (prepStatementUpdate!=null)
{
prepStatementUpdate.close();
prepStatementUpdate=null;
}
if (pstmt_seq!=null)
{
pstmt_seq.close();
pstmt_seq=null;
}
// See if there are other steps using this connection in a connection group.
// If so, we will hold commit & connection close until then.
//
if (!Const.isEmpty(connectionGroup))
{
DatabaseConnectionMap map = DatabaseConnectionMap.getInstance();
Database lookup = map.getDatabase(connectionGroup, partitionId, this);
if (lookup!=null)
{
lookup.opened--;
if (lookup.opened>0)
{
return;
}
else
{
map.removeConnection(connectionGroup, partitionId, this); // remove the trace of it.
// Before we close perform commit or rollback.
if (lookup.performRollbackAtLastDisconnect)
{
rollback(true);
}
else
{
commit(true);
}
}
}
}
else
{
if (!isAutoCommit()) // Do we really still need this commit??
{
commit();
}
}
if (connection!=null)
{
connection.close();
if (!databaseMeta.isUsingConnectionPool())
{
connection=null;
}
}
log.logDetailed(toString(), "Connection to database closed!");
}
catch(SQLException ex)
{
log.logError(toString(), "Error disconnecting from database:"+Const.CR+ex.getMessage());
log.logError(toString(), Const.getStackTracker(ex));
}
catch(KettleDatabaseException dbe)
{
log.logError(toString(), "Error disconnecting from database:"+Const.CR+dbe.getMessage());
log.logError(toString(), Const.getStackTracker(dbe));
}
}
/**
* Cancel the open/running queries on the database connection
* @throws KettleDatabaseException
*/
public void cancelQuery() throws KettleDatabaseException
{
cancelStatement(pstmt);
cancelStatement(sel_stmt);
}
/**
* Cancel an open/running SQL statement
* @param statement the statement to cancel
* @throws KettleDatabaseException
*/
public void cancelStatement(Statement statement) throws KettleDatabaseException
{
try
{
if (statement!=null)
{
statement.cancel();
}
log.logDetailed(toString(), "Statement canceled!");
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Error cancelling statement", ex);
}
}
/**
* Specify after how many rows a commit needs to occur when inserting or updating values.
* @param commsize The number of rows to wait before doing a commit on the connection.
*/
public void setCommit(int commsize)
{
commitsize=commsize;
String onOff = (commitsize<=0?"on":"off");
try
{
connection.setAutoCommit(commitsize<=0);
log.logDetailed(toString(), "Auto commit "+onOff);
}
catch(Exception e)
{
log.logError(toString(), "Can't turn auto commit "+onOff);
}
}
/**
* Perform a commit the connection if this is supported by the database
*/
public void commit() throws KettleDatabaseException
{
commit(false);
}
private void commit(boolean force) throws KettleDatabaseException
{
try
{
// Don't do the commit, wait until the end of the transformation.
// When the last database copy (opened counter) is about to be closed, we do a commit
// There is one catch, we need to catch the rollback
// The transformation will stop everything and then we'll do the rollback.
// The flag is in "performRollback", private only
//
if (!Const.isEmpty(connectionGroup) && !force)
{
return;
}
if (getDatabaseMetaData().supportsTransactions())
{
if (log.isDebug()) log.logDebug(toString(), "Commit on database connection ["+toString()+"]");
connection.commit();
}
else
{
log.logDetailed(toString(), "No commit possible on database connection ["+toString()+"]");
}
}
catch(Exception e)
{
if (databaseMeta.supportsEmptyTransactions())
throw new KettleDatabaseException("Error comitting connection", e);
}
}
public void rollback() throws KettleDatabaseException
{
rollback(false);
}
private void rollback(boolean force) throws KettleDatabaseException
{
try
{
if (!Const.isEmpty(connectionGroup) && !force)
{
DatabaseConnectionMap map = DatabaseConnectionMap.getInstance();
Database lookup = map.getDatabase(connectionGroup, partitionId, this);
lookup.performRollbackAtLastDisconnect=true;
return;
}
if (getDatabaseMetaData().supportsTransactions())
{
if (connection!=null) {
if (log.isDebug()) log.logDebug(toString(), "Rollback on database connection ["+toString()+"]");
connection.rollback();
}
}
else
{
log.logDetailed(toString(), "No rollback possible on database connection ["+toString()+"]");
}
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error performing rollback on connection", e);
}
}
/**
* Prepare inserting values into a table, using the fields & values in a Row
* @param rowMeta The row metadata to determine which values need to be inserted
* @param table The name of the table in which we want to insert rows
* @throws KettleDatabaseException if something went wrong.
*/
public void prepareInsert(RowMetaInterface rowMeta, String tableName) throws KettleDatabaseException
{
prepareInsert(rowMeta, null, tableName);
}
/**
* Prepare inserting values into a table, using the fields & values in a Row
* @param rowMeta The metadata row to determine which values need to be inserted
* @param schemaName The name of the schema in which we want to insert rows
* @param tableName The name of the table in which we want to insert rows
* @throws KettleDatabaseException if something went wrong.
*/
public void prepareInsert(RowMetaInterface rowMeta, String schemaName, String tableName) throws KettleDatabaseException
{
if (rowMeta.size()==0)
{
throw new KettleDatabaseException("No fields in row, can't insert!");
}
String ins = getInsertStatement(schemaName, tableName, rowMeta);
log.logDetailed(toString(),"Preparing statement: "+Const.CR+ins);
prepStatementInsert=prepareSQL(ins);
}
/**
* Prepare a statement to be executed on the database. (does not return generated keys)
* @param sql The SQL to be prepared
* @return The PreparedStatement object.
* @throws KettleDatabaseException
*/
public PreparedStatement prepareSQL(String sql)
throws KettleDatabaseException
{
return prepareSQL(sql, false);
}
/**
* Prepare a statement to be executed on the database.
* @param sql The SQL to be prepared
* @param returnKeys set to true if you want to return generated keys from an insert statement
* @return The PreparedStatement object.
* @throws KettleDatabaseException
*/
public PreparedStatement prepareSQL(String sql, boolean returnKeys) throws KettleDatabaseException
{
try
{
if (returnKeys)
{
return connection.prepareStatement(databaseMeta.stripCR(sql), Statement.RETURN_GENERATED_KEYS);
}
else
{
return connection.prepareStatement(databaseMeta.stripCR(sql));
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't prepare statement:"+Const.CR+sql, ex);
}
}
public void closeLookup() throws KettleDatabaseException
{
closePreparedStatement(pstmt);
pstmt=null;
}
public void closePreparedStatement(PreparedStatement ps) throws KettleDatabaseException
{
if (ps!=null)
{
try
{
ps.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing prepared statement", e);
}
}
}
public void closeInsert() throws KettleDatabaseException
{
if (prepStatementInsert!=null)
{
try
{
prepStatementInsert.close();
prepStatementInsert = null;
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing insert prepared statement.", e);
}
}
}
public void closeUpdate() throws KettleDatabaseException
{
if (prepStatementUpdate!=null)
{
try
{
prepStatementUpdate.close();
prepStatementUpdate=null;
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing update prepared statement.", e);
}
}
}
public void setValues(RowMetaInterface rowMeta, Object[] data) throws KettleDatabaseException
{
setValues(rowMeta, data, pstmt);
}
public void setValues(RowMetaAndData row) throws KettleDatabaseException
{
setValues(row.getRowMeta(), row.getData());
}
public void setValuesInsert(RowMetaInterface rowMeta, Object[] data) throws KettleDatabaseException
{
setValues(rowMeta, data, prepStatementInsert);
}
public void setValuesInsert(RowMetaAndData row) throws KettleDatabaseException
{
setValues(row.getRowMeta(), row.getData(), prepStatementInsert);
}
public void setValuesUpdate(RowMetaInterface rowMeta, Object[] data) throws KettleDatabaseException
{
setValues(rowMeta, data, prepStatementUpdate);
}
public void setValuesLookup(RowMetaInterface rowMeta, Object[] data) throws KettleDatabaseException
{
setValues(rowMeta, data, prepStatementLookup);
}
public void setProcValues(RowMetaInterface rowMeta, Object[] data, int argnrs[], String argdir[], boolean result) throws KettleDatabaseException
{
int pos;
if (result) pos=2; else pos=1;
for (int i=0;i<argnrs.length;i++)
{
if (argdir[i].equalsIgnoreCase("IN") || argdir[i].equalsIgnoreCase("INOUT"))
{
ValueMetaInterface valueMeta = rowMeta.getValueMeta(argnrs[i]);
Object value = data[argnrs[i]];
setValue(cstmt, valueMeta, value, pos);
pos++;
} else {
pos++; //next parameter when OUT
}
}
}
public void setValue(PreparedStatement ps, ValueMetaInterface v, Object object, int pos) throws KettleDatabaseException
{
String debug = "";
try
{
switch(v.getType())
{
case ValueMetaInterface.TYPE_NUMBER :
if (object!=null)
{
debug="Number, not null, getting number from value";
double num = v.getNumber(object).doubleValue();
if (databaseMeta.supportsFloatRoundingOnUpdate() && v.getPrecision()>=0)
{
debug="Number, rounding to precision ["+v.getPrecision()+"]";
num = Const.round(num, v.getPrecision());
}
debug="Number, setting ["+num+"] on position #"+pos+" of the prepared statement";
ps.setDouble(pos, num);
}
else
{
ps.setNull(pos, java.sql.Types.DOUBLE);
}
break;
case ValueMetaInterface.TYPE_INTEGER:
debug="Integer";
if (object!=null)
{
if (databaseMeta.supportsSetLong())
{
ps.setLong(pos, v.getInteger(object).longValue() );
}
else
{
double d = v.getNumber(object).doubleValue();
if (databaseMeta.supportsFloatRoundingOnUpdate() && v.getPrecision()>=0)
{
ps.setDouble(pos, d );
}
else
{
ps.setDouble(pos, Const.round( d, v.getPrecision() ) );
}
}
}
else
{
ps.setNull(pos, java.sql.Types.INTEGER);
}
break;
case ValueMetaInterface.TYPE_STRING :
debug="String";
if (v.getLength()<DatabaseMeta.CLOB_LENGTH)
{
if (object!=null)
{
ps.setString(pos, v.getString(object));
}
else
{
ps.setNull(pos, java.sql.Types.VARCHAR);
}
}
else
{
if (object!=null)
{
String string = v.getString(object);
int maxlen = databaseMeta.getMaxTextFieldLength();
int len = string.length();
// Take the last maxlen characters of the string...
int begin = len - maxlen;
if (begin<0) begin=0;
// Get the substring!
String logging = string.substring(begin);
if (databaseMeta.supportsSetCharacterStream())
{
StringReader sr = new StringReader(logging);
ps.setCharacterStream(pos, sr, logging.length());
}
else
{
ps.setString(pos, logging);
}
}
else
{
ps.setNull(pos, java.sql.Types.VARCHAR);
}
}
break;
case ValueMetaInterface.TYPE_DATE :
debug="Date";
if (object!=null)
{
long dat = v.getInteger(object).longValue(); // converts using Date.getTime()
if(v.getPrecision()==1 || !databaseMeta.supportsTimeStampToDateConversion())
{
// Convert to DATE!
java.sql.Date ddate = new java.sql.Date(dat);
ps.setDate(pos, ddate);
}
else
{
java.sql.Timestamp sdate = new java.sql.Timestamp(dat);
ps.setTimestamp(pos, sdate);
}
}
else
{
if(v.getPrecision()==1 || !databaseMeta.supportsTimeStampToDateConversion())
{
ps.setNull(pos, java.sql.Types.DATE);
}
else
{
ps.setNull(pos, java.sql.Types.TIMESTAMP);
}
}
break;
case ValueMetaInterface.TYPE_BOOLEAN:
debug="Boolean";
if (databaseMeta.supportsBooleanDataType())
{
if (object!=null)
{
ps.setBoolean(pos, v.getBoolean(object).booleanValue());
}
else
{
ps.setNull(pos, java.sql.Types.BOOLEAN);
}
}
else
{
if (object!=null)
{
ps.setString(pos, v.getBoolean(object).booleanValue()?"Y":"N");
}
else
{
ps.setNull(pos, java.sql.Types.CHAR);
}
}
break;
case ValueMetaInterface.TYPE_BIGNUMBER:
debug="BigNumber";
if (object!=null)
{
ps.setBigDecimal(pos, v.getBigNumber(object));
}
else
{
ps.setNull(pos, java.sql.Types.DECIMAL);
}
break;
case ValueMetaInterface.TYPE_BINARY:
debug="Binary";
if (object!=null)
{
ps.setBytes(pos, v.getBinary(object));
}
else
{
ps.setNull(pos, java.sql.Types.BINARY);
}
break;
default:
debug="default";
// placeholder
ps.setNull(pos, java.sql.Types.VARCHAR);
break;
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Error setting value #"+pos+" ["+v.toString()+"] on prepared statement ("+debug+")"+Const.CR+ex.toString(), ex);
}
catch(Exception e)
{
throw new KettleDatabaseException("Error setting value #"+pos+" ["+(v==null?"NULL":v.toString())+"] on prepared statement ("+debug+")"+Const.CR+e.toString(), e);
}
}
public void setValues(RowMetaAndData row, PreparedStatement ps) throws KettleDatabaseException
{
setValues(row.getRowMeta(), row.getData(), ps);
}
public void setValues(RowMetaInterface rowMeta, Object[] data, PreparedStatement ps) throws KettleDatabaseException
{
// now set the values in the row!
for (int i=0;i<rowMeta.size();i++)
{
ValueMetaInterface v = rowMeta.getValueMeta(i);
Object object = data[i];
try
{
setValue(ps, v, object, i+1);
}
catch(KettleDatabaseException e)
{
throw new KettleDatabaseException("offending row : "+rowMeta, e);
}
}
}
/**
* Sets the values of the preparedStatement pstmt.
* @param rowMeta
* @param data
*/
public void setValues(RowMetaInterface rowMeta, Object[] data, PreparedStatement ps, int ignoreThisValueIndex) throws KettleDatabaseException
{
// now set the values in the row!
int index=0;
for (int i=0;i<rowMeta.size();i++)
{
if (i!=ignoreThisValueIndex)
{
ValueMetaInterface v = rowMeta.getValueMeta(i);
Object object = data[i];
try
{
setValue(ps, v, object, index+1);
index++;
}
catch(KettleDatabaseException e)
{
throw new KettleDatabaseException("offending row : "+rowMeta, e);
}
}
}
}
/**
* @param ps The prepared insert statement to use
* @return The generated keys in auto-increment fields
* @throws KettleDatabaseException in case something goes wrong retrieving the keys.
*/
public RowMetaAndData getGeneratedKeys(PreparedStatement ps) throws KettleDatabaseException
{
ResultSet keys = null;
try
{
keys=ps.getGeneratedKeys(); // 1 row of keys
ResultSetMetaData resultSetMetaData = keys.getMetaData();
RowMetaInterface rowMeta = getRowInfo(resultSetMetaData, false, false);
return new RowMetaAndData(rowMeta, getRow(keys, resultSetMetaData, rowMeta));
}
catch(Exception ex)
{
throw new KettleDatabaseException("Unable to retrieve key(s) from auto-increment field(s)", ex);
}
finally
{
if (keys!=null)
{
try
{
keys.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to close resultset of auto-generated keys", e);
}
}
}
}
public Long getNextSequenceValue(String sequenceName, String keyfield) throws KettleDatabaseException
{
return getNextSequenceValue(null, sequenceName, keyfield);
}
public Long getNextSequenceValue(String schemaName, String sequenceName, String keyfield) throws KettleDatabaseException
{
Long retval=null;
String schemaSequence = databaseMeta.getQuotedSchemaTableCombination(schemaName, sequenceName);
try
{
if (pstmt_seq==null)
{
pstmt_seq=connection.prepareStatement(databaseMeta.getSeqNextvalSQL(databaseMeta.stripCR(schemaSequence)));
}
ResultSet rs=null;
try
{
rs = pstmt_seq.executeQuery();
if (rs.next())
{
retval = Long.valueOf( rs.getLong(1) );
}
}
finally
{
if ( rs != null ) rs.close();
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to get next value for sequence : "+schemaSequence, ex);
}
return retval;
}
public void insertRow(String tableName, RowMetaInterface fields, Object[] data) throws KettleDatabaseException
{
prepareInsert(fields, tableName);
setValuesInsert(fields, data);
insertRow();
closeInsert();
}
public String getInsertStatement(String tableName, RowMetaInterface fields)
{
return getInsertStatement(null, tableName, fields);
}
public String getInsertStatement(String schemaName, String tableName, RowMetaInterface fields)
{
StringBuffer ins=new StringBuffer(128);
String schemaTable = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName);
ins.append("INSERT INTO ").append(schemaTable).append('(');
// now add the names in the row:
for (int i=0;i<fields.size();i++)
{
if (i>0) ins.append(", ");
String name = fields.getValueMeta(i).getName();
ins.append(databaseMeta.quoteField(name));
}
ins.append(") VALUES (");
// Add placeholders...
for (int i=0;i<fields.size();i++)
{
if (i>0) ins.append(", ");
ins.append(" ?");
}
ins.append(')');
return ins.toString();
}
public void insertRow()
throws KettleDatabaseException
{
insertRow(prepStatementInsert);
}
public void insertRow(boolean batch) throws KettleDatabaseException
{
insertRow(prepStatementInsert, batch);
}
public void updateRow()
throws KettleDatabaseException
{
insertRow(prepStatementUpdate);
}
public void insertRow(PreparedStatement ps)
throws KettleDatabaseException
{
insertRow(ps, false);
}
/**
* @param batchCounterMap The batch counter map to set.
*/
public void setBatchCounterMap(Map<PreparedStatement, Integer> batchCounterMap)
{
this.batchCounterMap = batchCounterMap;
}
/**
* @return Returns the batch counter map.
*/
public Map<PreparedStatement, Integer> getBatchCounterMap()
{
return batchCounterMap;
}
/**
* Insert a row into the database using a prepared statement that has all values set.
* @param ps The prepared statement
* @param batch True if you want to use batch inserts (size = commit size)
* @return true if the rows are safe: if batch of rows was sent to the database OR if a commit was done.
* @throws KettleDatabaseException
*/
public boolean insertRow(PreparedStatement ps, boolean batch) throws KettleDatabaseException
{
String debug="insertRow start";
boolean rowsAreSafe=false;
Integer batchCounter = null;
try
{
// Unique connections and Batch inserts don't mix when you want to roll back on certain databases.
// That's why we disable the batch insert in that case.
//
boolean useBatchInsert = batch && getDatabaseMetaData().supportsBatchUpdates() && databaseMeta.supportsBatchUpdates() && Const.isEmpty(connectionGroup);
//
// Add support for batch inserts...
//
if (!isAutoCommit())
{
if (useBatchInsert)
{
debug="insertRow add batch";
// Increment the counter...
//
batchCounter = batchCounterMap.get(ps);
if (batchCounter==null) {
batchCounterMap.put(ps, 1);
}
else {
batchCounterMap.put(ps, Integer.valueOf(batchCounter.intValue()+1));
}
ps.addBatch(); // Add the batch, but don't forget to run the batch
}
else
{
debug="insertRow exec update";
ps.executeUpdate();
}
}
else
{
ps.executeUpdate();
}
written++;
if (!isAutoCommit() && (written%commitsize)==0)
{
if (useBatchInsert)
{
debug="insertRow executeBatch commit";
ps.executeBatch();
commit();
ps.clearBatch();
batchCounterMap.put(ps, Integer.valueOf(0));
}
else
{
debug="insertRow normal commit";
commit();
}
rowsAreSafe=true;
}
return rowsAreSafe;
}
catch(BatchUpdateException ex)
{
KettleDatabaseBatchException kdbe = new KettleDatabaseBatchException("Error updating batch", ex);
kdbe.setUpdateCounts(ex.getUpdateCounts());
List<Exception> exceptions = new ArrayList<Exception>();
// 'seed' the loop with the root exception
SQLException nextException = ex;
do
{
exceptions.add(nextException);
// while current exception has next exception, add to list
}
while ((nextException = nextException.getNextException())!=null);
kdbe.setExceptionsList(exceptions);
throw kdbe;
}
catch(SQLException ex)
{
// log.logError(toString(), Const.getStackTracker(ex));
throw new KettleDatabaseException("Error inserting row", ex);
}
catch(Exception e)
{
// System.out.println("Unexpected exception in ["+debug+"] : "+e.getMessage());
throw new KettleDatabaseException("Unexpected error inserting row in part ["+debug+"]", e);
}
}
/**
* Clears batch of insert prepared statement
* @deprecated
* @throws KettleDatabaseException
*/
public void clearInsertBatch() throws KettleDatabaseException
{
clearBatch(prepStatementInsert);
}
public void clearBatch(PreparedStatement preparedStatement) throws KettleDatabaseException
{
try
{
preparedStatement.clearBatch();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to clear batch for prepared statement", e);
}
}
public void insertFinished(boolean batch) throws KettleDatabaseException
{
insertFinished(prepStatementInsert, batch);
prepStatementInsert = null;
}
/**
* Empty and close a prepared statement.
*
* @param ps The prepared statement to empty and close.
* @param batch true if you are using batch processing (typically true for this method)
* @param psBatchCounter The number of rows on the batch queue
* @throws KettleDatabaseException
*/
public void insertFinished(PreparedStatement ps, boolean batch) throws KettleDatabaseException
{
try
{
if (ps!=null)
{
if (!isAutoCommit())
{
// Get the batch counter. This counter is unique per Prepared Statement.
// It is increased in method insertRow()
//
Integer batchCounter = batchCounterMap.get(ps);
// Execute the batch or just perform a commit.
//
if (batch && getDatabaseMetaData().supportsBatchUpdates() && batchCounter!=null && batchCounter.intValue()>0)
{
// The problem with the batch counters is that you can't just execute the current batch.
// Certain databases have a problem if you execute the batch and if there are no statements in it.
// You can't just catch the exception either because you would have to roll back on certain databases before you can then continue to do anything.
// That leaves the task of keeping track of the number of rows up to our responsibility.
//
ps.executeBatch();
commit();
}
else
{
commit();
}
}
// Let's not forget to close the prepared statement.
//
ps.close();
}
}
catch(BatchUpdateException ex)
{
KettleDatabaseBatchException kdbe = new KettleDatabaseBatchException("Error updating batch", ex);
kdbe.setUpdateCounts(ex.getUpdateCounts());
List<Exception> exceptions = new ArrayList<Exception>();
SQLException nextException = ex.getNextException();
SQLException oldException = null;
// This construction is specifically done for some JDBC drivers, these drivers
// always return the same exception on getNextException() (and thus go into an infinite loop).
// So it's not "equals" but != (comments from Sven Boden).
while ( (nextException != null) && (oldException != nextException) )
{
exceptions.add(nextException);
oldException = nextException;
nextException = nextException.getNextException();
}
kdbe.setExceptionsList(exceptions);
throw kdbe;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to commit connection after having inserted rows.", ex);
}
finally
{
// Remove the batch counter to avoid memory leaks in the database driver
//
batchCounterMap.remove(ps);
}
}
/**
* Execute an SQL statement on the database connection (has to be open)
* @param sql The SQL to execute
* @return a Result object indicating the number of lines read, deleted, inserted, updated, ...
* @throws KettleDatabaseException in case anything goes wrong.
*/
public Result execStatement(String sql) throws KettleDatabaseException
{
return execStatement(sql, null, null);
}
public Result execStatement(String sql, RowMetaInterface params, Object[] data) throws KettleDatabaseException
{
Result result = new Result();
try
{
boolean resultSet;
int count;
if (params!=null)
{
PreparedStatement prep_stmt = connection.prepareStatement(databaseMeta.stripCR(sql));
setValues(params, data, prep_stmt); // set the parameters!
resultSet = prep_stmt.execute();
count = prep_stmt.getUpdateCount();
prep_stmt.close();
}
else
{
String sqlStripped = databaseMeta.stripCR(sql);
// log.logDetailed(toString(), "Executing SQL Statement: ["+sqlStripped+"]");
Statement stmt = connection.createStatement();
resultSet = stmt.execute(sqlStripped);
count = stmt.getUpdateCount();
stmt.close();
}
if (resultSet)
{
// the result is a resultset, but we don't do anything with it!
// You should have called something else!
// log.logDetailed(toString(), "What to do with ResultSet??? (count="+count+")");
}
else
{
if (count > 0)
{
if (sql.toUpperCase().startsWith("INSERT")) result.setNrLinesOutput(count);
if (sql.toUpperCase().startsWith("UPDATE")) result.setNrLinesUpdated(count);
if (sql.toUpperCase().startsWith("DELETE")) result.setNrLinesDeleted(count);
}
}
// See if a cache needs to be cleared...
if (sql.toUpperCase().startsWith("ALTER TABLE") ||
sql.toUpperCase().startsWith("DROP TABLE") ||
sql.toUpperCase().startsWith("CREATE TABLE")
)
{
DBCache.getInstance().clear(databaseMeta.getName());
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't execute SQL: "+sql+Const.CR, ex);
}
catch(Exception e)
{
throw new KettleDatabaseException("Unexpected error executing SQL: "+Const.CR, e);
}
return result;
}
/**
* Execute a series of SQL statements, separated by ;
*
* We are already connected...
* Multiple statements have to be split into parts
* We use the ";" to separate statements...
*
* We keep the results in Result object from Jobs
*
* @param script The SQL script to be execute
* @throws KettleDatabaseException In case an error occurs
* @return A result with counts of the number or records updates, inserted, deleted or read.
*/
public Result execStatements(String script) throws KettleDatabaseException
{
Result result = new Result();
String all = script;
int from=0;
int to=0;
int length = all.length();
int nrstats = 0;
while (to<length)
{
char c = all.charAt(to);
if (c=='"')
{
to++;
c=' ';
while (to<length && c!='"') { c=all.charAt(to); to++; }
}
else
if (c=='\'') // skip until next '
{
to++;
c=' ';
while (to<length && c!='\'') { c=all.charAt(to); to++; }
}
else
if (all.substring(to).startsWith("--")) // -- means: ignore comment until end of line...
{
to++;
while (to<length && c!='\n' && c!='\r') { c=all.charAt(to); to++; }
}
if (c==';' || to>=length-1) // end of statement
{
if (to>=length-1) to++; // grab last char also!
String stat;
if (to<=length) stat = all.substring(from, to);
else stat = all.substring(from);
// If it ends with a ; remove that ;
// Oracle for example can't stand it when this happens...
if (stat.length()>0 && stat.charAt(stat.length()-1)==';')
{
stat = stat.substring(0,stat.length()-1);
}
if (!Const.onlySpaces(stat))
{
String sql=Const.trim(stat);
if (sql.toUpperCase().startsWith("SELECT"))
{
// A Query
log.logDetailed(toString(), "launch SELECT statement: "+Const.CR+sql);
nrstats++;
ResultSet rs = null;
try
{
rs = openQuery(sql);
if (rs!=null)
{
Object[] row = getRow(rs);
while (row!=null)
{
result.setNrLinesRead(result.getNrLinesRead()+1);
if (log.isDetailed()) log.logDetailed(toString(), rowMeta.getString(row));
row = getRow(rs);
}
}
else
{
if (log.isDebug()) log.logDebug(toString(), "Error executing query: "+Const.CR+sql);
}
} catch (KettleValueException e) {
throw new KettleDatabaseException(e); // just pass the error upwards.
}
finally
{
try
{
if ( rs != null ) rs.close();
}
catch (SQLException ex )
{
if (log.isDebug()) log.logDebug(toString(), "Error closing query: "+Const.CR+sql);
}
}
}
else // any kind of statement
{
log.logDetailed(toString(), "launch DDL statement: "+Const.CR+sql);
// A DDL statement
nrstats++;
Result res = execStatement(sql);
result.add(res);
}
}
to++;
from=to;
}
else
{
to++;
}
}
log.logDetailed(toString(), nrstats+" statement"+(nrstats==1?"":"s")+" executed");
return result;
}
public ResultSet openQuery(String sql) throws KettleDatabaseException
{
return openQuery(sql, null, null);
}
/**
* Open a query on the database with a set of parameters stored in a Kettle Row
* @param sql The SQL to launch with question marks (?) as placeholders for the parameters
* @param params The parameters or null if no parameters are used.
* @data the parameter data to open the query with
* @return A JDBC ResultSet
* @throws KettleDatabaseException when something goes wrong with the query.
*/
public ResultSet openQuery(String sql, RowMetaInterface params, Object[] data) throws KettleDatabaseException
{
return openQuery(sql, params, data, ResultSet.FETCH_FORWARD);
}
public ResultSet openQuery(String sql, RowMetaInterface params, Object[] data, int fetch_mode) throws KettleDatabaseException
{
return openQuery(sql, params, data, fetch_mode, false);
}
public ResultSet openQuery(String sql, RowMetaInterface params, Object[] data, int fetch_mode, boolean lazyConversion) throws KettleDatabaseException
{
ResultSet res;
String debug = "Start";
// Create a Statement
try
{
if (params!=null)
{
debug = "P create prepared statement (con==null? "+(connection==null)+")";
pstmt = connection.prepareStatement(databaseMeta.stripCR(sql), ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
debug = "P Set values";
setValues(params, data); // set the dates etc!
if (canWeSetFetchSize(pstmt) )
{
debug = "P Set fetchsize";
int fs = Const.FETCH_SIZE<=pstmt.getMaxRows()?pstmt.getMaxRows():Const.FETCH_SIZE;
// System.out.println("Setting pstmt fetchsize to : "+fs);
{
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL && databaseMeta.isStreamingResults())
{
pstmt.setFetchSize(Integer.MIN_VALUE);
}
else
pstmt.setFetchSize(fs);
}
debug = "P Set fetch direction";
pstmt.setFetchDirection(fetch_mode);
}
debug = "P Set max rows";
if (rowlimit>0 && databaseMeta.supportsSetMaxRows()) pstmt.setMaxRows(rowlimit);
debug = "exec query";
res = pstmt.executeQuery();
}
else
{
debug = "create statement";
sel_stmt = connection.createStatement();
if (canWeSetFetchSize(sel_stmt))
{
debug = "Set fetchsize";
int fs = Const.FETCH_SIZE<=sel_stmt.getMaxRows()?sel_stmt.getMaxRows():Const.FETCH_SIZE;
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL && databaseMeta.isStreamingResults())
{
sel_stmt.setFetchSize(Integer.MIN_VALUE);
}
else
{
sel_stmt.setFetchSize(fs);
}
debug = "Set fetch direction";
sel_stmt.setFetchDirection(fetch_mode);
}
debug = "Set max rows";
if (rowlimit>0 && databaseMeta.supportsSetMaxRows()) sel_stmt.setMaxRows(rowlimit);
debug = "exec query";
res=sel_stmt.executeQuery(databaseMeta.stripCR(sql));
}
debug = "openQuery : get rowinfo";
// MySQL Hack only. It seems too much for the cursor type of operation on MySQL, to have another cursor opened
// to get the length of a String field. So, on MySQL, we ingore the length of Strings in result rows.
//
rowMeta = getRowInfo(res.getMetaData(), databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL, lazyConversion);
}
catch(SQLException ex)
{
// log.logError(toString(), "ERROR executing ["+sql+"]");
// log.logError(toString(), "ERROR in part: ["+debug+"]");
// printSQLException(ex);
throw new KettleDatabaseException("An error occurred executing SQL: "+Const.CR+sql, ex);
}
catch(Exception e)
{
log.logError(toString(), "ERROR executing query: "+e.toString());
log.logError(toString(), "ERROR in part: "+debug);
throw new KettleDatabaseException("An error occurred executing SQL in part ["+debug+"]:"+Const.CR+sql, e);
}
return res;
}
private boolean canWeSetFetchSize(Statement statement) throws SQLException
{
return databaseMeta.isFetchSizeSupported() &&
( statement.getMaxRows()>0 ||
databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_POSTGRES ||
( databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_MYSQL && databaseMeta.isStreamingResults() )
);
}
public ResultSet openQuery(PreparedStatement ps, RowMetaInterface params, Object[] data) throws KettleDatabaseException
{
ResultSet res;
String debug = "Start";
// Create a Statement
try
{
debug = "OQ Set values";
setValues(params, data, ps); // set the parameters!
if (canWeSetFetchSize(ps))
{
debug = "OQ Set fetchsize";
int fs = Const.FETCH_SIZE<=ps.getMaxRows()?ps.getMaxRows():Const.FETCH_SIZE;
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL && databaseMeta.isStreamingResults())
{
ps.setFetchSize(Integer.MIN_VALUE);
}
else
{
ps.setFetchSize(fs);
}
debug = "OQ Set fetch direction";
ps.setFetchDirection(ResultSet.FETCH_FORWARD);
}
debug = "OQ Set max rows";
if (rowlimit>0 && databaseMeta.supportsSetMaxRows()) ps.setMaxRows(rowlimit);
debug = "OQ exec query";
res = ps.executeQuery();
debug = "OQ getRowInfo()";
// rowinfo = getRowInfo(res.getMetaData());
// MySQL Hack only. It seems too much for the cursor type of operation on MySQL, to have another cursor opened
// to get the length of a String field. So, on MySQL, we ingore the length of Strings in result rows.
//
rowMeta = getRowInfo(res.getMetaData(), databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL, false);
}
catch(SQLException ex)
{
throw new KettleDatabaseException("ERROR executing query in part["+debug+"]", ex);
}
catch(Exception e)
{
throw new KettleDatabaseException("ERROR executing query in part["+debug+"]", e);
}
return res;
}
public RowMetaInterface getTableFields(String tablename) throws KettleDatabaseException
{
return getQueryFields(databaseMeta.getSQLQueryFields(tablename), false);
}
public RowMetaInterface getQueryFields(String sql, boolean param) throws KettleDatabaseException
{
return getQueryFields(sql, param, null, null);
}
/**
* See if the table specified exists by reading
* @param tablename The name of the table to check.
* @return true if the table exists, false if it doesn't.
*/
public boolean checkTableExists(String tablename) throws KettleDatabaseException
{
try
{
log.logDebug(toString(), "Checking if table ["+tablename+"] exists!");
// Just try to read from the table.
String sql = databaseMeta.getSQLTableExists(tablename);
try
{
getOneRow(sql);
return true;
}
catch(KettleDatabaseException e)
{
return false;
}
/*
if (getDatabaseMetaData()!=null)
{
ResultSet alltables = getDatabaseMetaData().getTables(null, null, "%" , new String[] { "TABLE", "VIEW", "SYNONYM" } );
boolean found = false;
if (alltables!=null)
{
while (alltables.next() && !found)
{
String schemaName = alltables.getString("TABLE_SCHEM");
String name = alltables.getString("TABLE_NAME");
if ( tablename.equalsIgnoreCase(name) ||
( schemaName!=null && tablename.equalsIgnoreCase( databaseMeta.getSchemaTableCombination(schemaName, name)) )
)
{
log.logDebug(toString(), "table ["+tablename+"] was found!");
found=true;
}
}
alltables.close();
return found;
}
else
{
throw new KettleDatabaseException("Unable to read table-names from the database meta-data.");
}
}
else
{
throw new KettleDatabaseException("Unable to get database meta-data from the database.");
}
*/
}
catch(Exception e)
{
throw new KettleDatabaseException("Unable to check if table ["+tablename+"] exists on connection ["+databaseMeta.getName()+"]", e);
}
}
/**
* Check whether the sequence exists, Oracle only!
* @param sequenceName The name of the sequence
* @return true if the sequence exists.
*/
public boolean checkSequenceExists(String sequenceName) throws KettleDatabaseException
{
return checkSequenceExists(null, sequenceName);
}
/**
* Check whether the sequence exists, Oracle only!
* @param sequenceName The name of the sequence
* @return true if the sequence exists.
*/
public boolean checkSequenceExists(String schemaName, String sequenceName) throws KettleDatabaseException
{
boolean retval=false;
if (!databaseMeta.supportsSequences()) return retval;
String schemaSequence = databaseMeta.getQuotedSchemaTableCombination(schemaName, sequenceName);
try
{
//
// Get the info from the data dictionary...
//
String sql = databaseMeta.getSQLSequenceExists(schemaSequence);
ResultSet res = openQuery(sql);
if (res!=null)
{
Object[] row = getRow(res);
if (row!=null)
{
retval=true;
}
closeQuery(res);
}
}
catch(Exception e)
{
throw new KettleDatabaseException("Unexpected error checking whether or not sequence ["+schemaSequence+"] exists", e);
}
return retval;
}
/**
* Check if an index on certain fields in a table exists.
* @param tableName The table on which the index is checked
* @param idx_fields The fields on which the indexe is checked
* @return True if the index exists
*/
public boolean checkIndexExists(String tableName, String idx_fields[]) throws KettleDatabaseException
{
return checkIndexExists(null, tableName, idx_fields);
}
/**
* Check if an index on certain fields in a table exists.
* @param tablename The table on which the index is checked
* @param idx_fields The fields on which the indexe is checked
* @return True if the index exists
*/
public boolean checkIndexExists(String schemaName, String tableName, String idx_fields[]) throws KettleDatabaseException
{
String tablename = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName);
if (!checkTableExists(tablename)) return false;
log.logDebug(toString(), "CheckIndexExists() tablename = "+tablename+" type = "+databaseMeta.getDatabaseTypeDesc());
boolean exists[] = new boolean[idx_fields.length];
for (int i=0;i<exists.length;i++) exists[i]=false;
try
{
switch(databaseMeta.getDatabaseType())
{
case DatabaseMeta.TYPE_DATABASE_MSSQL:
{
//
// Get the info from the data dictionary...
//
StringBuffer sql = new StringBuffer(128);
sql.append("select i.name table_name, c.name column_name ");
sql.append("from sysindexes i, sysindexkeys k, syscolumns c ");
sql.append("where i.name = '"+tablename+"' ");
sql.append("AND i.id = k.id ");
sql.append("AND i.id = c.id ");
sql.append("AND k.colid = c.colid ");
ResultSet res = null;
try
{
res = openQuery(sql.toString());
if (res!=null)
{
Object[] row = getRow(res);
while (row!=null)
{
String column = rowMeta.getString(row, "column_name", "");
int idx = Const.indexOfString(column, idx_fields);
if (idx>=0) exists[idx]=true;
row = getRow(res);
}
}
else
{
return false;
}
}
finally
{
if ( res != null ) closeQuery(res);
}
}
break;
case DatabaseMeta.TYPE_DATABASE_ORACLE:
{
//
// Get the info from the data dictionary...
//
String sql = "SELECT * FROM USER_IND_COLUMNS WHERE TABLE_NAME = '"+tableName+"'";
ResultSet res = null;
try {
res = openQuery(sql);
if (res!=null)
{
Object[] row = getRow(res);
while (row!=null)
{
String column = rowMeta.getString(row, "COLUMN_NAME", "");
int idx = Const.indexOfString(column, idx_fields);
if (idx>=0)
{
exists[idx]=true;
}
row = getRow(res);
}
}
else
{
return false;
}
}
finally
{
if ( res != null ) closeQuery(res);
}
}
break;
case DatabaseMeta.TYPE_DATABASE_ACCESS:
{
// Get a list of all the indexes for this table
ResultSet indexList = null;
try
{
indexList = getDatabaseMetaData().getIndexInfo(null,null,tablename,false,true);
while (indexList.next())
{
// String tablen = indexList.getString("TABLE_NAME");
// String indexn = indexList.getString("INDEX_NAME");
String column = indexList.getString("COLUMN_NAME");
// int pos = indexList.getShort("ORDINAL_POSITION");
// int type = indexList.getShort("TYPE");
int idx = Const.indexOfString(column, idx_fields);
if (idx>=0)
{
exists[idx]=true;
}
}
}
finally
{
if ( indexList != null ) indexList.close();
}
}
break;
default:
{
// Get a list of all the indexes for this table
ResultSet indexList = null;
try
{
indexList = getDatabaseMetaData().getIndexInfo(null,null,tablename,false,true);
while (indexList.next())
{
// String tablen = indexList.getString("TABLE_NAME");
// String indexn = indexList.getString("INDEX_NAME");
String column = indexList.getString("COLUMN_NAME");
// int pos = indexList.getShort("ORDINAL_POSITION");
// int type = indexList.getShort("TYPE");
int idx = Const.indexOfString(column, idx_fields);
if (idx>=0)
{
exists[idx]=true;
}
}
}
finally
{
if ( indexList != null ) indexList.close();
}
}
break;
}
// See if all the fields are indexed...
boolean all=true;
for (int i=0;i<exists.length && all;i++) if (!exists[i]) all=false;
return all;
}
catch(Exception e)
{
log.logError(toString(), Const.getStackTracker(e));
throw new KettleDatabaseException("Unable to determine if indexes exists on table ["+tablename+"]", e);
}
}
public String getCreateIndexStatement(String tablename, String indexname, String idx_fields[], boolean tk, boolean unique, boolean bitmap, boolean semi_colon)
{
return getCreateIndexStatement(null, tablename, indexname, idx_fields, tk, unique, bitmap, semi_colon);
}
public String getCreateIndexStatement(String schemaname, String tablename, String indexname, String idx_fields[], boolean tk, boolean unique, boolean bitmap, boolean semi_colon)
{
String cr_index="";
cr_index += "CREATE ";
if (unique || ( tk && databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_SYBASE))
cr_index += "UNIQUE ";
if (bitmap && databaseMeta.supportsBitmapIndex())
cr_index += "BITMAP ";
cr_index += "INDEX "+databaseMeta.quoteField(indexname)+Const.CR+" ";
cr_index += "ON ";
// assume table has already been quoted (and possibly includes schema)
cr_index += tablename;
cr_index += Const.CR + "( "+Const.CR;
for (int i=0;i<idx_fields.length;i++)
{
if (i>0) cr_index+=", "; else cr_index+=" ";
cr_index += databaseMeta.quoteField(idx_fields[i])+Const.CR;
}
cr_index+=")"+Const.CR;
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE &&
databaseMeta.getIndexTablespace()!=null && databaseMeta.getIndexTablespace().length()>0)
{
cr_index+="TABLESPACE "+databaseMeta.quoteField(databaseMeta.getIndexTablespace());
}
if (semi_colon)
{
cr_index+=";"+Const.CR;
}
return cr_index;
}
public String getCreateSequenceStatement(String sequence, long start_at, long increment_by, long max_value, boolean semi_colon)
{
return getCreateSequenceStatement(null, sequence, Long.toString(start_at), Long.toString(increment_by), Long.toString(max_value), semi_colon);
}
public String getCreateSequenceStatement(String sequence, String start_at, String increment_by, String max_value, boolean semi_colon)
{
return getCreateSequenceStatement(null, sequence, start_at, increment_by, max_value, semi_colon);
}
public String getCreateSequenceStatement(String schemaName, String sequence, long start_at, long increment_by, long max_value, boolean semi_colon)
{
return getCreateSequenceStatement(schemaName, sequence, Long.toString(start_at), Long.toString(increment_by), Long.toString(max_value), semi_colon);
}
public String getCreateSequenceStatement(String schemaName, String sequenceName, String start_at, String increment_by, String max_value, boolean semi_colon)
{
String cr_seq="";
if (Const.isEmpty(sequenceName)) return cr_seq;
if (databaseMeta.supportsSequences())
{
String schemaSequence = databaseMeta.getQuotedSchemaTableCombination(schemaName, sequenceName);
cr_seq += "CREATE SEQUENCE "+schemaSequence+" "+Const.CR; // Works for both Oracle and PostgreSQL :-)
cr_seq += "START WITH "+start_at+" "+Const.CR;
cr_seq += "INCREMENT BY "+increment_by+" "+Const.CR;
if (max_value != null) cr_seq += "MAXVALUE "+max_value+Const.CR;
if (semi_colon) cr_seq+=";"+Const.CR;
}
return cr_seq;
}
public RowMetaInterface getQueryFields(String sql, boolean param, RowMetaInterface inform, Object[] data) throws KettleDatabaseException
{
RowMetaInterface fields;
DBCache dbcache = DBCache.getInstance();
DBCacheEntry entry=null;
// Check the cache first!
//
if (dbcache!=null)
{
entry = new DBCacheEntry(databaseMeta.getName(), sql);
fields = dbcache.get(entry);
if (fields!=null)
{
return fields;
}
}
if (connection==null) return null; // Cache test without connect.
// No cache entry found
// The new method of retrieving the query fields fails on Oracle because
// they failed to implement the getMetaData method on a prepared statement. (!!!)
// Even recent drivers like 10.2 fail because of it.
//
// There might be other databases that don't support it (we have no knowledge of this at the time of writing).
// If we discover other RDBMSs, we will create an interface for it.
// For now, we just try to get the field layout on the re-bound in the exception block below.
//
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE ||
databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_H2 ||
databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_GENERIC)
{
return getQueryFieldsFallback(sql, param, inform, data);
}
else
{
// On with the regular program.
//
PreparedStatement preparedStatement = null;
try
{
preparedStatement = connection.prepareStatement(databaseMeta.stripCR(sql), ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
ResultSetMetaData rsmd = preparedStatement.getMetaData();
fields = getRowInfo(rsmd, false, false);
}
catch(Exception e)
{
fields = getQueryFieldsFallback(sql, param, inform, data);
}
finally
{
if (preparedStatement!=null)
{
try
{
preparedStatement.close();
}
catch (SQLException e)
{
throw new KettleDatabaseException("Unable to close prepared statement after determining SQL layout", e);
}
}
}
}
// Store in cache!!
if (dbcache!=null && entry!=null)
{
if (fields!=null)
{
dbcache.put(entry, fields);
}
}
return fields;
}
private RowMetaInterface getQueryFieldsFallback(String sql, boolean param, RowMetaInterface inform, Object[] data) throws KettleDatabaseException
{
RowMetaInterface fields;
try
{
if (inform==null
// Hack for MSSQL jtds 1.2 when using xxx NOT IN yyy we have to use a prepared statement (see BugID 3214)
&& databaseMeta.getDatabaseType()!=DatabaseMeta.TYPE_DATABASE_MSSQL
)
{
sel_stmt = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
if (databaseMeta.isFetchSizeSupported() && sel_stmt.getMaxRows()>=1)
{
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL)
{
sel_stmt.setFetchSize(Integer.MIN_VALUE);
}
else
{
sel_stmt.setFetchSize(1);
}
}
if (databaseMeta.supportsSetMaxRows()) sel_stmt.setMaxRows(1);
ResultSet r=sel_stmt.executeQuery(databaseMeta.stripCR(sql));
fields = getRowInfo(r.getMetaData(), false, false);
r.close();
sel_stmt.close();
sel_stmt=null;
}
else
{
PreparedStatement ps = connection.prepareStatement(databaseMeta.stripCR(sql));
if (param)
{
RowMetaInterface par = inform;
if (par==null || par.isEmpty()) par = getParameterMetaData(ps);
if (par==null || par.isEmpty()) par = getParameterMetaData(sql, inform, data);
setValues(par, data, ps);
}
ResultSet r = ps.executeQuery();
fields=getRowInfo(ps.getMetaData(), false, false);
r.close();
ps.close();
}
}
catch(Exception ex)
{
throw new KettleDatabaseException("Couldn't get field info from ["+sql+"]"+Const.CR, ex);
}
return fields;
}
public void closeQuery(ResultSet res) throws KettleDatabaseException
{
// close everything involved in the query!
try
{
if (res!=null) res.close();
if (sel_stmt!=null) { sel_stmt.close(); sel_stmt=null; }
if (pstmt!=null) { pstmt.close(); pstmt=null;}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't close query: resultset or prepared statements", ex);
}
}
/**
* Build the row using ResultSetMetaData rsmd
* @param rm The resultset metadata to inquire
* @param ignoreLength true if you want to ignore the length (workaround for MySQL bug/problem)
* @param lazyConversion true if lazy conversion needs to be enabled where possible
*/
private RowMetaInterface getRowInfo(ResultSetMetaData rm, boolean ignoreLength, boolean lazyConversion) throws KettleDatabaseException
{
if (rm==null) return null;
rowMeta = new RowMeta();
try
{
// TODO If we do lazy conversion, we need to find out about the encoding
//
int fieldNr = 1;
int nrcols=rm.getColumnCount();
for (int i=1;i<=nrcols;i++)
{
String name=new String(rm.getColumnName(i));
// Check the name, sometimes it's empty.
//
if (Const.isEmpty(name) || Const.onlySpaces(name))
{
name = "Field"+fieldNr;
fieldNr++;
}
ValueMetaInterface v = getValueFromSQLType(name, rm, i, ignoreLength, lazyConversion);
rowMeta.addValueMeta(v);
}
return rowMeta;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Error getting row information from database: ", ex);
}
}
private ValueMetaInterface getValueFromSQLType(String name, ResultSetMetaData rm, int index, boolean ignoreLength, boolean lazyConversion) throws SQLException
{
int length=-1;
int precision=-1;
int valtype=ValueMetaInterface.TYPE_NONE;
boolean isClob = false;
int type = rm.getColumnType(index);
switch(type)
{
case java.sql.Types.CHAR:
case java.sql.Types.VARCHAR:
case java.sql.Types.LONGVARCHAR: // Character Large Object
valtype=ValueMetaInterface.TYPE_STRING;
if (!ignoreLength) length=rm.getColumnDisplaySize(index);
break;
case java.sql.Types.CLOB:
valtype=ValueMetaInterface.TYPE_STRING;
length=DatabaseMeta.CLOB_LENGTH;
isClob=true;
break;
case java.sql.Types.BIGINT:
valtype=ValueMetaInterface.TYPE_INTEGER;
precision=0; // Max 9.223.372.036.854.775.807
length=15;
break;
case java.sql.Types.INTEGER:
valtype=ValueMetaInterface.TYPE_INTEGER;
precision=0; // Max 2.147.483.647
length=9;
break;
case java.sql.Types.SMALLINT:
valtype=ValueMetaInterface.TYPE_INTEGER;
precision=0; // Max 32.767
length=4;
break;
case java.sql.Types.TINYINT:
valtype=ValueMetaInterface.TYPE_INTEGER;
precision=0; // Max 127
length=2;
break;
case java.sql.Types.DECIMAL:
case java.sql.Types.DOUBLE:
case java.sql.Types.FLOAT:
case java.sql.Types.REAL:
case java.sql.Types.NUMERIC:
valtype=ValueMetaInterface.TYPE_NUMBER;
length=rm.getPrecision(index);
precision=rm.getScale(index);
if (length >=126) length=-1;
if (precision >=126) precision=-1;
if (type==java.sql.Types.DOUBLE || type==java.sql.Types.FLOAT || type==java.sql.Types.REAL)
{
if (precision==0)
{
precision=-1; // precision is obviously incorrect if the type if Double/Float/Real
}
// If we're dealing with PostgreSQL and double precision types
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_POSTGRES && type==java.sql.Types.DOUBLE && precision==16 && length==16)
{
precision=-1;
length=-1;
}
// MySQL: max resolution is double precision floating point (double)
// The (12,31) that is given back is not correct
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL)
{
if (precision >= length) {
precision=-1;
length=-1;
}
}
}
else
{
if (precision==0 && length<18 && length>0) // Among others Oracle is affected here.
{
valtype=ValueMetaInterface.TYPE_INTEGER;
}
}
if (length>18 || precision>18) valtype=ValueMetaInterface.TYPE_BIGNUMBER;
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE)
{
if (precision == 0 && length == 38 )
{
valtype=ValueMetaInterface.TYPE_INTEGER;
}
if (precision<=0 && length<=0) // undefined size: NUMBER
{
valtype=ValueMetaInterface.TYPE_NUMBER;
length=-1;
precision=-1;
}
}
break;
case java.sql.Types.DATE:
case java.sql.Types.TIME:
case java.sql.Types.TIMESTAMP:
valtype=ValueMetaInterface.TYPE_DATE;
//
if (databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_MYSQL) {
String property = databaseMeta.getConnectionProperties().getProperty("yearIsDateType");
if (property != null && property.equalsIgnoreCase("false")
&& rm.getColumnTypeName(index).equalsIgnoreCase("YEAR")) {
valtype = ValueMetaInterface.TYPE_INTEGER;
precision = 0;
length = 4;
break;
}
}
break;
case java.sql.Types.BOOLEAN:
case java.sql.Types.BIT:
valtype=ValueMetaInterface.TYPE_BOOLEAN;
break;
case java.sql.Types.BINARY:
case java.sql.Types.BLOB:
case java.sql.Types.VARBINARY:
case java.sql.Types.LONGVARBINARY:
valtype=ValueMetaInterface.TYPE_BINARY;
if (databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_DB2 &&
(2 * rm.getPrecision(index)) == rm.getColumnDisplaySize(index))
{
// set the length for "CHAR(X) FOR BIT DATA"
length = rm.getPrecision(index);
}
else
if (databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_ORACLE &&
( type==java.sql.Types.VARBINARY || type==java.sql.Types.LONGVARBINARY )
)
{
// set the length for Oracle "RAW" or "LONGRAW" data types
valtype = ValueMetaInterface.TYPE_STRING;
length = rm.getColumnDisplaySize(index);
}
else
{
length=-1;
}
precision=-1;
break;
default:
valtype=ValueMetaInterface.TYPE_STRING;
precision=rm.getScale(index);
break;
}
// Grab the comment as a description to the field as well.
String comments=rm.getColumnLabel(index);
ValueMetaInterface v=new ValueMeta(name, valtype);
v.setLength(length);
v.setPrecision(precision);
v.setComments(comments);
v.setLargeTextField(isClob);
// See if we need to enable lazy conversion...
//
if (lazyConversion && valtype==ValueMetaInterface.TYPE_STRING) {
v.setStorageType(ValueMetaInterface.STORAGE_TYPE_BINARY_STRING);
// TODO set some encoding to go with this.
// Also set the storage metadata. a copy of the parent, set to String too.
//
ValueMetaInterface storageMetaData = v.clone();
storageMetaData.setType(ValueMetaInterface.TYPE_STRING);
storageMetaData.setStorageType(ValueMetaInterface.STORAGE_TYPE_NORMAL);
v.setStorageMetadata(storageMetaData);
}
return v;
}
public boolean absolute(ResultSet rs, int position) throws KettleDatabaseException
{
try
{
return rs.absolute(position);
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to move resultset to position "+position, e);
}
}
public boolean relative(ResultSet rs, int rows) throws KettleDatabaseException
{
try
{
return rs.relative(rows);
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to move the resultset forward "+rows+" rows", e);
}
}
public void afterLast(ResultSet rs)
throws KettleDatabaseException
{
try
{
rs.afterLast();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to move resultset to after the last position", e);
}
}
public void first(ResultSet rs) throws KettleDatabaseException
{
try
{
rs.first();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to move resultset to the first position", e);
}
}
/**
* Get a row from the resultset. Do not use lazy conversion
* @param rs The resultset to get the row from
* @return one row or null if no row was found on the resultset or if an error occurred.
*/
public Object[] getRow(ResultSet rs) throws KettleDatabaseException
{
return getRow(rs, false);
}
/**
* Get a row from the resultset.
* @param rs The resultset to get the row from
* @param lazyConversion set to true if strings need to have lazy conversion enabled
* @return one row or null if no row was found on the resultset or if an error occurred.
*/
public Object[] getRow(ResultSet rs, boolean lazyConversion) throws KettleDatabaseException
{
if (rowMeta==null)
{
ResultSetMetaData rsmd = null;
try
{
rsmd = rs.getMetaData();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to retrieve metadata from resultset", e);
}
rowMeta = getRowInfo(rsmd, false, lazyConversion);
}
return getRow(rs, null, rowMeta);
}
/**
* Get a row from the resultset.
* @param rs The resultset to get the row from
* @return one row or null if no row was found on the resultset or if an error occurred.
*/
public Object[] getRow(ResultSet rs, ResultSetMetaData dummy, RowMetaInterface rowInfo) throws KettleDatabaseException
{
try
{
int nrcols=rowInfo.size();
Object[] data = RowDataUtil.allocateRowData(nrcols);
if (rs.next())
{
for (int i=0;i<nrcols;i++)
{
ValueMetaInterface val = rowInfo.getValueMeta(i);
switch(val.getType())
{
case ValueMetaInterface.TYPE_BOOLEAN : data[i] = Boolean.valueOf( rs.getBoolean(i+1) ); break;
case ValueMetaInterface.TYPE_NUMBER : data[i] = new Double( rs.getDouble(i+1) ); break;
case ValueMetaInterface.TYPE_BIGNUMBER : data[i] = rs.getBigDecimal(i+1); break;
case ValueMetaInterface.TYPE_INTEGER : data[i] = Long.valueOf( rs.getLong(i+1) ); break;
case ValueMetaInterface.TYPE_STRING :
{
if (val.isStorageBinaryString()) {
data[i] = rs.getBytes(i+1);
}
else {
data[i] = rs.getString(i+1);
}
}
break;
case ValueMetaInterface.TYPE_BINARY :
{
if (databaseMeta.supportsGetBlob())
{
Blob blob = rs.getBlob(i+1);
if (blob!=null)
{
data[i] = blob.getBytes(1L, (int)blob.length());
}
else
{
data[i] = null;
}
}
else
{
data[i] = rs.getBytes(i+1);
}
}
break;
case ValueMetaInterface.TYPE_DATE :
if (databaseMeta.supportsTimeStampToDateConversion())
{
data[i] = rs.getTimestamp(i+1); break; // Timestamp extends java.util.Date
}
else
{
data[i] = rs.getDate(i+1); break;
}
default: break;
}
if (rs.wasNull()) data[i] = null; // null value, it's the default but we want it just to make sure we handle this case too.
}
}
else
{
data=null;
}
return data;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't get row from result set", ex);
}
}
public void printSQLException(SQLException ex)
{
log.logError(toString(), "==> SQLException: ");
while (ex != null)
{
log.logError(toString(), "Message: " + ex.getMessage ());
log.logError(toString(), "SQLState: " + ex.getSQLState ());
log.logError(toString(), "ErrorCode: " + ex.getErrorCode ());
ex = ex.getNextException();
log.logError(toString(), "");
}
}
public void setLookup(String table, String codes[], String condition[],
String gets[], String rename[], String orderby
) throws KettleDatabaseException
{
setLookup(table, codes, condition, gets, rename, orderby, false);
}
public void setLookup(String schema, String table, String codes[], String condition[],
String gets[], String rename[], String orderby
) throws KettleDatabaseException
{
setLookup(schema, table, codes, condition, gets, rename, orderby, false);
}
public void setLookup(String tableName, String codes[], String condition[],
String gets[], String rename[], String orderby,
boolean checkForMultipleResults) throws KettleDatabaseException
{
setLookup(null, tableName, codes, condition, gets, rename, orderby, checkForMultipleResults);
}
// Lookup certain fields in a table
public void setLookup(String schemaName, String tableName, String codes[], String condition[],
String gets[], String rename[], String orderby,
boolean checkForMultipleResults) throws KettleDatabaseException
{
String table = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName);
String sql = "SELECT ";
for (int i=0;i<gets.length;i++)
{
if (i!=0) sql += ", ";
sql += databaseMeta.quoteField(gets[i]);
if (rename!=null && rename[i]!=null && !gets[i].equalsIgnoreCase(rename[i]))
{
sql+=" AS "+databaseMeta.quoteField(rename[i]);
}
}
sql += " FROM "+table+" WHERE ";
for (int i=0;i<codes.length;i++)
{
if (i!=0) sql += " AND ";
sql += databaseMeta.quoteField(codes[i]);
if ("BETWEEN".equalsIgnoreCase(condition[i]))
{
sql+=" BETWEEN ? AND ? ";
}
else
if ("IS NULL".equalsIgnoreCase(condition[i]) || "IS NOT NULL".equalsIgnoreCase(condition[i]))
{
sql+=" "+condition[i]+" ";
}
else
{
sql+=" "+condition[i]+" ? ";
}
}
if (orderby!=null && orderby.length()!=0)
{
sql += " ORDER BY "+orderby;
}
try
{
log.logDetailed(toString(), "Setting preparedStatement to ["+sql+"]");
prepStatementLookup=connection.prepareStatement(databaseMeta.stripCR(sql));
if (!checkForMultipleResults && databaseMeta.supportsSetMaxRows())
{
prepStatementLookup.setMaxRows(1); // alywas get only 1 line back!
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare statement for update ["+sql+"]", ex);
}
}
public boolean prepareUpdate(String table, String codes[], String condition[], String sets[])
{
return prepareUpdate(null, table, codes, condition, sets);
}
// Lookup certain fields in a table
public boolean prepareUpdate(String schemaName, String tableName, String codes[], String condition[], String sets[])
{
StringBuffer sql = new StringBuffer(128);
String schemaTable = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName);
sql.append("UPDATE ").append(schemaTable).append(Const.CR).append("SET ");
for (int i=0;i<sets.length;i++)
{
if (i!=0) sql.append(", ");
sql.append(databaseMeta.quoteField(sets[i]));
sql.append(" = ?").append(Const.CR);
}
sql.append("WHERE ");
for (int i=0;i<codes.length;i++)
{
if (i!=0) sql.append("AND ");
sql.append(databaseMeta.quoteField(codes[i]));
if ("BETWEEN".equalsIgnoreCase(condition[i]))
{
sql.append(" BETWEEN ? AND ? ");
}
else
if ("IS NULL".equalsIgnoreCase(condition[i]) || "IS NOT NULL".equalsIgnoreCase(condition[i]))
{
sql.append(' ').append(condition[i]).append(' ');
}
else
{
sql.append(' ').append(condition[i]).append(" ? ");
}
}
try
{
String s = sql.toString();
log.logDetailed(toString(), "Setting update preparedStatement to ["+s+"]");
prepStatementUpdate=connection.prepareStatement(databaseMeta.stripCR(s));
}
catch(SQLException ex)
{
printSQLException(ex);
return false;
}
return true;
}
/**
* Prepare a delete statement by giving it the tablename, fields and conditions to work with.
* @param table The table-name to delete in
* @param codes
* @param condition
* @return true when everything went OK, false when something went wrong.
*/
public boolean prepareDelete(String table, String codes[], String condition[])
{
return prepareDelete(null, table, codes, condition);
}
/**
* Prepare a delete statement by giving it the tablename, fields and conditions to work with.
* @param schemaName the schema-name to delete in
* @param tableName The table-name to delete in
* @param codes
* @param condition
* @return true when everything went OK, false when something went wrong.
*/
public boolean prepareDelete(String schemaName, String tableName, String codes[], String condition[])
{
String sql;
String table = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName);
sql = "DELETE FROM "+table+Const.CR;
sql+= "WHERE ";
for (int i=0;i<codes.length;i++)
{
if (i!=0) sql += "AND ";
sql += codes[i];
if ("BETWEEN".equalsIgnoreCase(condition[i]))
{
sql+=" BETWEEN ? AND ? ";
}
else
if ("IS NULL".equalsIgnoreCase(condition[i]) || "IS NOT NULL".equalsIgnoreCase(condition[i]))
{
sql+=" "+condition[i]+" ";
}
else
{
sql+=" "+condition[i]+" ? ";
}
}
try
{
log.logDetailed(toString(), "Setting update preparedStatement to ["+sql+"]");
prepStatementUpdate=connection.prepareStatement(databaseMeta.stripCR(sql));
}
catch(SQLException ex)
{
printSQLException(ex);
return false;
}
return true;
}
public void setProcLookup(String proc, String arg[], String argdir[], int argtype[], String returnvalue, int returntype)
throws KettleDatabaseException
{
String sql;
int pos=0;
sql = "{ ";
if (returnvalue!=null && returnvalue.length()!=0)
{
sql+="? = ";
}
sql+="call "+proc+" ";
if (arg.length>0) sql+="(";
for (int i=0;i<arg.length;i++)
{
if (i!=0) sql += ", ";
sql += " ?";
}
if (arg.length>0) sql+=")";
sql+="}";
try
{
log.logDetailed(toString(), "DBA setting callableStatement to ["+sql+"]");
cstmt=connection.prepareCall(sql);
pos=1;
if (!Const.isEmpty(returnvalue))
{
switch(returntype)
{
case ValueMetaInterface.TYPE_NUMBER : cstmt.registerOutParameter(pos, java.sql.Types.DOUBLE); break;
case ValueMetaInterface.TYPE_BIGNUMBER : cstmt.registerOutParameter(pos, java.sql.Types.DECIMAL); break;
case ValueMetaInterface.TYPE_INTEGER : cstmt.registerOutParameter(pos, java.sql.Types.BIGINT); break;
case ValueMetaInterface.TYPE_STRING : cstmt.registerOutParameter(pos, java.sql.Types.VARCHAR); break;
case ValueMetaInterface.TYPE_DATE : cstmt.registerOutParameter(pos, java.sql.Types.TIMESTAMP); break;
case ValueMetaInterface.TYPE_BOOLEAN : cstmt.registerOutParameter(pos, java.sql.Types.BOOLEAN); break;
default: break;
}
pos++;
}
for (int i=0;i<arg.length;i++)
{
if (argdir[i].equalsIgnoreCase("OUT") || argdir[i].equalsIgnoreCase("INOUT"))
{
switch(argtype[i])
{
case ValueMetaInterface.TYPE_NUMBER : cstmt.registerOutParameter(i+pos, java.sql.Types.DOUBLE); break;
case ValueMetaInterface.TYPE_BIGNUMBER : cstmt.registerOutParameter(i+pos, java.sql.Types.DECIMAL); break;
case ValueMetaInterface.TYPE_INTEGER : cstmt.registerOutParameter(i+pos, java.sql.Types.BIGINT); break;
case ValueMetaInterface.TYPE_STRING : cstmt.registerOutParameter(i+pos, java.sql.Types.VARCHAR); break;
case ValueMetaInterface.TYPE_DATE : cstmt.registerOutParameter(i+pos, java.sql.Types.TIMESTAMP); break;
case ValueMetaInterface.TYPE_BOOLEAN : cstmt.registerOutParameter(i+pos, java.sql.Types.BOOLEAN); break;
default: break;
}
}
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare database procedure call", ex);
}
}
public Object[] getLookup() throws KettleDatabaseException
{
return getLookup(prepStatementLookup);
}
public Object[] getLookup(boolean failOnMultipleResults) throws KettleDatabaseException
{
return getLookup(prepStatementLookup, failOnMultipleResults);
}
public Object[] getLookup(PreparedStatement ps) throws KettleDatabaseException
{
return getLookup(ps, false);
}
public Object[] getLookup(PreparedStatement ps, boolean failOnMultipleResults) throws KettleDatabaseException
{
String debug = "start";
ResultSet res = null;
try
{
debug = "pstmt.executeQuery()";
res = ps.executeQuery();
debug = "getRowInfo()";
rowMeta = getRowInfo(res.getMetaData(), false, false);
debug = "getRow(res)";
Object[] ret = getRow(res);
if (failOnMultipleResults)
{
if (ret != null && res.next())
{
// if the previous row was null, there's no reason to try res.next() again.
// on DB2 this will even cause an exception (because of the buggy DB2 JDBC driver).
throw new KettleDatabaseException("Only 1 row was expected as a result of a lookup, and at least 2 were found!");
}
}
return ret;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Error looking up row in database ("+debug+")", ex);
}
finally
{
try
{
debug = "res.close()";
if (res!=null) res.close(); // close resultset!
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to close resultset after looking up data", e);
}
}
}
public DatabaseMetaData getDatabaseMetaData() throws KettleDatabaseException
{
try
{
if (dbmd==null) dbmd = connection.getMetaData(); // Only get the metadata once!
}
catch(Exception e)
{
throw new KettleDatabaseException("Unable to get database metadata from this database connection", e);
}
return dbmd;
}
public String getDDL(String tablename, RowMetaInterface fields) throws KettleDatabaseException
{
return getDDL(tablename, fields, null, false, null, true);
}
public String getDDL(String tablename, RowMetaInterface fields, String tk, boolean use_autoinc, String pk) throws KettleDatabaseException
{
return getDDL(tablename, fields, tk, use_autoinc, pk, true);
}
public String getDDL(String tableName, RowMetaInterface fields, String tk, boolean use_autoinc, String pk, boolean semicolon) throws KettleDatabaseException
{
String retval;
// First, check for reserved SQL in the input row r...
databaseMeta.quoteReservedWords(fields);
String quotedTk = tk != null ? databaseMeta.quoteField(tk) : null;
if (checkTableExists(tableName))
{
retval=getAlterTableStatement(tableName, fields, quotedTk, use_autoinc, pk, semicolon);
}
else
{
retval=getCreateTableStatement(tableName, fields, quotedTk, use_autoinc, pk, semicolon);
}
return retval;
}
/**
* Generates SQL
* @param tableName the table name or schema/table combination: this needs to be quoted properly in advance.
* @param fields the fields
* @param tk the name of the technical key field
* @param use_autoinc true if we need to use auto-increment fields for a primary key
* @param pk the name of the primary/technical key field
* @param semicolon append semicolon to the statement
* @return the SQL needed to create the specified table and fields.
*/
public String getCreateTableStatement(String tableName, RowMetaInterface fields, String tk, boolean use_autoinc, String pk, boolean semicolon)
{
String retval;
retval = "CREATE TABLE "+tableName+Const.CR;
retval+= "("+Const.CR;
for (int i=0;i<fields.size();i++)
{
if (i>0) retval+=", "; else retval+=" ";
ValueMetaInterface v=fields.getValueMeta(i);
retval+=databaseMeta.getFieldDefinition(v, tk, pk, use_autoinc);
}
// At the end, before the closing of the statement, we might need to add some constraints...
// Technical keys
if (tk!=null)
{
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_CACHE)
{
retval+=", PRIMARY KEY ("+tk+")"+Const.CR;
}
}
// Primary keys
if (pk!=null)
{
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE)
{
retval+=", PRIMARY KEY ("+pk+")"+Const.CR;
}
}
retval+= ")"+Const.CR;
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE &&
databaseMeta.getIndexTablespace()!=null && databaseMeta.getIndexTablespace().length()>0)
{
retval+="TABLESPACE "+databaseMeta.getDataTablespace();
}
if (semicolon) retval+=";";
retval+=Const.CR;
return retval;
}
public String getAlterTableStatement(String tableName, RowMetaInterface fields, String tk, boolean use_autoinc, String pk, boolean semicolon) throws KettleDatabaseException
{
String retval="";
// Get the fields that are in the table now:
RowMetaInterface tabFields = getTableFields(tableName);
// Don't forget to quote these as well...
databaseMeta.quoteReservedWords(tabFields);
// Find the missing fields
RowMetaInterface missing = new RowMeta();
for (int i=0;i<fields.size();i++)
{
ValueMetaInterface v = fields.getValueMeta(i);
// Not found?
if (tabFields.searchValueMeta( v.getName() )==null )
{
missing.addValueMeta(v); // nope --> Missing!
}
}
if (missing.size()!=0)
{
for (int i=0;i<missing.size();i++)
{
ValueMetaInterface v=missing.getValueMeta(i);
retval+=databaseMeta.getAddColumnStatement(tableName, v, tk, use_autoinc, pk, true);
}
}
// Find the surplus fields
RowMetaInterface surplus = new RowMeta();
for (int i=0;i<tabFields.size();i++)
{
ValueMetaInterface v = tabFields.getValueMeta(i);
// Found in table, not in input ?
if (fields.searchValueMeta( v.getName() )==null )
{
surplus.addValueMeta(v); // yes --> surplus!
}
}
if (surplus.size()!=0)
{
for (int i=0;i<surplus.size();i++)
{
ValueMetaInterface v=surplus.getValueMeta(i);
retval+=databaseMeta.getDropColumnStatement(tableName, v, tk, use_autoinc, pk, true);
}
}
//
// OK, see if there are fields for wich we need to modify the type... (length, precision)
//
RowMetaInterface modify = new RowMeta();
for (int i=0;i<fields.size();i++)
{
ValueMetaInterface desiredField = fields.getValueMeta(i);
ValueMetaInterface currentField = tabFields.searchValueMeta( desiredField.getName());
if (currentField!=null)
{
boolean mod = false;
mod |= ( currentField.getLength() < desiredField.getLength() ) && desiredField.getLength()>0;
mod |= ( currentField.getPrecision() < desiredField.getPrecision() ) && desiredField.getPrecision()>0;
// Numeric values...
mod |= ( currentField.getType() != desiredField.getType() ) && ( currentField.isNumber()^desiredField.isNumeric() );
// TODO: this is not an optimal way of finding out changes.
// Perhaps we should just generate the data types strings for existing and new data type and see if anything changed.
//
if (mod)
{
// System.out.println("Desired field: ["+desiredField.toStringMeta()+"], current field: ["+currentField.toStringMeta()+"]");
modify.addValueMeta(desiredField);
}
}
}
if (modify.size()>0)
{
for (int i=0;i<modify.size();i++)
{
ValueMetaInterface v=modify.getValueMeta(i);
retval+=databaseMeta.getModifyColumnStatement(tableName, v, tk, use_autoinc, pk, true);
}
}
return retval;
}
public void truncateTable(String tablename) throws KettleDatabaseException
{
if (Const.isEmpty(connectionGroup))
{
execStatement(databaseMeta.getTruncateTableStatement(null, tablename));
}
else
{
execStatement("DELETE FROM "+databaseMeta.quoteField(tablename));
}
}
public void truncateTable(String schema, String tablename) throws KettleDatabaseException
{
if (Const.isEmpty(connectionGroup))
{
execStatement(databaseMeta.getTruncateTableStatement(schema, tablename));
}
else
{
execStatement("DELETE FROM "+databaseMeta.getQuotedSchemaTableCombination(schema, tablename));
}
}
/**
* Execute a query and return at most one row from the resultset
* @param sql The SQL for the query
* @return one Row with data or null if nothing was found.
*/
public RowMetaAndData getOneRow(String sql) throws KettleDatabaseException
{
ResultSet rs = openQuery(sql);
if (rs!=null)
{
Object[] row = getRow(rs); // One row only;
try { rs.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close resultset", e); }
if (pstmt!=null)
{
try { pstmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement pstmt", e); }
pstmt=null;
}
if (sel_stmt!=null)
{
try { sel_stmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement sel_stmt", e); }
sel_stmt=null;
}
return new RowMetaAndData(rowMeta, row);
}
else
{
throw new KettleDatabaseException("error opening resultset for query: "+sql);
}
}
public RowMeta getMetaFromRow( Object[] row, ResultSetMetaData md ) throws SQLException {
RowMeta meta = new RowMeta();
for( int i=0; i<md.getColumnCount(); i++ ) {
String name = md.getColumnName(i+1);
ValueMetaInterface valueMeta = getValueFromSQLType( name, md, i+1, true, false );
meta.addValueMeta( valueMeta );
}
return meta;
}
public RowMetaAndData getOneRow(String sql, RowMetaInterface param, Object[] data) throws KettleDatabaseException
{
ResultSet rs = openQuery(sql, param, data);
if (rs!=null)
{
Object[] row = getRow(rs); // One value: a number;
rowMeta=null;
RowMeta tmpMeta = null;
try {
ResultSetMetaData md = rs.getMetaData();
tmpMeta = getMetaFromRow( row, md );
} catch (Exception e) {
e.printStackTrace();
} finally {
try { rs.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close resultset", e); }
if (pstmt!=null)
{
try { pstmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement pstmt", e); }
pstmt=null;
}
if (sel_stmt!=null)
{
try { sel_stmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement sel_stmt", e); }
sel_stmt=null;
}
}
return new RowMetaAndData(tmpMeta, row);
}
else
{
return null;
}
}
public RowMetaInterface getParameterMetaData(PreparedStatement ps)
{
RowMetaInterface par = new RowMeta();
try
{
ParameterMetaData pmd = ps.getParameterMetaData();
for (int i=1;i<=pmd.getParameterCount();i++)
{
String name = "par"+i;
int sqltype = pmd.getParameterType(i);
int length = pmd.getPrecision(i);
int precision = pmd.getScale(i);
ValueMeta val;
switch(sqltype)
{
case java.sql.Types.CHAR:
case java.sql.Types.VARCHAR:
val=new ValueMeta(name, ValueMetaInterface.TYPE_STRING);
break;
case java.sql.Types.BIGINT:
case java.sql.Types.INTEGER:
case java.sql.Types.NUMERIC:
case java.sql.Types.SMALLINT:
case java.sql.Types.TINYINT:
val=new ValueMeta(name, ValueMetaInterface.TYPE_INTEGER);
break;
case java.sql.Types.DECIMAL:
case java.sql.Types.DOUBLE:
case java.sql.Types.FLOAT:
case java.sql.Types.REAL:
val=new ValueMeta(name, ValueMetaInterface.TYPE_NUMBER);
break;
case java.sql.Types.DATE:
case java.sql.Types.TIME:
case java.sql.Types.TIMESTAMP:
val=new ValueMeta(name, ValueMetaInterface.TYPE_DATE);
break;
case java.sql.Types.BOOLEAN:
case java.sql.Types.BIT:
val=new ValueMeta(name, ValueMetaInterface.TYPE_BOOLEAN);
break;
default:
val=new ValueMeta(name, ValueMetaInterface.TYPE_NONE);
break;
}
if (val.isNumeric() && ( length>18 || precision>18) )
{
val = new ValueMeta(name, ValueMetaInterface.TYPE_BIGNUMBER);
}
par.addValueMeta(val);
}
}
// Oops: probably the database or JDBC doesn't support it.
catch(AbstractMethodError e) { return null; }
catch(SQLException e) { return null; }
catch(Exception e) { return null; }
return par;
}
public int countParameters(String sql)
{
int q=0;
boolean quote_opened=false;
boolean dquote_opened=false;
for (int x=0;x<sql.length();x++)
{
char c = sql.charAt(x);
switch(c)
{
case '\'': quote_opened= !quote_opened; break;
case '"' : dquote_opened=!dquote_opened; break;
case '?' : if (!quote_opened && !dquote_opened) q++; break;
}
}
return q;
}
// Get the fields back from an SQL query
public RowMetaInterface getParameterMetaData(String sql, RowMetaInterface inform, Object[] data)
{
// The database couldn't handle it: try manually!
int q=countParameters(sql);
RowMetaInterface par=new RowMeta();
if (inform!=null && q==inform.size())
{
for (int i=0;i<q;i++)
{
ValueMetaInterface inf=inform.getValueMeta(i);
ValueMetaInterface v = inf.clone();
par.addValueMeta(v);
}
}
else
{
for (int i=0;i<q;i++)
{
ValueMetaInterface v = new ValueMeta("name"+i, ValueMetaInterface.TYPE_NUMBER);
par.addValueMeta(v);
}
}
return par;
}
public static final RowMetaInterface getTransLogrecordFields(boolean update, boolean use_batchid, boolean use_logfield)
{
RowMetaInterface r = new RowMeta();
ValueMetaInterface v;
if (use_batchid && !update)
{
v=new ValueMeta("ID_BATCH", ValueMetaInterface.TYPE_INTEGER, 8, 0); r.addValueMeta(v);
}
if (!update)
{
v=new ValueMeta("TRANSNAME", ValueMetaInterface.TYPE_STRING , 50, 0); r.addValueMeta(v);
}
v=new ValueMeta("STATUS", ValueMetaInterface.TYPE_STRING , 15, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_READ", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_WRITTEN", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_UPDATED", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_INPUT", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_OUTPUT", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("ERRORS", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("STARTDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("ENDDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("LOGDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("DEPDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("REPLAYDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
if (use_logfield)
{
v=new ValueMeta("LOG_FIELD", ValueMetaInterface.TYPE_STRING, DatabaseMeta.CLOB_LENGTH, 0);
r.addValueMeta(v);
}
if (use_batchid && update)
{
v=new ValueMeta("ID_BATCH", ValueMetaInterface.TYPE_INTEGER, 8, 0); r.addValueMeta(v);
}
return r;
}
public static final RowMetaInterface getJobLogrecordFields(boolean update, boolean use_jobid, boolean use_logfield)
{
RowMetaInterface r = new RowMeta();
ValueMetaInterface v;
if (use_jobid && !update)
{
v=new ValueMeta("ID_JOB", ValueMetaInterface.TYPE_INTEGER, 8, 0); r.addValueMeta(v);
}
if (!update)
{
v=new ValueMeta("JOBNAME", ValueMetaInterface.TYPE_STRING, 50, 0); r.addValueMeta(v);
}
v=new ValueMeta("STATUS", ValueMetaInterface.TYPE_STRING, 15, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_READ", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_WRITTEN", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_UPDATED", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_INPUT", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_OUTPUT", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("ERRORS", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("STARTDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("ENDDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("LOGDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("DEPDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("REPLAYDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
if (use_logfield)
{
v=new ValueMeta("LOG_FIELD", ValueMetaInterface.TYPE_STRING, DatabaseMeta.CLOB_LENGTH, 0);
r.addValueMeta(v);
}
if (use_jobid && update)
{
v=new ValueMeta("ID_JOB", ValueMetaInterface.TYPE_INTEGER, 8, 0); r.addValueMeta(v);
}
return r;
}
public void writeLogRecord( String logtable,
boolean use_id,
long id,
boolean job,
String name,
String status,
long read, long written, long updated,
long input, long output, long errors,
java.util.Date startdate, java.util.Date enddate,
java.util.Date logdate, java.util.Date depdate,
java.util.Date replayDate,
String log_string
)
throws KettleDatabaseException
{
if (use_id && log_string!=null && !status.equalsIgnoreCase("start"))
{
String sql = "UPDATE "+logtable+" SET STATUS=?, LINES_READ=?, LINES_WRITTEN=?, LINES_INPUT=?," +
" LINES_OUTPUT=?, LINES_UPDATED=?, ERRORS=?, STARTDATE=?, ENDDATE=?, LOGDATE=?, DEPDATE=?, REPLAYDATE=?, LOG_FIELD=? " +
"WHERE ";
if (job) sql+="ID_JOB=?"; else sql+="ID_BATCH=?";
RowMetaInterface rowMeta;
if (job) rowMeta = getJobLogrecordFields(true, use_id, true);
else rowMeta = getTransLogrecordFields(true, use_id, true);
Object[] data = new Object[] {
status,
Long.valueOf(read),
Long.valueOf(written),
Long.valueOf(input),
Long.valueOf(output),
Long.valueOf(updated),
Long.valueOf(errors),
startdate,
enddate,
logdate,
depdate,
replayDate,
log_string,
Long.valueOf(id),
};
execStatement(sql, rowMeta, data);
}
else
{
int parms;
String sql = "INSERT INTO "+logtable+" ( ";
if (job)
{
if (use_id)
{
sql+="ID_JOB, JOBNAME";
parms=14;
}
else
{
sql+="JOBNAME";
parms=13;
}
}
else
{
if (use_id)
{
sql+="ID_BATCH, TRANSNAME";
parms=14;
}
else
{
sql+="TRANSNAME";
parms=13;
}
}
sql+=", STATUS, LINES_READ, LINES_WRITTEN, LINES_UPDATED, LINES_INPUT, LINES_OUTPUT, ERRORS, STARTDATE, ENDDATE, LOGDATE, DEPDATE, REPLAYDATE";
if (log_string!=null && log_string.length()>0) sql+=", LOG_FIELD"; // This is possibly a CLOB!
sql+=") VALUES(";
for (int i=0;i<parms;i++) if (i==0) sql+="?"; else sql+=", ?";
if (log_string!=null && log_string.length()>0) sql+=", ?";
sql+=")";
try
{
pstmt = connection.prepareStatement(databaseMeta.stripCR(sql));
RowMetaInterface rowMeta = new RowMeta();
List<Object> data = new ArrayList<Object>();
if (job)
{
if (use_id)
{
rowMeta.addValueMeta( new ValueMeta("ID_BATCH", ValueMetaInterface.TYPE_INTEGER));
data.add(Long.valueOf(id));
}
rowMeta.addValueMeta( new ValueMeta("TRANSNAME", ValueMetaInterface.TYPE_STRING));
data.add(name);
}
else
{
if (use_id)
{
rowMeta.addValueMeta( new ValueMeta("ID_JOB", ValueMetaInterface.TYPE_INTEGER));
data.add(Long.valueOf(id));
}
rowMeta.addValueMeta( new ValueMeta("JOBNAME", ValueMetaInterface.TYPE_STRING));
data.add(name);
}
rowMeta.addValueMeta( new ValueMeta("STATUS", ValueMetaInterface.TYPE_STRING )); data.add(status);
rowMeta.addValueMeta( new ValueMeta("LINES_READ", ValueMetaInterface.TYPE_INTEGER)); data.add(Long.valueOf(read));
rowMeta.addValueMeta( new ValueMeta("LINES_WRITTEN", ValueMetaInterface.TYPE_INTEGER)); data.add(Long.valueOf(written));
rowMeta.addValueMeta( new ValueMeta("LINES_UPDATED", ValueMetaInterface.TYPE_INTEGER)); data.add(Long.valueOf(updated));
rowMeta.addValueMeta( new ValueMeta("LINES_INPUT", ValueMetaInterface.TYPE_INTEGER)); data.add(Long.valueOf(input));
rowMeta.addValueMeta( new ValueMeta("LINES_OUTPUT", ValueMetaInterface.TYPE_INTEGER)); data.add(Long.valueOf(output));
rowMeta.addValueMeta( new ValueMeta("ERRORS", ValueMetaInterface.TYPE_INTEGER)); data.add(Long.valueOf(errors));
rowMeta.addValueMeta( new ValueMeta("STARTDATE", ValueMetaInterface.TYPE_DATE )); data.add(startdate);
rowMeta.addValueMeta( new ValueMeta("ENDDATE", ValueMetaInterface.TYPE_DATE )); data.add(enddate);
rowMeta.addValueMeta( new ValueMeta("LOGDATE", ValueMetaInterface.TYPE_DATE )); data.add(logdate);
rowMeta.addValueMeta( new ValueMeta("DEPDATE", ValueMetaInterface.TYPE_DATE )); data.add(depdate);
rowMeta.addValueMeta( new ValueMeta("REPLAYDATE", ValueMetaInterface.TYPE_DATE )); data.add(replayDate);
if (!Const.isEmpty(log_string))
{
ValueMetaInterface large = new ValueMeta("LOG_FIELD", ValueMetaInterface.TYPE_STRING);
large.setLength(DatabaseMeta.CLOB_LENGTH);
rowMeta.addValueMeta( large );
data.add(log_string);
}
setValues(rowMeta, data.toArray(new Object[data.size()]));
pstmt.executeUpdate();
pstmt.close(); pstmt=null;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to write log record to log table "+logtable, ex);
}
}
}
public Object[] getLastLogDate( String logtable, String name, boolean job, String status ) throws KettleDatabaseException
{
Object[] row = null;
String jobtrans = job?"JOBNAME":"TRANSNAME";
String sql = "";
sql+=" SELECT ENDDATE, DEPDATE, STARTDATE";
sql+=" FROM "+logtable;
sql+=" WHERE ERRORS = 0";
sql+=" AND STATUS = 'end'";
sql+=" AND "+jobtrans+" = ?";
sql+=" ORDER BY LOGDATE DESC, ENDDATE DESC";
try
{
pstmt = connection.prepareStatement(databaseMeta.stripCR(sql));
RowMetaInterface r = new RowMeta();
r.addValueMeta( new ValueMeta("TRANSNAME", ValueMetaInterface.TYPE_STRING));
setValues(r, new Object[] { name });
ResultSet res = pstmt.executeQuery();
if (res!=null)
{
rowMeta = getRowInfo(res.getMetaData(), false, false);
row = getRow(res);
res.close();
}
pstmt.close(); pstmt=null;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to obtain last logdate from table "+logtable, ex);
}
return row;
}
public synchronized Long getNextValue(Hashtable<String,Counter> counters, String tableName, String val_key) throws KettleDatabaseException
{
return getNextValue(counters, null, tableName, val_key);
}
public synchronized Long getNextValue(Hashtable<String,Counter> counters, String schemaName, String tableName, String val_key) throws KettleDatabaseException
{
Long nextValue = null;
String schemaTable = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName);
String lookup = schemaTable+"."+databaseMeta.quoteField(val_key);
// Try to find the previous sequence value...
Counter counter = null;
if (counters!=null) counter=counters.get(lookup);
if (counter==null)
{
RowMetaAndData rmad = getOneRow("SELECT MAX("+databaseMeta.quoteField(val_key)+") FROM "+schemaTable);
if (rmad!=null)
{
long previous;
try
{
Long tmp = rmad.getRowMeta().getInteger(rmad.getData(), 0);
// A "select max(x)" on a table with no matching rows will return null.
if ( tmp != null )
previous = tmp.longValue();
else
previous = 0L;
}
catch (KettleValueException e)
{
throw new KettleDatabaseException("Error getting the first long value from the max value returned from table : "+schemaTable);
}
counter = new Counter(previous+1, 1);
nextValue = Long.valueOf( counter.next() );
if (counters!=null) counters.put(lookup, counter);
}
else
{
throw new KettleDatabaseException("Couldn't find maximum key value from table "+schemaTable);
}
}
else
{
nextValue = Long.valueOf( counter.next() );
}
return nextValue;
}
public String toString()
{
if (databaseMeta!=null) return databaseMeta.getName();
else return "-";
}
public boolean isSystemTable(String table_name)
{
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MSSQL)
{
if ( table_name.startsWith("sys")) return true;
if ( table_name.equals("dtproperties")) return true;
}
else
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_GUPTA)
{
if ( table_name.startsWith("SYS")) return true;
}
return false;
}
/** Reads the result of an SQL query into an ArrayList
*
* @param sql The SQL to launch
* @param limit <=0 means unlimited, otherwise this specifies the maximum number of rows read.
* @return An ArrayList of rows.
* @throws KettleDatabaseException if something goes wrong.
*/
public List<Object[]> getRows(String sql, int limit) throws KettleDatabaseException
{
return getRows(sql, limit, null);
}
/** Reads the result of an SQL query into an ArrayList
*
* @param sql The SQL to launch
* @param limit <=0 means unlimited, otherwise this specifies the maximum number of rows read.
* @param monitor The progress monitor to update while getting the rows.
* @return An ArrayList of rows.
* @throws KettleDatabaseException if something goes wrong.
*/
public List<Object[]> getRows(String sql, int limit, IProgressMonitor monitor) throws KettleDatabaseException
{
if (monitor!=null) monitor.setTaskName("Opening query...");
ResultSet rset = openQuery(sql);
return getRows(rset, limit, monitor);
}
/** Reads the result of a ResultSet into an ArrayList
*
* @param rset the ResultSet to read out
* @param limit <=0 means unlimited, otherwise this specifies the maximum number of rows read.
* @param monitor The progress monitor to update while getting the rows.
* @return An ArrayList of rows.
* @throws KettleDatabaseException if something goes wrong.
*/
public List<Object[]> getRows(ResultSet rset, int limit, IProgressMonitor monitor) throws KettleDatabaseException
{
try
{
List<Object[]> result = new ArrayList<Object[]>();
boolean stop=false;
int i=0;
if (rset!=null)
{
if (monitor!=null && limit>0) monitor.beginTask("Reading rows...", limit);
while ((limit<=0 || i<limit) && !stop)
{
Object[] row = getRow(rset);
if (row!=null)
{
result.add(row);
i++;
}
else
{
stop=true;
}
if (monitor!=null && limit>0) monitor.worked(1);
}
closeQuery(rset);
if (monitor!=null) monitor.done();
}
return result;
}
catch(Exception e)
{
throw new KettleDatabaseException("Unable to get list of rows from ResultSet : ", e);
}
}
public List<Object[]> getFirstRows(String table_name, int limit) throws KettleDatabaseException
{
return getFirstRows(table_name, limit, null);
}
/**
* Get the first rows from a table (for preview)
* @param table_name The table name (or schema/table combination): this needs to be quoted properly
* @param limit limit <=0 means unlimited, otherwise this specifies the maximum number of rows read.
* @param monitor The progress monitor to update while getting the rows.
* @return An ArrayList of rows.
* @throws KettleDatabaseException in case something goes wrong
*/
public List<Object[]> getFirstRows(String table_name, int limit, IProgressMonitor monitor) throws KettleDatabaseException
{
String sql = "SELECT * FROM "+table_name;
if (limit>0)
{
sql+=databaseMeta.getLimitClause(limit);
}
return getRows(sql, limit, monitor);
}
public RowMetaInterface getReturnRowMeta()
{
return rowMeta;
}
public String[] getTableTypes() throws KettleDatabaseException
{
try
{
ArrayList<String> types = new ArrayList<String>();
ResultSet rstt = getDatabaseMetaData().getTableTypes();
while(rstt.next())
{
String ttype = rstt.getString("TABLE_TYPE");
types.add(ttype);
}
return types.toArray(new String[types.size()]);
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to get table types from database!", e);
}
}
public String[] getTablenames() throws KettleDatabaseException
{
return getTablenames(false);
}
public String[] getTablenames(boolean includeSchema) throws KettleDatabaseException
{
String schemaname = null;
if (databaseMeta.useSchemaNameForTableList()) schemaname = databaseMeta.getUsername().toUpperCase();
List<String> names = new ArrayList<String>();
ResultSet alltables=null;
try
{
alltables = getDatabaseMetaData().getTables(null, schemaname, null, databaseMeta.getTableTypes() );
while (alltables.next())
{
String table = alltables.getString("TABLE_NAME");
String schema = alltables.getString("TABLE_SCHEM");
if (Const.isEmpty(schema)) schema = alltables.getString("TABLE_CAT"); // retry for the catalog.
String schemaTable;
if (includeSchema) schemaTable = databaseMeta.getQuotedSchemaTableCombination(schema, table);
else schemaTable = table;
if (log.isRowLevel()) log.logRowlevel(toString(), "got table from meta-data: "+schemaTable);
names.add(schemaTable);
}
}
catch(SQLException e)
{
log.logError(toString(), "Error getting tablenames from schema ["+schemaname+"]");
}
finally
{
try
{
if (alltables!=null) alltables.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing resultset after getting views from schema ["+schemaname+"]", e);
}
}
log.logDetailed(toString(), "read :"+names.size()+" table names from db meta-data.");
return names.toArray(new String[names.size()]);
}
public String[] getViews() throws KettleDatabaseException
{
return getViews(false);
}
public String[] getViews(boolean includeSchema) throws KettleDatabaseException
{
if (!databaseMeta.supportsViews()) return new String[] {};
String schemaname = null;
if (databaseMeta.useSchemaNameForTableList()) schemaname=databaseMeta.getUsername().toUpperCase();
ArrayList<String> names = new ArrayList<String>();
ResultSet alltables=null;
try
{
alltables = dbmd.getTables(null, schemaname, null, databaseMeta.getViewTypes() );
while (alltables.next())
{
String table = alltables.getString("TABLE_NAME");
String schema = alltables.getString("TABLE_SCHEM");
if (Const.isEmpty(schema)) schema = alltables.getString("TABLE_CAT"); // retry for the catalog.
String schemaTable;
if (includeSchema) schemaTable = databaseMeta.getQuotedSchemaTableCombination(schema, table);
else schemaTable = table;
if (log.isRowLevel()) log.logRowlevel(toString(), "got view from meta-data: "+schemaTable);
names.add(schemaTable);
}
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error getting views from schema ["+schemaname+"]", e);
}
finally
{
try
{
if (alltables!=null) alltables.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing resultset after getting views from schema ["+schemaname+"]", e);
}
}
log.logDetailed(toString(), "read :"+names.size()+" views from db meta-data.");
return names.toArray(new String[names.size()]);
}
public String[] getSynonyms() throws KettleDatabaseException
{
return getViews(false);
}
public String[] getSynonyms(boolean includeSchema) throws KettleDatabaseException
{
if (!databaseMeta.supportsSynonyms()) return new String[] {};
String schemaname = null;
if (databaseMeta.useSchemaNameForTableList()) schemaname=databaseMeta.getUsername().toUpperCase();
ArrayList<String> names = new ArrayList<String>();
ResultSet alltables=null;
try
{
alltables = dbmd.getTables(null, schemaname, null, databaseMeta.getSynonymTypes() );
while (alltables.next())
{
String table = alltables.getString("TABLE_NAME");
String schema = alltables.getString("TABLE_SCHEM");
if (Const.isEmpty(schema)) schema = alltables.getString("TABLE_CAT"); // retry for the catalog.
String schemaTable;
if (includeSchema) schemaTable = databaseMeta.getQuotedSchemaTableCombination(schema, table);
else schemaTable = table;
if (log.isRowLevel()) log.logRowlevel(toString(), "got view from meta-data: "+schemaTable);
names.add(schemaTable);
}
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error getting synonyms from schema ["+schemaname+"]", e);
}
finally
{
try
{
if (alltables!=null) alltables.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing resultset after getting synonyms from schema ["+schemaname+"]", e);
}
}
log.logDetailed(toString(), "read :"+names.size()+" views from db meta-data.");
return names.toArray(new String[names.size()]);
}
public String[] getProcedures() throws KettleDatabaseException
{
String sql = databaseMeta.getSQLListOfProcedures();
if (sql!=null)
{
//System.out.println("SQL= "+sql);
List<Object[]> procs = getRows(sql, 1000);
//System.out.println("Found "+procs.size()+" rows");
String[] str = new String[procs.size()];
for (int i=0;i<procs.size();i++)
{
str[i] = ((Object[])procs.get(i))[0].toString();
}
return str;
}
else
{
ResultSet rs = null;
try
{
DatabaseMetaData dbmd = getDatabaseMetaData();
rs = dbmd.getProcedures(null, null, null);
List<Object[]> rows = getRows(rs, 0, null);
String result[] = new String[rows.size()];
for (int i=0;i<rows.size();i++)
{
Object[] row = (Object[])rows.get(i);
String procCatalog = rowMeta.getString(row, "PROCEDURE_CAT", null);
String procSchema = rowMeta.getString(row, "PROCEDURE_SCHEMA", null);
String procName = rowMeta.getString(row, "PROCEDURE_NAME", "");
String name = "";
if (procCatalog!=null) name+=procCatalog+".";
else if (procSchema!=null) name+=procSchema+".";
name+=procName;
result[i] = name;
}
return result;
}
catch(Exception e)
{
throw new KettleDatabaseException("Unable to get list of procedures from database meta-data: ", e);
}
finally
{
if (rs!=null) try { rs.close(); } catch(Exception e) {}
}
}
}
public boolean isAutoCommit()
{
return commitsize<=0;
}
/**
* @return Returns the databaseMeta.
*/
public DatabaseMeta getDatabaseMeta()
{
return databaseMeta;
}
/**
* Lock a tables in the database for write operations
* @param tableNames The tables to lock
* @throws KettleDatabaseException
*/
public void lockTables(String tableNames[]) throws KettleDatabaseException
{
if (Const.isEmpty(tableNames)) return;
// Quote table names too...
//
String[] quotedTableNames = new String[tableNames.length];
for (int i=0;i<tableNames.length;i++) quotedTableNames[i] = databaseMeta.quoteField(tableNames[i]);
// Get the SQL to lock the (quoted) tables
//
String sql = databaseMeta.getSQLLockTables(quotedTableNames);
if (sql!=null)
{
execStatements(sql);
}
}
/**
* Unlock certain tables in the database for write operations
* @param tableNames The tables to unlock
* @throws KettleDatabaseException
*/
public void unlockTables(String tableNames[]) throws KettleDatabaseException
{
if (Const.isEmpty(tableNames)) return;
// Quote table names too...
//
String[] quotedTableNames = new String[tableNames.length];
for (int i=0;i<tableNames.length;i++) quotedTableNames[i] = databaseMeta.quoteField(tableNames[i]);
// Get the SQL to unlock the (quoted) tables
//
String sql = databaseMeta.getSQLUnlockTables(quotedTableNames);
if (sql!=null)
{
execStatement(sql);
}
}
/**
* @return the opened
*/
public int getOpened()
{
return opened;
}
/**
* @param opened the opened to set
*/
public void setOpened(int opened)
{
this.opened = opened;
}
/**
* @return the connectionGroup
*/
public String getConnectionGroup()
{
return connectionGroup;
}
/**
* @param connectionGroup the connectionGroup to set
*/
public void setConnectionGroup(String connectionGroup)
{
this.connectionGroup = connectionGroup;
}
/**
* @return the partitionId
*/
public String getPartitionId()
{
return partitionId;
}
/**
* @param partitionId the partitionId to set
*/
public void setPartitionId(String partitionId)
{
this.partitionId = partitionId;
}
/**
* @return the copy
*/
public int getCopy()
{
return copy;
}
/**
* @param copy the copy to set
*/
public void setCopy(int copy)
{
this.copy = copy;
}
public void copyVariablesFrom(VariableSpace space)
{
variables.copyVariablesFrom(space);
}
public String environmentSubstitute(String aString)
{
return variables.environmentSubstitute(aString);
}
public String[] environmentSubstitute(String aString[])
{
return variables.environmentSubstitute(aString);
}
public VariableSpace getParentVariableSpace()
{
return variables.getParentVariableSpace();
}
public void setParentVariableSpace(VariableSpace parent)
{
variables.setParentVariableSpace(parent);
}
public String getVariable(String variableName, String defaultValue)
{
return variables.getVariable(variableName, defaultValue);
}
public String getVariable(String variableName)
{
return variables.getVariable(variableName);
}
public boolean getBooleanValueOfVariable(String variableName, boolean defaultValue) {
if (!Const.isEmpty(variableName))
{
String value = environmentSubstitute(variableName);
if (!Const.isEmpty(value))
{
return ValueMeta.convertStringToBoolean(value);
}
}
return defaultValue;
}
public void initializeVariablesFrom(VariableSpace parent)
{
variables.initializeVariablesFrom(parent);
}
public String[] listVariables()
{
return variables.listVariables();
}
public void setVariable(String variableName, String variableValue)
{
variables.setVariable(variableName, variableValue);
}
public void shareVariablesWith(VariableSpace space)
{
variables = space;
// Also share the variables with the meta data object
// Make sure it's not the databaseMeta object itself. We would get an infinite loop in that case.
//
if (space!=databaseMeta) databaseMeta.shareVariablesWith(space);
}
public void injectVariables(Map<String,String> prop)
{
variables.injectVariables(prop);
}
public RowMetaAndData callProcedure(String arg[], String argdir[], int argtype[],
String resultname, int resulttype) throws KettleDatabaseException {
RowMetaAndData ret;
try {
cstmt.execute();
ret = new RowMetaAndData();
int pos = 1;
if (resultname != null && resultname.length() != 0) {
ValueMeta vMeta = new ValueMeta(resultname, resulttype);
Object v =null;
switch (resulttype) {
case ValueMetaInterface.TYPE_BOOLEAN:
v=Boolean.valueOf(cstmt.getBoolean(pos));
break;
case ValueMetaInterface.TYPE_NUMBER:
v=new Double(cstmt.getDouble(pos));
break;
case ValueMetaInterface.TYPE_BIGNUMBER:
v=cstmt.getBigDecimal(pos);
break;
case ValueMetaInterface.TYPE_INTEGER:
v=Long.valueOf(cstmt.getLong(pos));
break;
case ValueMetaInterface.TYPE_STRING:
v=cstmt.getString(pos);
break;
case ValueMetaInterface.TYPE_DATE:
v=cstmt.getDate(pos);
break;
}
ret.addValue(vMeta, v);
pos++;
}
for (int i = 0; i < arg.length; i++) {
if (argdir[i].equalsIgnoreCase("OUT")
|| argdir[i].equalsIgnoreCase("INOUT")) {
ValueMeta vMeta = new ValueMeta(arg[i], argtype[i]);
Object v=null;
switch (argtype[i]) {
case ValueMetaInterface.TYPE_BOOLEAN:
v=Boolean.valueOf(cstmt.getBoolean(pos + i));
break;
case ValueMetaInterface.TYPE_NUMBER:
v=new Double(cstmt.getDouble(pos + i));
break;
case ValueMetaInterface.TYPE_BIGNUMBER:
v=cstmt.getBigDecimal(pos + i);
break;
case ValueMetaInterface.TYPE_INTEGER:
v=Long.valueOf(cstmt.getLong(pos + i));
break;
case ValueMetaInterface.TYPE_STRING:
v=cstmt.getString(pos + i);
break;
case ValueMetaInterface.TYPE_DATE:
v=cstmt.getTimestamp(pos + i);
break;
}
ret.addValue(vMeta, v);
}
}
return ret;
} catch (SQLException ex) {
throw new KettleDatabaseException("Unable to call procedure", ex);
}
}
}
|
src/org/pentaho/di/core/database/Database.java
|
/*
* Copyright (c) 2007 Pentaho Corporation. All rights reserved.
* This software was developed by Pentaho Corporation and is provided under the terms
* of the GNU Lesser General Public License, Version 2.1. You may not use
* this file except in compliance with the license. If you need a copy of the license,
* please go to http://www.gnu.org/licenses/lgpl-2.1.txt. The Original Code is Pentaho
* Data Integration. The Initial Developer is Pentaho Corporation.
*
* Software distributed under the GNU Lesser Public License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to
* the license for the specific language governing your rights and limitations.
*/
/**********************************************************************
** **
** **
** Kettle, from version 2.2 on, is released into the public domain **
** under the Lesser GNU Public License (LGPL). **
** **
** For more details, please read the document LICENSE.txt, included **
** in this project **
** **
** http://www.kettle.be **
** info@kettle.be **
** **
**********************************************************************/
package org.pentaho.di.core.database;
import java.io.File;
import java.io.StringReader;
import java.sql.BatchUpdateException;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.sql.DataSource;
import org.eclipse.core.runtime.IProgressMonitor;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.Counter;
import org.pentaho.di.core.DBCache;
import org.pentaho.di.core.DBCacheEntry;
import org.pentaho.di.core.Result;
import org.pentaho.di.core.RowMetaAndData;
import org.pentaho.di.core.database.map.DatabaseConnectionMap;
import org.pentaho.di.core.database.util.DatabaseUtil;
import org.pentaho.di.core.exception.KettleDatabaseBatchException;
import org.pentaho.di.core.exception.KettleDatabaseException;
import org.pentaho.di.core.exception.KettleValueException;
import org.pentaho.di.core.logging.LogWriter;
import org.pentaho.di.core.row.RowDataUtil;
import org.pentaho.di.core.row.RowMeta;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMeta;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.core.variables.Variables;
/**
* Database handles the process of connecting to, reading from, writing to and updating databases.
* The database specific parameters are defined in DatabaseInfo.
*
* @author Matt
* @since 05-04-2003
*
*/
public class Database implements VariableSpace
{
private DatabaseMeta databaseMeta;
private int rowlimit;
private int commitsize;
private Connection connection;
private Statement sel_stmt;
private PreparedStatement pstmt;
private PreparedStatement prepStatementLookup;
private PreparedStatement prepStatementUpdate;
private PreparedStatement prepStatementInsert;
private PreparedStatement pstmt_seq;
private CallableStatement cstmt;
// private ResultSetMetaData rsmd;
private DatabaseMetaData dbmd;
private RowMetaInterface rowMeta;
private int written;
private LogWriter log;
/**
* Counts the number of rows written to a batch for a certain PreparedStatement.
*/
private Map<PreparedStatement, Integer> batchCounterMap;
/**
* Number of times a connection was opened using this object.
* Only used in the context of a database connection map
*/
private int opened;
/**
* The copy is equal to opened at the time of creation.
*/
private int copy;
private String connectionGroup;
private boolean performRollbackAtLastDisconnect;
private String partitionId;
private VariableSpace variables = new Variables();
/**
* Construct a new Database Connection
* @param inf The Database Connection Info to construct the connection with.
*/
public Database(DatabaseMeta inf)
{
log=LogWriter.getInstance();
databaseMeta = inf;
shareVariablesWith(inf);
batchCounterMap = new HashMap<PreparedStatement, Integer>();
pstmt = null;
rowMeta = null;
dbmd = null;
rowlimit=0;
written=0;
performRollbackAtLastDisconnect=false;
log.logDetailed(toString(), "New database connection defined");
}
public boolean equals(Object obj)
{
Database other = (Database) obj;
return other.databaseMeta.equals(other.databaseMeta);
}
/**
* Allows for the injection of a "life" connection, generated by a piece of software outside of Kettle.
* @param connection
*/
public void setConnection(Connection connection) {
this.connection = connection;
}
/**
* @return Returns the connection.
*/
public Connection getConnection()
{
return connection;
}
/**
* Set the maximum number of records to retrieve from a query.
* @param rows
*/
public void setQueryLimit(int rows)
{
rowlimit = rows;
}
/**
* @return Returns the prepStatementInsert.
*/
public PreparedStatement getPrepStatementInsert()
{
return prepStatementInsert;
}
/**
* @return Returns the prepStatementLookup.
*/
public PreparedStatement getPrepStatementLookup()
{
return prepStatementLookup;
}
/**
* @return Returns the prepStatementUpdate.
*/
public PreparedStatement getPrepStatementUpdate()
{
return prepStatementUpdate;
}
/**
* Open the database connection.
* @throws KettleDatabaseException if something went wrong.
*/
public void connect() throws KettleDatabaseException
{
connect(null);
}
/**
* Open the database connection.
* @param partitionId the partition ID in the cluster to connect to.
* @throws KettleDatabaseException if something went wrong.
*/
public void connect(String partitionId) throws KettleDatabaseException
{
connect(null, partitionId);
}
public synchronized void connect(String group, String partitionId) throws KettleDatabaseException
{
// Before anything else, let's see if we already have a connection defined for this group/partition!
// The group is called after the thread-name of the transformation or job that is running
// The name of that threadname is expected to be unique (it is in Kettle)
// So the deal is that if there is another thread using that, we go for it.
//
if (!Const.isEmpty(group))
{
this.connectionGroup = group;
this.partitionId = partitionId;
DatabaseConnectionMap map = DatabaseConnectionMap.getInstance();
// Try to find the conection for the group
Database lookup = map.getDatabase(group, partitionId, this);
if (lookup==null) // We already opened this connection for the partition & database in this group
{
// Do a normal connect and then store this database object for later re-use.
normalConnect(partitionId);
opened++;
copy = opened;
map.storeDatabase(group, partitionId, this);
}
else
{
connection = lookup.getConnection();
lookup.setOpened(lookup.getOpened()+1); // if this counter hits 0 again, close the connection.
copy = lookup.getOpened();
}
}
else
{
// Proceed with a normal connect
normalConnect(partitionId);
}
}
/**
* Open the database connection.
* @param partitionId the partition ID in the cluster to connect to.
* @throws KettleDatabaseException if something went wrong.
*/
public void normalConnect(String partitionId) throws KettleDatabaseException
{
if (databaseMeta==null)
{
throw new KettleDatabaseException("No valid database connection defined!");
}
try
{
// First see if we use connection pooling...
//
if ( databaseMeta.isUsingConnectionPool() && // default = false for backward compatibility
databaseMeta.getAccessType()!=DatabaseMeta.TYPE_ACCESS_JNDI // JNDI does pooling on it's own.
)
{
try
{
this.connection = ConnectionPoolUtil.getConnection(databaseMeta, partitionId);
}
catch (Exception e)
{
throw new KettleDatabaseException("Error occured while trying to connect to the database", e);
}
}
else
{
connectUsingClass(databaseMeta.getDriverClass(), partitionId );
log.logDetailed(toString(), "Connected to database.");
// See if we need to execute extra SQL statemtent...
String sql = environmentSubstitute( databaseMeta.getConnectSQL() );
// only execute if the SQL is not empty, null and is not just a bunch of spaces, tabs, CR etc.
if (!Const.isEmpty(sql) && !Const.onlySpaces(sql))
{
execStatements(sql);
log.logDetailed(toString(), "Executed connect time SQL statements:"+Const.CR+sql);
}
}
}
catch(Exception e)
{
throw new KettleDatabaseException("Error occured while trying to connect to the database", e);
}
}
private void initWithJNDI(String jndiName) throws KettleDatabaseException {
connection = null;
try {
DataSource dataSource = DatabaseUtil.getDataSourceFromJndi(jndiName);
if (dataSource != null) {
connection = dataSource.getConnection();
if (connection == null) {
throw new KettleDatabaseException( "Invalid JNDI connection "+ jndiName); //$NON-NLS-1$
}
} else {
throw new KettleDatabaseException( "Invalid JNDI connection "+ jndiName); //$NON-NLS-1$
}
} catch (Exception e) {
throw new KettleDatabaseException( "Invalid JNDI connection "+ jndiName + " : " + e.getMessage()); //$NON-NLS-1$
}
}
/**
* Connect using the correct classname
* @param classname for example "org.gjt.mm.mysql.Driver"
* @return true if the connect was succesfull, false if something went wrong.
*/
private void connectUsingClass(String classname, String partitionId) throws KettleDatabaseException
{
// Install and load the jdbc Driver
// first see if this is a JNDI connection
if( databaseMeta.getAccessType() == DatabaseMeta.TYPE_ACCESS_JNDI ) {
initWithJNDI( environmentSubstitute(databaseMeta.getDatabaseName()) );
return;
}
try
{
Class.forName(classname);
}
catch(NoClassDefFoundError e)
{
throw new KettleDatabaseException("Exception while loading class", e);
}
catch(ClassNotFoundException e)
{
throw new KettleDatabaseException("Exception while loading class", e);
}
catch(Exception e)
{
throw new KettleDatabaseException("Exception while loading class", e);
}
try
{
String url;
if (databaseMeta.isPartitioned() && !Const.isEmpty(partitionId))
{
url = environmentSubstitute(databaseMeta.getURL(partitionId));
}
else
{
url = environmentSubstitute(databaseMeta.getURL());
}
String clusterUsername=null;
String clusterPassword=null;
if (databaseMeta.isPartitioned() && !Const.isEmpty(partitionId))
{
// Get the cluster information...
PartitionDatabaseMeta partition = databaseMeta.getPartitionMeta(partitionId);
if (partition!=null)
{
clusterUsername = partition.getUsername();
clusterPassword = partition.getPassword();
}
}
String username;
String password;
if (!Const.isEmpty(clusterUsername))
{
username = clusterUsername;
password = clusterPassword;
}
else
{
username = environmentSubstitute(databaseMeta.getUsername());
password = environmentSubstitute(databaseMeta.getPassword());
}
if (databaseMeta.supportsOptionsInURL())
{
if (!Const.isEmpty(username) || !Const.isEmpty(password))
{
// also allow for empty username with given password, in this case username must be given with one space
connection = DriverManager.getConnection(url, Const.NVL(username, " "), Const.NVL(password, ""));
}
else
{
// Perhaps the username is in the URL or no username is required...
connection = DriverManager.getConnection(url);
}
}
else
{
Properties properties = databaseMeta.getConnectionProperties();
if (!Const.isEmpty(username)) properties.put("user", username);
if (!Const.isEmpty(password)) properties.put("password", password);
connection = DriverManager.getConnection(url, properties);
}
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error connecting to database: (using class "+classname+")", e);
}
catch(Throwable e)
{
throw new KettleDatabaseException("Error connecting to database: (using class "+classname+")", e);
}
}
/**
* Disconnect from the database and close all open prepared statements.
*/
public synchronized void disconnect()
{
try
{
if (connection==null)
{
return ; // Nothing to do...
}
if (connection.isClosed())
{
return ; // Nothing to do...
}
if (pstmt !=null)
{
pstmt.close();
pstmt=null;
}
if (prepStatementLookup!=null)
{
prepStatementLookup.close();
prepStatementLookup=null;
}
if (prepStatementInsert!=null)
{
prepStatementInsert.close();
prepStatementInsert=null;
}
if (prepStatementUpdate!=null)
{
prepStatementUpdate.close();
prepStatementUpdate=null;
}
if (pstmt_seq!=null)
{
pstmt_seq.close();
pstmt_seq=null;
}
// See if there are other steps using this connection in a connection group.
// If so, we will hold commit & connection close until then.
//
if (!Const.isEmpty(connectionGroup))
{
DatabaseConnectionMap map = DatabaseConnectionMap.getInstance();
Database lookup = map.getDatabase(connectionGroup, partitionId, this);
if (lookup!=null)
{
lookup.opened--;
if (lookup.opened>0)
{
return;
}
else
{
map.removeConnection(connectionGroup, partitionId, this); // remove the trace of it.
// Before we close perform commit or rollback.
if (performRollbackAtLastDisconnect)
{
rollback(true);
}
else
{
commit(true);
}
}
}
}
else
{
if (!isAutoCommit()) // Do we really still need this commit??
{
commit();
}
}
if (connection!=null)
{
connection.close();
if (!databaseMeta.isUsingConnectionPool())
{
connection=null;
}
}
log.logDetailed(toString(), "Connection to database closed!");
}
catch(SQLException ex)
{
log.logError(toString(), "Error disconnecting from database:"+Const.CR+ex.getMessage());
log.logError(toString(), Const.getStackTracker(ex));
}
catch(KettleDatabaseException dbe)
{
log.logError(toString(), "Error disconnecting from database:"+Const.CR+dbe.getMessage());
log.logError(toString(), Const.getStackTracker(dbe));
}
}
/**
* Cancel the open/running queries on the database connection
* @throws KettleDatabaseException
*/
public void cancelQuery() throws KettleDatabaseException
{
cancelStatement(pstmt);
cancelStatement(sel_stmt);
}
/**
* Cancel an open/running SQL statement
* @param statement the statement to cancel
* @throws KettleDatabaseException
*/
public void cancelStatement(Statement statement) throws KettleDatabaseException
{
try
{
if (statement!=null)
{
statement.cancel();
}
log.logDetailed(toString(), "Statement canceled!");
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Error cancelling statement", ex);
}
}
/**
* Specify after how many rows a commit needs to occur when inserting or updating values.
* @param commsize The number of rows to wait before doing a commit on the connection.
*/
public void setCommit(int commsize)
{
commitsize=commsize;
String onOff = (commitsize<=0?"on":"off");
try
{
connection.setAutoCommit(commitsize<=0);
log.logDetailed(toString(), "Auto commit "+onOff);
}
catch(Exception e)
{
log.logError(toString(), "Can't turn auto commit "+onOff);
}
}
/**
* Perform a commit the connection if this is supported by the database
*/
public void commit() throws KettleDatabaseException
{
commit(false);
}
private void commit(boolean force) throws KettleDatabaseException
{
try
{
// Don't do the commit, wait until the end of the transformation.
// When the last database copy (opened counter) is about to be closed, we do a commit
// There is one catch, we need to catch the rollback
// The transformation will stop everything and then we'll do the rollback.
// The flag is in "performRollback", private only
//
if (!Const.isEmpty(connectionGroup) && !force)
{
return;
}
if (getDatabaseMetaData().supportsTransactions())
{
connection.commit();
}
else
{
log.logDetailed(toString(), "No commit possible on database connection ["+toString()+"]");
}
}
catch(Exception e)
{
if (databaseMeta.supportsEmptyTransactions())
throw new KettleDatabaseException("Error comitting connection", e);
}
}
public void rollback() throws KettleDatabaseException
{
rollback(false);
}
private void rollback(boolean force) throws KettleDatabaseException
{
try
{
if (!Const.isEmpty(connectionGroup) && !force)
{
performRollbackAtLastDisconnect=true;
return;
}
if (getDatabaseMetaData().supportsTransactions())
{
if (connection!=null) connection.rollback();
}
else
{
log.logDetailed(toString(), "No rollback possible on database connection ["+toString()+"]");
}
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error performing rollback on connection", e);
}
}
/**
* Prepare inserting values into a table, using the fields & values in a Row
* @param rowMeta The row metadata to determine which values need to be inserted
* @param table The name of the table in which we want to insert rows
* @throws KettleDatabaseException if something went wrong.
*/
public void prepareInsert(RowMetaInterface rowMeta, String tableName) throws KettleDatabaseException
{
prepareInsert(rowMeta, null, tableName);
}
/**
* Prepare inserting values into a table, using the fields & values in a Row
* @param rowMeta The metadata row to determine which values need to be inserted
* @param schemaName The name of the schema in which we want to insert rows
* @param tableName The name of the table in which we want to insert rows
* @throws KettleDatabaseException if something went wrong.
*/
public void prepareInsert(RowMetaInterface rowMeta, String schemaName, String tableName) throws KettleDatabaseException
{
if (rowMeta.size()==0)
{
throw new KettleDatabaseException("No fields in row, can't insert!");
}
String ins = getInsertStatement(schemaName, tableName, rowMeta);
log.logDetailed(toString(),"Preparing statement: "+Const.CR+ins);
prepStatementInsert=prepareSQL(ins);
}
/**
* Prepare a statement to be executed on the database. (does not return generated keys)
* @param sql The SQL to be prepared
* @return The PreparedStatement object.
* @throws KettleDatabaseException
*/
public PreparedStatement prepareSQL(String sql)
throws KettleDatabaseException
{
return prepareSQL(sql, false);
}
/**
* Prepare a statement to be executed on the database.
* @param sql The SQL to be prepared
* @param returnKeys set to true if you want to return generated keys from an insert statement
* @return The PreparedStatement object.
* @throws KettleDatabaseException
*/
public PreparedStatement prepareSQL(String sql, boolean returnKeys) throws KettleDatabaseException
{
try
{
if (returnKeys)
{
return connection.prepareStatement(databaseMeta.stripCR(sql), Statement.RETURN_GENERATED_KEYS);
}
else
{
return connection.prepareStatement(databaseMeta.stripCR(sql));
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't prepare statement:"+Const.CR+sql, ex);
}
}
public void closeLookup() throws KettleDatabaseException
{
closePreparedStatement(pstmt);
pstmt=null;
}
public void closePreparedStatement(PreparedStatement ps) throws KettleDatabaseException
{
if (ps!=null)
{
try
{
ps.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing prepared statement", e);
}
}
}
public void closeInsert() throws KettleDatabaseException
{
if (prepStatementInsert!=null)
{
try
{
prepStatementInsert.close();
prepStatementInsert = null;
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing insert prepared statement.", e);
}
}
}
public void closeUpdate() throws KettleDatabaseException
{
if (prepStatementUpdate!=null)
{
try
{
prepStatementUpdate.close();
prepStatementUpdate=null;
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing update prepared statement.", e);
}
}
}
public void setValues(RowMetaInterface rowMeta, Object[] data) throws KettleDatabaseException
{
setValues(rowMeta, data, pstmt);
}
public void setValues(RowMetaAndData row) throws KettleDatabaseException
{
setValues(row.getRowMeta(), row.getData());
}
public void setValuesInsert(RowMetaInterface rowMeta, Object[] data) throws KettleDatabaseException
{
setValues(rowMeta, data, prepStatementInsert);
}
public void setValuesInsert(RowMetaAndData row) throws KettleDatabaseException
{
setValues(row.getRowMeta(), row.getData(), prepStatementInsert);
}
public void setValuesUpdate(RowMetaInterface rowMeta, Object[] data) throws KettleDatabaseException
{
setValues(rowMeta, data, prepStatementUpdate);
}
public void setValuesLookup(RowMetaInterface rowMeta, Object[] data) throws KettleDatabaseException
{
setValues(rowMeta, data, prepStatementLookup);
}
public void setProcValues(RowMetaInterface rowMeta, Object[] data, int argnrs[], String argdir[], boolean result) throws KettleDatabaseException
{
int pos;
if (result) pos=2; else pos=1;
for (int i=0;i<argnrs.length;i++)
{
if (argdir[i].equalsIgnoreCase("IN") || argdir[i].equalsIgnoreCase("INOUT"))
{
ValueMetaInterface valueMeta = rowMeta.getValueMeta(argnrs[i]);
Object value = data[argnrs[i]];
setValue(cstmt, valueMeta, value, pos);
pos++;
} else {
pos++; //next parameter when OUT
}
}
}
public void setValue(PreparedStatement ps, ValueMetaInterface v, Object object, int pos) throws KettleDatabaseException
{
String debug = "";
try
{
switch(v.getType())
{
case ValueMetaInterface.TYPE_NUMBER :
if (object!=null)
{
debug="Number, not null, getting number from value";
double num = v.getNumber(object).doubleValue();
if (databaseMeta.supportsFloatRoundingOnUpdate() && v.getPrecision()>=0)
{
debug="Number, rounding to precision ["+v.getPrecision()+"]";
num = Const.round(num, v.getPrecision());
}
debug="Number, setting ["+num+"] on position #"+pos+" of the prepared statement";
ps.setDouble(pos, num);
}
else
{
ps.setNull(pos, java.sql.Types.DOUBLE);
}
break;
case ValueMetaInterface.TYPE_INTEGER:
debug="Integer";
if (object!=null)
{
if (databaseMeta.supportsSetLong())
{
ps.setLong(pos, v.getInteger(object).longValue() );
}
else
{
double d = v.getNumber(object).doubleValue();
if (databaseMeta.supportsFloatRoundingOnUpdate() && v.getPrecision()>=0)
{
ps.setDouble(pos, d );
}
else
{
ps.setDouble(pos, Const.round( d, v.getPrecision() ) );
}
}
}
else
{
ps.setNull(pos, java.sql.Types.INTEGER);
}
break;
case ValueMetaInterface.TYPE_STRING :
debug="String";
if (v.getLength()<DatabaseMeta.CLOB_LENGTH)
{
if (object!=null)
{
ps.setString(pos, v.getString(object));
}
else
{
ps.setNull(pos, java.sql.Types.VARCHAR);
}
}
else
{
if (object!=null)
{
String string = v.getString(object);
int maxlen = databaseMeta.getMaxTextFieldLength();
int len = string.length();
// Take the last maxlen characters of the string...
int begin = len - maxlen;
if (begin<0) begin=0;
// Get the substring!
String logging = string.substring(begin);
if (databaseMeta.supportsSetCharacterStream())
{
StringReader sr = new StringReader(logging);
ps.setCharacterStream(pos, sr, logging.length());
}
else
{
ps.setString(pos, logging);
}
}
else
{
ps.setNull(pos, java.sql.Types.VARCHAR);
}
}
break;
case ValueMetaInterface.TYPE_DATE :
debug="Date";
if (object!=null)
{
long dat = v.getInteger(object).longValue(); // converts using Date.getTime()
if(v.getPrecision()==1 || !databaseMeta.supportsTimeStampToDateConversion())
{
// Convert to DATE!
java.sql.Date ddate = new java.sql.Date(dat);
ps.setDate(pos, ddate);
}
else
{
java.sql.Timestamp sdate = new java.sql.Timestamp(dat);
ps.setTimestamp(pos, sdate);
}
}
else
{
if(v.getPrecision()==1 || !databaseMeta.supportsTimeStampToDateConversion())
{
ps.setNull(pos, java.sql.Types.DATE);
}
else
{
ps.setNull(pos, java.sql.Types.TIMESTAMP);
}
}
break;
case ValueMetaInterface.TYPE_BOOLEAN:
debug="Boolean";
if (databaseMeta.supportsBooleanDataType())
{
if (object!=null)
{
ps.setBoolean(pos, v.getBoolean(object).booleanValue());
}
else
{
ps.setNull(pos, java.sql.Types.BOOLEAN);
}
}
else
{
if (object!=null)
{
ps.setString(pos, v.getBoolean(object).booleanValue()?"Y":"N");
}
else
{
ps.setNull(pos, java.sql.Types.CHAR);
}
}
break;
case ValueMetaInterface.TYPE_BIGNUMBER:
debug="BigNumber";
if (object!=null)
{
ps.setBigDecimal(pos, v.getBigNumber(object));
}
else
{
ps.setNull(pos, java.sql.Types.DECIMAL);
}
break;
case ValueMetaInterface.TYPE_BINARY:
debug="Binary";
if (object!=null)
{
ps.setBytes(pos, v.getBinary(object));
}
else
{
ps.setNull(pos, java.sql.Types.BINARY);
}
break;
default:
debug="default";
// placeholder
ps.setNull(pos, java.sql.Types.VARCHAR);
break;
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Error setting value #"+pos+" ["+v.toString()+"] on prepared statement ("+debug+")"+Const.CR+ex.toString(), ex);
}
catch(Exception e)
{
throw new KettleDatabaseException("Error setting value #"+pos+" ["+(v==null?"NULL":v.toString())+"] on prepared statement ("+debug+")"+Const.CR+e.toString(), e);
}
}
public void setValues(RowMetaAndData row, PreparedStatement ps) throws KettleDatabaseException
{
setValues(row.getRowMeta(), row.getData(), ps);
}
public void setValues(RowMetaInterface rowMeta, Object[] data, PreparedStatement ps) throws KettleDatabaseException
{
// now set the values in the row!
for (int i=0;i<rowMeta.size();i++)
{
ValueMetaInterface v = rowMeta.getValueMeta(i);
Object object = data[i];
try
{
setValue(ps, v, object, i+1);
}
catch(KettleDatabaseException e)
{
throw new KettleDatabaseException("offending row : "+rowMeta, e);
}
}
}
/**
* Sets the values of the preparedStatement pstmt.
* @param rowMeta
* @param data
*/
public void setValues(RowMetaInterface rowMeta, Object[] data, PreparedStatement ps, int ignoreThisValueIndex) throws KettleDatabaseException
{
// now set the values in the row!
int index=0;
for (int i=0;i<rowMeta.size();i++)
{
if (i!=ignoreThisValueIndex)
{
ValueMetaInterface v = rowMeta.getValueMeta(i);
Object object = data[i];
try
{
setValue(ps, v, object, index+1);
index++;
}
catch(KettleDatabaseException e)
{
throw new KettleDatabaseException("offending row : "+rowMeta, e);
}
}
}
}
/**
* @param ps The prepared insert statement to use
* @return The generated keys in auto-increment fields
* @throws KettleDatabaseException in case something goes wrong retrieving the keys.
*/
public RowMetaAndData getGeneratedKeys(PreparedStatement ps) throws KettleDatabaseException
{
ResultSet keys = null;
try
{
keys=ps.getGeneratedKeys(); // 1 row of keys
ResultSetMetaData resultSetMetaData = keys.getMetaData();
RowMetaInterface rowMeta = getRowInfo(resultSetMetaData, false, false);
return new RowMetaAndData(rowMeta, getRow(keys, resultSetMetaData, rowMeta));
}
catch(Exception ex)
{
throw new KettleDatabaseException("Unable to retrieve key(s) from auto-increment field(s)", ex);
}
finally
{
if (keys!=null)
{
try
{
keys.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to close resultset of auto-generated keys", e);
}
}
}
}
public Long getNextSequenceValue(String sequenceName, String keyfield) throws KettleDatabaseException
{
return getNextSequenceValue(null, sequenceName, keyfield);
}
public Long getNextSequenceValue(String schemaName, String sequenceName, String keyfield) throws KettleDatabaseException
{
Long retval=null;
String schemaSequence = databaseMeta.getQuotedSchemaTableCombination(schemaName, sequenceName);
try
{
if (pstmt_seq==null)
{
pstmt_seq=connection.prepareStatement(databaseMeta.getSeqNextvalSQL(databaseMeta.stripCR(schemaSequence)));
}
ResultSet rs=null;
try
{
rs = pstmt_seq.executeQuery();
if (rs.next())
{
retval = Long.valueOf( rs.getLong(1) );
}
}
finally
{
if ( rs != null ) rs.close();
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to get next value for sequence : "+schemaSequence, ex);
}
return retval;
}
public void insertRow(String tableName, RowMetaInterface fields, Object[] data) throws KettleDatabaseException
{
prepareInsert(fields, tableName);
setValuesInsert(fields, data);
insertRow();
closeInsert();
}
public String getInsertStatement(String tableName, RowMetaInterface fields)
{
return getInsertStatement(null, tableName, fields);
}
public String getInsertStatement(String schemaName, String tableName, RowMetaInterface fields)
{
StringBuffer ins=new StringBuffer(128);
String schemaTable = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName);
ins.append("INSERT INTO ").append(schemaTable).append('(');
// now add the names in the row:
for (int i=0;i<fields.size();i++)
{
if (i>0) ins.append(", ");
String name = fields.getValueMeta(i).getName();
ins.append(databaseMeta.quoteField(name));
}
ins.append(") VALUES (");
// Add placeholders...
for (int i=0;i<fields.size();i++)
{
if (i>0) ins.append(", ");
ins.append(" ?");
}
ins.append(')');
return ins.toString();
}
public void insertRow()
throws KettleDatabaseException
{
insertRow(prepStatementInsert);
}
public void insertRow(boolean batch) throws KettleDatabaseException
{
insertRow(prepStatementInsert, batch);
}
public void updateRow()
throws KettleDatabaseException
{
insertRow(prepStatementUpdate);
}
public void insertRow(PreparedStatement ps)
throws KettleDatabaseException
{
insertRow(ps, false);
}
/**
* @param batchCounterMap The batch counter map to set.
*/
public void setBatchCounterMap(Map<PreparedStatement, Integer> batchCounterMap)
{
this.batchCounterMap = batchCounterMap;
}
/**
* @return Returns the batch counter map.
*/
public Map<PreparedStatement, Integer> getBatchCounterMap()
{
return batchCounterMap;
}
/**
* Insert a row into the database using a prepared statement that has all values set.
* @param ps The prepared statement
* @param batch True if you want to use batch inserts (size = commit size)
* @return true if the rows are safe: if batch of rows was sent to the database OR if a commit was done.
* @throws KettleDatabaseException
*/
public boolean insertRow(PreparedStatement ps, boolean batch) throws KettleDatabaseException
{
String debug="insertRow start";
boolean rowsAreSafe=false;
Integer batchCounter = null;
try
{
// Unique connections and Batch inserts don't mix when you want to roll back on certain databases.
// That's why we disable the batch insert in that case.
//
boolean useBatchInsert = batch && getDatabaseMetaData().supportsBatchUpdates() && databaseMeta.supportsBatchUpdates() && Const.isEmpty(connectionGroup);
//
// Add support for batch inserts...
//
if (!isAutoCommit())
{
if (useBatchInsert)
{
debug="insertRow add batch";
// Increment the counter...
//
batchCounter = batchCounterMap.get(ps);
if (batchCounter==null) {
batchCounterMap.put(ps, 1);
}
else {
batchCounterMap.put(ps, Integer.valueOf(batchCounter.intValue()+1));
}
ps.addBatch(); // Add the batch, but don't forget to run the batch
}
else
{
debug="insertRow exec update";
ps.executeUpdate();
}
}
else
{
ps.executeUpdate();
}
written++;
if (!isAutoCommit() && (written%commitsize)==0)
{
if (useBatchInsert)
{
debug="insertRow executeBatch commit";
ps.executeBatch();
commit();
ps.clearBatch();
batchCounterMap.put(ps, Integer.valueOf(0));
}
else
{
debug="insertRow normal commit";
commit();
}
rowsAreSafe=true;
}
return rowsAreSafe;
}
catch(BatchUpdateException ex)
{
KettleDatabaseBatchException kdbe = new KettleDatabaseBatchException("Error updating batch", ex);
kdbe.setUpdateCounts(ex.getUpdateCounts());
List<Exception> exceptions = new ArrayList<Exception>();
// 'seed' the loop with the root exception
SQLException nextException = ex;
do
{
exceptions.add(nextException);
// while current exception has next exception, add to list
}
while ((nextException = nextException.getNextException())!=null);
kdbe.setExceptionsList(exceptions);
throw kdbe;
}
catch(SQLException ex)
{
// log.logError(toString(), Const.getStackTracker(ex));
throw new KettleDatabaseException("Error inserting row", ex);
}
catch(Exception e)
{
// System.out.println("Unexpected exception in ["+debug+"] : "+e.getMessage());
throw new KettleDatabaseException("Unexpected error inserting row in part ["+debug+"]", e);
}
}
/**
* Clears batch of insert prepared statement
* @deprecated
* @throws KettleDatabaseException
*/
public void clearInsertBatch() throws KettleDatabaseException
{
clearBatch(prepStatementInsert);
}
public void clearBatch(PreparedStatement preparedStatement) throws KettleDatabaseException
{
try
{
preparedStatement.clearBatch();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to clear batch for prepared statement", e);
}
}
public void insertFinished(boolean batch) throws KettleDatabaseException
{
insertFinished(prepStatementInsert, batch);
prepStatementInsert = null;
}
/**
* Empty and close a prepared statement.
*
* @param ps The prepared statement to empty and close.
* @param batch true if you are using batch processing (typically true for this method)
* @param psBatchCounter The number of rows on the batch queue
* @throws KettleDatabaseException
*/
public void insertFinished(PreparedStatement ps, boolean batch) throws KettleDatabaseException
{
try
{
if (ps!=null)
{
if (!isAutoCommit())
{
// Get the batch counter. This counter is unique per Prepared Statement.
// It is increased in method insertRow()
//
Integer batchCounter = batchCounterMap.get(ps);
// Execute the batch or just perform a commit.
//
if (batch && getDatabaseMetaData().supportsBatchUpdates() && batchCounter!=null && batchCounter.intValue()>0)
{
// The problem with the batch counters is that you can't just execute the current batch.
// Certain databases have a problem if you execute the batch and if there are no statements in it.
// You can't just catch the exception either because you would have to roll back on certain databases before you can then continue to do anything.
// That leaves the task of keeping track of the number of rows up to our responsibility.
//
ps.executeBatch();
commit();
}
else
{
commit();
}
}
// Let's not forget to close the prepared statement.
//
ps.close();
}
}
catch(BatchUpdateException ex)
{
KettleDatabaseBatchException kdbe = new KettleDatabaseBatchException("Error updating batch", ex);
kdbe.setUpdateCounts(ex.getUpdateCounts());
List<Exception> exceptions = new ArrayList<Exception>();
SQLException nextException = ex.getNextException();
SQLException oldException = null;
// This construction is specifically done for some JDBC drivers, these drivers
// always return the same exception on getNextException() (and thus go into an infinite loop).
// So it's not "equals" but != (comments from Sven Boden).
while ( (nextException != null) && (oldException != nextException) )
{
exceptions.add(nextException);
oldException = nextException;
nextException = nextException.getNextException();
}
kdbe.setExceptionsList(exceptions);
throw kdbe;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to commit connection after having inserted rows.", ex);
}
finally
{
// Remove the batch counter to avoid memory leaks in the database driver
//
batchCounterMap.remove(ps);
}
}
/**
* Execute an SQL statement on the database connection (has to be open)
* @param sql The SQL to execute
* @return a Result object indicating the number of lines read, deleted, inserted, updated, ...
* @throws KettleDatabaseException in case anything goes wrong.
*/
public Result execStatement(String sql) throws KettleDatabaseException
{
return execStatement(sql, null, null);
}
public Result execStatement(String sql, RowMetaInterface params, Object[] data) throws KettleDatabaseException
{
Result result = new Result();
try
{
boolean resultSet;
int count;
if (params!=null)
{
PreparedStatement prep_stmt = connection.prepareStatement(databaseMeta.stripCR(sql));
setValues(params, data, prep_stmt); // set the parameters!
resultSet = prep_stmt.execute();
count = prep_stmt.getUpdateCount();
prep_stmt.close();
}
else
{
String sqlStripped = databaseMeta.stripCR(sql);
// log.logDetailed(toString(), "Executing SQL Statement: ["+sqlStripped+"]");
Statement stmt = connection.createStatement();
resultSet = stmt.execute(sqlStripped);
count = stmt.getUpdateCount();
stmt.close();
}
if (resultSet)
{
// the result is a resultset, but we don't do anything with it!
// You should have called something else!
// log.logDetailed(toString(), "What to do with ResultSet??? (count="+count+")");
}
else
{
if (count > 0)
{
if (sql.toUpperCase().startsWith("INSERT")) result.setNrLinesOutput(count);
if (sql.toUpperCase().startsWith("UPDATE")) result.setNrLinesUpdated(count);
if (sql.toUpperCase().startsWith("DELETE")) result.setNrLinesDeleted(count);
}
}
// See if a cache needs to be cleared...
if (sql.toUpperCase().startsWith("ALTER TABLE") ||
sql.toUpperCase().startsWith("DROP TABLE") ||
sql.toUpperCase().startsWith("CREATE TABLE")
)
{
DBCache.getInstance().clear(databaseMeta.getName());
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't execute SQL: "+sql+Const.CR, ex);
}
catch(Exception e)
{
throw new KettleDatabaseException("Unexpected error executing SQL: "+Const.CR, e);
}
return result;
}
/**
* Execute a series of SQL statements, separated by ;
*
* We are already connected...
* Multiple statements have to be split into parts
* We use the ";" to separate statements...
*
* We keep the results in Result object from Jobs
*
* @param script The SQL script to be execute
* @throws KettleDatabaseException In case an error occurs
* @return A result with counts of the number or records updates, inserted, deleted or read.
*/
public Result execStatements(String script) throws KettleDatabaseException
{
Result result = new Result();
String all = script;
int from=0;
int to=0;
int length = all.length();
int nrstats = 0;
while (to<length)
{
char c = all.charAt(to);
if (c=='"')
{
to++;
c=' ';
while (to<length && c!='"') { c=all.charAt(to); to++; }
}
else
if (c=='\'') // skip until next '
{
to++;
c=' ';
while (to<length && c!='\'') { c=all.charAt(to); to++; }
}
else
if (all.substring(to).startsWith("--")) // -- means: ignore comment until end of line...
{
to++;
while (to<length && c!='\n' && c!='\r') { c=all.charAt(to); to++; }
}
if (c==';' || to>=length-1) // end of statement
{
if (to>=length-1) to++; // grab last char also!
String stat;
if (to<=length) stat = all.substring(from, to);
else stat = all.substring(from);
// If it ends with a ; remove that ;
// Oracle for example can't stand it when this happens...
if (stat.length()>0 && stat.charAt(stat.length()-1)==';')
{
stat = stat.substring(0,stat.length()-1);
}
if (!Const.onlySpaces(stat))
{
String sql=Const.trim(stat);
if (sql.toUpperCase().startsWith("SELECT"))
{
// A Query
log.logDetailed(toString(), "launch SELECT statement: "+Const.CR+sql);
nrstats++;
ResultSet rs = null;
try
{
rs = openQuery(sql);
if (rs!=null)
{
Object[] row = getRow(rs);
while (row!=null)
{
result.setNrLinesRead(result.getNrLinesRead()+1);
if (log.isDetailed()) log.logDetailed(toString(), rowMeta.getString(row));
row = getRow(rs);
}
}
else
{
if (log.isDebug()) log.logDebug(toString(), "Error executing query: "+Const.CR+sql);
}
} catch (KettleValueException e) {
throw new KettleDatabaseException(e); // just pass the error upwards.
}
finally
{
try
{
if ( rs != null ) rs.close();
}
catch (SQLException ex )
{
if (log.isDebug()) log.logDebug(toString(), "Error closing query: "+Const.CR+sql);
}
}
}
else // any kind of statement
{
log.logDetailed(toString(), "launch DDL statement: "+Const.CR+sql);
// A DDL statement
nrstats++;
Result res = execStatement(sql);
result.add(res);
}
}
to++;
from=to;
}
else
{
to++;
}
}
log.logDetailed(toString(), nrstats+" statement"+(nrstats==1?"":"s")+" executed");
return result;
}
public ResultSet openQuery(String sql) throws KettleDatabaseException
{
return openQuery(sql, null, null);
}
/**
* Open a query on the database with a set of parameters stored in a Kettle Row
* @param sql The SQL to launch with question marks (?) as placeholders for the parameters
* @param params The parameters or null if no parameters are used.
* @data the parameter data to open the query with
* @return A JDBC ResultSet
* @throws KettleDatabaseException when something goes wrong with the query.
*/
public ResultSet openQuery(String sql, RowMetaInterface params, Object[] data) throws KettleDatabaseException
{
return openQuery(sql, params, data, ResultSet.FETCH_FORWARD);
}
public ResultSet openQuery(String sql, RowMetaInterface params, Object[] data, int fetch_mode) throws KettleDatabaseException
{
return openQuery(sql, params, data, fetch_mode, false);
}
public ResultSet openQuery(String sql, RowMetaInterface params, Object[] data, int fetch_mode, boolean lazyConversion) throws KettleDatabaseException
{
ResultSet res;
String debug = "Start";
// Create a Statement
try
{
if (params!=null)
{
debug = "P create prepared statement (con==null? "+(connection==null)+")";
pstmt = connection.prepareStatement(databaseMeta.stripCR(sql), ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
debug = "P Set values";
setValues(params, data); // set the dates etc!
if (canWeSetFetchSize(pstmt) )
{
debug = "P Set fetchsize";
int fs = Const.FETCH_SIZE<=pstmt.getMaxRows()?pstmt.getMaxRows():Const.FETCH_SIZE;
// System.out.println("Setting pstmt fetchsize to : "+fs);
{
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL && databaseMeta.isStreamingResults())
{
pstmt.setFetchSize(Integer.MIN_VALUE);
}
else
pstmt.setFetchSize(fs);
}
debug = "P Set fetch direction";
pstmt.setFetchDirection(fetch_mode);
}
debug = "P Set max rows";
if (rowlimit>0 && databaseMeta.supportsSetMaxRows()) pstmt.setMaxRows(rowlimit);
debug = "exec query";
res = pstmt.executeQuery();
}
else
{
debug = "create statement";
sel_stmt = connection.createStatement();
if (canWeSetFetchSize(sel_stmt))
{
debug = "Set fetchsize";
int fs = Const.FETCH_SIZE<=sel_stmt.getMaxRows()?sel_stmt.getMaxRows():Const.FETCH_SIZE;
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL && databaseMeta.isStreamingResults())
{
sel_stmt.setFetchSize(Integer.MIN_VALUE);
}
else
{
sel_stmt.setFetchSize(fs);
}
debug = "Set fetch direction";
sel_stmt.setFetchDirection(fetch_mode);
}
debug = "Set max rows";
if (rowlimit>0 && databaseMeta.supportsSetMaxRows()) sel_stmt.setMaxRows(rowlimit);
debug = "exec query";
res=sel_stmt.executeQuery(databaseMeta.stripCR(sql));
}
debug = "openQuery : get rowinfo";
// MySQL Hack only. It seems too much for the cursor type of operation on MySQL, to have another cursor opened
// to get the length of a String field. So, on MySQL, we ingore the length of Strings in result rows.
//
rowMeta = getRowInfo(res.getMetaData(), databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL, lazyConversion);
}
catch(SQLException ex)
{
// log.logError(toString(), "ERROR executing ["+sql+"]");
// log.logError(toString(), "ERROR in part: ["+debug+"]");
// printSQLException(ex);
throw new KettleDatabaseException("An error occurred executing SQL: "+Const.CR+sql, ex);
}
catch(Exception e)
{
log.logError(toString(), "ERROR executing query: "+e.toString());
log.logError(toString(), "ERROR in part: "+debug);
throw new KettleDatabaseException("An error occurred executing SQL in part ["+debug+"]:"+Const.CR+sql, e);
}
return res;
}
private boolean canWeSetFetchSize(Statement statement) throws SQLException
{
return databaseMeta.isFetchSizeSupported() &&
( statement.getMaxRows()>0 ||
databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_POSTGRES ||
( databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_MYSQL && databaseMeta.isStreamingResults() )
);
}
public ResultSet openQuery(PreparedStatement ps, RowMetaInterface params, Object[] data) throws KettleDatabaseException
{
ResultSet res;
String debug = "Start";
// Create a Statement
try
{
debug = "OQ Set values";
setValues(params, data, ps); // set the parameters!
if (canWeSetFetchSize(ps))
{
debug = "OQ Set fetchsize";
int fs = Const.FETCH_SIZE<=ps.getMaxRows()?ps.getMaxRows():Const.FETCH_SIZE;
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL && databaseMeta.isStreamingResults())
{
ps.setFetchSize(Integer.MIN_VALUE);
}
else
{
ps.setFetchSize(fs);
}
debug = "OQ Set fetch direction";
ps.setFetchDirection(ResultSet.FETCH_FORWARD);
}
debug = "OQ Set max rows";
if (rowlimit>0 && databaseMeta.supportsSetMaxRows()) ps.setMaxRows(rowlimit);
debug = "OQ exec query";
res = ps.executeQuery();
debug = "OQ getRowInfo()";
// rowinfo = getRowInfo(res.getMetaData());
// MySQL Hack only. It seems too much for the cursor type of operation on MySQL, to have another cursor opened
// to get the length of a String field. So, on MySQL, we ingore the length of Strings in result rows.
//
rowMeta = getRowInfo(res.getMetaData(), databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL, false);
}
catch(SQLException ex)
{
throw new KettleDatabaseException("ERROR executing query in part["+debug+"]", ex);
}
catch(Exception e)
{
throw new KettleDatabaseException("ERROR executing query in part["+debug+"]", e);
}
return res;
}
public RowMetaInterface getTableFields(String tablename) throws KettleDatabaseException
{
return getQueryFields(databaseMeta.getSQLQueryFields(tablename), false);
}
public RowMetaInterface getQueryFields(String sql, boolean param) throws KettleDatabaseException
{
return getQueryFields(sql, param, null, null);
}
/**
* See if the table specified exists by reading
* @param tablename The name of the table to check.
* @return true if the table exists, false if it doesn't.
*/
public boolean checkTableExists(String tablename) throws KettleDatabaseException
{
try
{
log.logDebug(toString(), "Checking if table ["+tablename+"] exists!");
// Just try to read from the table.
String sql = databaseMeta.getSQLTableExists(tablename);
try
{
getOneRow(sql);
return true;
}
catch(KettleDatabaseException e)
{
return false;
}
/*
if (getDatabaseMetaData()!=null)
{
ResultSet alltables = getDatabaseMetaData().getTables(null, null, "%" , new String[] { "TABLE", "VIEW", "SYNONYM" } );
boolean found = false;
if (alltables!=null)
{
while (alltables.next() && !found)
{
String schemaName = alltables.getString("TABLE_SCHEM");
String name = alltables.getString("TABLE_NAME");
if ( tablename.equalsIgnoreCase(name) ||
( schemaName!=null && tablename.equalsIgnoreCase( databaseMeta.getSchemaTableCombination(schemaName, name)) )
)
{
log.logDebug(toString(), "table ["+tablename+"] was found!");
found=true;
}
}
alltables.close();
return found;
}
else
{
throw new KettleDatabaseException("Unable to read table-names from the database meta-data.");
}
}
else
{
throw new KettleDatabaseException("Unable to get database meta-data from the database.");
}
*/
}
catch(Exception e)
{
throw new KettleDatabaseException("Unable to check if table ["+tablename+"] exists on connection ["+databaseMeta.getName()+"]", e);
}
}
/**
* Check whether the sequence exists, Oracle only!
* @param sequenceName The name of the sequence
* @return true if the sequence exists.
*/
public boolean checkSequenceExists(String sequenceName) throws KettleDatabaseException
{
return checkSequenceExists(null, sequenceName);
}
/**
* Check whether the sequence exists, Oracle only!
* @param sequenceName The name of the sequence
* @return true if the sequence exists.
*/
public boolean checkSequenceExists(String schemaName, String sequenceName) throws KettleDatabaseException
{
boolean retval=false;
if (!databaseMeta.supportsSequences()) return retval;
String schemaSequence = databaseMeta.getQuotedSchemaTableCombination(schemaName, sequenceName);
try
{
//
// Get the info from the data dictionary...
//
String sql = databaseMeta.getSQLSequenceExists(schemaSequence);
ResultSet res = openQuery(sql);
if (res!=null)
{
Object[] row = getRow(res);
if (row!=null)
{
retval=true;
}
closeQuery(res);
}
}
catch(Exception e)
{
throw new KettleDatabaseException("Unexpected error checking whether or not sequence ["+schemaSequence+"] exists", e);
}
return retval;
}
/**
* Check if an index on certain fields in a table exists.
* @param tableName The table on which the index is checked
* @param idx_fields The fields on which the indexe is checked
* @return True if the index exists
*/
public boolean checkIndexExists(String tableName, String idx_fields[]) throws KettleDatabaseException
{
return checkIndexExists(null, tableName, idx_fields);
}
/**
* Check if an index on certain fields in a table exists.
* @param tablename The table on which the index is checked
* @param idx_fields The fields on which the indexe is checked
* @return True if the index exists
*/
public boolean checkIndexExists(String schemaName, String tableName, String idx_fields[]) throws KettleDatabaseException
{
String tablename = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName);
if (!checkTableExists(tablename)) return false;
log.logDebug(toString(), "CheckIndexExists() tablename = "+tablename+" type = "+databaseMeta.getDatabaseTypeDesc());
boolean exists[] = new boolean[idx_fields.length];
for (int i=0;i<exists.length;i++) exists[i]=false;
try
{
switch(databaseMeta.getDatabaseType())
{
case DatabaseMeta.TYPE_DATABASE_MSSQL:
{
//
// Get the info from the data dictionary...
//
StringBuffer sql = new StringBuffer(128);
sql.append("select i.name table_name, c.name column_name ");
sql.append("from sysindexes i, sysindexkeys k, syscolumns c ");
sql.append("where i.name = '"+tablename+"' ");
sql.append("AND i.id = k.id ");
sql.append("AND i.id = c.id ");
sql.append("AND k.colid = c.colid ");
ResultSet res = null;
try
{
res = openQuery(sql.toString());
if (res!=null)
{
Object[] row = getRow(res);
while (row!=null)
{
String column = rowMeta.getString(row, "column_name", "");
int idx = Const.indexOfString(column, idx_fields);
if (idx>=0) exists[idx]=true;
row = getRow(res);
}
}
else
{
return false;
}
}
finally
{
if ( res != null ) closeQuery(res);
}
}
break;
case DatabaseMeta.TYPE_DATABASE_ORACLE:
{
//
// Get the info from the data dictionary...
//
String sql = "SELECT * FROM USER_IND_COLUMNS WHERE TABLE_NAME = '"+tableName+"'";
ResultSet res = null;
try {
res = openQuery(sql);
if (res!=null)
{
Object[] row = getRow(res);
while (row!=null)
{
String column = rowMeta.getString(row, "COLUMN_NAME", "");
int idx = Const.indexOfString(column, idx_fields);
if (idx>=0)
{
exists[idx]=true;
}
row = getRow(res);
}
}
else
{
return false;
}
}
finally
{
if ( res != null ) closeQuery(res);
}
}
break;
case DatabaseMeta.TYPE_DATABASE_ACCESS:
{
// Get a list of all the indexes for this table
ResultSet indexList = null;
try
{
indexList = getDatabaseMetaData().getIndexInfo(null,null,tablename,false,true);
while (indexList.next())
{
// String tablen = indexList.getString("TABLE_NAME");
// String indexn = indexList.getString("INDEX_NAME");
String column = indexList.getString("COLUMN_NAME");
// int pos = indexList.getShort("ORDINAL_POSITION");
// int type = indexList.getShort("TYPE");
int idx = Const.indexOfString(column, idx_fields);
if (idx>=0)
{
exists[idx]=true;
}
}
}
finally
{
if ( indexList != null ) indexList.close();
}
}
break;
default:
{
// Get a list of all the indexes for this table
ResultSet indexList = null;
try
{
indexList = getDatabaseMetaData().getIndexInfo(null,null,tablename,false,true);
while (indexList.next())
{
// String tablen = indexList.getString("TABLE_NAME");
// String indexn = indexList.getString("INDEX_NAME");
String column = indexList.getString("COLUMN_NAME");
// int pos = indexList.getShort("ORDINAL_POSITION");
// int type = indexList.getShort("TYPE");
int idx = Const.indexOfString(column, idx_fields);
if (idx>=0)
{
exists[idx]=true;
}
}
}
finally
{
if ( indexList != null ) indexList.close();
}
}
break;
}
// See if all the fields are indexed...
boolean all=true;
for (int i=0;i<exists.length && all;i++) if (!exists[i]) all=false;
return all;
}
catch(Exception e)
{
log.logError(toString(), Const.getStackTracker(e));
throw new KettleDatabaseException("Unable to determine if indexes exists on table ["+tablename+"]", e);
}
}
public String getCreateIndexStatement(String tablename, String indexname, String idx_fields[], boolean tk, boolean unique, boolean bitmap, boolean semi_colon)
{
return getCreateIndexStatement(null, tablename, indexname, idx_fields, tk, unique, bitmap, semi_colon);
}
public String getCreateIndexStatement(String schemaname, String tablename, String indexname, String idx_fields[], boolean tk, boolean unique, boolean bitmap, boolean semi_colon)
{
String cr_index="";
cr_index += "CREATE ";
if (unique || ( tk && databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_SYBASE))
cr_index += "UNIQUE ";
if (bitmap && databaseMeta.supportsBitmapIndex())
cr_index += "BITMAP ";
cr_index += "INDEX "+databaseMeta.quoteField(indexname)+Const.CR+" ";
cr_index += "ON ";
// assume table has already been quoted (and possibly includes schema)
cr_index += tablename;
cr_index += Const.CR + "( "+Const.CR;
for (int i=0;i<idx_fields.length;i++)
{
if (i>0) cr_index+=", "; else cr_index+=" ";
cr_index += databaseMeta.quoteField(idx_fields[i])+Const.CR;
}
cr_index+=")"+Const.CR;
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE &&
databaseMeta.getIndexTablespace()!=null && databaseMeta.getIndexTablespace().length()>0)
{
cr_index+="TABLESPACE "+databaseMeta.quoteField(databaseMeta.getIndexTablespace());
}
if (semi_colon)
{
cr_index+=";"+Const.CR;
}
return cr_index;
}
public String getCreateSequenceStatement(String sequence, long start_at, long increment_by, long max_value, boolean semi_colon)
{
return getCreateSequenceStatement(null, sequence, Long.toString(start_at), Long.toString(increment_by), Long.toString(max_value), semi_colon);
}
public String getCreateSequenceStatement(String sequence, String start_at, String increment_by, String max_value, boolean semi_colon)
{
return getCreateSequenceStatement(null, sequence, start_at, increment_by, max_value, semi_colon);
}
public String getCreateSequenceStatement(String schemaName, String sequence, long start_at, long increment_by, long max_value, boolean semi_colon)
{
return getCreateSequenceStatement(schemaName, sequence, Long.toString(start_at), Long.toString(increment_by), Long.toString(max_value), semi_colon);
}
public String getCreateSequenceStatement(String schemaName, String sequenceName, String start_at, String increment_by, String max_value, boolean semi_colon)
{
String cr_seq="";
if (Const.isEmpty(sequenceName)) return cr_seq;
if (databaseMeta.supportsSequences())
{
String schemaSequence = databaseMeta.getQuotedSchemaTableCombination(schemaName, sequenceName);
cr_seq += "CREATE SEQUENCE "+schemaSequence+" "+Const.CR; // Works for both Oracle and PostgreSQL :-)
cr_seq += "START WITH "+start_at+" "+Const.CR;
cr_seq += "INCREMENT BY "+increment_by+" "+Const.CR;
if (max_value != null) cr_seq += "MAXVALUE "+max_value+Const.CR;
if (semi_colon) cr_seq+=";"+Const.CR;
}
return cr_seq;
}
public RowMetaInterface getQueryFields(String sql, boolean param, RowMetaInterface inform, Object[] data) throws KettleDatabaseException
{
RowMetaInterface fields;
DBCache dbcache = DBCache.getInstance();
DBCacheEntry entry=null;
// Check the cache first!
//
if (dbcache!=null)
{
entry = new DBCacheEntry(databaseMeta.getName(), sql);
fields = dbcache.get(entry);
if (fields!=null)
{
return fields;
}
}
if (connection==null) return null; // Cache test without connect.
// No cache entry found
// The new method of retrieving the query fields fails on Oracle because
// they failed to implement the getMetaData method on a prepared statement. (!!!)
// Even recent drivers like 10.2 fail because of it.
//
// There might be other databases that don't support it (we have no knowledge of this at the time of writing).
// If we discover other RDBMSs, we will create an interface for it.
// For now, we just try to get the field layout on the re-bound in the exception block below.
//
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE ||
databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_H2 ||
databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_GENERIC)
{
return getQueryFieldsFallback(sql, param, inform, data);
}
else
{
// On with the regular program.
//
PreparedStatement preparedStatement = null;
try
{
preparedStatement = connection.prepareStatement(databaseMeta.stripCR(sql), ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
ResultSetMetaData rsmd = preparedStatement.getMetaData();
fields = getRowInfo(rsmd, false, false);
}
catch(Exception e)
{
fields = getQueryFieldsFallback(sql, param, inform, data);
}
finally
{
if (preparedStatement!=null)
{
try
{
preparedStatement.close();
}
catch (SQLException e)
{
throw new KettleDatabaseException("Unable to close prepared statement after determining SQL layout", e);
}
}
}
}
// Store in cache!!
if (dbcache!=null && entry!=null)
{
if (fields!=null)
{
dbcache.put(entry, fields);
}
}
return fields;
}
private RowMetaInterface getQueryFieldsFallback(String sql, boolean param, RowMetaInterface inform, Object[] data) throws KettleDatabaseException
{
RowMetaInterface fields;
try
{
if (inform==null
// Hack for MSSQL jtds 1.2 when using xxx NOT IN yyy we have to use a prepared statement (see BugID 3214)
&& databaseMeta.getDatabaseType()!=DatabaseMeta.TYPE_DATABASE_MSSQL
)
{
sel_stmt = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
if (databaseMeta.isFetchSizeSupported() && sel_stmt.getMaxRows()>=1)
{
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL)
{
sel_stmt.setFetchSize(Integer.MIN_VALUE);
}
else
{
sel_stmt.setFetchSize(1);
}
}
if (databaseMeta.supportsSetMaxRows()) sel_stmt.setMaxRows(1);
ResultSet r=sel_stmt.executeQuery(databaseMeta.stripCR(sql));
fields = getRowInfo(r.getMetaData(), false, false);
r.close();
sel_stmt.close();
sel_stmt=null;
}
else
{
PreparedStatement ps = connection.prepareStatement(databaseMeta.stripCR(sql));
if (param)
{
RowMetaInterface par = inform;
if (par==null || par.isEmpty()) par = getParameterMetaData(ps);
if (par==null || par.isEmpty()) par = getParameterMetaData(sql, inform, data);
setValues(par, data, ps);
}
ResultSet r = ps.executeQuery();
fields=getRowInfo(ps.getMetaData(), false, false);
r.close();
ps.close();
}
}
catch(Exception ex)
{
throw new KettleDatabaseException("Couldn't get field info from ["+sql+"]"+Const.CR, ex);
}
return fields;
}
public void closeQuery(ResultSet res) throws KettleDatabaseException
{
// close everything involved in the query!
try
{
if (res!=null) res.close();
if (sel_stmt!=null) { sel_stmt.close(); sel_stmt=null; }
if (pstmt!=null) { pstmt.close(); pstmt=null;}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't close query: resultset or prepared statements", ex);
}
}
/**
* Build the row using ResultSetMetaData rsmd
* @param rm The resultset metadata to inquire
* @param ignoreLength true if you want to ignore the length (workaround for MySQL bug/problem)
* @param lazyConversion true if lazy conversion needs to be enabled where possible
*/
private RowMetaInterface getRowInfo(ResultSetMetaData rm, boolean ignoreLength, boolean lazyConversion) throws KettleDatabaseException
{
if (rm==null) return null;
rowMeta = new RowMeta();
try
{
// TODO If we do lazy conversion, we need to find out about the encoding
//
int fieldNr = 1;
int nrcols=rm.getColumnCount();
for (int i=1;i<=nrcols;i++)
{
String name=new String(rm.getColumnName(i));
// Check the name, sometimes it's empty.
//
if (Const.isEmpty(name) || Const.onlySpaces(name))
{
name = "Field"+fieldNr;
fieldNr++;
}
ValueMetaInterface v = getValueFromSQLType(name, rm, i, ignoreLength, lazyConversion);
rowMeta.addValueMeta(v);
}
return rowMeta;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Error getting row information from database: ", ex);
}
}
private ValueMetaInterface getValueFromSQLType(String name, ResultSetMetaData rm, int index, boolean ignoreLength, boolean lazyConversion) throws SQLException
{
int length=-1;
int precision=-1;
int valtype=ValueMetaInterface.TYPE_NONE;
boolean isClob = false;
int type = rm.getColumnType(index);
switch(type)
{
case java.sql.Types.CHAR:
case java.sql.Types.VARCHAR:
case java.sql.Types.LONGVARCHAR: // Character Large Object
valtype=ValueMetaInterface.TYPE_STRING;
if (!ignoreLength) length=rm.getColumnDisplaySize(index);
break;
case java.sql.Types.CLOB:
valtype=ValueMetaInterface.TYPE_STRING;
length=DatabaseMeta.CLOB_LENGTH;
isClob=true;
break;
case java.sql.Types.BIGINT:
valtype=ValueMetaInterface.TYPE_INTEGER;
precision=0; // Max 9.223.372.036.854.775.807
length=15;
break;
case java.sql.Types.INTEGER:
valtype=ValueMetaInterface.TYPE_INTEGER;
precision=0; // Max 2.147.483.647
length=9;
break;
case java.sql.Types.SMALLINT:
valtype=ValueMetaInterface.TYPE_INTEGER;
precision=0; // Max 32.767
length=4;
break;
case java.sql.Types.TINYINT:
valtype=ValueMetaInterface.TYPE_INTEGER;
precision=0; // Max 127
length=2;
break;
case java.sql.Types.DECIMAL:
case java.sql.Types.DOUBLE:
case java.sql.Types.FLOAT:
case java.sql.Types.REAL:
case java.sql.Types.NUMERIC:
valtype=ValueMetaInterface.TYPE_NUMBER;
length=rm.getPrecision(index);
precision=rm.getScale(index);
if (length >=126) length=-1;
if (precision >=126) precision=-1;
if (type==java.sql.Types.DOUBLE || type==java.sql.Types.FLOAT || type==java.sql.Types.REAL)
{
if (precision==0)
{
precision=-1; // precision is obviously incorrect if the type if Double/Float/Real
}
// If we're dealing with PostgreSQL and double precision types
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_POSTGRES && type==java.sql.Types.DOUBLE && precision==16 && length==16)
{
precision=-1;
length=-1;
}
// MySQL: max resolution is double precision floating point (double)
// The (12,31) that is given back is not correct
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL)
{
if (precision >= length) {
precision=-1;
length=-1;
}
}
}
else
{
if (precision==0 && length<18 && length>0) // Among others Oracle is affected here.
{
valtype=ValueMetaInterface.TYPE_INTEGER;
}
}
if (length>18 || precision>18) valtype=ValueMetaInterface.TYPE_BIGNUMBER;
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE)
{
if (precision == 0 && length == 38 )
{
valtype=ValueMetaInterface.TYPE_INTEGER;
}
if (precision<=0 && length<=0) // undefined size: NUMBER
{
valtype=ValueMetaInterface.TYPE_NUMBER;
length=-1;
precision=-1;
}
}
break;
case java.sql.Types.DATE:
case java.sql.Types.TIME:
case java.sql.Types.TIMESTAMP:
valtype=ValueMetaInterface.TYPE_DATE;
//
if (databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_MYSQL) {
String property = databaseMeta.getConnectionProperties().getProperty("yearIsDateType");
if (property != null && property.equalsIgnoreCase("false")
&& rm.getColumnTypeName(index).equalsIgnoreCase("YEAR")) {
valtype = ValueMetaInterface.TYPE_INTEGER;
precision = 0;
length = 4;
break;
}
}
break;
case java.sql.Types.BOOLEAN:
case java.sql.Types.BIT:
valtype=ValueMetaInterface.TYPE_BOOLEAN;
break;
case java.sql.Types.BINARY:
case java.sql.Types.BLOB:
case java.sql.Types.VARBINARY:
case java.sql.Types.LONGVARBINARY:
valtype=ValueMetaInterface.TYPE_BINARY;
if (databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_DB2 &&
(2 * rm.getPrecision(index)) == rm.getColumnDisplaySize(index))
{
// set the length for "CHAR(X) FOR BIT DATA"
length = rm.getPrecision(index);
}
else
if (databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_ORACLE &&
( type==java.sql.Types.VARBINARY || type==java.sql.Types.LONGVARBINARY )
)
{
// set the length for Oracle "RAW" or "LONGRAW" data types
valtype = ValueMetaInterface.TYPE_STRING;
length = rm.getColumnDisplaySize(index);
}
else
{
length=-1;
}
precision=-1;
break;
default:
valtype=ValueMetaInterface.TYPE_STRING;
precision=rm.getScale(index);
break;
}
// Grab the comment as a description to the field as well.
String comments=rm.getColumnLabel(index);
ValueMetaInterface v=new ValueMeta(name, valtype);
v.setLength(length);
v.setPrecision(precision);
v.setComments(comments);
v.setLargeTextField(isClob);
// See if we need to enable lazy conversion...
//
if (lazyConversion && valtype==ValueMetaInterface.TYPE_STRING) {
v.setStorageType(ValueMetaInterface.STORAGE_TYPE_BINARY_STRING);
// TODO set some encoding to go with this.
// Also set the storage metadata. a copy of the parent, set to String too.
//
ValueMetaInterface storageMetaData = v.clone();
storageMetaData.setType(ValueMetaInterface.TYPE_STRING);
storageMetaData.setStorageType(ValueMetaInterface.STORAGE_TYPE_NORMAL);
v.setStorageMetadata(storageMetaData);
}
return v;
}
public boolean absolute(ResultSet rs, int position) throws KettleDatabaseException
{
try
{
return rs.absolute(position);
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to move resultset to position "+position, e);
}
}
public boolean relative(ResultSet rs, int rows) throws KettleDatabaseException
{
try
{
return rs.relative(rows);
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to move the resultset forward "+rows+" rows", e);
}
}
public void afterLast(ResultSet rs)
throws KettleDatabaseException
{
try
{
rs.afterLast();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to move resultset to after the last position", e);
}
}
public void first(ResultSet rs) throws KettleDatabaseException
{
try
{
rs.first();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to move resultset to the first position", e);
}
}
/**
* Get a row from the resultset. Do not use lazy conversion
* @param rs The resultset to get the row from
* @return one row or null if no row was found on the resultset or if an error occurred.
*/
public Object[] getRow(ResultSet rs) throws KettleDatabaseException
{
return getRow(rs, false);
}
/**
* Get a row from the resultset.
* @param rs The resultset to get the row from
* @param lazyConversion set to true if strings need to have lazy conversion enabled
* @return one row or null if no row was found on the resultset or if an error occurred.
*/
public Object[] getRow(ResultSet rs, boolean lazyConversion) throws KettleDatabaseException
{
if (rowMeta==null)
{
ResultSetMetaData rsmd = null;
try
{
rsmd = rs.getMetaData();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to retrieve metadata from resultset", e);
}
rowMeta = getRowInfo(rsmd, false, lazyConversion);
}
return getRow(rs, null, rowMeta);
}
/**
* Get a row from the resultset.
* @param rs The resultset to get the row from
* @return one row or null if no row was found on the resultset or if an error occurred.
*/
public Object[] getRow(ResultSet rs, ResultSetMetaData dummy, RowMetaInterface rowInfo) throws KettleDatabaseException
{
try
{
int nrcols=rowInfo.size();
Object[] data = RowDataUtil.allocateRowData(nrcols);
if (rs.next())
{
for (int i=0;i<nrcols;i++)
{
ValueMetaInterface val = rowInfo.getValueMeta(i);
switch(val.getType())
{
case ValueMetaInterface.TYPE_BOOLEAN : data[i] = Boolean.valueOf( rs.getBoolean(i+1) ); break;
case ValueMetaInterface.TYPE_NUMBER : data[i] = new Double( rs.getDouble(i+1) ); break;
case ValueMetaInterface.TYPE_BIGNUMBER : data[i] = rs.getBigDecimal(i+1); break;
case ValueMetaInterface.TYPE_INTEGER : data[i] = Long.valueOf( rs.getLong(i+1) ); break;
case ValueMetaInterface.TYPE_STRING :
{
if (val.isStorageBinaryString()) {
data[i] = rs.getBytes(i+1);
}
else {
data[i] = rs.getString(i+1);
}
}
break;
case ValueMetaInterface.TYPE_BINARY :
{
if (databaseMeta.supportsGetBlob())
{
Blob blob = rs.getBlob(i+1);
if (blob!=null)
{
data[i] = blob.getBytes(1L, (int)blob.length());
}
else
{
data[i] = null;
}
}
else
{
data[i] = rs.getBytes(i+1);
}
}
break;
case ValueMetaInterface.TYPE_DATE :
if (databaseMeta.supportsTimeStampToDateConversion())
{
data[i] = rs.getTimestamp(i+1); break; // Timestamp extends java.util.Date
}
else
{
data[i] = rs.getDate(i+1); break;
}
default: break;
}
if (rs.wasNull()) data[i] = null; // null value, it's the default but we want it just to make sure we handle this case too.
}
}
else
{
data=null;
}
return data;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't get row from result set", ex);
}
}
public void printSQLException(SQLException ex)
{
log.logError(toString(), "==> SQLException: ");
while (ex != null)
{
log.logError(toString(), "Message: " + ex.getMessage ());
log.logError(toString(), "SQLState: " + ex.getSQLState ());
log.logError(toString(), "ErrorCode: " + ex.getErrorCode ());
ex = ex.getNextException();
log.logError(toString(), "");
}
}
public void setLookup(String table, String codes[], String condition[],
String gets[], String rename[], String orderby
) throws KettleDatabaseException
{
setLookup(table, codes, condition, gets, rename, orderby, false);
}
public void setLookup(String schema, String table, String codes[], String condition[],
String gets[], String rename[], String orderby
) throws KettleDatabaseException
{
setLookup(schema, table, codes, condition, gets, rename, orderby, false);
}
public void setLookup(String tableName, String codes[], String condition[],
String gets[], String rename[], String orderby,
boolean checkForMultipleResults) throws KettleDatabaseException
{
setLookup(null, tableName, codes, condition, gets, rename, orderby, checkForMultipleResults);
}
// Lookup certain fields in a table
public void setLookup(String schemaName, String tableName, String codes[], String condition[],
String gets[], String rename[], String orderby,
boolean checkForMultipleResults) throws KettleDatabaseException
{
String table = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName);
String sql = "SELECT ";
for (int i=0;i<gets.length;i++)
{
if (i!=0) sql += ", ";
sql += databaseMeta.quoteField(gets[i]);
if (rename!=null && rename[i]!=null && !gets[i].equalsIgnoreCase(rename[i]))
{
sql+=" AS "+databaseMeta.quoteField(rename[i]);
}
}
sql += " FROM "+table+" WHERE ";
for (int i=0;i<codes.length;i++)
{
if (i!=0) sql += " AND ";
sql += databaseMeta.quoteField(codes[i]);
if ("BETWEEN".equalsIgnoreCase(condition[i]))
{
sql+=" BETWEEN ? AND ? ";
}
else
if ("IS NULL".equalsIgnoreCase(condition[i]) || "IS NOT NULL".equalsIgnoreCase(condition[i]))
{
sql+=" "+condition[i]+" ";
}
else
{
sql+=" "+condition[i]+" ? ";
}
}
if (orderby!=null && orderby.length()!=0)
{
sql += " ORDER BY "+orderby;
}
try
{
log.logDetailed(toString(), "Setting preparedStatement to ["+sql+"]");
prepStatementLookup=connection.prepareStatement(databaseMeta.stripCR(sql));
if (!checkForMultipleResults && databaseMeta.supportsSetMaxRows())
{
prepStatementLookup.setMaxRows(1); // alywas get only 1 line back!
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare statement for update ["+sql+"]", ex);
}
}
public boolean prepareUpdate(String table, String codes[], String condition[], String sets[])
{
return prepareUpdate(null, table, codes, condition, sets);
}
// Lookup certain fields in a table
public boolean prepareUpdate(String schemaName, String tableName, String codes[], String condition[], String sets[])
{
StringBuffer sql = new StringBuffer(128);
String schemaTable = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName);
sql.append("UPDATE ").append(schemaTable).append(Const.CR).append("SET ");
for (int i=0;i<sets.length;i++)
{
if (i!=0) sql.append(", ");
sql.append(databaseMeta.quoteField(sets[i]));
sql.append(" = ?").append(Const.CR);
}
sql.append("WHERE ");
for (int i=0;i<codes.length;i++)
{
if (i!=0) sql.append("AND ");
sql.append(databaseMeta.quoteField(codes[i]));
if ("BETWEEN".equalsIgnoreCase(condition[i]))
{
sql.append(" BETWEEN ? AND ? ");
}
else
if ("IS NULL".equalsIgnoreCase(condition[i]) || "IS NOT NULL".equalsIgnoreCase(condition[i]))
{
sql.append(' ').append(condition[i]).append(' ');
}
else
{
sql.append(' ').append(condition[i]).append(" ? ");
}
}
try
{
String s = sql.toString();
log.logDetailed(toString(), "Setting update preparedStatement to ["+s+"]");
prepStatementUpdate=connection.prepareStatement(databaseMeta.stripCR(s));
}
catch(SQLException ex)
{
printSQLException(ex);
return false;
}
return true;
}
/**
* Prepare a delete statement by giving it the tablename, fields and conditions to work with.
* @param table The table-name to delete in
* @param codes
* @param condition
* @return true when everything went OK, false when something went wrong.
*/
public boolean prepareDelete(String table, String codes[], String condition[])
{
return prepareDelete(null, table, codes, condition);
}
/**
* Prepare a delete statement by giving it the tablename, fields and conditions to work with.
* @param schemaName the schema-name to delete in
* @param tableName The table-name to delete in
* @param codes
* @param condition
* @return true when everything went OK, false when something went wrong.
*/
public boolean prepareDelete(String schemaName, String tableName, String codes[], String condition[])
{
String sql;
String table = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName);
sql = "DELETE FROM "+table+Const.CR;
sql+= "WHERE ";
for (int i=0;i<codes.length;i++)
{
if (i!=0) sql += "AND ";
sql += codes[i];
if ("BETWEEN".equalsIgnoreCase(condition[i]))
{
sql+=" BETWEEN ? AND ? ";
}
else
if ("IS NULL".equalsIgnoreCase(condition[i]) || "IS NOT NULL".equalsIgnoreCase(condition[i]))
{
sql+=" "+condition[i]+" ";
}
else
{
sql+=" "+condition[i]+" ? ";
}
}
try
{
log.logDetailed(toString(), "Setting update preparedStatement to ["+sql+"]");
prepStatementUpdate=connection.prepareStatement(databaseMeta.stripCR(sql));
}
catch(SQLException ex)
{
printSQLException(ex);
return false;
}
return true;
}
public void setProcLookup(String proc, String arg[], String argdir[], int argtype[], String returnvalue, int returntype)
throws KettleDatabaseException
{
String sql;
int pos=0;
sql = "{ ";
if (returnvalue!=null && returnvalue.length()!=0)
{
sql+="? = ";
}
sql+="call "+proc+" ";
if (arg.length>0) sql+="(";
for (int i=0;i<arg.length;i++)
{
if (i!=0) sql += ", ";
sql += " ?";
}
if (arg.length>0) sql+=")";
sql+="}";
try
{
log.logDetailed(toString(), "DBA setting callableStatement to ["+sql+"]");
cstmt=connection.prepareCall(sql);
pos=1;
if (!Const.isEmpty(returnvalue))
{
switch(returntype)
{
case ValueMetaInterface.TYPE_NUMBER : cstmt.registerOutParameter(pos, java.sql.Types.DOUBLE); break;
case ValueMetaInterface.TYPE_BIGNUMBER : cstmt.registerOutParameter(pos, java.sql.Types.DECIMAL); break;
case ValueMetaInterface.TYPE_INTEGER : cstmt.registerOutParameter(pos, java.sql.Types.BIGINT); break;
case ValueMetaInterface.TYPE_STRING : cstmt.registerOutParameter(pos, java.sql.Types.VARCHAR); break;
case ValueMetaInterface.TYPE_DATE : cstmt.registerOutParameter(pos, java.sql.Types.TIMESTAMP); break;
case ValueMetaInterface.TYPE_BOOLEAN : cstmt.registerOutParameter(pos, java.sql.Types.BOOLEAN); break;
default: break;
}
pos++;
}
for (int i=0;i<arg.length;i++)
{
if (argdir[i].equalsIgnoreCase("OUT") || argdir[i].equalsIgnoreCase("INOUT"))
{
switch(argtype[i])
{
case ValueMetaInterface.TYPE_NUMBER : cstmt.registerOutParameter(i+pos, java.sql.Types.DOUBLE); break;
case ValueMetaInterface.TYPE_BIGNUMBER : cstmt.registerOutParameter(i+pos, java.sql.Types.DECIMAL); break;
case ValueMetaInterface.TYPE_INTEGER : cstmt.registerOutParameter(i+pos, java.sql.Types.BIGINT); break;
case ValueMetaInterface.TYPE_STRING : cstmt.registerOutParameter(i+pos, java.sql.Types.VARCHAR); break;
case ValueMetaInterface.TYPE_DATE : cstmt.registerOutParameter(i+pos, java.sql.Types.TIMESTAMP); break;
case ValueMetaInterface.TYPE_BOOLEAN : cstmt.registerOutParameter(i+pos, java.sql.Types.BOOLEAN); break;
default: break;
}
}
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare database procedure call", ex);
}
}
public Object[] getLookup() throws KettleDatabaseException
{
return getLookup(prepStatementLookup);
}
public Object[] getLookup(boolean failOnMultipleResults) throws KettleDatabaseException
{
return getLookup(prepStatementLookup, failOnMultipleResults);
}
public Object[] getLookup(PreparedStatement ps) throws KettleDatabaseException
{
return getLookup(ps, false);
}
public Object[] getLookup(PreparedStatement ps, boolean failOnMultipleResults) throws KettleDatabaseException
{
String debug = "start";
ResultSet res = null;
try
{
debug = "pstmt.executeQuery()";
res = ps.executeQuery();
debug = "getRowInfo()";
rowMeta = getRowInfo(res.getMetaData(), false, false);
debug = "getRow(res)";
Object[] ret = getRow(res);
if (failOnMultipleResults)
{
if (ret != null && res.next())
{
// if the previous row was null, there's no reason to try res.next() again.
// on DB2 this will even cause an exception (because of the buggy DB2 JDBC driver).
throw new KettleDatabaseException("Only 1 row was expected as a result of a lookup, and at least 2 were found!");
}
}
return ret;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Error looking up row in database ("+debug+")", ex);
}
finally
{
try
{
debug = "res.close()";
if (res!=null) res.close(); // close resultset!
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to close resultset after looking up data", e);
}
}
}
public DatabaseMetaData getDatabaseMetaData() throws KettleDatabaseException
{
try
{
if (dbmd==null) dbmd = connection.getMetaData(); // Only get the metadata once!
}
catch(Exception e)
{
throw new KettleDatabaseException("Unable to get database metadata from this database connection", e);
}
return dbmd;
}
public String getDDL(String tablename, RowMetaInterface fields) throws KettleDatabaseException
{
return getDDL(tablename, fields, null, false, null, true);
}
public String getDDL(String tablename, RowMetaInterface fields, String tk, boolean use_autoinc, String pk) throws KettleDatabaseException
{
return getDDL(tablename, fields, tk, use_autoinc, pk, true);
}
public String getDDL(String tableName, RowMetaInterface fields, String tk, boolean use_autoinc, String pk, boolean semicolon) throws KettleDatabaseException
{
String retval;
// First, check for reserved SQL in the input row r...
databaseMeta.quoteReservedWords(fields);
String quotedTk = tk != null ? databaseMeta.quoteField(tk) : null;
if (checkTableExists(tableName))
{
retval=getAlterTableStatement(tableName, fields, quotedTk, use_autoinc, pk, semicolon);
}
else
{
retval=getCreateTableStatement(tableName, fields, quotedTk, use_autoinc, pk, semicolon);
}
return retval;
}
/**
* Generates SQL
* @param tableName the table name or schema/table combination: this needs to be quoted properly in advance.
* @param fields the fields
* @param tk the name of the technical key field
* @param use_autoinc true if we need to use auto-increment fields for a primary key
* @param pk the name of the primary/technical key field
* @param semicolon append semicolon to the statement
* @return the SQL needed to create the specified table and fields.
*/
public String getCreateTableStatement(String tableName, RowMetaInterface fields, String tk, boolean use_autoinc, String pk, boolean semicolon)
{
String retval;
retval = "CREATE TABLE "+tableName+Const.CR;
retval+= "("+Const.CR;
for (int i=0;i<fields.size();i++)
{
if (i>0) retval+=", "; else retval+=" ";
ValueMetaInterface v=fields.getValueMeta(i);
retval+=databaseMeta.getFieldDefinition(v, tk, pk, use_autoinc);
}
// At the end, before the closing of the statement, we might need to add some constraints...
// Technical keys
if (tk!=null)
{
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_CACHE)
{
retval+=", PRIMARY KEY ("+tk+")"+Const.CR;
}
}
// Primary keys
if (pk!=null)
{
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE)
{
retval+=", PRIMARY KEY ("+pk+")"+Const.CR;
}
}
retval+= ")"+Const.CR;
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE &&
databaseMeta.getIndexTablespace()!=null && databaseMeta.getIndexTablespace().length()>0)
{
retval+="TABLESPACE "+databaseMeta.getDataTablespace();
}
if (semicolon) retval+=";";
retval+=Const.CR;
return retval;
}
public String getAlterTableStatement(String tableName, RowMetaInterface fields, String tk, boolean use_autoinc, String pk, boolean semicolon) throws KettleDatabaseException
{
String retval="";
// Get the fields that are in the table now:
RowMetaInterface tabFields = getTableFields(tableName);
// Don't forget to quote these as well...
databaseMeta.quoteReservedWords(tabFields);
// Find the missing fields
RowMetaInterface missing = new RowMeta();
for (int i=0;i<fields.size();i++)
{
ValueMetaInterface v = fields.getValueMeta(i);
// Not found?
if (tabFields.searchValueMeta( v.getName() )==null )
{
missing.addValueMeta(v); // nope --> Missing!
}
}
if (missing.size()!=0)
{
for (int i=0;i<missing.size();i++)
{
ValueMetaInterface v=missing.getValueMeta(i);
retval+=databaseMeta.getAddColumnStatement(tableName, v, tk, use_autoinc, pk, true);
}
}
// Find the surplus fields
RowMetaInterface surplus = new RowMeta();
for (int i=0;i<tabFields.size();i++)
{
ValueMetaInterface v = tabFields.getValueMeta(i);
// Found in table, not in input ?
if (fields.searchValueMeta( v.getName() )==null )
{
surplus.addValueMeta(v); // yes --> surplus!
}
}
if (surplus.size()!=0)
{
for (int i=0;i<surplus.size();i++)
{
ValueMetaInterface v=surplus.getValueMeta(i);
retval+=databaseMeta.getDropColumnStatement(tableName, v, tk, use_autoinc, pk, true);
}
}
//
// OK, see if there are fields for wich we need to modify the type... (length, precision)
//
RowMetaInterface modify = new RowMeta();
for (int i=0;i<fields.size();i++)
{
ValueMetaInterface desiredField = fields.getValueMeta(i);
ValueMetaInterface currentField = tabFields.searchValueMeta( desiredField.getName());
if (currentField!=null)
{
boolean mod = false;
mod |= ( currentField.getLength() < desiredField.getLength() ) && desiredField.getLength()>0;
mod |= ( currentField.getPrecision() < desiredField.getPrecision() ) && desiredField.getPrecision()>0;
// Numeric values...
mod |= ( currentField.getType() != desiredField.getType() ) && ( currentField.isNumber()^desiredField.isNumeric() );
// TODO: this is not an optimal way of finding out changes.
// Perhaps we should just generate the data types strings for existing and new data type and see if anything changed.
//
if (mod)
{
// System.out.println("Desired field: ["+desiredField.toStringMeta()+"], current field: ["+currentField.toStringMeta()+"]");
modify.addValueMeta(desiredField);
}
}
}
if (modify.size()>0)
{
for (int i=0;i<modify.size();i++)
{
ValueMetaInterface v=modify.getValueMeta(i);
retval+=databaseMeta.getModifyColumnStatement(tableName, v, tk, use_autoinc, pk, true);
}
}
return retval;
}
public void truncateTable(String tablename) throws KettleDatabaseException
{
if (Const.isEmpty(connectionGroup))
{
execStatement(databaseMeta.getTruncateTableStatement(null, tablename));
}
else
{
execStatement("DELETE FROM "+databaseMeta.quoteField(tablename));
}
}
public void truncateTable(String schema, String tablename) throws KettleDatabaseException
{
if (Const.isEmpty(connectionGroup))
{
execStatement(databaseMeta.getTruncateTableStatement(schema, tablename));
}
else
{
execStatement("DELETE FROM "+databaseMeta.getQuotedSchemaTableCombination(schema, tablename));
}
}
/**
* Execute a query and return at most one row from the resultset
* @param sql The SQL for the query
* @return one Row with data or null if nothing was found.
*/
public RowMetaAndData getOneRow(String sql) throws KettleDatabaseException
{
ResultSet rs = openQuery(sql);
if (rs!=null)
{
Object[] row = getRow(rs); // One row only;
try { rs.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close resultset", e); }
if (pstmt!=null)
{
try { pstmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement pstmt", e); }
pstmt=null;
}
if (sel_stmt!=null)
{
try { sel_stmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement sel_stmt", e); }
sel_stmt=null;
}
return new RowMetaAndData(rowMeta, row);
}
else
{
throw new KettleDatabaseException("error opening resultset for query: "+sql);
}
}
public RowMeta getMetaFromRow( Object[] row, ResultSetMetaData md ) throws SQLException {
RowMeta meta = new RowMeta();
for( int i=0; i<md.getColumnCount(); i++ ) {
String name = md.getColumnName(i+1);
ValueMetaInterface valueMeta = getValueFromSQLType( name, md, i+1, true, false );
meta.addValueMeta( valueMeta );
}
return meta;
}
public RowMetaAndData getOneRow(String sql, RowMetaInterface param, Object[] data) throws KettleDatabaseException
{
ResultSet rs = openQuery(sql, param, data);
if (rs!=null)
{
Object[] row = getRow(rs); // One value: a number;
rowMeta=null;
RowMeta tmpMeta = null;
try {
ResultSetMetaData md = rs.getMetaData();
tmpMeta = getMetaFromRow( row, md );
} catch (Exception e) {
e.printStackTrace();
} finally {
try { rs.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close resultset", e); }
if (pstmt!=null)
{
try { pstmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement pstmt", e); }
pstmt=null;
}
if (sel_stmt!=null)
{
try { sel_stmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement sel_stmt", e); }
sel_stmt=null;
}
}
return new RowMetaAndData(tmpMeta, row);
}
else
{
return null;
}
}
public RowMetaInterface getParameterMetaData(PreparedStatement ps)
{
RowMetaInterface par = new RowMeta();
try
{
ParameterMetaData pmd = ps.getParameterMetaData();
for (int i=1;i<=pmd.getParameterCount();i++)
{
String name = "par"+i;
int sqltype = pmd.getParameterType(i);
int length = pmd.getPrecision(i);
int precision = pmd.getScale(i);
ValueMeta val;
switch(sqltype)
{
case java.sql.Types.CHAR:
case java.sql.Types.VARCHAR:
val=new ValueMeta(name, ValueMetaInterface.TYPE_STRING);
break;
case java.sql.Types.BIGINT:
case java.sql.Types.INTEGER:
case java.sql.Types.NUMERIC:
case java.sql.Types.SMALLINT:
case java.sql.Types.TINYINT:
val=new ValueMeta(name, ValueMetaInterface.TYPE_INTEGER);
break;
case java.sql.Types.DECIMAL:
case java.sql.Types.DOUBLE:
case java.sql.Types.FLOAT:
case java.sql.Types.REAL:
val=new ValueMeta(name, ValueMetaInterface.TYPE_NUMBER);
break;
case java.sql.Types.DATE:
case java.sql.Types.TIME:
case java.sql.Types.TIMESTAMP:
val=new ValueMeta(name, ValueMetaInterface.TYPE_DATE);
break;
case java.sql.Types.BOOLEAN:
case java.sql.Types.BIT:
val=new ValueMeta(name, ValueMetaInterface.TYPE_BOOLEAN);
break;
default:
val=new ValueMeta(name, ValueMetaInterface.TYPE_NONE);
break;
}
if (val.isNumeric() && ( length>18 || precision>18) )
{
val = new ValueMeta(name, ValueMetaInterface.TYPE_BIGNUMBER);
}
par.addValueMeta(val);
}
}
// Oops: probably the database or JDBC doesn't support it.
catch(AbstractMethodError e) { return null; }
catch(SQLException e) { return null; }
catch(Exception e) { return null; }
return par;
}
public int countParameters(String sql)
{
int q=0;
boolean quote_opened=false;
boolean dquote_opened=false;
for (int x=0;x<sql.length();x++)
{
char c = sql.charAt(x);
switch(c)
{
case '\'': quote_opened= !quote_opened; break;
case '"' : dquote_opened=!dquote_opened; break;
case '?' : if (!quote_opened && !dquote_opened) q++; break;
}
}
return q;
}
// Get the fields back from an SQL query
public RowMetaInterface getParameterMetaData(String sql, RowMetaInterface inform, Object[] data)
{
// The database couldn't handle it: try manually!
int q=countParameters(sql);
RowMetaInterface par=new RowMeta();
if (inform!=null && q==inform.size())
{
for (int i=0;i<q;i++)
{
ValueMetaInterface inf=inform.getValueMeta(i);
ValueMetaInterface v = inf.clone();
par.addValueMeta(v);
}
}
else
{
for (int i=0;i<q;i++)
{
ValueMetaInterface v = new ValueMeta("name"+i, ValueMetaInterface.TYPE_NUMBER);
par.addValueMeta(v);
}
}
return par;
}
public static final RowMetaInterface getTransLogrecordFields(boolean update, boolean use_batchid, boolean use_logfield)
{
RowMetaInterface r = new RowMeta();
ValueMetaInterface v;
if (use_batchid && !update)
{
v=new ValueMeta("ID_BATCH", ValueMetaInterface.TYPE_INTEGER, 8, 0); r.addValueMeta(v);
}
if (!update)
{
v=new ValueMeta("TRANSNAME", ValueMetaInterface.TYPE_STRING , 50, 0); r.addValueMeta(v);
}
v=new ValueMeta("STATUS", ValueMetaInterface.TYPE_STRING , 15, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_READ", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_WRITTEN", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_UPDATED", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_INPUT", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_OUTPUT", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("ERRORS", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("STARTDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("ENDDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("LOGDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("DEPDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("REPLAYDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
if (use_logfield)
{
v=new ValueMeta("LOG_FIELD", ValueMetaInterface.TYPE_STRING, DatabaseMeta.CLOB_LENGTH, 0);
r.addValueMeta(v);
}
if (use_batchid && update)
{
v=new ValueMeta("ID_BATCH", ValueMetaInterface.TYPE_INTEGER, 8, 0); r.addValueMeta(v);
}
return r;
}
public static final RowMetaInterface getJobLogrecordFields(boolean update, boolean use_jobid, boolean use_logfield)
{
RowMetaInterface r = new RowMeta();
ValueMetaInterface v;
if (use_jobid && !update)
{
v=new ValueMeta("ID_JOB", ValueMetaInterface.TYPE_INTEGER, 8, 0); r.addValueMeta(v);
}
if (!update)
{
v=new ValueMeta("JOBNAME", ValueMetaInterface.TYPE_STRING, 50, 0); r.addValueMeta(v);
}
v=new ValueMeta("STATUS", ValueMetaInterface.TYPE_STRING, 15, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_READ", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_WRITTEN", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_UPDATED", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_INPUT", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_OUTPUT", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("ERRORS", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("STARTDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("ENDDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("LOGDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("DEPDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("REPLAYDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
if (use_logfield)
{
v=new ValueMeta("LOG_FIELD", ValueMetaInterface.TYPE_STRING, DatabaseMeta.CLOB_LENGTH, 0);
r.addValueMeta(v);
}
if (use_jobid && update)
{
v=new ValueMeta("ID_JOB", ValueMetaInterface.TYPE_INTEGER, 8, 0); r.addValueMeta(v);
}
return r;
}
public void writeLogRecord( String logtable,
boolean use_id,
long id,
boolean job,
String name,
String status,
long read, long written, long updated,
long input, long output, long errors,
java.util.Date startdate, java.util.Date enddate,
java.util.Date logdate, java.util.Date depdate,
java.util.Date replayDate,
String log_string
)
throws KettleDatabaseException
{
if (use_id && log_string!=null && !status.equalsIgnoreCase("start"))
{
String sql = "UPDATE "+logtable+" SET STATUS=?, LINES_READ=?, LINES_WRITTEN=?, LINES_INPUT=?," +
" LINES_OUTPUT=?, LINES_UPDATED=?, ERRORS=?, STARTDATE=?, ENDDATE=?, LOGDATE=?, DEPDATE=?, REPLAYDATE=?, LOG_FIELD=? " +
"WHERE ";
if (job) sql+="ID_JOB=?"; else sql+="ID_BATCH=?";
RowMetaInterface rowMeta;
if (job) rowMeta = getJobLogrecordFields(true, use_id, true);
else rowMeta = getTransLogrecordFields(true, use_id, true);
Object[] data = new Object[] {
status,
Long.valueOf(read),
Long.valueOf(written),
Long.valueOf(input),
Long.valueOf(output),
Long.valueOf(updated),
Long.valueOf(errors),
startdate,
enddate,
logdate,
depdate,
replayDate,
log_string,
Long.valueOf(id),
};
execStatement(sql, rowMeta, data);
}
else
{
int parms;
String sql = "INSERT INTO "+logtable+" ( ";
if (job)
{
if (use_id)
{
sql+="ID_JOB, JOBNAME";
parms=14;
}
else
{
sql+="JOBNAME";
parms=13;
}
}
else
{
if (use_id)
{
sql+="ID_BATCH, TRANSNAME";
parms=14;
}
else
{
sql+="TRANSNAME";
parms=13;
}
}
sql+=", STATUS, LINES_READ, LINES_WRITTEN, LINES_UPDATED, LINES_INPUT, LINES_OUTPUT, ERRORS, STARTDATE, ENDDATE, LOGDATE, DEPDATE, REPLAYDATE";
if (log_string!=null && log_string.length()>0) sql+=", LOG_FIELD"; // This is possibly a CLOB!
sql+=") VALUES(";
for (int i=0;i<parms;i++) if (i==0) sql+="?"; else sql+=", ?";
if (log_string!=null && log_string.length()>0) sql+=", ?";
sql+=")";
try
{
pstmt = connection.prepareStatement(databaseMeta.stripCR(sql));
RowMetaInterface rowMeta = new RowMeta();
List<Object> data = new ArrayList<Object>();
if (job)
{
if (use_id)
{
rowMeta.addValueMeta( new ValueMeta("ID_BATCH", ValueMetaInterface.TYPE_INTEGER));
data.add(Long.valueOf(id));
}
rowMeta.addValueMeta( new ValueMeta("TRANSNAME", ValueMetaInterface.TYPE_STRING));
data.add(name);
}
else
{
if (use_id)
{
rowMeta.addValueMeta( new ValueMeta("ID_JOB", ValueMetaInterface.TYPE_INTEGER));
data.add(Long.valueOf(id));
}
rowMeta.addValueMeta( new ValueMeta("JOBNAME", ValueMetaInterface.TYPE_STRING));
data.add(name);
}
rowMeta.addValueMeta( new ValueMeta("STATUS", ValueMetaInterface.TYPE_STRING )); data.add(status);
rowMeta.addValueMeta( new ValueMeta("LINES_READ", ValueMetaInterface.TYPE_INTEGER)); data.add(Long.valueOf(read));
rowMeta.addValueMeta( new ValueMeta("LINES_WRITTEN", ValueMetaInterface.TYPE_INTEGER)); data.add(Long.valueOf(written));
rowMeta.addValueMeta( new ValueMeta("LINES_UPDATED", ValueMetaInterface.TYPE_INTEGER)); data.add(Long.valueOf(updated));
rowMeta.addValueMeta( new ValueMeta("LINES_INPUT", ValueMetaInterface.TYPE_INTEGER)); data.add(Long.valueOf(input));
rowMeta.addValueMeta( new ValueMeta("LINES_OUTPUT", ValueMetaInterface.TYPE_INTEGER)); data.add(Long.valueOf(output));
rowMeta.addValueMeta( new ValueMeta("ERRORS", ValueMetaInterface.TYPE_INTEGER)); data.add(Long.valueOf(errors));
rowMeta.addValueMeta( new ValueMeta("STARTDATE", ValueMetaInterface.TYPE_DATE )); data.add(startdate);
rowMeta.addValueMeta( new ValueMeta("ENDDATE", ValueMetaInterface.TYPE_DATE )); data.add(enddate);
rowMeta.addValueMeta( new ValueMeta("LOGDATE", ValueMetaInterface.TYPE_DATE )); data.add(logdate);
rowMeta.addValueMeta( new ValueMeta("DEPDATE", ValueMetaInterface.TYPE_DATE )); data.add(depdate);
rowMeta.addValueMeta( new ValueMeta("REPLAYDATE", ValueMetaInterface.TYPE_DATE )); data.add(replayDate);
if (!Const.isEmpty(log_string))
{
ValueMetaInterface large = new ValueMeta("LOG_FIELD", ValueMetaInterface.TYPE_STRING);
large.setLength(DatabaseMeta.CLOB_LENGTH);
rowMeta.addValueMeta( large );
data.add(log_string);
}
setValues(rowMeta, data.toArray(new Object[data.size()]));
pstmt.executeUpdate();
pstmt.close(); pstmt=null;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to write log record to log table "+logtable, ex);
}
}
}
public Object[] getLastLogDate( String logtable, String name, boolean job, String status ) throws KettleDatabaseException
{
Object[] row = null;
String jobtrans = job?"JOBNAME":"TRANSNAME";
String sql = "";
sql+=" SELECT ENDDATE, DEPDATE, STARTDATE";
sql+=" FROM "+logtable;
sql+=" WHERE ERRORS = 0";
sql+=" AND STATUS = 'end'";
sql+=" AND "+jobtrans+" = ?";
sql+=" ORDER BY LOGDATE DESC, ENDDATE DESC";
try
{
pstmt = connection.prepareStatement(databaseMeta.stripCR(sql));
RowMetaInterface r = new RowMeta();
r.addValueMeta( new ValueMeta("TRANSNAME", ValueMetaInterface.TYPE_STRING));
setValues(r, new Object[] { name });
ResultSet res = pstmt.executeQuery();
if (res!=null)
{
rowMeta = getRowInfo(res.getMetaData(), false, false);
row = getRow(res);
res.close();
}
pstmt.close(); pstmt=null;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to obtain last logdate from table "+logtable, ex);
}
return row;
}
public synchronized Long getNextValue(Hashtable<String,Counter> counters, String tableName, String val_key) throws KettleDatabaseException
{
return getNextValue(counters, null, tableName, val_key);
}
public synchronized Long getNextValue(Hashtable<String,Counter> counters, String schemaName, String tableName, String val_key) throws KettleDatabaseException
{
Long nextValue = null;
String schemaTable = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName);
String lookup = schemaTable+"."+databaseMeta.quoteField(val_key);
// Try to find the previous sequence value...
Counter counter = null;
if (counters!=null) counter=counters.get(lookup);
if (counter==null)
{
RowMetaAndData rmad = getOneRow("SELECT MAX("+databaseMeta.quoteField(val_key)+") FROM "+schemaTable);
if (rmad!=null)
{
long previous;
try
{
Long tmp = rmad.getRowMeta().getInteger(rmad.getData(), 0);
// A "select max(x)" on a table with no matching rows will return null.
if ( tmp != null )
previous = tmp.longValue();
else
previous = 0L;
}
catch (KettleValueException e)
{
throw new KettleDatabaseException("Error getting the first long value from the max value returned from table : "+schemaTable);
}
counter = new Counter(previous+1, 1);
nextValue = Long.valueOf( counter.next() );
if (counters!=null) counters.put(lookup, counter);
}
else
{
throw new KettleDatabaseException("Couldn't find maximum key value from table "+schemaTable);
}
}
else
{
nextValue = Long.valueOf( counter.next() );
}
return nextValue;
}
public String toString()
{
if (databaseMeta!=null) return databaseMeta.getName();
else return "-";
}
public boolean isSystemTable(String table_name)
{
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MSSQL)
{
if ( table_name.startsWith("sys")) return true;
if ( table_name.equals("dtproperties")) return true;
}
else
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_GUPTA)
{
if ( table_name.startsWith("SYS")) return true;
}
return false;
}
/** Reads the result of an SQL query into an ArrayList
*
* @param sql The SQL to launch
* @param limit <=0 means unlimited, otherwise this specifies the maximum number of rows read.
* @return An ArrayList of rows.
* @throws KettleDatabaseException if something goes wrong.
*/
public List<Object[]> getRows(String sql, int limit) throws KettleDatabaseException
{
return getRows(sql, limit, null);
}
/** Reads the result of an SQL query into an ArrayList
*
* @param sql The SQL to launch
* @param limit <=0 means unlimited, otherwise this specifies the maximum number of rows read.
* @param monitor The progress monitor to update while getting the rows.
* @return An ArrayList of rows.
* @throws KettleDatabaseException if something goes wrong.
*/
public List<Object[]> getRows(String sql, int limit, IProgressMonitor monitor) throws KettleDatabaseException
{
if (monitor!=null) monitor.setTaskName("Opening query...");
ResultSet rset = openQuery(sql);
return getRows(rset, limit, monitor);
}
/** Reads the result of a ResultSet into an ArrayList
*
* @param rset the ResultSet to read out
* @param limit <=0 means unlimited, otherwise this specifies the maximum number of rows read.
* @param monitor The progress monitor to update while getting the rows.
* @return An ArrayList of rows.
* @throws KettleDatabaseException if something goes wrong.
*/
public List<Object[]> getRows(ResultSet rset, int limit, IProgressMonitor monitor) throws KettleDatabaseException
{
try
{
List<Object[]> result = new ArrayList<Object[]>();
boolean stop=false;
int i=0;
if (rset!=null)
{
if (monitor!=null && limit>0) monitor.beginTask("Reading rows...", limit);
while ((limit<=0 || i<limit) && !stop)
{
Object[] row = getRow(rset);
if (row!=null)
{
result.add(row);
i++;
}
else
{
stop=true;
}
if (monitor!=null && limit>0) monitor.worked(1);
}
closeQuery(rset);
if (monitor!=null) monitor.done();
}
return result;
}
catch(Exception e)
{
throw new KettleDatabaseException("Unable to get list of rows from ResultSet : ", e);
}
}
public List<Object[]> getFirstRows(String table_name, int limit) throws KettleDatabaseException
{
return getFirstRows(table_name, limit, null);
}
/**
* Get the first rows from a table (for preview)
* @param table_name The table name (or schema/table combination): this needs to be quoted properly
* @param limit limit <=0 means unlimited, otherwise this specifies the maximum number of rows read.
* @param monitor The progress monitor to update while getting the rows.
* @return An ArrayList of rows.
* @throws KettleDatabaseException in case something goes wrong
*/
public List<Object[]> getFirstRows(String table_name, int limit, IProgressMonitor monitor) throws KettleDatabaseException
{
String sql = "SELECT * FROM "+table_name;
if (limit>0)
{
sql+=databaseMeta.getLimitClause(limit);
}
return getRows(sql, limit, monitor);
}
public RowMetaInterface getReturnRowMeta()
{
return rowMeta;
}
public String[] getTableTypes() throws KettleDatabaseException
{
try
{
ArrayList<String> types = new ArrayList<String>();
ResultSet rstt = getDatabaseMetaData().getTableTypes();
while(rstt.next())
{
String ttype = rstt.getString("TABLE_TYPE");
types.add(ttype);
}
return types.toArray(new String[types.size()]);
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to get table types from database!", e);
}
}
public String[] getTablenames() throws KettleDatabaseException
{
return getTablenames(false);
}
public String[] getTablenames(boolean includeSchema) throws KettleDatabaseException
{
String schemaname = null;
if (databaseMeta.useSchemaNameForTableList()) schemaname = databaseMeta.getUsername().toUpperCase();
List<String> names = new ArrayList<String>();
ResultSet alltables=null;
try
{
alltables = getDatabaseMetaData().getTables(null, schemaname, null, databaseMeta.getTableTypes() );
while (alltables.next())
{
String table = alltables.getString("TABLE_NAME");
String schema = alltables.getString("TABLE_SCHEM");
if (Const.isEmpty(schema)) schema = alltables.getString("TABLE_CAT"); // retry for the catalog.
String schemaTable;
if (includeSchema) schemaTable = databaseMeta.getQuotedSchemaTableCombination(schema, table);
else schemaTable = table;
if (log.isRowLevel()) log.logRowlevel(toString(), "got table from meta-data: "+schemaTable);
names.add(schemaTable);
}
}
catch(SQLException e)
{
log.logError(toString(), "Error getting tablenames from schema ["+schemaname+"]");
}
finally
{
try
{
if (alltables!=null) alltables.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing resultset after getting views from schema ["+schemaname+"]", e);
}
}
log.logDetailed(toString(), "read :"+names.size()+" table names from db meta-data.");
return names.toArray(new String[names.size()]);
}
public String[] getViews() throws KettleDatabaseException
{
return getViews(false);
}
public String[] getViews(boolean includeSchema) throws KettleDatabaseException
{
if (!databaseMeta.supportsViews()) return new String[] {};
String schemaname = null;
if (databaseMeta.useSchemaNameForTableList()) schemaname=databaseMeta.getUsername().toUpperCase();
ArrayList<String> names = new ArrayList<String>();
ResultSet alltables=null;
try
{
alltables = dbmd.getTables(null, schemaname, null, databaseMeta.getViewTypes() );
while (alltables.next())
{
String table = alltables.getString("TABLE_NAME");
String schema = alltables.getString("TABLE_SCHEM");
if (Const.isEmpty(schema)) schema = alltables.getString("TABLE_CAT"); // retry for the catalog.
String schemaTable;
if (includeSchema) schemaTable = databaseMeta.getQuotedSchemaTableCombination(schema, table);
else schemaTable = table;
if (log.isRowLevel()) log.logRowlevel(toString(), "got view from meta-data: "+schemaTable);
names.add(schemaTable);
}
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error getting views from schema ["+schemaname+"]", e);
}
finally
{
try
{
if (alltables!=null) alltables.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing resultset after getting views from schema ["+schemaname+"]", e);
}
}
log.logDetailed(toString(), "read :"+names.size()+" views from db meta-data.");
return names.toArray(new String[names.size()]);
}
public String[] getSynonyms() throws KettleDatabaseException
{
return getViews(false);
}
public String[] getSynonyms(boolean includeSchema) throws KettleDatabaseException
{
if (!databaseMeta.supportsSynonyms()) return new String[] {};
String schemaname = null;
if (databaseMeta.useSchemaNameForTableList()) schemaname=databaseMeta.getUsername().toUpperCase();
ArrayList<String> names = new ArrayList<String>();
ResultSet alltables=null;
try
{
alltables = dbmd.getTables(null, schemaname, null, databaseMeta.getSynonymTypes() );
while (alltables.next())
{
String table = alltables.getString("TABLE_NAME");
String schema = alltables.getString("TABLE_SCHEM");
if (Const.isEmpty(schema)) schema = alltables.getString("TABLE_CAT"); // retry for the catalog.
String schemaTable;
if (includeSchema) schemaTable = databaseMeta.getQuotedSchemaTableCombination(schema, table);
else schemaTable = table;
if (log.isRowLevel()) log.logRowlevel(toString(), "got view from meta-data: "+schemaTable);
names.add(schemaTable);
}
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error getting synonyms from schema ["+schemaname+"]", e);
}
finally
{
try
{
if (alltables!=null) alltables.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing resultset after getting synonyms from schema ["+schemaname+"]", e);
}
}
log.logDetailed(toString(), "read :"+names.size()+" views from db meta-data.");
return names.toArray(new String[names.size()]);
}
public String[] getProcedures() throws KettleDatabaseException
{
String sql = databaseMeta.getSQLListOfProcedures();
if (sql!=null)
{
//System.out.println("SQL= "+sql);
List<Object[]> procs = getRows(sql, 1000);
//System.out.println("Found "+procs.size()+" rows");
String[] str = new String[procs.size()];
for (int i=0;i<procs.size();i++)
{
str[i] = ((Object[])procs.get(i))[0].toString();
}
return str;
}
else
{
ResultSet rs = null;
try
{
DatabaseMetaData dbmd = getDatabaseMetaData();
rs = dbmd.getProcedures(null, null, null);
List<Object[]> rows = getRows(rs, 0, null);
String result[] = new String[rows.size()];
for (int i=0;i<rows.size();i++)
{
Object[] row = (Object[])rows.get(i);
String procCatalog = rowMeta.getString(row, "PROCEDURE_CAT", null);
String procSchema = rowMeta.getString(row, "PROCEDURE_SCHEMA", null);
String procName = rowMeta.getString(row, "PROCEDURE_NAME", "");
String name = "";
if (procCatalog!=null) name+=procCatalog+".";
else if (procSchema!=null) name+=procSchema+".";
name+=procName;
result[i] = name;
}
return result;
}
catch(Exception e)
{
throw new KettleDatabaseException("Unable to get list of procedures from database meta-data: ", e);
}
finally
{
if (rs!=null) try { rs.close(); } catch(Exception e) {}
}
}
}
public boolean isAutoCommit()
{
return commitsize<=0;
}
/**
* @return Returns the databaseMeta.
*/
public DatabaseMeta getDatabaseMeta()
{
return databaseMeta;
}
/**
* Lock a tables in the database for write operations
* @param tableNames The tables to lock
* @throws KettleDatabaseException
*/
public void lockTables(String tableNames[]) throws KettleDatabaseException
{
if (Const.isEmpty(tableNames)) return;
// Quote table names too...
//
String[] quotedTableNames = new String[tableNames.length];
for (int i=0;i<tableNames.length;i++) quotedTableNames[i] = databaseMeta.quoteField(tableNames[i]);
// Get the SQL to lock the (quoted) tables
//
String sql = databaseMeta.getSQLLockTables(quotedTableNames);
if (sql!=null)
{
execStatements(sql);
}
}
/**
* Unlock certain tables in the database for write operations
* @param tableNames The tables to unlock
* @throws KettleDatabaseException
*/
public void unlockTables(String tableNames[]) throws KettleDatabaseException
{
if (Const.isEmpty(tableNames)) return;
// Quote table names too...
//
String[] quotedTableNames = new String[tableNames.length];
for (int i=0;i<tableNames.length;i++) quotedTableNames[i] = databaseMeta.quoteField(tableNames[i]);
// Get the SQL to unlock the (quoted) tables
//
String sql = databaseMeta.getSQLUnlockTables(quotedTableNames);
if (sql!=null)
{
execStatement(sql);
}
}
/**
* @return the opened
*/
public int getOpened()
{
return opened;
}
/**
* @param opened the opened to set
*/
public void setOpened(int opened)
{
this.opened = opened;
}
/**
* @return the connectionGroup
*/
public String getConnectionGroup()
{
return connectionGroup;
}
/**
* @param connectionGroup the connectionGroup to set
*/
public void setConnectionGroup(String connectionGroup)
{
this.connectionGroup = connectionGroup;
}
/**
* @return the partitionId
*/
public String getPartitionId()
{
return partitionId;
}
/**
* @param partitionId the partitionId to set
*/
public void setPartitionId(String partitionId)
{
this.partitionId = partitionId;
}
/**
* @return the copy
*/
public int getCopy()
{
return copy;
}
/**
* @param copy the copy to set
*/
public void setCopy(int copy)
{
this.copy = copy;
}
public void copyVariablesFrom(VariableSpace space)
{
variables.copyVariablesFrom(space);
}
public String environmentSubstitute(String aString)
{
return variables.environmentSubstitute(aString);
}
public String[] environmentSubstitute(String aString[])
{
return variables.environmentSubstitute(aString);
}
public VariableSpace getParentVariableSpace()
{
return variables.getParentVariableSpace();
}
public void setParentVariableSpace(VariableSpace parent)
{
variables.setParentVariableSpace(parent);
}
public String getVariable(String variableName, String defaultValue)
{
return variables.getVariable(variableName, defaultValue);
}
public String getVariable(String variableName)
{
return variables.getVariable(variableName);
}
public boolean getBooleanValueOfVariable(String variableName, boolean defaultValue) {
if (!Const.isEmpty(variableName))
{
String value = environmentSubstitute(variableName);
if (!Const.isEmpty(value))
{
return ValueMeta.convertStringToBoolean(value);
}
}
return defaultValue;
}
public void initializeVariablesFrom(VariableSpace parent)
{
variables.initializeVariablesFrom(parent);
}
public String[] listVariables()
{
return variables.listVariables();
}
public void setVariable(String variableName, String variableValue)
{
variables.setVariable(variableName, variableValue);
}
public void shareVariablesWith(VariableSpace space)
{
variables = space;
// Also share the variables with the meta data object
// Make sure it's not the databaseMeta object itself. We would get an infinite loop in that case.
//
if (space!=databaseMeta) databaseMeta.shareVariablesWith(space);
}
public void injectVariables(Map<String,String> prop)
{
variables.injectVariables(prop);
}
public RowMetaAndData callProcedure(String arg[], String argdir[], int argtype[],
String resultname, int resulttype) throws KettleDatabaseException {
RowMetaAndData ret;
try {
cstmt.execute();
ret = new RowMetaAndData();
int pos = 1;
if (resultname != null && resultname.length() != 0) {
ValueMeta vMeta = new ValueMeta(resultname, resulttype);
Object v =null;
switch (resulttype) {
case ValueMetaInterface.TYPE_BOOLEAN:
v=Boolean.valueOf(cstmt.getBoolean(pos));
break;
case ValueMetaInterface.TYPE_NUMBER:
v=new Double(cstmt.getDouble(pos));
break;
case ValueMetaInterface.TYPE_BIGNUMBER:
v=cstmt.getBigDecimal(pos);
break;
case ValueMetaInterface.TYPE_INTEGER:
v=Long.valueOf(cstmt.getLong(pos));
break;
case ValueMetaInterface.TYPE_STRING:
v=cstmt.getString(pos);
break;
case ValueMetaInterface.TYPE_DATE:
v=cstmt.getDate(pos);
break;
}
ret.addValue(vMeta, v);
pos++;
}
for (int i = 0; i < arg.length; i++) {
if (argdir[i].equalsIgnoreCase("OUT")
|| argdir[i].equalsIgnoreCase("INOUT")) {
ValueMeta vMeta = new ValueMeta(arg[i], argtype[i]);
Object v=null;
switch (argtype[i]) {
case ValueMetaInterface.TYPE_BOOLEAN:
v=Boolean.valueOf(cstmt.getBoolean(pos + i));
break;
case ValueMetaInterface.TYPE_NUMBER:
v=new Double(cstmt.getDouble(pos + i));
break;
case ValueMetaInterface.TYPE_BIGNUMBER:
v=cstmt.getBigDecimal(pos + i);
break;
case ValueMetaInterface.TYPE_INTEGER:
v=Long.valueOf(cstmt.getLong(pos + i));
break;
case ValueMetaInterface.TYPE_STRING:
v=cstmt.getString(pos + i);
break;
case ValueMetaInterface.TYPE_DATE:
v=cstmt.getTimestamp(pos + i);
break;
}
ret.addValue(vMeta, v);
}
}
return ret;
} catch (SQLException ex) {
throw new KettleDatabaseException("Unable to call procedure", ex);
}
}
}
|
PDI-673: Transformation wide rollback with unique connections does not work in specific conditions
git-svn-id: 51b39fcfd0d3a6ea7caa15377cad4af13b9d2664@6439 5fb7f6ec-07c1-534a-b4ca-9155e429e800
|
src/org/pentaho/di/core/database/Database.java
|
PDI-673: Transformation wide rollback with unique connections does not work in specific conditions
|
|
Java
|
apache-2.0
|
e3a2b54b4e32a9bf83c97b95e167e730fc4fe0b6
| 0
|
tsmgeek/traccar,jon-stumpf/traccar,duke2906/traccar,5of9/traccar,ninioe/traccar,tsmgeek/traccar,AnshulJain1985/Roadcast-Tracker,al3x1s/traccar,orcoliver/traccar,joseant/traccar-1,stalien/traccar_test,vipien/traccar,tananaev/traccar,renaudallard/traccar,ninioe/traccar,5of9/traccar,duke2906/traccar,stalien/traccar_test,jssenyange/traccar,orcoliver/traccar,jon-stumpf/traccar,al3x1s/traccar,AnshulJain1985/Roadcast-Tracker,tsmgeek/traccar,jssenyange/traccar,vipien/traccar,jssenyange/traccar,ninioe/traccar,jon-stumpf/traccar,tananaev/traccar,joseant/traccar-1,orcoliver/traccar,renaudallard/traccar,tananaev/traccar
|
/*
* Copyright 2012 - 2013 Anton Tananaev (anton.tananaev@gmail.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.traccar.model;
import java.io.File;
import java.io.StringReader;
import java.net.URL;
import java.net.URLClassLoader;
import java.sql.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.namespace.QName;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.traccar.helper.AdvancedConnection;
import org.traccar.helper.DriverDelegate;
import org.traccar.helper.Log;
import org.traccar.helper.NamedParameterStatement;
import org.xml.sax.InputSource;
/**
* Database abstraction class
*/
public class DatabaseDataManager implements DataManager {
public DatabaseDataManager(Properties properties) throws Exception {
initDatabase(properties);
}
/**
* Database statements
*/
private NamedParameterStatement queryGetDevices;
private NamedParameterStatement queryAddPosition;
private NamedParameterStatement queryUpdateLatestPosition;
/**
* Initialize database
*/
private void initDatabase(Properties properties) throws Exception {
// Load driver
String driver = properties.getProperty("database.driver");
if (driver != null) {
String driverFile = properties.getProperty("database.driverFile");
if (driverFile != null) {
URL url = new URL("jar:file:" + new File(driverFile).getAbsolutePath() + "!/");
URLClassLoader cl = new URLClassLoader(new URL[] { url });
Driver d = (Driver) Class.forName(driver, true, cl).newInstance();
DriverManager.registerDriver(new DriverDelegate(d));
} else {
Class.forName(driver);
}
}
// Refresh delay
String refreshDelay = properties.getProperty("database.refreshDelay");
if (refreshDelay != null) {
devicesRefreshDelay = Long.valueOf(refreshDelay) * 1000;
} else {
devicesRefreshDelay = new Long(300) * 1000; // Magic number
}
// Connect database
String url = properties.getProperty("database.url");
String user = properties.getProperty("database.user");
String password = properties.getProperty("database.password");
AdvancedConnection connection = new AdvancedConnection(url, user, password);
// Load statements from configuration
String query;
query = properties.getProperty("database.selectDevice");
if (query != null) {
queryGetDevices = new NamedParameterStatement(connection, query);
}
query = properties.getProperty("database.insertPosition");
if (query != null) {
queryAddPosition = new NamedParameterStatement(connection, query);
}
query = properties.getProperty("database.updateLatestPosition");
if (query != null) {
queryUpdateLatestPosition = new NamedParameterStatement(connection, query);
}
}
@Override
public synchronized List<Device> getDevices() throws SQLException {
List<Device> deviceList = new LinkedList<Device>();
if (queryGetDevices != null) {
queryGetDevices.prepare();
ResultSet result = queryGetDevices.executeQuery();
while (result.next()) {
Device device = new Device();
device.setId(result.getLong("id"));
device.setImei(result.getString("imei"));
deviceList.add(device);
}
}
return deviceList;
}
/**
* Devices cache
*/
private Map<String, Device> devices;
private Calendar devicesLastUpdate;
private Long devicesRefreshDelay;
@Override
public Device getDeviceByImei(String imei) throws SQLException {
if ((devices == null) || (Calendar.getInstance().getTimeInMillis() - devicesLastUpdate.getTimeInMillis() > devicesRefreshDelay)) {
List<Device> list = getDevices();
devices = new HashMap<String, Device>();
for (Device device: list) {
devices.put(device.getImei(), device);
}
devicesLastUpdate = Calendar.getInstance();
}
return devices.get(imei);
}
@Override
public synchronized Long addPosition(Position position) throws SQLException {
if (queryAddPosition != null) {
queryAddPosition.prepare(Statement.RETURN_GENERATED_KEYS);
queryAddPosition.setLong("device_id", position.getDeviceId());
queryAddPosition.setTimestamp("time", position.getTime());
queryAddPosition.setBoolean("valid", position.getValid());
queryAddPosition.setDouble("altitude", position.getAltitude());
queryAddPosition.setDouble("latitude", position.getLatitude());
queryAddPosition.setDouble("longitude", position.getLongitude());
queryAddPosition.setDouble("speed", position.getSpeed());
queryAddPosition.setDouble("course", position.getCourse());
queryAddPosition.setString("address", position.getAddress());
queryAddPosition.setString("extended_info", position.getExtendedInfo());
// DELME: Temporary compatibility support
XPath xpath = XPathFactory.newInstance().newXPath();
try {
InputSource source = new InputSource(new StringReader(position.getExtendedInfo()));
String index = xpath.evaluate("/info/index", source);
if (!index.isEmpty()) {
queryAddPosition.setLong("id", Long.valueOf(index));
} else {
queryAddPosition.setLong("id", null);
}
source = new InputSource(new StringReader(position.getExtendedInfo()));
String power = xpath.evaluate("/info/power", source);
if (!power.isEmpty()) {
queryAddPosition.setDouble("power", Double.valueOf(power));
} else {
queryAddPosition.setLong("power", null);
}
} catch (XPathExpressionException e) {
Log.warning("Error in XML: " + position.getExtendedInfo(), e);
queryAddPosition.setLong("id", null);
queryAddPosition.setLong("power", null);
}
queryAddPosition.executeUpdate();
ResultSet result = queryAddPosition.getGeneratedKeys();
if (result != null && result.next()) {
return result.getLong(1);
}
}
return null;
}
@Override
public void updateLatestPosition(Long deviceId, Long positionId) throws SQLException {
if (queryUpdateLatestPosition != null) {
queryUpdateLatestPosition.prepare();
queryUpdateLatestPosition.setLong("device_id", deviceId);
queryUpdateLatestPosition.setLong("id", positionId);
queryUpdateLatestPosition.executeUpdate();
}
}
}
|
src/org/traccar/model/DatabaseDataManager.java
|
/*
* Copyright 2012 - 2013 Anton Tananaev (anton.tananaev@gmail.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.traccar.model;
import java.io.File;
import java.io.StringReader;
import java.net.URL;
import java.net.URLClassLoader;
import java.sql.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.traccar.helper.AdvancedConnection;
import org.traccar.helper.DriverDelegate;
import org.traccar.helper.Log;
import org.traccar.helper.NamedParameterStatement;
import org.xml.sax.InputSource;
/**
* Database abstraction class
*/
public class DatabaseDataManager implements DataManager {
public DatabaseDataManager(Properties properties) throws Exception {
initDatabase(properties);
}
/**
* Database statements
*/
private NamedParameterStatement queryGetDevices;
private NamedParameterStatement queryAddPosition;
private NamedParameterStatement queryUpdateLatestPosition;
/**
* Initialize database
*/
private void initDatabase(Properties properties) throws Exception {
// Load driver
String driver = properties.getProperty("database.driver");
if (driver != null) {
String driverFile = properties.getProperty("database.driverFile");
if (driverFile != null) {
URL url = new URL("jar:file:" + new File(driverFile).getAbsolutePath() + "!/");
URLClassLoader cl = new URLClassLoader(new URL[] { url });
Driver d = (Driver) Class.forName(driver, true, cl).newInstance();
DriverManager.registerDriver(new DriverDelegate(d));
} else {
Class.forName(driver);
}
}
// Refresh delay
String refreshDelay = properties.getProperty("database.refreshDelay");
if (refreshDelay != null) {
devicesRefreshDelay = Long.valueOf(refreshDelay) * 1000;
} else {
devicesRefreshDelay = new Long(300) * 1000; // Magic number
}
// Connect database
String url = properties.getProperty("database.url");
String user = properties.getProperty("database.user");
String password = properties.getProperty("database.password");
AdvancedConnection connection = new AdvancedConnection(url, user, password);
// Load statements from configuration
String query;
query = properties.getProperty("database.selectDevice");
if (query != null) {
queryGetDevices = new NamedParameterStatement(connection, query);
}
query = properties.getProperty("database.insertPosition");
if (query != null) {
queryAddPosition = new NamedParameterStatement(connection, query);
}
query = properties.getProperty("database.updateLatestPosition");
if (query != null) {
queryUpdateLatestPosition = new NamedParameterStatement(connection, query);
}
}
@Override
public synchronized List<Device> getDevices() throws SQLException {
List<Device> deviceList = new LinkedList<Device>();
if (queryGetDevices != null) {
queryGetDevices.prepare();
ResultSet result = queryGetDevices.executeQuery();
while (result.next()) {
Device device = new Device();
device.setId(result.getLong("id"));
device.setImei(result.getString("imei"));
deviceList.add(device);
}
}
return deviceList;
}
/**
* Devices cache
*/
private Map<String, Device> devices;
private Calendar devicesLastUpdate;
private Long devicesRefreshDelay;
@Override
public Device getDeviceByImei(String imei) throws SQLException {
if ((devices == null) || (Calendar.getInstance().getTimeInMillis() - devicesLastUpdate.getTimeInMillis() > devicesRefreshDelay)) {
List<Device> list = getDevices();
devices = new HashMap<String, Device>();
for (Device device: list) {
devices.put(device.getImei(), device);
}
devicesLastUpdate = Calendar.getInstance();
}
return devices.get(imei);
}
@Override
public synchronized Long addPosition(Position position) throws SQLException {
if (queryAddPosition != null) {
queryAddPosition.prepare(Statement.RETURN_GENERATED_KEYS);
queryAddPosition.setLong("device_id", position.getDeviceId());
queryAddPosition.setTimestamp("time", position.getTime());
queryAddPosition.setBoolean("valid", position.getValid());
queryAddPosition.setDouble("altitude", position.getAltitude());
queryAddPosition.setDouble("latitude", position.getLatitude());
queryAddPosition.setDouble("longitude", position.getLongitude());
queryAddPosition.setDouble("speed", position.getSpeed());
queryAddPosition.setDouble("course", position.getCourse());
queryAddPosition.setString("address", position.getAddress());
queryAddPosition.setString("extended_info", position.getExtendedInfo());
// DELME: Temporary compatibility support
XPath xpath = XPathFactory.newInstance().newXPath();
InputSource source = new InputSource(new StringReader(position.getExtendedInfo()));
try {
String index = xpath.evaluate("/info/index", source);
if (!index.isEmpty()) {
queryAddPosition.setLong("id", Long.valueOf(index));
} else {
queryAddPosition.setLong("id", null);
}
String power = xpath.evaluate("/info/power", source);
if (!power.isEmpty()) {
queryAddPosition.setDouble("power", Double.valueOf(power));
} else {
queryAddPosition.setLong("power", null);
}
} catch (XPathExpressionException e) {
Log.warning("Error in XML: " + position.getExtendedInfo(), e);
queryAddPosition.setLong("id", null);
queryAddPosition.setLong("power", null);
}
queryAddPosition.executeUpdate();
ResultSet result = queryAddPosition.getGeneratedKeys();
if (result != null && result.next()) {
return result.getLong(1);
}
}
return null;
}
@Override
public void updateLatestPosition(Long deviceId, Long positionId) throws SQLException {
if (queryUpdateLatestPosition != null) {
queryUpdateLatestPosition.prepare();
queryUpdateLatestPosition.setLong("device_id", deviceId);
queryUpdateLatestPosition.setLong("id", positionId);
queryUpdateLatestPosition.executeUpdate();
}
}
}
|
Fix database data manager
|
src/org/traccar/model/DatabaseDataManager.java
|
Fix database data manager
|
|
Java
|
apache-2.0
|
abbe2752bf511f8abc5cb0c7ab68a051afc809c3
| 0
|
TestingForum/seleniumtestsframework,tarun3kumar/seleniumtestsframework,SaiVDivya04/Automation-Code-,tarun3kumar/seleniumtestsframework,SaiVDivya04/Automation-Code-,TestingForum/seleniumtestsframework,SaiVDivya04/Automation-Code-,tarun3kumar/seleniumtestsframework,TestingForum/seleniumtestsframework
|
/*
* Copyright 2015 www.seleniumtests.com
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.seleniumtests.webelements;
import org.openqa.selenium.By;
import com.seleniumtests.core.TestLogging;
public class TextFieldElement extends HtmlElement {
public TextFieldElement(final String label, final By by) {
super(label, by);
}
public void clear() {
TestLogging.logWebStep("Remove data From " + toHTML(), false);
findElement();
if (!element.getAttribute("type").equalsIgnoreCase("file")) {
element.clear();
}
}
public void sendKeys(final String keysToSend) {
TestLogging.logWebStep("Enter data: \"" + keysToSend + "\" on " + toHTML(), false);
findElement();
element.sendKeys(keysToSend);
}
public void type(final String keysToSend) {
sendKeys(keysToSend);
}
public void clearAndType(final String keysToSend) {
clear();
type(keysToSend);
}
}
|
src/main/java/com/seleniumtests/webelements/TextFieldElement.java
|
/*
* Copyright 2015 www.seleniumtests.com
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.seleniumtests.webelements;
import org.openqa.selenium.By;
import com.seleniumtests.core.TestLogging;
public class TextFieldElement extends HtmlElement {
public TextFieldElement(final String label, final By by) {
super(label, by);
}
public void clear() {
TestLogging.logWebStep(null, "Remove data From " + toHTML(), false);
findElement();
if (!element.getAttribute("type").equalsIgnoreCase("file")) {
element.clear();
}
}
public void sendKeys(final String keysToSend) {
TestLogging.logWebStep(null, "Enter data: \"" + keysToSend + "\" on " + toHTML(), false);
findElement();
element.sendKeys(keysToSend);
}
public void type(final String keysToSend) {
sendKeys(keysToSend);
}
public void clearAndType(final String keysToSend) {
clear();
type(keysToSend);
}
}
|
remove unused parameter
|
src/main/java/com/seleniumtests/webelements/TextFieldElement.java
|
remove unused parameter
|
|
Java
|
apache-2.0
|
8a5f2aab44857192ab162c265e551ff3142402ad
| 0
|
SerCeMan/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,fitermay/intellij-community,semonte/intellij-community,robovm/robovm-studio,MichaelNedzelsky/intellij-community,signed/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,kool79/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,ernestp/consulo,adedayo/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,signed/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,jagguli/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,da1z/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,da1z/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,signed/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,fitermay/intellij-community,signed/intellij-community,fnouama/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,apixandru/intellij-community,petteyg/intellij-community,izonder/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,signed/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,FHannes/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,ernestp/consulo,xfournet/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,diorcety/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,caot/intellij-community,ernestp/consulo,jagguli/intellij-community,holmes/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,signed/intellij-community,ibinti/intellij-community,retomerz/intellij-community,ernestp/consulo,adedayo/intellij-community,MER-GROUP/intellij-community,consulo/consulo,samthor/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,hurricup/intellij-community,samthor/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,slisson/intellij-community,diorcety/intellij-community,diorcety/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,caot/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,blademainer/intellij-community,fnouama/intellij-community,jagguli/intellij-community,ernestp/consulo,diorcety/intellij-community,samthor/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,robovm/robovm-studio,vladmm/intellij-community,Lekanich/intellij-community,caot/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,FHannes/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,samthor/intellij-community,ryano144/intellij-community,FHannes/intellij-community,slisson/intellij-community,holmes/intellij-community,ahb0327/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,fnouama/intellij-community,supersven/intellij-community,clumsy/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,allotria/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,dslomov/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,ivan-fedorov/intellij-community,ftomassetti/intellij-community,consulo/consulo,ahb0327/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,gnuhub/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,caot/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,clumsy/intellij-community,supersven/intellij-community,petteyg/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,signed/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,petteyg/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,vladmm/intellij-community,caot/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,izonder/intellij-community,kool79/intellij-community,retomerz/intellij-community,supersven/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,kool79/intellij-community,ibinti/intellij-community,amith01994/intellij-community,retomerz/intellij-community,xfournet/intellij-community,diorcety/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,caot/intellij-community,retomerz/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,kool79/intellij-community,semonte/intellij-community,hurricup/intellij-community,semonte/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,vladmm/intellij-community,retomerz/intellij-community,xfournet/intellij-community,supersven/intellij-community,amith01994/intellij-community,blademainer/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,consulo/consulo,idea4bsd/idea4bsd,diorcety/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,retomerz/intellij-community,hurricup/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,asedunov/intellij-community,kool79/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,slisson/intellij-community,holmes/intellij-community,robovm/robovm-studio,izonder/intellij-community,caot/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,ibinti/intellij-community,joewalnes/idea-community,alphafoobar/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,semonte/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,slisson/intellij-community,orekyuu/intellij-community,kool79/intellij-community,apixandru/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,jagguli/intellij-community,holmes/intellij-community,petteyg/intellij-community,ryano144/intellij-community,supersven/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,semonte/intellij-community,caot/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,asedunov/intellij-community,clumsy/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,da1z/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,xfournet/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,samthor/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,asedunov/intellij-community,adedayo/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,joewalnes/idea-community,izonder/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,jagguli/intellij-community,holmes/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,michaelgallacher/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,izonder/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,gnuhub/intellij-community,samthor/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,samthor/intellij-community,apixandru/intellij-community,robovm/robovm-studio,xfournet/intellij-community,allotria/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,consulo/consulo,caot/intellij-community,joewalnes/idea-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,dslomov/intellij-community,diorcety/intellij-community,ibinti/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,samthor/intellij-community,holmes/intellij-community,vladmm/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,adedayo/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,supersven/intellij-community,dslomov/intellij-community,joewalnes/idea-community,MER-GROUP/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,holmes/intellij-community,ibinti/intellij-community,adedayo/intellij-community,clumsy/intellij-community,consulo/consulo,allotria/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,signed/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,slisson/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,asedunov/intellij-community,amith01994/intellij-community,izonder/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,joewalnes/idea-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,apixandru/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,ryano144/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,FHannes/intellij-community,xfournet/intellij-community,blademainer/intellij-community,amith01994/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,wreckJ/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,clumsy/intellij-community,joewalnes/idea-community,kdwink/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,fnouama/intellij-community,jagguli/intellij-community,joewalnes/idea-community,suncycheng/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,ernestp/consulo,idea4bsd/idea4bsd,orekyuu/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,Lekanich/intellij-community,supersven/intellij-community,fnouama/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,slisson/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,signed/intellij-community,da1z/intellij-community,joewalnes/idea-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,holmes/intellij-community,hurricup/intellij-community,FHannes/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,signed/intellij-community,signed/intellij-community,caot/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,slisson/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,izonder/intellij-community,amith01994/intellij-community,adedayo/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,consulo/consulo,dslomov/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,blademainer/intellij-community,ibinti/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,supersven/intellij-community,nicolargo/intellij-community,da1z/intellij-community,orekyuu/intellij-community,allotria/intellij-community,asedunov/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,da1z/intellij-community,ahb0327/intellij-community,allotria/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,jagguli/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,supersven/intellij-community,fitermay/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,Distrotech/intellij-community,signed/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,joewalnes/idea-community,pwoodworth/intellij-community,kool79/intellij-community,diorcety/intellij-community,vladmm/intellij-community,caot/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,adedayo/intellij-community,semonte/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,allotria/intellij-community,nicolargo/intellij-community,supersven/intellij-community
|
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.completion;
import com.intellij.codeInsight.CodeInsightActionHandler;
import com.intellij.codeInsight.CodeInsightSettings;
import com.intellij.codeInsight.TailType;
import com.intellij.codeInsight.completion.impl.CompletionServiceImpl;
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer;
import com.intellij.codeInsight.editorActions.CompletionAutoPopupHandler;
import com.intellij.codeInsight.hint.EditorHintListener;
import com.intellij.codeInsight.hint.HintManager;
import com.intellij.codeInsight.lookup.*;
import com.intellij.codeInsight.lookup.impl.LookupImpl;
import com.intellij.featureStatistics.FeatureUsageTracker;
import com.intellij.injected.editor.EditorWindow;
import com.intellij.lang.Language;
import com.intellij.lang.injection.InjectedLanguageManager;
import com.intellij.openapi.application.ApplicationAdapter;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.application.ex.ApplicationEx;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.ScrollType;
import com.intellij.openapi.editor.ex.util.EditorUtil;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.util.ProgressWrapper;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.IndexNotReadyException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.impl.PsiFileEx;
import com.intellij.psi.impl.source.PostprocessReformattingAspect;
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil;
import com.intellij.psi.util.PsiUtilBase;
import com.intellij.reference.SoftReference;
import com.intellij.ui.LightweightHint;
import com.intellij.util.Consumer;
import com.intellij.util.ThreeState;
import com.intellij.util.concurrency.Semaphore;
import com.intellij.util.messages.MessageBusConnection;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
public class CodeCompletionHandlerBase implements CodeInsightActionHandler {
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.completion.CodeCompletionHandlerBase");
private final CompletionType myCompletionType;
final boolean invokedExplicitly;
final boolean autopopup;
public CodeCompletionHandlerBase(final CompletionType completionType) {
this(completionType, true, false);
}
public CodeCompletionHandlerBase(CompletionType completionType, boolean invokedExplicitly, boolean autopopup) {
myCompletionType = completionType;
this.invokedExplicitly = invokedExplicitly;
this.autopopup = autopopup;
}
public final void invoke(final Project project, final Editor editor) {
invoke(project, editor, PsiUtilBase.getPsiFileInEditor(editor, project));
}
public final void invoke(@NotNull final Project project, @NotNull final Editor editor, @NotNull PsiFile psiFile) {
if (editor.isViewer()) {
editor.getDocument().fireReadOnlyModificationAttempt();
return;
}
try {
invokeCompletion(project, editor, psiFile, autopopup ? 0 : 1);
}
catch (IndexNotReadyException e) {
DumbService.getInstance(project).showDumbModeNotification("Code completion is not available here while indices are being built");
}
}
public void invokeCompletion(final Project project, final Editor editor, final PsiFile psiFile, int time) {
if (CompletionAutoPopupHandler.ourTestingAutopopup) {
System.out.println("CodeCompletionHandlerBase.doComplete");
}
if (!ApplicationManager.getApplication().isUnitTestMode()) {
assert !ApplicationManager.getApplication().isWriteAccessAllowed() : "Completion should not be invoked inside write action";
}
final Document document = editor.getDocument();
if (!FileDocumentManager.getInstance().requestWriting(document, project)) {
return;
}
psiFile.putUserData(PsiFileEx.BATCH_REFERENCE_PROCESSING, Boolean.TRUE);
final CompletionProgressIndicator indicator = CompletionServiceImpl.getCompletionService().getCurrentCompletion();
if (indicator != null) {
boolean repeated = indicator.isRepeatedInvocation(myCompletionType, editor);
if (repeated && !indicator.isRunning() && (!isAutocompleteCommonPrefixOnInvocation() || indicator.fillInCommonPrefix(true))) {
return;
}
if (repeated) {
time = indicator.getParameters().getInvocationCount() + 1;
indicator.restorePrefix();
} else {
indicator.closeAndFinish(false);
}
}
if (time > 1) {
if (myCompletionType == CompletionType.CLASS_NAME) {
FeatureUsageTracker.getInstance().triggerFeatureUsed(CodeCompletionFeatures.SECOND_CLASS_NAME_COMPLETION);
}
else if (myCompletionType == CompletionType.BASIC) {
FeatureUsageTracker.getInstance().triggerFeatureUsed(CodeCompletionFeatures.SECOND_BASIC_COMPLETION);
}
}
final CompletionInitializationContext[] initializationContext = {null};
Runnable initCmd = new Runnable() {
@Override
public void run() {
Runnable runnable = new Runnable() {
public void run() {
final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
EditorUtil.fillVirtualSpaceUntilCaret(editor);
documentManager.commitAllDocuments();
assert editor.getDocument().getTextLength() == psiFile.getTextLength() : "unsuccessful commit";
final Ref<CompletionContributor> current = Ref.create(null);
initializationContext[0] = new CompletionInitializationContext(editor, psiFile, myCompletionType) {
CompletionContributor dummyIdentifierChanger;
@Override
public void setFileCopyPatcher(@NotNull FileCopyPatcher fileCopyPatcher) {
super.setFileCopyPatcher(fileCopyPatcher);
if (dummyIdentifierChanger != null) {
LOG.error("Changing the dummy identifier twice, already changed by " + dummyIdentifierChanger);
}
dummyIdentifierChanger = current.get();
}
};
for (final CompletionContributor contributor : CompletionContributor.forLanguage(initializationContext[0].getPositionLanguage())) {
if (DumbService.getInstance(project).isDumb() && !DumbService.isDumbAware(contributor)) {
continue;
}
current.set(contributor);
contributor.beforeCompletion(initializationContext[0]);
assert !documentManager.isUncommited(document) : "Contributor " + contributor + " left the document uncommitted";
}
}
};
ApplicationManager.getApplication().runWriteAction(runnable);
}
};
if (autopopup) {
CommandProcessor.getInstance().runUndoTransparentAction(initCmd);
int offset = editor.getCaretModel().getOffset();
assert offset > 0;
PsiElement elementAt = InjectedLanguageUtil.findInjectedElementNoCommit(psiFile, offset - 1);
if (elementAt == null) {
elementAt = psiFile.findElementAt(offset - 1);
}
Language language = elementAt != null ? PsiUtilBase.findLanguageFromElement(elementAt):psiFile.getLanguage();
for (CompletionConfidence confidence : CompletionConfidenceEP.forLanguage(language)) {
final ThreeState result = confidence.shouldSkipAutopopup(elementAt, psiFile, offset); // TODO: Peter Lazy API
if (result == ThreeState.YES) return;
if (result == ThreeState.NO) break;
}
} else {
CommandProcessor.getInstance().executeCommand(project, initCmd, null, null);
}
doComplete(time, initializationContext[0]);
}
private boolean shouldFocusLookup(CompletionParameters parameters) {
if (!autopopup) {
return true;
}
final Language language = PsiUtilBase.getLanguageAtOffset(parameters.getPosition().getContainingFile(), parameters.getOffset());
for (CompletionConfidence confidence : CompletionConfidenceEP.forLanguage(language)) {
final ThreeState result = confidence.shouldFocusLookup(parameters);
if (result != ThreeState.UNSURE) {
return result == ThreeState.YES;
}
}
return false;
}
@NotNull
private LookupImpl obtainLookup(Editor editor) {
LookupImpl existing = (LookupImpl)LookupManager.getActiveLookup(editor);
if (existing != null && existing.isCompletion()) {
existing.markReused();
if (!autopopup) {
existing.setFocused(true);
}
return existing;
}
LookupImpl lookup = (LookupImpl)LookupManager.getInstance(editor.getProject()).createLookup(editor, LookupElement.EMPTY_ARRAY, "", LookupArranger.DEFAULT);
if (editor.isOneLineMode()) {
lookup.setCancelOnClickOutside(true);
lookup.setCancelOnOtherWindowOpen(true);
lookup.setResizable(false);
lookup.setForceLightweightPopup(false);
}
lookup.setFocused(!autopopup);
return lookup;
}
private void doComplete(final int invocationCount, CompletionInitializationContext initContext) {
if (CompletionAutoPopupHandler.ourTestingAutopopup) {
System.out.println("CodeCompletionHandlerBase.doComplete");
}
final Editor editor = initContext.getEditor();
final CompletionParameters parameters = createCompletionParameters(invocationCount, initContext);
final LookupImpl lookup = obtainLookup(editor);
final Semaphore freezeSemaphore = new Semaphore();
freezeSemaphore.down();
final CompletionProgressIndicator indicator = new CompletionProgressIndicator(editor, parameters, this, freezeSemaphore,
initContext.getOffsetMap(), lookup);
final AtomicReference<LookupElement[]> data = startCompletionThread(parameters, indicator, initContext);
if (!invokedExplicitly && (!ApplicationManager.getApplication().isUnitTestMode() || CompletionAutoPopupHandler.ourTestingAutopopup)) {
indicator.notifyBackgrounded();
return;
}
if (freezeSemaphore.waitFor(2000)) {
final LookupElement[] allItems = data.get();
if (CompletionAutoPopupHandler.ourTestingAutopopup) {
System.out.println("allItems = " + allItems);
}
if (allItems != null) { // the completion is really finished, now we may auto-insert or show lookup
completionFinished(initContext.getStartOffset(), initContext.getSelectionEndOffset(), indicator, allItems);
return;
}
}
if (CompletionAutoPopupHandler.ourTestingAutopopup) {
System.out.println("backgrounded");
}
indicator.notifyBackgrounded();
indicator.showLookup();
}
private AtomicReference<LookupElement[]> startCompletionThread(final CompletionParameters parameters,
final CompletionProgressIndicator indicator,
final CompletionInitializationContext initContext) {
final ApplicationAdapter listener = new ApplicationAdapter() {
@Override
public void beforeWriteActionStart(Object action) {
indicator.cancelByWriteAction();
}
};
ApplicationManager.getApplication().addApplicationListener(listener);
final Semaphore startSemaphore = new Semaphore();
startSemaphore.down();
startSemaphore.down();
spawnProcess(ProgressWrapper.wrap(indicator), new Runnable() {
public void run() {
try {
ApplicationManager.getApplication().runReadAction(new Runnable() {
public void run() {
startSemaphore.up();
indicator.setFocusLookupWhenDone(autopopup && shouldFocusLookup(parameters));
indicator.duringCompletion(initContext);
}
});
}
finally {
indicator.duringCompletionPassed();
}
}
});
final AtomicReference<LookupElement[]> data = new AtomicReference<LookupElement[]>(null);
spawnProcess(indicator, new Runnable() {
public void run() {
try {
ApplicationManager.getApplication().runReadAction(new Runnable() {
public void run() {
try {
startSemaphore.up();
ProgressManager.checkCanceled();
final LookupElement[] result = CompletionService.getCompletionService().performCompletion(parameters, new Consumer<LookupElement>() {
public void consume(final LookupElement lookupElement) {
indicator.addItem(lookupElement);
}
});
indicator.ensureDuringCompletionPassed();
data.set(result);
}
finally {
ApplicationManager.getApplication().removeApplicationListener(listener);
}
}
});
}
catch (ProcessCanceledException ignored) {
}
}
});
startSemaphore.waitFor();
return data;
}
private static void spawnProcess(final ProgressIndicator indicator, final Runnable process) {
final Runnable computeRunnable = new Runnable() {
public void run() {
ProgressManager.getInstance().runProcess(process, indicator);
}
};
if (ApplicationManager.getApplication().isUnitTestMode()) {
computeRunnable.run();
} else {
ApplicationManager.getApplication().executeOnPooledThread(computeRunnable);
}
}
private CompletionParameters createCompletionParameters(int invocationCount, final CompletionInitializationContext initContext) {
final Ref<CompletionContext> ref = Ref.create(null);
CommandProcessor.getInstance().runUndoTransparentAction(new Runnable() {
@Override
public void run() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
ref.set(insertDummyIdentifier(initContext));
}
});
}
});
final CompletionContext newContext = ref.get();
final int offset = newContext.getStartOffset();
final PsiFile fileCopy = newContext.file;
final PsiElement insertedElement = newContext.file.findElementAt(newContext.getStartOffset());
if (insertedElement == null) {
throw new AssertionError("offset " + newContext.getStartOffset() + " at:\n text=\"" + fileCopy.getText() + "\"\n instance=" + fileCopy);
}
insertedElement.putUserData(CompletionContext.COMPLETION_CONTEXT_KEY, newContext);
LOG.assertTrue(fileCopy.findElementAt(offset) == insertedElement, "wrong offset");
final TextRange range = insertedElement.getTextRange();
if (!range.substring(fileCopy.getText()).equals(insertedElement.getText())) {
LOG.error("wrong text: copy='" + fileCopy.getText() + "'; element='" + insertedElement.getText() + "'");
}
return new CompletionParameters(insertedElement, fileCopy.getOriginalFile(), myCompletionType, offset, invocationCount);
}
private AutoCompletionDecision shouldAutoComplete(
final CompletionProgressIndicator indicator,
final LookupElement[] items) {
if (!invokedExplicitly) {
return AutoCompletionDecision.SHOW_LOOKUP;
}
final CompletionParameters parameters = indicator.getParameters();
final LookupElement item = items[0];
if (items.length == 1) {
final AutoCompletionPolicy policy = getAutocompletionPolicy(item);
if (policy == AutoCompletionPolicy.NEVER_AUTOCOMPLETE) return AutoCompletionDecision.SHOW_LOOKUP;
if (policy == AutoCompletionPolicy.ALWAYS_AUTOCOMPLETE) return AutoCompletionDecision.insertItem(item);
}
if (!isAutocompleteOnInvocation(parameters.getCompletionType())) {
return AutoCompletionDecision.SHOW_LOOKUP;
}
if (isInsideIdentifier(indicator.getOffsetMap())) {
return AutoCompletionDecision.SHOW_LOOKUP;
}
if (items.length == 1 && getAutocompletionPolicy(item) == AutoCompletionPolicy.GIVE_CHANCE_TO_OVERWRITE) {
return AutoCompletionDecision.insertItem(item);
}
for (final CompletionContributor contributor : CompletionContributor.forParameters(parameters)) {
final AutoCompletionDecision decision = contributor.handleAutoCompletionPossibility(new AutoCompletionContext(parameters, items, indicator.getOffsetMap()));
if (decision != null) {
return decision;
}
}
return AutoCompletionDecision.SHOW_LOOKUP;
}
@Nullable
private static AutoCompletionPolicy getAutocompletionPolicy(LookupElement element) {
final AutoCompletionPolicy policy = AutoCompletionPolicy.getPolicy(element);
if (policy != null) {
return policy;
}
final LookupItem item = element.as(LookupItem.class);
if (item != null) {
return item.getAutoCompletionPolicy();
}
return null;
}
private static boolean isInsideIdentifier(final OffsetMap offsetMap) {
return offsetMap.getOffset(CompletionInitializationContext.IDENTIFIER_END_OFFSET) != offsetMap.getOffset(CompletionInitializationContext.SELECTION_END_OFFSET);
}
protected void completionFinished(final int offset1,
final int offset2,
final CompletionProgressIndicator indicator,
final LookupElement[] items) {
if (CompletionAutoPopupHandler.ourTestingAutopopup) {
System.out.println("CodeCompletionHandlerBase.completionFinished");
System.out.println("items " + Arrays.asList(items));
}
if (items.length == 0) {
LookupManager.getInstance(indicator.getProject()).hideActiveLookup();
handleEmptyLookup(indicator.getProject(), indicator.getEditor(), indicator.getParameters(), indicator);
return;
}
final AutoCompletionDecision decision = shouldAutoComplete(indicator, items);
if (decision == AutoCompletionDecision.SHOW_LOOKUP) {
indicator.getLookup().setCalculating(false);
indicator.showLookup();
if (isAutocompleteCommonPrefixOnInvocation() && items.length > 1) {
indicator.fillInCommonPrefix(false);
}
}
else if (decision instanceof AutoCompletionDecision.InsertItem) {
final LookupElement item = ((AutoCompletionDecision.InsertItem)decision).getElement();
indicator.closeAndFinish(true);
indicator.rememberDocumentState();
indicator.getOffsetMap()
.addOffset(CompletionInitializationContext.START_OFFSET, (offset1 - item.getPrefixMatcher().getPrefix().length()));
handleSingleItem(offset2, indicator, items, item.getLookupString(), item);
// the insert handler may have started a live template with completion
if (CompletionService.getCompletionService().getCurrentCompletion() == null) {
indicator.liveAfterDeath(null);
}
}
}
protected static void handleSingleItem(final int offset2, final CompletionProgressIndicator context, final LookupElement[] items, final String _uniqueText, final LookupElement item) {
new WriteCommandAction(context.getProject()) {
protected void run(Result result) throws Throwable {
String uniqueText = _uniqueText;
if (item.getObject() instanceof DeferredUserLookupValue && item.as(LookupItem.class) != null) {
if (!((DeferredUserLookupValue)item.getObject()).handleUserSelection(item.as(LookupItem.class), context.getProject())) {
return;
}
uniqueText = item.getLookupString(); // text may be not ready yet
}
if (!StringUtil.startsWithIgnoreCase(uniqueText, item.getPrefixMatcher().getPrefix())) {
FeatureUsageTracker.getInstance().triggerFeatureUsed(CodeCompletionFeatures.EDITING_COMPLETION_CAMEL_HUMPS);
}
insertLookupString(offset2, uniqueText, context.getEditor(), context.getOffsetMap());
context.getEditor().getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
lookupItemSelected(context, item, Lookup.AUTO_INSERT_SELECT_CHAR, Arrays.asList(items));
}
}.execute();
}
private static void insertLookupString(final int currentOffset, final String newText, final Editor editor, final OffsetMap offsetMap) {
editor.getDocument().replaceString(offsetMap.getOffset(CompletionInitializationContext.START_OFFSET), currentOffset, newText);
editor.getCaretModel().moveToOffset(offsetMap.getOffset(CompletionInitializationContext.START_OFFSET) + newText.length());
editor.getSelectionModel().removeSelection();
}
protected static void selectLookupItem(final LookupElement item, final char completionChar, final CompletionProgressIndicator context, final List<LookupElement> items) {
final int caretOffset = context.getEditor().getCaretModel().getOffset();
context.getOffsetMap().addOffset(CompletionInitializationContext.SELECTION_END_OFFSET, caretOffset);
final int idEnd = context.getIdentifierEndOffset();
final int identifierEndOffset =
CompletionUtil.isOverwrite(item, completionChar) && context.getSelectionEndOffset() == idEnd ?
caretOffset :
Math.max(caretOffset, idEnd);
context.getOffsetMap().addOffset(CompletionInitializationContext.IDENTIFIER_END_OFFSET, identifierEndOffset);
lookupItemSelected(context, item, completionChar, items);
}
private CompletionContext insertDummyIdentifier(CompletionInitializationContext initContext) {
final PsiFile originalFile = initContext.getFile();
PsiFile fileCopy = createFileCopy(originalFile);
PsiFile hostFile = InjectedLanguageUtil.getTopLevelFile(fileCopy);
final InjectedLanguageManager injectedLanguageManager = InjectedLanguageManager.getInstance(hostFile.getProject());
int hostStartOffset = injectedLanguageManager.injectedToHost(fileCopy, initContext.getStartOffset());
final Editor hostEditor = InjectedLanguageUtil.getTopLevelEditor(initContext.getEditor());
final OffsetMap hostMap = new OffsetMap(hostEditor.getDocument());
final OffsetMap original = initContext.getOffsetMap();
for (final OffsetKey key : original.keySet()) {
hostMap.addOffset(key, injectedLanguageManager.injectedToHost(fileCopy, original.getOffset(key)));
}
Document document = fileCopy.getViewProvider().getDocument();
assert document != null : "no document";
initContext.getFileCopyPatcher().patchFileCopy(fileCopy, document, initContext.getOffsetMap());
final Document hostDocument = hostFile.getViewProvider().getDocument();
assert hostDocument != null : "no host document";
PsiDocumentManager.getInstance(hostFile.getProject()).commitDocument(hostDocument);
assert hostFile.isValid() : "file became invalid";
assert hostMap.getOffset(CompletionInitializationContext.START_OFFSET) < hostFile.getTextLength() : "startOffset outside the host file";
CompletionContext context;
PsiFile injected = InjectedLanguageUtil.findInjectedPsiNoCommit(hostFile, hostStartOffset);
if (injected != null) {
assert hostStartOffset >= injectedLanguageManager.injectedToHost(injected, 0) : "startOffset before injected";
assert hostStartOffset <= injectedLanguageManager.injectedToHost(injected, injected.getTextLength()) : "startOffset after injected";
EditorWindow injectedEditor = (EditorWindow)InjectedLanguageUtil.getEditorForInjectedLanguageNoCommit(hostEditor, hostFile, hostStartOffset);
assert injected == injectedEditor.getInjectedFile();
final OffsetMap map = new OffsetMap(injectedEditor.getDocument());
for (final OffsetKey key : hostMap.keySet()) {
map.addOffset(key, injectedEditor.logicalPositionToOffset(injectedEditor.hostToInjected(hostEditor.offsetToLogicalPosition(hostMap.getOffset(key)))));
}
context = new CompletionContext(initContext.getProject(), injectedEditor, injected, map);
assert hostStartOffset == injectedLanguageManager.injectedToHost(injected, context.getStartOffset()) : "inconsistent injected offset translation";
} else {
context = new CompletionContext(initContext.getProject(), hostEditor, hostFile, hostMap);
}
assert context.getStartOffset() < context.file.getTextLength() : "start outside the file";
assert context.getStartOffset() >= 0 : "start < 0";
return context;
}
private boolean isAutocompleteCommonPrefixOnInvocation() {
return invokedExplicitly && CodeInsightSettings.getInstance().AUTOCOMPLETE_COMMON_PREFIX;
}
protected void handleEmptyLookup(Project project, Editor editor, final CompletionParameters parameters, final CompletionProgressIndicator indicator) {
if (ApplicationManager.getApplication().isUnitTestMode()) return;
if (!invokedExplicitly) {
return;
}
for (final CompletionContributor contributor : CompletionContributor.forParameters(parameters)) {
final String text = contributor.handleEmptyLookup(parameters, editor);
if (StringUtil.isNotEmpty(text)) {
final EditorHintListener listener = new EditorHintListener() {
public void hintShown(final Project project, final LightweightHint hint, final int flags) {
indicator.liveAfterDeath(hint);
}
};
final MessageBusConnection connection = project.getMessageBus().connect();
connection.subscribe(EditorHintListener.TOPIC, listener);
HintManager.getInstance().showErrorHint(editor, text);
connection.disconnect();
break;
}
}
DaemonCodeAnalyzer codeAnalyzer = DaemonCodeAnalyzer.getInstance(project);
if (codeAnalyzer != null) {
codeAnalyzer.updateVisibleHighlighters(editor);
}
}
private static void lookupItemSelected(final CompletionProgressIndicator context, @NotNull final LookupElement item, final char completionChar,
final List<LookupElement> items) {
if (context.getHandler().autopopup) {
FeatureUsageTracker.getInstance().triggerFeatureUsed(CodeCompletionFeatures.EDITING_COMPLETION_BASIC);
}
final Editor editor = context.getEditor();
final PsiFile file = context.getParameters().getOriginalFile();
final InsertionContext context1 = new InsertionContext(context.getOffsetMap(), completionChar, items.toArray(new LookupElement[items.size()]), file, editor);
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
final int idEndOffset = context.getIdentifierEndOffset();
if (idEndOffset != context.getSelectionEndOffset() && CompletionUtil.isOverwrite(item, completionChar)) {
editor.getDocument().deleteString(context.getSelectionEndOffset(), idEndOffset);
}
PsiDocumentManager.getInstance(context.getProject()).commitAllDocuments();
item.handleInsert(context1);
PostprocessReformattingAspect.getInstance(context.getProject()).doPostponedFormatting();
if (context1.shouldAddCompletionChar() &&
completionChar != Lookup.AUTO_INSERT_SELECT_CHAR && completionChar != Lookup.REPLACE_SELECT_CHAR &&
completionChar != Lookup.NORMAL_SELECT_CHAR && completionChar != Lookup.COMPLETE_STATEMENT_SELECT_CHAR) {
TailType.insertChar(editor, context1.getTailOffset(), completionChar);
}
editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
}
});
final Runnable runnable = context1.getLaterRunnable();
if (runnable != null) {
final Runnable runnable1 = new Runnable() {
public void run() {
final Project project = context1.getProject();
if (project.isDisposed()) return;
runnable.run();
}
};
if (!ApplicationManager.getApplication().isUnitTestMode()) {
ApplicationManager.getApplication().invokeLater(runnable1);
} else {
runnable1.run();
}
}
}
public boolean startInWriteAction() {
return false;
}
public static final Key<SoftReference<PsiFile>> FILE_COPY_KEY = Key.create("CompletionFileCopy");
protected PsiFile createFileCopy(PsiFile file) {
final VirtualFile virtualFile = file.getVirtualFile();
if (file.isPhysical() && virtualFile != null && virtualFile.getFileSystem() == LocalFileSystem.getInstance()
// must not cache injected file copy, since it does not reflect changes in host document
&& !InjectedLanguageManager.getInstance(file.getProject()).isInjectedFragment(file)) {
final SoftReference<PsiFile> reference = file.getUserData(FILE_COPY_KEY);
if (reference != null) {
final PsiFile copy = reference.get();
if (copy != null && copy.isValid() && copy.getClass().equals(file.getClass())) {
final Document document = copy.getViewProvider().getDocument();
assert document != null;
final String oldDocumentText = document.getText();
final String oldCopyText = copy.getText();
final String newText = file.getText();
document.setText(newText);
try {
PsiDocumentManager.getInstance(copy.getProject()).commitDocument(document);
return copy;
}
catch (Throwable e) {
document.setText("");
if (((ApplicationEx)ApplicationManager.getApplication()).isInternal()) {
final StringBuilder sb = new StringBuilder();
boolean oldsAreSame = Comparing.equal(oldCopyText, oldDocumentText);
if (oldsAreSame) {
sb.append("oldCopyText == oldDocumentText");
}
else {
sb.append("oldCopyText != oldDocumentText");
sb.append("\n--- oldCopyText ------------------------------------------------\n").append(oldCopyText);
sb.append("\n--- oldDocumentText ------------------------------------------------\n").append(oldDocumentText);
}
if (Comparing.equal(oldCopyText, newText)) {
sb.insert(0, "newText == oldCopyText; ");
}
else if (!oldsAreSame && Comparing.equal(oldDocumentText, newText)) {
sb.insert(0, "newText == oldDocumentText; ");
}
else {
sb.insert(0, "newText != oldCopyText, oldDocumentText; ");
if (oldsAreSame) {
sb.append("\n--- oldCopyText ------------------------------------------------\n").append(oldCopyText);
}
sb.append("\n--- newText ------------------------------------------------\n").append(newText);
}
LOG.error(sb.toString(), e);
}
}
}
}
}
final PsiFile copy = (PsiFile)file.copy();
file.putUserData(FILE_COPY_KEY, new SoftReference<PsiFile>(copy));
return copy;
}
private static boolean isAutocompleteOnInvocation(final CompletionType type) {
final CodeInsightSettings settings = CodeInsightSettings.getInstance();
switch (type) {
case CLASS_NAME: return settings.AUTOCOMPLETE_ON_CLASS_NAME_COMPLETION;
case SMART: return settings.AUTOCOMPLETE_ON_SMART_TYPE_COMPLETION;
case BASIC:
default: return settings.AUTOCOMPLETE_ON_CODE_COMPLETION;
}
}
}
|
platform/lang-impl/src/com/intellij/codeInsight/completion/CodeCompletionHandlerBase.java
|
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.completion;
import com.intellij.codeInsight.CodeInsightActionHandler;
import com.intellij.codeInsight.CodeInsightSettings;
import com.intellij.codeInsight.TailType;
import com.intellij.codeInsight.completion.impl.CompletionServiceImpl;
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer;
import com.intellij.codeInsight.editorActions.CompletionAutoPopupHandler;
import com.intellij.codeInsight.hint.EditorHintListener;
import com.intellij.codeInsight.hint.HintManager;
import com.intellij.codeInsight.lookup.*;
import com.intellij.codeInsight.lookup.impl.LookupImpl;
import com.intellij.featureStatistics.FeatureUsageTracker;
import com.intellij.injected.editor.EditorWindow;
import com.intellij.lang.Language;
import com.intellij.lang.injection.InjectedLanguageManager;
import com.intellij.openapi.application.ApplicationAdapter;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.application.ex.ApplicationEx;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.ScrollType;
import com.intellij.openapi.editor.ex.util.EditorUtil;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.util.ProgressWrapper;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.IndexNotReadyException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.impl.PsiFileEx;
import com.intellij.psi.impl.source.PostprocessReformattingAspect;
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil;
import com.intellij.psi.util.PsiUtilBase;
import com.intellij.reference.SoftReference;
import com.intellij.ui.LightweightHint;
import com.intellij.util.Consumer;
import com.intellij.util.ThreeState;
import com.intellij.util.concurrency.Semaphore;
import com.intellij.util.messages.MessageBusConnection;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
public class CodeCompletionHandlerBase implements CodeInsightActionHandler {
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.completion.CodeCompletionHandlerBase");
private final CompletionType myCompletionType;
final boolean invokedExplicitly;
final boolean autopopup;
public CodeCompletionHandlerBase(final CompletionType completionType) {
this(completionType, true, false);
}
public CodeCompletionHandlerBase(CompletionType completionType, boolean invokedExplicitly, boolean autopopup) {
myCompletionType = completionType;
this.invokedExplicitly = invokedExplicitly;
this.autopopup = autopopup;
}
public final void invoke(final Project project, final Editor editor) {
invoke(project, editor, PsiUtilBase.getPsiFileInEditor(editor, project));
}
public final void invoke(@NotNull final Project project, @NotNull final Editor editor, @NotNull PsiFile psiFile) {
if (editor.isViewer()) {
editor.getDocument().fireReadOnlyModificationAttempt();
return;
}
try {
invokeCompletion(project, editor, psiFile, autopopup ? 0 : 1);
}
catch (IndexNotReadyException e) {
DumbService.getInstance(project).showDumbModeNotification("Code completion is not available here while indices are being built");
}
}
public void invokeCompletion(final Project project, final Editor editor, final PsiFile psiFile, int time) {
if (CompletionAutoPopupHandler.ourTestingAutopopup) {
System.out.println("CodeCompletionHandlerBase.doComplete");
}
if (!ApplicationManager.getApplication().isUnitTestMode()) {
assert !ApplicationManager.getApplication().isWriteAccessAllowed() : "Completion should not be invoked inside write action";
}
final Document document = editor.getDocument();
if (!FileDocumentManager.getInstance().requestWriting(document, project)) {
return;
}
psiFile.putUserData(PsiFileEx.BATCH_REFERENCE_PROCESSING, Boolean.TRUE);
final CompletionProgressIndicator indicator = CompletionServiceImpl.getCompletionService().getCurrentCompletion();
if (indicator != null) {
boolean repeated = indicator.isRepeatedInvocation(myCompletionType, editor);
if (repeated && !indicator.isRunning() && (!isAutocompleteCommonPrefixOnInvocation() || indicator.fillInCommonPrefix(true))) {
return;
}
if (repeated) {
time = indicator.getParameters().getInvocationCount() + 1;
indicator.restorePrefix();
} else {
indicator.closeAndFinish(false);
}
}
if (time > 1) {
if (myCompletionType == CompletionType.CLASS_NAME) {
FeatureUsageTracker.getInstance().triggerFeatureUsed(CodeCompletionFeatures.SECOND_CLASS_NAME_COMPLETION);
}
else if (myCompletionType == CompletionType.BASIC) {
FeatureUsageTracker.getInstance().triggerFeatureUsed(CodeCompletionFeatures.SECOND_BASIC_COMPLETION);
}
}
final CompletionInitializationContext[] initializationContext = {null};
Runnable initCmd = new Runnable() {
@Override
public void run() {
Runnable runnable = new Runnable() {
public void run() {
final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
EditorUtil.fillVirtualSpaceUntilCaret(editor);
documentManager.commitAllDocuments();
assert editor.getDocument().getTextLength() == psiFile.getTextLength() : "unsuccessful commit";
final Ref<CompletionContributor> current = Ref.create(null);
initializationContext[0] = new CompletionInitializationContext(editor, psiFile, myCompletionType) {
CompletionContributor dummyIdentifierChanger;
@Override
public void setFileCopyPatcher(@NotNull FileCopyPatcher fileCopyPatcher) {
super.setFileCopyPatcher(fileCopyPatcher);
if (dummyIdentifierChanger != null) {
LOG.error("Changing the dummy identifier twice, already changed by " + dummyIdentifierChanger);
}
dummyIdentifierChanger = current.get();
}
};
for (final CompletionContributor contributor : CompletionContributor.forLanguage(initializationContext[0].getPositionLanguage())) {
if (DumbService.getInstance(project).isDumb() && !DumbService.isDumbAware(contributor)) {
continue;
}
current.set(contributor);
contributor.beforeCompletion(initializationContext[0]);
assert !documentManager.isUncommited(document) : "Contributor " + contributor + " left the document uncommitted";
}
}
};
ApplicationManager.getApplication().runWriteAction(runnable);
}
};
if (autopopup) {
CommandProcessor.getInstance().runUndoTransparentAction(initCmd);
int offset = editor.getCaretModel().getOffset();
assert offset > 0;
PsiElement elementAt = InjectedLanguageUtil.findInjectedElementNoCommit(psiFile, offset - 1);
if (elementAt == null) {
elementAt = psiFile.findElementAt(offset - 1);
}
Language language = elementAt != null ? PsiUtilBase.findLanguageFromElement(elementAt):psiFile.getLanguage();
for (CompletionConfidence confidence : CompletionConfidenceEP.forLanguage(language)) {
final ThreeState result = confidence.shouldSkipAutopopup(elementAt, psiFile, offset); // TODO: Peter Lazy API
if (result == ThreeState.YES) return;
if (result == ThreeState.NO) break;
}
} else {
CommandProcessor.getInstance().executeCommand(project, initCmd, null, null);
}
doComplete(time, initializationContext[0]);
}
private boolean shouldFocusLookup(CompletionParameters parameters) {
if (!autopopup) {
return true;
}
final Language language = PsiUtilBase.getLanguageAtOffset(parameters.getPosition().getContainingFile(), parameters.getOffset());
for (CompletionConfidence confidence : CompletionConfidenceEP.forLanguage(language)) {
final ThreeState result = confidence.shouldFocusLookup(parameters);
if (result != ThreeState.UNSURE) {
return result == ThreeState.YES;
}
}
return false;
}
@NotNull
private LookupImpl obtainLookup(Editor editor) {
LookupImpl existing = (LookupImpl)LookupManager.getActiveLookup(editor);
if (existing != null && existing.isCompletion()) {
existing.markReused();
if (!autopopup) {
existing.setFocused(true);
}
return existing;
}
LookupImpl lookup = (LookupImpl)LookupManager.getInstance(editor.getProject()).createLookup(editor, LookupElement.EMPTY_ARRAY, "", LookupArranger.DEFAULT);
if (editor.isOneLineMode()) {
lookup.setCancelOnClickOutside(true);
lookup.setCancelOnOtherWindowOpen(true);
lookup.setResizable(false);
lookup.setForceLightweightPopup(false);
}
lookup.setFocused(!autopopup);
return lookup;
}
private void doComplete(final int invocationCount, CompletionInitializationContext initContext) {
if (CompletionAutoPopupHandler.ourTestingAutopopup) {
System.out.println("CodeCompletionHandlerBase.doComplete");
}
final Editor editor = initContext.getEditor();
final CompletionParameters parameters = createCompletionParameters(invocationCount, initContext);
final LookupImpl lookup = obtainLookup(editor);
final Semaphore freezeSemaphore = new Semaphore();
freezeSemaphore.down();
final CompletionProgressIndicator indicator = new CompletionProgressIndicator(editor, parameters, this, freezeSemaphore,
initContext.getOffsetMap(), lookup);
final AtomicReference<LookupElement[]> data = startCompletionThread(parameters, indicator, initContext);
if (!invokedExplicitly && (!ApplicationManager.getApplication().isUnitTestMode() || CompletionAutoPopupHandler.ourTestingAutopopup)) {
indicator.notifyBackgrounded();
return;
}
if (freezeSemaphore.waitFor(2000)) {
final LookupElement[] allItems = data.get();
if (CompletionAutoPopupHandler.ourTestingAutopopup) {
System.out.println("allItems = " + allItems);
}
if (allItems != null) { // the completion is really finished, now we may auto-insert or show lookup
completionFinished(initContext.getStartOffset(), initContext.getSelectionEndOffset(), indicator, allItems);
return;
}
}
if (CompletionAutoPopupHandler.ourTestingAutopopup) {
System.out.println("backgrounded");
}
indicator.notifyBackgrounded();
indicator.showLookup();
}
private AtomicReference<LookupElement[]> startCompletionThread(final CompletionParameters parameters,
final CompletionProgressIndicator indicator,
final CompletionInitializationContext initContext) {
final ApplicationAdapter listener = new ApplicationAdapter() {
@Override
public void beforeWriteActionStart(Object action) {
indicator.cancelByWriteAction();
}
};
ApplicationManager.getApplication().addApplicationListener(listener);
final Semaphore startSemaphore = new Semaphore();
startSemaphore.down();
startSemaphore.down();
spawnProcess(ProgressWrapper.wrap(indicator), new Runnable() {
public void run() {
try {
ApplicationManager.getApplication().runReadAction(new Runnable() {
public void run() {
startSemaphore.up();
indicator.setFocusLookupWhenDone(autopopup && shouldFocusLookup(parameters));
indicator.duringCompletion(initContext);
}
});
}
finally {
indicator.duringCompletionPassed();
}
}
});
final AtomicReference<LookupElement[]> data = new AtomicReference<LookupElement[]>(null);
spawnProcess(indicator, new Runnable() {
public void run() {
try {
ApplicationManager.getApplication().runReadAction(new Runnable() {
public void run() {
try {
startSemaphore.up();
ProgressManager.checkCanceled();
final LookupElement[] result = CompletionService.getCompletionService().performCompletion(parameters, new Consumer<LookupElement>() {
public void consume(final LookupElement lookupElement) {
indicator.addItem(lookupElement);
}
});
indicator.ensureDuringCompletionPassed();
data.set(result);
}
finally {
ApplicationManager.getApplication().removeApplicationListener(listener);
}
}
});
}
catch (ProcessCanceledException ignored) {
}
}
});
startSemaphore.waitFor();
return data;
}
private static void spawnProcess(final ProgressIndicator indicator, final Runnable process) {
final Runnable computeRunnable = new Runnable() {
public void run() {
ProgressManager.getInstance().runProcess(process, indicator);
}
};
if (ApplicationManager.getApplication().isUnitTestMode()) {
computeRunnable.run();
} else {
ApplicationManager.getApplication().executeOnPooledThread(computeRunnable);
}
}
private CompletionParameters createCompletionParameters(int invocationCount, final CompletionInitializationContext initContext) {
final Ref<CompletionContext> ref = Ref.create(null);
CommandProcessor.getInstance().runUndoTransparentAction(new Runnable() {
@Override
public void run() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
ref.set(insertDummyIdentifier(initContext));
}
});
}
});
final CompletionContext newContext = ref.get();
final int offset = newContext.getStartOffset();
final PsiFile fileCopy = newContext.file;
final PsiElement insertedElement = newContext.file.findElementAt(newContext.getStartOffset());
if (insertedElement == null) {
throw new AssertionError("offset " + newContext.getStartOffset() + " at:\n text=\"" + fileCopy.getText() + "\"\n instance=" + fileCopy);
}
insertedElement.putUserData(CompletionContext.COMPLETION_CONTEXT_KEY, newContext);
LOG.assertTrue(fileCopy.findElementAt(offset) == insertedElement, "wrong offset");
final TextRange range = insertedElement.getTextRange();
LOG.assertTrue(range.substring(fileCopy.getText()).equals(insertedElement.getText()), "wrong text");
return new CompletionParameters(insertedElement, fileCopy.getOriginalFile(), myCompletionType, offset, invocationCount);
}
private AutoCompletionDecision shouldAutoComplete(
final CompletionProgressIndicator indicator,
final LookupElement[] items) {
if (!invokedExplicitly) {
return AutoCompletionDecision.SHOW_LOOKUP;
}
final CompletionParameters parameters = indicator.getParameters();
final LookupElement item = items[0];
if (items.length == 1) {
final AutoCompletionPolicy policy = getAutocompletionPolicy(item);
if (policy == AutoCompletionPolicy.NEVER_AUTOCOMPLETE) return AutoCompletionDecision.SHOW_LOOKUP;
if (policy == AutoCompletionPolicy.ALWAYS_AUTOCOMPLETE) return AutoCompletionDecision.insertItem(item);
}
if (!isAutocompleteOnInvocation(parameters.getCompletionType())) {
return AutoCompletionDecision.SHOW_LOOKUP;
}
if (isInsideIdentifier(indicator.getOffsetMap())) {
return AutoCompletionDecision.SHOW_LOOKUP;
}
if (items.length == 1 && getAutocompletionPolicy(item) == AutoCompletionPolicy.GIVE_CHANCE_TO_OVERWRITE) {
return AutoCompletionDecision.insertItem(item);
}
for (final CompletionContributor contributor : CompletionContributor.forParameters(parameters)) {
final AutoCompletionDecision decision = contributor.handleAutoCompletionPossibility(new AutoCompletionContext(parameters, items, indicator.getOffsetMap()));
if (decision != null) {
return decision;
}
}
return AutoCompletionDecision.SHOW_LOOKUP;
}
@Nullable
private static AutoCompletionPolicy getAutocompletionPolicy(LookupElement element) {
final AutoCompletionPolicy policy = AutoCompletionPolicy.getPolicy(element);
if (policy != null) {
return policy;
}
final LookupItem item = element.as(LookupItem.class);
if (item != null) {
return item.getAutoCompletionPolicy();
}
return null;
}
private static boolean isInsideIdentifier(final OffsetMap offsetMap) {
return offsetMap.getOffset(CompletionInitializationContext.IDENTIFIER_END_OFFSET) != offsetMap.getOffset(CompletionInitializationContext.SELECTION_END_OFFSET);
}
protected void completionFinished(final int offset1,
final int offset2,
final CompletionProgressIndicator indicator,
final LookupElement[] items) {
if (CompletionAutoPopupHandler.ourTestingAutopopup) {
System.out.println("CodeCompletionHandlerBase.completionFinished");
System.out.println("items " + Arrays.asList(items));
}
if (items.length == 0) {
LookupManager.getInstance(indicator.getProject()).hideActiveLookup();
handleEmptyLookup(indicator.getProject(), indicator.getEditor(), indicator.getParameters(), indicator);
return;
}
final AutoCompletionDecision decision = shouldAutoComplete(indicator, items);
if (decision == AutoCompletionDecision.SHOW_LOOKUP) {
indicator.getLookup().setCalculating(false);
indicator.showLookup();
if (isAutocompleteCommonPrefixOnInvocation() && items.length > 1) {
indicator.fillInCommonPrefix(false);
}
}
else if (decision instanceof AutoCompletionDecision.InsertItem) {
final LookupElement item = ((AutoCompletionDecision.InsertItem)decision).getElement();
indicator.closeAndFinish(true);
indicator.rememberDocumentState();
indicator.getOffsetMap()
.addOffset(CompletionInitializationContext.START_OFFSET, (offset1 - item.getPrefixMatcher().getPrefix().length()));
handleSingleItem(offset2, indicator, items, item.getLookupString(), item);
// the insert handler may have started a live template with completion
if (CompletionService.getCompletionService().getCurrentCompletion() == null) {
indicator.liveAfterDeath(null);
}
}
}
protected static void handleSingleItem(final int offset2, final CompletionProgressIndicator context, final LookupElement[] items, final String _uniqueText, final LookupElement item) {
new WriteCommandAction(context.getProject()) {
protected void run(Result result) throws Throwable {
String uniqueText = _uniqueText;
if (item.getObject() instanceof DeferredUserLookupValue && item.as(LookupItem.class) != null) {
if (!((DeferredUserLookupValue)item.getObject()).handleUserSelection(item.as(LookupItem.class), context.getProject())) {
return;
}
uniqueText = item.getLookupString(); // text may be not ready yet
}
if (!StringUtil.startsWithIgnoreCase(uniqueText, item.getPrefixMatcher().getPrefix())) {
FeatureUsageTracker.getInstance().triggerFeatureUsed(CodeCompletionFeatures.EDITING_COMPLETION_CAMEL_HUMPS);
}
insertLookupString(offset2, uniqueText, context.getEditor(), context.getOffsetMap());
context.getEditor().getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
lookupItemSelected(context, item, Lookup.AUTO_INSERT_SELECT_CHAR, Arrays.asList(items));
}
}.execute();
}
private static void insertLookupString(final int currentOffset, final String newText, final Editor editor, final OffsetMap offsetMap) {
editor.getDocument().replaceString(offsetMap.getOffset(CompletionInitializationContext.START_OFFSET), currentOffset, newText);
editor.getCaretModel().moveToOffset(offsetMap.getOffset(CompletionInitializationContext.START_OFFSET) + newText.length());
editor.getSelectionModel().removeSelection();
}
protected static void selectLookupItem(final LookupElement item, final char completionChar, final CompletionProgressIndicator context, final List<LookupElement> items) {
final int caretOffset = context.getEditor().getCaretModel().getOffset();
context.getOffsetMap().addOffset(CompletionInitializationContext.SELECTION_END_OFFSET, caretOffset);
final int idEnd = context.getIdentifierEndOffset();
final int identifierEndOffset =
CompletionUtil.isOverwrite(item, completionChar) && context.getSelectionEndOffset() == idEnd ?
caretOffset :
Math.max(caretOffset, idEnd);
context.getOffsetMap().addOffset(CompletionInitializationContext.IDENTIFIER_END_OFFSET, identifierEndOffset);
lookupItemSelected(context, item, completionChar, items);
}
private CompletionContext insertDummyIdentifier(CompletionInitializationContext initContext) {
final PsiFile originalFile = initContext.getFile();
PsiFile fileCopy = createFileCopy(originalFile);
PsiFile hostFile = InjectedLanguageUtil.getTopLevelFile(fileCopy);
final InjectedLanguageManager injectedLanguageManager = InjectedLanguageManager.getInstance(hostFile.getProject());
int hostStartOffset = injectedLanguageManager.injectedToHost(fileCopy, initContext.getStartOffset());
final Editor hostEditor = InjectedLanguageUtil.getTopLevelEditor(initContext.getEditor());
final OffsetMap hostMap = new OffsetMap(hostEditor.getDocument());
final OffsetMap original = initContext.getOffsetMap();
for (final OffsetKey key : original.keySet()) {
hostMap.addOffset(key, injectedLanguageManager.injectedToHost(fileCopy, original.getOffset(key)));
}
Document document = fileCopy.getViewProvider().getDocument();
assert document != null : "no document";
initContext.getFileCopyPatcher().patchFileCopy(fileCopy, document, initContext.getOffsetMap());
final Document hostDocument = hostFile.getViewProvider().getDocument();
assert hostDocument != null : "no host document";
PsiDocumentManager.getInstance(hostFile.getProject()).commitDocument(hostDocument);
assert hostFile.isValid() : "file became invalid";
assert hostMap.getOffset(CompletionInitializationContext.START_OFFSET) < hostFile.getTextLength() : "startOffset outside the host file";
CompletionContext context;
PsiFile injected = InjectedLanguageUtil.findInjectedPsiNoCommit(hostFile, hostStartOffset);
if (injected != null) {
assert hostStartOffset >= injectedLanguageManager.injectedToHost(injected, 0) : "startOffset before injected";
assert hostStartOffset <= injectedLanguageManager.injectedToHost(injected, injected.getTextLength()) : "startOffset after injected";
EditorWindow injectedEditor = (EditorWindow)InjectedLanguageUtil.getEditorForInjectedLanguageNoCommit(hostEditor, hostFile, hostStartOffset);
assert injected == injectedEditor.getInjectedFile();
final OffsetMap map = new OffsetMap(injectedEditor.getDocument());
for (final OffsetKey key : hostMap.keySet()) {
map.addOffset(key, injectedEditor.logicalPositionToOffset(injectedEditor.hostToInjected(hostEditor.offsetToLogicalPosition(hostMap.getOffset(key)))));
}
context = new CompletionContext(initContext.getProject(), injectedEditor, injected, map);
assert hostStartOffset == injectedLanguageManager.injectedToHost(injected, context.getStartOffset()) : "inconsistent injected offset translation";
} else {
context = new CompletionContext(initContext.getProject(), hostEditor, hostFile, hostMap);
}
assert context.getStartOffset() < context.file.getTextLength() : "start outside the file";
assert context.getStartOffset() >= 0 : "start < 0";
return context;
}
private boolean isAutocompleteCommonPrefixOnInvocation() {
return invokedExplicitly && CodeInsightSettings.getInstance().AUTOCOMPLETE_COMMON_PREFIX;
}
protected void handleEmptyLookup(Project project, Editor editor, final CompletionParameters parameters, final CompletionProgressIndicator indicator) {
if (ApplicationManager.getApplication().isUnitTestMode()) return;
if (!invokedExplicitly) {
return;
}
for (final CompletionContributor contributor : CompletionContributor.forParameters(parameters)) {
final String text = contributor.handleEmptyLookup(parameters, editor);
if (StringUtil.isNotEmpty(text)) {
final EditorHintListener listener = new EditorHintListener() {
public void hintShown(final Project project, final LightweightHint hint, final int flags) {
indicator.liveAfterDeath(hint);
}
};
final MessageBusConnection connection = project.getMessageBus().connect();
connection.subscribe(EditorHintListener.TOPIC, listener);
HintManager.getInstance().showErrorHint(editor, text);
connection.disconnect();
break;
}
}
DaemonCodeAnalyzer codeAnalyzer = DaemonCodeAnalyzer.getInstance(project);
if (codeAnalyzer != null) {
codeAnalyzer.updateVisibleHighlighters(editor);
}
}
private static void lookupItemSelected(final CompletionProgressIndicator context, @NotNull final LookupElement item, final char completionChar,
final List<LookupElement> items) {
if (context.getHandler().autopopup) {
FeatureUsageTracker.getInstance().triggerFeatureUsed(CodeCompletionFeatures.EDITING_COMPLETION_BASIC);
}
final Editor editor = context.getEditor();
final PsiFile file = context.getParameters().getOriginalFile();
final InsertionContext context1 = new InsertionContext(context.getOffsetMap(), completionChar, items.toArray(new LookupElement[items.size()]), file, editor);
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
final int idEndOffset = context.getIdentifierEndOffset();
if (idEndOffset != context.getSelectionEndOffset() && CompletionUtil.isOverwrite(item, completionChar)) {
editor.getDocument().deleteString(context.getSelectionEndOffset(), idEndOffset);
}
PsiDocumentManager.getInstance(context.getProject()).commitAllDocuments();
item.handleInsert(context1);
PostprocessReformattingAspect.getInstance(context.getProject()).doPostponedFormatting();
if (context1.shouldAddCompletionChar() &&
completionChar != Lookup.AUTO_INSERT_SELECT_CHAR && completionChar != Lookup.REPLACE_SELECT_CHAR &&
completionChar != Lookup.NORMAL_SELECT_CHAR && completionChar != Lookup.COMPLETE_STATEMENT_SELECT_CHAR) {
TailType.insertChar(editor, context1.getTailOffset(), completionChar);
}
editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
}
});
final Runnable runnable = context1.getLaterRunnable();
if (runnable != null) {
final Runnable runnable1 = new Runnable() {
public void run() {
final Project project = context1.getProject();
if (project.isDisposed()) return;
runnable.run();
}
};
if (!ApplicationManager.getApplication().isUnitTestMode()) {
ApplicationManager.getApplication().invokeLater(runnable1);
} else {
runnable1.run();
}
}
}
public boolean startInWriteAction() {
return false;
}
public static final Key<SoftReference<PsiFile>> FILE_COPY_KEY = Key.create("CompletionFileCopy");
protected PsiFile createFileCopy(PsiFile file) {
final VirtualFile virtualFile = file.getVirtualFile();
if (file.isPhysical() && virtualFile != null && virtualFile.getFileSystem() == LocalFileSystem.getInstance()
// must not cache injected file copy, since it does not reflect changes in host document
&& !InjectedLanguageManager.getInstance(file.getProject()).isInjectedFragment(file)) {
final SoftReference<PsiFile> reference = file.getUserData(FILE_COPY_KEY);
if (reference != null) {
final PsiFile copy = reference.get();
if (copy != null && copy.isValid() && copy.getClass().equals(file.getClass())) {
final Document document = copy.getViewProvider().getDocument();
assert document != null;
final String oldDocumentText = document.getText();
final String oldCopyText = copy.getText();
final String newText = file.getText();
document.setText(newText);
try {
PsiDocumentManager.getInstance(copy.getProject()).commitDocument(document);
return copy;
}
catch (Throwable e) {
document.setText("");
if (((ApplicationEx)ApplicationManager.getApplication()).isInternal()) {
final StringBuilder sb = new StringBuilder();
boolean oldsAreSame = Comparing.equal(oldCopyText, oldDocumentText);
if (oldsAreSame) {
sb.append("oldCopyText == oldDocumentText");
}
else {
sb.append("oldCopyText != oldDocumentText");
sb.append("\n--- oldCopyText ------------------------------------------------\n").append(oldCopyText);
sb.append("\n--- oldDocumentText ------------------------------------------------\n").append(oldDocumentText);
}
if (Comparing.equal(oldCopyText, newText)) {
sb.insert(0, "newText == oldCopyText; ");
}
else if (!oldsAreSame && Comparing.equal(oldDocumentText, newText)) {
sb.insert(0, "newText == oldDocumentText; ");
}
else {
sb.insert(0, "newText != oldCopyText, oldDocumentText; ");
if (oldsAreSame) {
sb.append("\n--- oldCopyText ------------------------------------------------\n").append(oldCopyText);
}
sb.append("\n--- newText ------------------------------------------------\n").append(newText);
}
LOG.error(sb.toString(), e);
}
}
}
}
}
final PsiFile copy = (PsiFile)file.copy();
file.putUserData(FILE_COPY_KEY, new SoftReference<PsiFile>(copy));
return copy;
}
private static boolean isAutocompleteOnInvocation(final CompletionType type) {
final CodeInsightSettings settings = CodeInsightSettings.getInstance();
switch (type) {
case CLASS_NAME: return settings.AUTOCOMPLETE_ON_CLASS_NAME_COMPLETION;
case SMART: return settings.AUTOCOMPLETE_ON_SMART_TYPE_COMPLETION;
case BASIC:
default: return settings.AUTOCOMPLETE_ON_CODE_COMPLETION;
}
}
}
|
diagnostics expanded for EA-23759
|
platform/lang-impl/src/com/intellij/codeInsight/completion/CodeCompletionHandlerBase.java
|
diagnostics expanded for EA-23759
|
|
Java
|
apache-2.0
|
569a8ba4be412658e836933861719e16831e0821
| 0
|
ryano144/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,asedunov/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,signed/intellij-community,nicolargo/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,SerCeMan/intellij-community,adedayo/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,kdwink/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,ftomassetti/intellij-community,robovm/robovm-studio,retomerz/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,supersven/intellij-community,da1z/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,allotria/intellij-community,Distrotech/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,nicolargo/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,clumsy/intellij-community,kool79/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,petteyg/intellij-community,amith01994/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,semonte/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,slisson/intellij-community,hurricup/intellij-community,signed/intellij-community,supersven/intellij-community,signed/intellij-community,supersven/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,semonte/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,da1z/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,adedayo/intellij-community,FHannes/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,semonte/intellij-community,slisson/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,semonte/intellij-community,izonder/intellij-community,supersven/intellij-community,allotria/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,supersven/intellij-community,suncycheng/intellij-community,akosyakov/intellij-community,caot/intellij-community,FHannes/intellij-community,kool79/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,retomerz/intellij-community,fnouama/intellij-community,adedayo/intellij-community,xfournet/intellij-community,slisson/intellij-community,fnouama/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,petteyg/intellij-community,retomerz/intellij-community,semonte/intellij-community,amith01994/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,caot/intellij-community,xfournet/intellij-community,jagguli/intellij-community,izonder/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,samthor/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,apixandru/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,izonder/intellij-community,semonte/intellij-community,signed/intellij-community,ahb0327/intellij-community,kool79/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,da1z/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,da1z/intellij-community,amith01994/intellij-community,samthor/intellij-community,caot/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,supersven/intellij-community,fnouama/intellij-community,da1z/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,apixandru/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,izonder/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,kool79/intellij-community,apixandru/intellij-community,asedunov/intellij-community,amith01994/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,holmes/intellij-community,blademainer/intellij-community,ryano144/intellij-community,ryano144/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,signed/intellij-community,kool79/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,robovm/robovm-studio,ibinti/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,izonder/intellij-community,xfournet/intellij-community,fitermay/intellij-community,ibinti/intellij-community,FHannes/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,signed/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,hurricup/intellij-community,allotria/intellij-community,asedunov/intellij-community,FHannes/intellij-community,diorcety/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,samthor/intellij-community,hurricup/intellij-community,supersven/intellij-community,apixandru/intellij-community,ryano144/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,asedunov/intellij-community,vladmm/intellij-community,clumsy/intellij-community,petteyg/intellij-community,ibinti/intellij-community,xfournet/intellij-community,vladmm/intellij-community,caot/intellij-community,asedunov/intellij-community,kool79/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,kdwink/intellij-community,suncycheng/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,robovm/robovm-studio,blademainer/intellij-community,samthor/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,petteyg/intellij-community,vladmm/intellij-community,izonder/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,apixandru/intellij-community,caot/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,kool79/intellij-community,clumsy/intellij-community,adedayo/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,blademainer/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,izonder/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,slisson/intellij-community,robovm/robovm-studio,fitermay/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,akosyakov/intellij-community,allotria/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,retomerz/intellij-community,izonder/intellij-community,Lekanich/intellij-community,samthor/intellij-community,vladmm/intellij-community,fnouama/intellij-community,fitermay/intellij-community,dslomov/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,amith01994/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,da1z/intellij-community,da1z/intellij-community,fitermay/intellij-community,signed/intellij-community,diorcety/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,holmes/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,signed/intellij-community,slisson/intellij-community,robovm/robovm-studio,holmes/intellij-community,samthor/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,allotria/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,robovm/robovm-studio,petteyg/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,kool79/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,signed/intellij-community,da1z/intellij-community,caot/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,caot/intellij-community,asedunov/intellij-community,supersven/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,hurricup/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,izonder/intellij-community,blademainer/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,ibinti/intellij-community,izonder/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,semonte/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,samthor/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,signed/intellij-community,retomerz/intellij-community,vladmm/intellij-community,blademainer/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,caot/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,semonte/intellij-community,wreckJ/intellij-community,samthor/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,semonte/intellij-community,gnuhub/intellij-community,holmes/intellij-community,xfournet/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,retomerz/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,samthor/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,slisson/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community
|
/*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python;
import com.intellij.openapi.projectRoots.ProjectJdkTable;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.projectRoots.SdkModificator;
import com.intellij.openapi.projectRoots.SdkType;
import com.intellij.openapi.projectRoots.impl.ProjectJdkImpl;
import com.intellij.openapi.roots.OrderRootType;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.psi.stubs.StubUpdatingIndex;
import com.intellij.util.indexing.FileBasedIndex;
import com.jetbrains.python.codeInsight.userSkeletons.PyUserSkeletonsUtil;
import com.jetbrains.python.psi.stubs.PyModuleNameIndex;
import com.jetbrains.python.sdk.PythonSdkType;
import org.jetbrains.annotations.NonNls;
import java.io.File;
import java.util.List;
/**
* @author yole
*/
public class PythonMockSdk {
@NonNls private static final String MOCK_SDK_NAME = "Mock Python SDK";
private PythonMockSdk() {
}
public static Sdk findOrCreate(String version) {
final List<Sdk> sdkList = ProjectJdkTable.getInstance().getSdksOfType(PythonSdkType.getInstance());
for (Sdk sdk : sdkList) {
if (sdk.getName().equals(MOCK_SDK_NAME + " " + version)) {
return sdk;
}
}
return create(version);
}
public static Sdk create(final String version) {
final String mock_path = PythonTestUtil.getTestDataPath() + "/MockSdk" + version + "/";
String sdkHome = new File(mock_path, "bin/python"+version).getPath();
SdkType sdkType = PythonSdkType.getInstance();
final Sdk sdk = new ProjectJdkImpl(MOCK_SDK_NAME + " " + version, sdkType) {
@Override
public String getVersionString() {
return "Python " + version + " Mock SDK";
}
};
final SdkModificator sdkModificator = sdk.getSdkModificator();
sdkModificator.setHomePath(sdkHome);
File libPath = new File(mock_path, "Lib");
if (libPath.exists()) {
sdkModificator.addRoot(LocalFileSystem.getInstance().refreshAndFindFileByIoFile(libPath), OrderRootType.CLASSES);
}
PyUserSkeletonsUtil.addUserSkeletonsRoot(sdkModificator);
String mock_stubs_path = mock_path + PythonSdkType.SKELETON_DIR_NAME;
sdkModificator.addRoot(LocalFileSystem.getInstance().refreshAndFindFileByPath(mock_stubs_path), PythonSdkType.BUILTIN_ROOT_TYPE);
sdkModificator.commitChanges();
final FileBasedIndex index = FileBasedIndex.getInstance();
index.requestRebuild(StubUpdatingIndex.INDEX_ID);
index.requestRebuild(PyModuleNameIndex.NAME);
return sdk;
}
}
|
python/testSrc/com/jetbrains/python/PythonMockSdk.java
|
/*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python;
import com.intellij.openapi.projectRoots.ProjectJdkTable;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.projectRoots.SdkModificator;
import com.intellij.openapi.projectRoots.SdkType;
import com.intellij.openapi.projectRoots.impl.ProjectJdkImpl;
import com.intellij.openapi.roots.OrderRootType;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.psi.stubs.StubUpdatingIndex;
import com.intellij.util.indexing.FileBasedIndex;
import com.jetbrains.python.codeInsight.userSkeletons.PyUserSkeletonsUtil;
import com.jetbrains.python.sdk.PythonSdkType;
import org.jetbrains.annotations.NonNls;
import java.io.File;
import java.util.List;
/**
* @author yole
*/
public class PythonMockSdk {
@NonNls private static final String MOCK_SDK_NAME = "Mock Python SDK";
private PythonMockSdk() {
}
public static Sdk findOrCreate(String version) {
final List<Sdk> sdkList = ProjectJdkTable.getInstance().getSdksOfType(PythonSdkType.getInstance());
for (Sdk sdk : sdkList) {
if (sdk.getName().equals(MOCK_SDK_NAME + " " + version)) {
return sdk;
}
}
return create(version);
}
public static Sdk create(final String version) {
final String mock_path = PythonTestUtil.getTestDataPath() + "/MockSdk" + version + "/";
String sdkHome = new File(mock_path, "bin/python"+version).getPath();
SdkType sdkType = PythonSdkType.getInstance();
final Sdk sdk = new ProjectJdkImpl(MOCK_SDK_NAME + " " + version, sdkType) {
@Override
public String getVersionString() {
return "Python " + version + " Mock SDK";
}
};
final SdkModificator sdkModificator = sdk.getSdkModificator();
sdkModificator.setHomePath(sdkHome);
File libPath = new File(mock_path, "Lib");
if (libPath.exists()) {
sdkModificator.addRoot(LocalFileSystem.getInstance().refreshAndFindFileByIoFile(libPath), OrderRootType.CLASSES);
}
PyUserSkeletonsUtil.addUserSkeletonsRoot(sdkModificator);
String mock_stubs_path = mock_path + PythonSdkType.SKELETON_DIR_NAME;
sdkModificator.addRoot(LocalFileSystem.getInstance().refreshAndFindFileByPath(mock_stubs_path), PythonSdkType.BUILTIN_ROOT_TYPE);
sdkModificator.commitChanges();
FileBasedIndex.getInstance().requestRebuild(StubUpdatingIndex.INDEX_ID);
return sdk;
}
}
|
Reset module name index in mock SDK setup for reproducible test results
|
python/testSrc/com/jetbrains/python/PythonMockSdk.java
|
Reset module name index in mock SDK setup for reproducible test results
|
|
Java
|
apache-2.0
|
23443afd6a928c72351206bb03f9e971f6bb20df
| 0
|
neo4j-contrib/neo4j-apoc-procedures,neo4j-contrib/neo4j-apoc-procedures,neo4j-contrib/neo4j-apoc-procedures,neo4j-contrib/neo4j-apoc-procedures
|
package apoc.schema;
import apoc.result.AssertSchemaResult;
import apoc.result.ConstraintRelationshipInfo;
import apoc.result.IndexConstraintNodeInfo;
import org.antlr.v4.runtime.atn.SemanticContext;
import org.apache.commons.lang3.StringUtils;
import org.neo4j.common.TokenNameLookup;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Label;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.schema.ConstraintDefinition;
import org.neo4j.graphdb.schema.ConstraintType;
import org.neo4j.graphdb.schema.IndexDefinition;
import org.neo4j.graphdb.schema.IndexType;
import org.neo4j.graphdb.schema.Schema;
import org.neo4j.internal.helpers.collection.Iterables;
import org.neo4j.internal.kernel.api.InternalIndexState;
import org.neo4j.internal.kernel.api.SchemaRead;
import org.neo4j.internal.kernel.api.TokenRead;
import org.neo4j.internal.kernel.api.exceptions.LabelNotFoundKernelException;
import org.neo4j.internal.kernel.api.exceptions.schema.IndexNotFoundKernelException;
import org.neo4j.internal.schema.ConstraintDescriptor;
import org.neo4j.internal.schema.IndexDescriptor;
import org.neo4j.kernel.api.KernelTransaction;
import org.neo4j.kernel.api.Statement;
import org.neo4j.procedure.*;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import static org.neo4j.graphdb.Label.label;
public class Schemas {
@Context
public GraphDatabaseService db;
@Context
public Transaction tx;
@Context
public KernelTransaction ktx;
@Procedure(value = "apoc.schema.assert", mode = Mode.SCHEMA)
@Description("apoc.schema.assert({indexLabel:[[indexKeys]], ...}, {constraintLabel:[constraintKeys], ...}, dropExisting : true) yield label, key, keys, unique, action - drops all other existing indexes and constraints when `dropExisting` is `true` (default is `true`), and asserts that at the end of the operation the given indexes and unique constraints are there, each label:key pair is considered one constraint/label. Non-constraint indexes can define compound indexes with label:[key1,key2...] pairings.")
public Stream<AssertSchemaResult> schemaAssert(@Name("indexes") Map<String, List<Object>> indexes, @Name("constraints") Map<String, List<Object>> constraints, @Name(value = "dropExisting", defaultValue = "true") boolean dropExisting) throws ExecutionException, InterruptedException {
return Stream.concat(
assertIndexes(indexes, dropExisting).stream(),
assertConstraints(constraints, dropExisting).stream());
}
@Procedure(value = "apoc.schema.nodes", mode = Mode.SCHEMA)
@Description("CALL apoc.schema.nodes([config]) yield name, label, properties, status, type")
public Stream<IndexConstraintNodeInfo> nodes(@Name(value = "config",defaultValue = "{}") Map<String,Object> config) throws IndexNotFoundKernelException {
return indexesAndConstraintsForNode(config);
}
@Procedure(value = "apoc.schema.relationships", mode = Mode.SCHEMA)
@Description("CALL apoc.schema.relationships([config]) yield name, startLabel, type, endLabel, properties, status")
public Stream<ConstraintRelationshipInfo> relationships(@Name(value = "config",defaultValue = "{}") Map<String,Object> config) {
return constraintsForRelationship(config);
}
@UserFunction(value = "apoc.schema.node.indexExists")
@Description("RETURN apoc.schema.node.indexExists(labelName, propertyNames)")
public Boolean indexExistsOnNode(@Name("labelName") String labelName, @Name("propertyName") List<String> propertyNames) {
return indexExists(labelName, propertyNames);
}
@UserFunction(value = "apoc.schema.node.constraintExists")
@Description("RETURN apoc.schema.node.constraintExists(labelName, propertyNames)")
public Boolean constraintExistsOnNode(@Name("labelName") String labelName, @Name("propertyName") List<String> propertyNames) {
return constraintsExists(labelName, propertyNames);
}
@UserFunction(value = "apoc.schema.relationship.constraintExists")
@Description("RETURN apoc.schema.relationship.constraintExists(type, propertyNames)")
public Boolean constraintExistsOnRelationship(@Name("type") String type, @Name("propertyName") List<String> propertyNames) {
return constraintsExistsForRelationship(type, propertyNames);
}
public List<AssertSchemaResult> assertConstraints(Map<String, List<Object>> constraints0, boolean dropExisting) throws ExecutionException, InterruptedException {
Map<String, List<Object>> constraints = copyMapOfObjects(constraints0);
List<AssertSchemaResult> result = new ArrayList<>(constraints.size());
Schema schema = tx.schema();
for (ConstraintDefinition definition : schema.getConstraints()) {
String label = definition.isConstraintType(ConstraintType.RELATIONSHIP_PROPERTY_EXISTENCE) ? definition.getRelationshipType().name() : definition.getLabel().name();
AssertSchemaResult info = new AssertSchemaResult(label, Iterables.asList(definition.getPropertyKeys())).unique();
if (!checkIfConstraintExists(label, constraints, info)) {
if (dropExisting) {
definition.drop();
info.dropped();
}
}
result.add(info);
}
for (Map.Entry<String, List<Object>> constraint : constraints.entrySet()) {
for (Object key : constraint.getValue()) {
if (key instanceof String) {
result.add(createUniqueConstraint(schema, constraint.getKey(), key.toString()));
} else if (key instanceof List) {
result.add(createNodeKeyConstraint(constraint.getKey(), (List<Object>) key));
}
}
}
return result;
}
private boolean checkIfConstraintExists(String label, Map<String, List<Object>> constraints, AssertSchemaResult info) {
if (constraints.containsKey(label)) {
return constraints.get(label).removeIf(item -> {
// when there is a constraint IS UNIQUE
if (item instanceof String) {
return item.equals(info.key);
// when there is a constraint IS NODE KEY
} else {
return info.keys.equals(item);
}
});
}
return false;
}
private AssertSchemaResult createNodeKeyConstraint(String lbl, List<Object> keys) {
String keyProperties = keys.stream()
.map( property -> String.format("n.`%s`", property))
.collect( Collectors.joining( "," ) );
tx.execute(String.format("CREATE CONSTRAINT ON (n:`%s`) ASSERT (%s) IS NODE KEY", lbl, keyProperties)).close();
List<String> keysToSting = keys.stream().map(Object::toString).collect(Collectors.toList());
return new AssertSchemaResult(lbl, keysToSting).unique().created();
}
private AssertSchemaResult createUniqueConstraint(Schema schema, String lbl, String key) {
schema.constraintFor(label(lbl)).assertPropertyIsUnique(key).create();
return new AssertSchemaResult(lbl, key).unique().created();
}
public List<AssertSchemaResult> assertIndexes(Map<String, List<Object>> indexes0, boolean dropExisting) throws ExecutionException, InterruptedException, IllegalArgumentException {
Schema schema = tx.schema();
Map<String, List<Object>> indexes = copyMapOfObjects(indexes0);
List<AssertSchemaResult> result = new ArrayList<>(indexes.size());
for (IndexDefinition definition : schema.getIndexes()) {
if (!definition.isNodeIndex())
continue;
if (definition.getIndexType() == IndexType.LOOKUP)
continue;
if (definition.isConstraintIndex())
continue;
String label = Iterables.single(definition.getLabels()).name();
List<String> keys = new ArrayList<>();
definition.getPropertyKeys().forEach(keys::add);
AssertSchemaResult info = new AssertSchemaResult(label, keys);
if(indexes.containsKey(label)) {
if (keys.size() > 1) {
indexes.get(label).remove(keys);
} else if (keys.size() == 1) {
indexes.get(label).remove(keys.get(0));
} else
throw new IllegalArgumentException("Label given with no keys.");
}
if (dropExisting) {
definition.drop();
info.dropped();
}
result.add(info);
}
if (dropExisting)
indexes = copyMapOfObjects(indexes0);
for (Map.Entry<String, List<Object>> index : indexes.entrySet()) {
for (Object key : index.getValue()) {
if (key instanceof String) {
result.add(createSinglePropertyIndex(schema, index.getKey(), (String) key));
} else if (key instanceof List) {
result.add(createCompoundIndex(index.getKey(), (List<String>) key));
}
}
}
return result;
}
private AssertSchemaResult createSinglePropertyIndex(Schema schema, String lbl, String key) {
schema.indexFor(label(lbl)).on(key).create();
return new AssertSchemaResult(lbl, key).created();
}
private AssertSchemaResult createCompoundIndex(String label, List<String> keys) {
List<String> backTickedKeys = new ArrayList<>();
keys.forEach(key->backTickedKeys.add(String.format("`%s`", key)));
tx.execute(String.format("CREATE INDEX ON :`%s` (%s)", label, String.join(",", backTickedKeys))).close();
return new AssertSchemaResult(label, keys).created();
}
private Map<String, List<Object>> copyMapOfObjects(Map<String, List<Object>> input) {
if (input == null) {
return Collections.emptyMap();
}
HashMap<String, List<Object>> result = new HashMap<>(input.size());
input.forEach((k, v) -> result.put(k, new ArrayList<>(v)));
return result;
}
/**
* Checks if an index exists for a given label and a list of properties
* This method checks for index on nodes
*
* @param labelName
* @param propertyNames
* @return true if the index exists otherwise it returns false
*/
private Boolean indexExists(String labelName, List<String> propertyNames) {
Schema schema = tx.schema();
for (IndexDefinition indexDefinition : Iterables.asList(schema.getIndexes(Label.label(labelName)))) {
List<String> properties = Iterables.asList(indexDefinition.getPropertyKeys());
if (properties.equals(propertyNames)) {
return true;
}
}
return false;
}
/**
* Checks if a constraint exists for a given label and a list of properties
* This method checks for constraints on node
*
* @param labelName
* @param propertyNames
* @return true if the constraint exists otherwise it returns false
*/
private Boolean constraintsExists(String labelName, List<String> propertyNames) {
Schema schema = tx.schema();
for (ConstraintDefinition constraintDefinition : Iterables.asList(schema.getConstraints(Label.label(labelName)))) {
List<String> properties = Iterables.asList(constraintDefinition.getPropertyKeys());
if (properties.equals(propertyNames)) {
return true;
}
}
return false;
}
/**
* Checks if a constraint exists for a given type and a list of properties
* This method checks for constraints on relationships
*
* @param type
* @param propertyNames
* @return true if the constraint exists otherwise it returns false
*/
private Boolean constraintsExistsForRelationship(String type, List<String> propertyNames) {
Schema schema = tx.schema();
for (ConstraintDefinition constraintDefinition : Iterables.asList(schema.getConstraints(RelationshipType.withName(type)))) {
List<String> properties = Iterables.asList(constraintDefinition.getPropertyKeys());
if (properties.equals(propertyNames)) {
return true;
}
}
return false;
}
/**
* Collects indexes and constraints for nodes
*
* @return
*/
private Stream<IndexConstraintNodeInfo> indexesAndConstraintsForNode(Map<String,Object> config) {
SchemaConfig schemaConfig = new SchemaConfig(config);
Set<String> includeLabels = schemaConfig.getLabels();
Set<String> excludeLabels = schemaConfig.getExcludeLabels();
try ( Statement ignore = ktx.acquireStatement() ) {
TokenRead tokenRead = ktx.tokenRead();
SchemaRead schemaRead = ktx.schemaRead();
Iterable<IndexDescriptor> indexesIterator;
Iterable<ConstraintDescriptor> constraintsIterator;
if (includeLabels.isEmpty()) {
Iterator<IndexDescriptor> allIndex = schemaRead.indexesGetAll();
indexesIterator = StreamSupport.stream(
Spliterators.spliteratorUnknownSize(allIndex, Spliterator.ORDERED),
false)
.filter(index -> !index.isTokenIndex())
.filter(index -> Arrays.stream(index.schema().getEntityTokenIds()).noneMatch(id -> {
try {
return excludeLabels.contains(tokenRead.nodeLabelName(id));
} catch (LabelNotFoundKernelException e) {
return false;
}
})).collect(Collectors.toList());
Iterable<ConstraintDescriptor> allConstraints = () -> schemaRead.constraintsGetAll();
constraintsIterator = StreamSupport.stream(allConstraints.spliterator(),false)
.filter(constraint -> Arrays.stream(constraint.schema().getEntityTokenIds()).noneMatch(id -> {
try {
return excludeLabels.contains(tokenRead.nodeLabelName(id));
} catch (LabelNotFoundKernelException e) {
return false;
}
}))
.collect(Collectors.toList());
} else {
constraintsIterator = includeLabels.stream()
.filter(label -> !excludeLabels.contains(label) && tokenRead.nodeLabel(label) != -1)
.flatMap(label -> {
Iterable<ConstraintDescriptor> indexesForLabel = () -> schemaRead.constraintsGetForLabel(tokenRead.nodeLabel(label));
return StreamSupport.stream(indexesForLabel.spliterator(), false);
})
.collect(Collectors.toList());
indexesIterator = includeLabels.stream()
.filter(label -> !excludeLabels.contains(label) && tokenRead.nodeLabel(label) != -1)
.flatMap(label -> {
Iterable<IndexDescriptor> indexesForLabel = () -> schemaRead.indexesGetForLabel(tokenRead.nodeLabel(label));
return StreamSupport.stream(indexesForLabel.spliterator(), false);
})
.collect(Collectors.toList());
}
Stream<IndexConstraintNodeInfo> constraintNodeInfoStream = StreamSupport.stream(constraintsIterator.spliterator(), false)
.filter(constraintDescriptor -> constraintDescriptor.type().equals(org.neo4j.internal.schema.ConstraintType.EXISTS))
.map(constraintDescriptor -> this.nodeInfoFromConstraintDescriptor(constraintDescriptor, tokenRead))
.sorted(Comparator.comparing(i -> i.label));
Stream<IndexConstraintNodeInfo> indexNodeInfoStream = StreamSupport.stream(indexesIterator.spliterator(), false)
.map(indexDescriptor -> this.nodeInfoFromIndexDefinition(indexDescriptor, schemaRead, tokenRead))
.sorted(Comparator.comparing(i -> i.label));
return Stream.of(constraintNodeInfoStream, indexNodeInfoStream).flatMap(e -> e);
}
}
/**
* Collects constraints for relationships
*
* @return
*/
private Stream<ConstraintRelationshipInfo> constraintsForRelationship(Map<String,Object> config) {
Schema schema = tx.schema();
SchemaConfig schemaConfig = new SchemaConfig(config);
Set<String> includeRelationships = schemaConfig.getRelationships();
Set<String> excludeRelationships = schemaConfig.getExcludeRelationships();
try ( Statement ignore = ktx.acquireStatement() ) {
TokenRead tokenRead = ktx.tokenRead();
Iterable<ConstraintDefinition> constraintsIterator;
if(!includeRelationships.isEmpty()) {
constraintsIterator = includeRelationships.stream()
.filter(type -> !excludeRelationships.contains(type) && tokenRead.relationshipType(type) != -1)
.flatMap(type -> {
Iterable<ConstraintDefinition> constraintsForType = schema.getConstraints(RelationshipType.withName(type));
return StreamSupport.stream(constraintsForType.spliterator(), false);
})
.collect(Collectors.toList());
} else {
Iterable<ConstraintDefinition> allConstraints = schema.getConstraints();
constraintsIterator = StreamSupport.stream(allConstraints.spliterator(),false)
.filter(index -> !excludeRelationships.contains(index.getRelationshipType().name()))
.collect(Collectors.toList());
}
Stream<ConstraintRelationshipInfo> constraintRelationshipInfoStream = StreamSupport.stream(constraintsIterator.spliterator(), false)
.filter(constraintDefinition -> constraintDefinition.isConstraintType(ConstraintType.RELATIONSHIP_PROPERTY_EXISTENCE))
.map(this::relationshipInfoFromConstraintDefinition);
return constraintRelationshipInfoStream;
}
}
/**
* ConstraintInfo info from ConstraintDescriptor
*
* @param constraintDescriptor
* @param tokens
* @return
*/
private IndexConstraintNodeInfo nodeInfoFromConstraintDescriptor(ConstraintDescriptor constraintDescriptor, TokenNameLookup tokens) {
String labelName = tokens.labelGetName(constraintDescriptor.schema().getLabelId());
List<String> properties = new ArrayList<>();
Arrays.stream(constraintDescriptor.schema().getPropertyIds()).forEach((i) -> properties.add(tokens.propertyKeyGetName(i)));
return new IndexConstraintNodeInfo(
// Pretty print for index name
String.format(":%s(%s)", labelName, StringUtils.join(properties, ",")),
labelName,
properties,
StringUtils.EMPTY,
ConstraintType.NODE_PROPERTY_EXISTENCE.toString(),
"NO FAILURE",
0,
0,
0,
constraintDescriptor.userDescription(tokens)
);
}
/**
* Index info from IndexDefinition
*
* @param indexDescriptor
* @param schemaRead
* @param tokens
* @return
*/
private IndexConstraintNodeInfo nodeInfoFromIndexDefinition(IndexDescriptor indexDescriptor, SchemaRead schemaRead, TokenNameLookup tokens){
int[] labelIds = indexDescriptor.schema().getEntityTokenIds();
if (labelIds.length != 1) throw new IllegalStateException("Index with more than one label");
String labelName = tokens.labelGetName(labelIds[0]);
List<String> properties = new ArrayList<>();
Arrays.stream(indexDescriptor.schema().getPropertyIds()).forEach((i) -> properties.add(tokens.propertyKeyGetName(i)));
try {
return new IndexConstraintNodeInfo(
// Pretty print for index name
String.format(":%s(%s)", labelName, StringUtils.join(properties, ",")),
labelName,
properties,
schemaRead.indexGetState(indexDescriptor).toString(),
!indexDescriptor.isUnique() ? "INDEX" : "UNIQUENESS",
schemaRead.indexGetState(indexDescriptor).equals(InternalIndexState.FAILED) ? schemaRead.indexGetFailure(indexDescriptor) : "NO FAILURE",
schemaRead.indexGetPopulationProgress(indexDescriptor).getCompleted() / schemaRead.indexGetPopulationProgress(indexDescriptor).getTotal() * 100,
schemaRead.indexSize(indexDescriptor),
schemaRead.indexUniqueValuesSelectivity(indexDescriptor),
indexDescriptor.userDescription(tokens)
);
} catch(IndexNotFoundKernelException e) {
return new IndexConstraintNodeInfo(
// Pretty print for index name
String.format(":%s(%s)", labelName, StringUtils.join(properties, ",")),
labelName,
properties,
"NOT_FOUND",
!indexDescriptor.isUnique() ? "INDEX" : "UNIQUENESS",
"NOT_FOUND",
0,0,0,
indexDescriptor.userDescription(tokens)
);
}
}
/**
* Constraint info from ConstraintDefinition for relationships
*
* @param constraintDefinition
* @return
*/
private ConstraintRelationshipInfo relationshipInfoFromConstraintDefinition(ConstraintDefinition constraintDefinition) {
return new ConstraintRelationshipInfo(
String.format("CONSTRAINT %s", constraintDefinition.toString()),
constraintDefinition.getConstraintType().name(),
Iterables.asList(constraintDefinition.getPropertyKeys()),
""
);
}
}
|
core/src/main/java/apoc/schema/Schemas.java
|
package apoc.schema;
import apoc.result.AssertSchemaResult;
import apoc.result.ConstraintRelationshipInfo;
import apoc.result.IndexConstraintNodeInfo;
import org.apache.commons.lang3.StringUtils;
import org.neo4j.common.TokenNameLookup;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Label;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.schema.ConstraintDefinition;
import org.neo4j.graphdb.schema.ConstraintType;
import org.neo4j.graphdb.schema.IndexDefinition;
import org.neo4j.graphdb.schema.Schema;
import org.neo4j.internal.helpers.collection.Iterables;
import org.neo4j.internal.kernel.api.InternalIndexState;
import org.neo4j.internal.kernel.api.SchemaRead;
import org.neo4j.internal.kernel.api.TokenRead;
import org.neo4j.internal.kernel.api.exceptions.LabelNotFoundKernelException;
import org.neo4j.internal.kernel.api.exceptions.schema.IndexNotFoundKernelException;
import org.neo4j.internal.schema.ConstraintDescriptor;
import org.neo4j.internal.schema.IndexDescriptor;
import org.neo4j.kernel.api.KernelTransaction;
import org.neo4j.kernel.api.Statement;
import org.neo4j.procedure.*;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import static org.neo4j.graphdb.Label.label;
public class Schemas {
@Context
public GraphDatabaseService db;
@Context
public Transaction tx;
@Context
public KernelTransaction ktx;
@Procedure(value = "apoc.schema.assert", mode = Mode.SCHEMA)
@Description("apoc.schema.assert({indexLabel:[[indexKeys]], ...}, {constraintLabel:[constraintKeys], ...}, dropExisting : true) yield label, key, keys, unique, action - drops all other existing indexes and constraints when `dropExisting` is `true` (default is `true`), and asserts that at the end of the operation the given indexes and unique constraints are there, each label:key pair is considered one constraint/label. Non-constraint indexes can define compound indexes with label:[key1,key2...] pairings.")
public Stream<AssertSchemaResult> schemaAssert(@Name("indexes") Map<String, List<Object>> indexes, @Name("constraints") Map<String, List<Object>> constraints, @Name(value = "dropExisting", defaultValue = "true") boolean dropExisting) throws ExecutionException, InterruptedException {
return Stream.concat(
assertIndexes(indexes, dropExisting).stream(),
assertConstraints(constraints, dropExisting).stream());
}
@Procedure(value = "apoc.schema.nodes", mode = Mode.SCHEMA)
@Description("CALL apoc.schema.nodes([config]) yield name, label, properties, status, type")
public Stream<IndexConstraintNodeInfo> nodes(@Name(value = "config",defaultValue = "{}") Map<String,Object> config) throws IndexNotFoundKernelException {
return indexesAndConstraintsForNode(config);
}
@Procedure(value = "apoc.schema.relationships", mode = Mode.SCHEMA)
@Description("CALL apoc.schema.relationships([config]) yield name, startLabel, type, endLabel, properties, status")
public Stream<ConstraintRelationshipInfo> relationships(@Name(value = "config",defaultValue = "{}") Map<String,Object> config) {
return constraintsForRelationship(config);
}
@UserFunction(value = "apoc.schema.node.indexExists")
@Description("RETURN apoc.schema.node.indexExists(labelName, propertyNames)")
public Boolean indexExistsOnNode(@Name("labelName") String labelName, @Name("propertyName") List<String> propertyNames) {
return indexExists(labelName, propertyNames);
}
@UserFunction(value = "apoc.schema.node.constraintExists")
@Description("RETURN apoc.schema.node.constraintExists(labelName, propertyNames)")
public Boolean constraintExistsOnNode(@Name("labelName") String labelName, @Name("propertyName") List<String> propertyNames) {
return constraintsExists(labelName, propertyNames);
}
@UserFunction(value = "apoc.schema.relationship.constraintExists")
@Description("RETURN apoc.schema.relationship.constraintExists(type, propertyNames)")
public Boolean constraintExistsOnRelationship(@Name("type") String type, @Name("propertyName") List<String> propertyNames) {
return constraintsExistsForRelationship(type, propertyNames);
}
public List<AssertSchemaResult> assertConstraints(Map<String, List<Object>> constraints0, boolean dropExisting) throws ExecutionException, InterruptedException {
Map<String, List<Object>> constraints = copyMapOfObjects(constraints0);
List<AssertSchemaResult> result = new ArrayList<>(constraints.size());
Schema schema = tx.schema();
for (ConstraintDefinition definition : schema.getConstraints()) {
String label = definition.isConstraintType(ConstraintType.RELATIONSHIP_PROPERTY_EXISTENCE) ? definition.getRelationshipType().name() : definition.getLabel().name();
AssertSchemaResult info = new AssertSchemaResult(label, Iterables.asList(definition.getPropertyKeys())).unique();
if (!checkIfConstraintExists(label, constraints, info)) {
if (dropExisting) {
definition.drop();
info.dropped();
}
}
result.add(info);
}
for (Map.Entry<String, List<Object>> constraint : constraints.entrySet()) {
for (Object key : constraint.getValue()) {
if (key instanceof String) {
result.add(createUniqueConstraint(schema, constraint.getKey(), key.toString()));
} else if (key instanceof List) {
result.add(createNodeKeyConstraint(constraint.getKey(), (List<Object>) key));
}
}
}
return result;
}
private boolean checkIfConstraintExists(String label, Map<String, List<Object>> constraints, AssertSchemaResult info) {
if (constraints.containsKey(label)) {
return constraints.get(label).removeIf(item -> {
// when there is a constraint IS UNIQUE
if (item instanceof String) {
return item.equals(info.key);
// when there is a constraint IS NODE KEY
} else {
return info.keys.equals(item);
}
});
}
return false;
}
private AssertSchemaResult createNodeKeyConstraint(String lbl, List<Object> keys) {
String keyProperties = keys.stream()
.map( property -> String.format("n.`%s`", property))
.collect( Collectors.joining( "," ) );
tx.execute(String.format("CREATE CONSTRAINT ON (n:`%s`) ASSERT (%s) IS NODE KEY", lbl, keyProperties)).close();
List<String> keysToSting = keys.stream().map(Object::toString).collect(Collectors.toList());
return new AssertSchemaResult(lbl, keysToSting).unique().created();
}
private AssertSchemaResult createUniqueConstraint(Schema schema, String lbl, String key) {
schema.constraintFor(label(lbl)).assertPropertyIsUnique(key).create();
return new AssertSchemaResult(lbl, key).unique().created();
}
public List<AssertSchemaResult> assertIndexes(Map<String, List<Object>> indexes0, boolean dropExisting) throws ExecutionException, InterruptedException, IllegalArgumentException {
Schema schema = tx.schema();
Map<String, List<Object>> indexes = copyMapOfObjects(indexes0);
List<AssertSchemaResult> result = new ArrayList<>(indexes.size());
for (IndexDefinition definition : schema.getIndexes()) {
if (definition.isConstraintIndex())
continue;
String label = Iterables.single(definition.getLabels()).name();
List<String> keys = new ArrayList<>();
definition.getPropertyKeys().forEach(keys::add);
AssertSchemaResult info = new AssertSchemaResult(label, keys);
if(indexes.containsKey(label)) {
if (keys.size() > 1) {
indexes.get(label).remove(keys);
} else if (keys.size() == 1) {
indexes.get(label).remove(keys.get(0));
} else
throw new IllegalArgumentException("Label given with no keys.");
}
if (dropExisting) {
definition.drop();
info.dropped();
}
result.add(info);
}
if (dropExisting)
indexes = copyMapOfObjects(indexes0);
for (Map.Entry<String, List<Object>> index : indexes.entrySet()) {
for (Object key : index.getValue()) {
if (key instanceof String) {
result.add(createSinglePropertyIndex(schema, index.getKey(), (String) key));
} else if (key instanceof List) {
result.add(createCompoundIndex(index.getKey(), (List<String>) key));
}
}
}
return result;
}
private AssertSchemaResult createSinglePropertyIndex(Schema schema, String lbl, String key) {
schema.indexFor(label(lbl)).on(key).create();
return new AssertSchemaResult(lbl, key).created();
}
private AssertSchemaResult createCompoundIndex(String label, List<String> keys) {
List<String> backTickedKeys = new ArrayList<>();
keys.forEach(key->backTickedKeys.add(String.format("`%s`", key)));
tx.execute(String.format("CREATE INDEX ON :`%s` (%s)", label, String.join(",", backTickedKeys))).close();
return new AssertSchemaResult(label, keys).created();
}
private Map<String, List<Object>> copyMapOfObjects(Map<String, List<Object>> input) {
if (input == null) {
return Collections.emptyMap();
}
HashMap<String, List<Object>> result = new HashMap<>(input.size());
input.forEach((k, v) -> result.put(k, new ArrayList<>(v)));
return result;
}
/**
* Checks if an index exists for a given label and a list of properties
* This method checks for index on nodes
*
* @param labelName
* @param propertyNames
* @return true if the index exists otherwise it returns false
*/
private Boolean indexExists(String labelName, List<String> propertyNames) {
Schema schema = tx.schema();
for (IndexDefinition indexDefinition : Iterables.asList(schema.getIndexes(Label.label(labelName)))) {
List<String> properties = Iterables.asList(indexDefinition.getPropertyKeys());
if (properties.equals(propertyNames)) {
return true;
}
}
return false;
}
/**
* Checks if a constraint exists for a given label and a list of properties
* This method checks for constraints on node
*
* @param labelName
* @param propertyNames
* @return true if the constraint exists otherwise it returns false
*/
private Boolean constraintsExists(String labelName, List<String> propertyNames) {
Schema schema = tx.schema();
for (ConstraintDefinition constraintDefinition : Iterables.asList(schema.getConstraints(Label.label(labelName)))) {
List<String> properties = Iterables.asList(constraintDefinition.getPropertyKeys());
if (properties.equals(propertyNames)) {
return true;
}
}
return false;
}
/**
* Checks if a constraint exists for a given type and a list of properties
* This method checks for constraints on relationships
*
* @param type
* @param propertyNames
* @return true if the constraint exists otherwise it returns false
*/
private Boolean constraintsExistsForRelationship(String type, List<String> propertyNames) {
Schema schema = tx.schema();
for (ConstraintDefinition constraintDefinition : Iterables.asList(schema.getConstraints(RelationshipType.withName(type)))) {
List<String> properties = Iterables.asList(constraintDefinition.getPropertyKeys());
if (properties.equals(propertyNames)) {
return true;
}
}
return false;
}
/**
* Collects indexes and constraints for nodes
*
* @return
*/
private Stream<IndexConstraintNodeInfo> indexesAndConstraintsForNode(Map<String,Object> config) {
SchemaConfig schemaConfig = new SchemaConfig(config);
Set<String> includeLabels = schemaConfig.getLabels();
Set<String> excludeLabels = schemaConfig.getExcludeLabels();
try ( Statement ignore = ktx.acquireStatement() ) {
TokenRead tokenRead = ktx.tokenRead();
SchemaRead schemaRead = ktx.schemaRead();
Iterable<IndexDescriptor> indexesIterator;
Iterable<ConstraintDescriptor> constraintsIterator;
if (includeLabels.isEmpty()) {
Iterator<IndexDescriptor> allIndex = schemaRead.indexesGetAll();
indexesIterator = StreamSupport.stream(
Spliterators.spliteratorUnknownSize(allIndex, Spliterator.ORDERED),
false)
.filter(index -> Arrays.stream(index.schema().getEntityTokenIds()).noneMatch(id -> {
try {
return excludeLabels.contains(tokenRead.nodeLabelName(id));
} catch (LabelNotFoundKernelException e) {
return false;
}
})).collect(Collectors.toList());
Iterable<ConstraintDescriptor> allConstraints = () -> schemaRead.constraintsGetAll();
constraintsIterator = StreamSupport.stream(allConstraints.spliterator(),false)
.filter(constraint -> Arrays.stream(constraint.schema().getEntityTokenIds()).noneMatch(id -> {
try {
return excludeLabels.contains(tokenRead.nodeLabelName(id));
} catch (LabelNotFoundKernelException e) {
return false;
}
}))
.collect(Collectors.toList());
} else {
constraintsIterator = includeLabels.stream()
.filter(label -> !excludeLabels.contains(label) && tokenRead.nodeLabel(label) != -1)
.flatMap(label -> {
Iterable<ConstraintDescriptor> indexesForLabel = () -> schemaRead.constraintsGetForLabel(tokenRead.nodeLabel(label));
return StreamSupport.stream(indexesForLabel.spliterator(), false);
})
.collect(Collectors.toList());
indexesIterator = includeLabels.stream()
.filter(label -> !excludeLabels.contains(label) && tokenRead.nodeLabel(label) != -1)
.flatMap(label -> {
Iterable<IndexDescriptor> indexesForLabel = () -> schemaRead.indexesGetForLabel(tokenRead.nodeLabel(label));
return StreamSupport.stream(indexesForLabel.spliterator(), false);
})
.collect(Collectors.toList());
}
Stream<IndexConstraintNodeInfo> constraintNodeInfoStream = StreamSupport.stream(constraintsIterator.spliterator(), false)
.filter(constraintDescriptor -> constraintDescriptor.type().equals(org.neo4j.internal.schema.ConstraintType.EXISTS))
.map(constraintDescriptor -> this.nodeInfoFromConstraintDescriptor(constraintDescriptor, tokenRead))
.sorted(Comparator.comparing(i -> i.label));
Stream<IndexConstraintNodeInfo> indexNodeInfoStream = StreamSupport.stream(indexesIterator.spliterator(), false)
.map(indexDescriptor -> this.nodeInfoFromIndexDefinition(indexDescriptor, schemaRead, tokenRead))
.sorted(Comparator.comparing(i -> i.label));
return Stream.of(constraintNodeInfoStream, indexNodeInfoStream).flatMap(e -> e);
}
}
/**
* Collects constraints for relationships
*
* @return
*/
private Stream<ConstraintRelationshipInfo> constraintsForRelationship(Map<String,Object> config) {
Schema schema = tx.schema();
SchemaConfig schemaConfig = new SchemaConfig(config);
Set<String> includeRelationships = schemaConfig.getRelationships();
Set<String> excludeRelationships = schemaConfig.getExcludeRelationships();
try ( Statement ignore = ktx.acquireStatement() ) {
TokenRead tokenRead = ktx.tokenRead();
Iterable<ConstraintDefinition> constraintsIterator;
if(!includeRelationships.isEmpty()) {
constraintsIterator = includeRelationships.stream()
.filter(type -> !excludeRelationships.contains(type) && tokenRead.relationshipType(type) != -1)
.flatMap(type -> {
Iterable<ConstraintDefinition> constraintsForType = schema.getConstraints(RelationshipType.withName(type));
return StreamSupport.stream(constraintsForType.spliterator(), false);
})
.collect(Collectors.toList());
} else {
Iterable<ConstraintDefinition> allConstraints = schema.getConstraints();
constraintsIterator = StreamSupport.stream(allConstraints.spliterator(),false)
.filter(index -> !excludeRelationships.contains(index.getRelationshipType().name()))
.collect(Collectors.toList());
}
Stream<ConstraintRelationshipInfo> constraintRelationshipInfoStream = StreamSupport.stream(constraintsIterator.spliterator(), false)
.filter(constraintDefinition -> constraintDefinition.isConstraintType(ConstraintType.RELATIONSHIP_PROPERTY_EXISTENCE))
.map(this::relationshipInfoFromConstraintDefinition);
return constraintRelationshipInfoStream;
}
}
/**
* ConstraintInfo info from ConstraintDescriptor
*
* @param constraintDescriptor
* @param tokens
* @return
*/
private IndexConstraintNodeInfo nodeInfoFromConstraintDescriptor(ConstraintDescriptor constraintDescriptor, TokenNameLookup tokens) {
String labelName = tokens.labelGetName(constraintDescriptor.schema().getLabelId());
List<String> properties = new ArrayList<>();
Arrays.stream(constraintDescriptor.schema().getPropertyIds()).forEach((i) -> properties.add(tokens.propertyKeyGetName(i)));
return new IndexConstraintNodeInfo(
// Pretty print for index name
String.format(":%s(%s)", labelName, StringUtils.join(properties, ",")),
labelName,
properties,
StringUtils.EMPTY,
ConstraintType.NODE_PROPERTY_EXISTENCE.toString(),
"NO FAILURE",
0,
0,
0,
constraintDescriptor.userDescription(tokens)
);
}
/**
* Index info from IndexDefinition
*
* @param indexDescriptor
* @param schemaRead
* @param tokens
* @return
*/
private IndexConstraintNodeInfo nodeInfoFromIndexDefinition(IndexDescriptor indexDescriptor, SchemaRead schemaRead, TokenNameLookup tokens){
int[] labelIds = indexDescriptor.schema().getEntityTokenIds();
if (labelIds.length != 1) throw new IllegalStateException("Index with more than one label");
String labelName = tokens.labelGetName(labelIds[0]);
List<String> properties = new ArrayList<>();
Arrays.stream(indexDescriptor.schema().getPropertyIds()).forEach((i) -> properties.add(tokens.propertyKeyGetName(i)));
try {
return new IndexConstraintNodeInfo(
// Pretty print for index name
String.format(":%s(%s)", labelName, StringUtils.join(properties, ",")),
labelName,
properties,
schemaRead.indexGetState(indexDescriptor).toString(),
!indexDescriptor.isUnique() ? "INDEX" : "UNIQUENESS",
schemaRead.indexGetState(indexDescriptor).equals(InternalIndexState.FAILED) ? schemaRead.indexGetFailure(indexDescriptor) : "NO FAILURE",
schemaRead.indexGetPopulationProgress(indexDescriptor).getCompleted() / schemaRead.indexGetPopulationProgress(indexDescriptor).getTotal() * 100,
schemaRead.indexSize(indexDescriptor),
schemaRead.indexUniqueValuesSelectivity(indexDescriptor),
indexDescriptor.userDescription(tokens)
);
} catch(IndexNotFoundKernelException e) {
return new IndexConstraintNodeInfo(
// Pretty print for index name
String.format(":%s(%s)", labelName, StringUtils.join(properties, ",")),
labelName,
properties,
"NOT_FOUND",
!indexDescriptor.isUnique() ? "INDEX" : "UNIQUENESS",
"NOT_FOUND",
0,0,0,
indexDescriptor.userDescription(tokens)
);
}
}
/**
* Constraint info from ConstraintDefinition for relationships
*
* @param constraintDefinition
* @return
*/
private ConstraintRelationshipInfo relationshipInfoFromConstraintDefinition(ConstraintDefinition constraintDefinition) {
return new ConstraintRelationshipInfo(
String.format("CONSTRAINT %s", constraintDefinition.toString()),
constraintDefinition.getConstraintType().name(),
Iterables.asList(constraintDefinition.getPropertyKeys()),
""
);
}
}
|
Skip not node indexes in assertIndexes
|
core/src/main/java/apoc/schema/Schemas.java
|
Skip not node indexes in assertIndexes
|
|
Java
|
apache-2.0
|
ad2b3d4bdd432b67cc761fafcd2cfecc24320e28
| 0
|
mmayorivera/jsimpledb,permazen/permazen,mmayorivera/jsimpledb,mmayorivera/jsimpledb,permazen/permazen,tempbottle/jsimpledb,permazen/permazen,tempbottle/jsimpledb,gmsconstantino/jsimpledb,gmsconstantino/jsimpledb,tempbottle/jsimpledb,gmsconstantino/jsimpledb,archiecobbs/jsimpledb,archiecobbs/jsimpledb,archiecobbs/jsimpledb
|
/*
* Copyright (C) 2014 Archie L. Cobbs. All rights reserved.
*
* $Id$
*/
package org.jsimpledb.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation for methods that are to be invoked whenever an object's schema version has just changed.
*
* <p><b>Method Parameters</b></p>
*
* <p>
* The annotated method must be an instance method (i.e., not static), return void, and
* take one, two, or all three of the following parameters in order:
* <ol>
* <li>{@code int oldVersion} - previous schema version; should be present only if {@link #oldVersion} is zero</li>
* <li>{@code int newVersion} - new schema version; should be present only if {@link #newVersion} is zero</li>
* <li>{@code Map<Integer, Object> oldValues} <i>or</i> {@code Map<String, Object> oldValues} - immutable map containing
* all field values from the previous version of the object, indexed by either storage ID or field name.</li>
* </ol>
* </p>
*
* <p>
* If a class has multiple {@link OnVersionChange @OnVersionChange}-annotated methods, methods with more specific
* constraint(s) (i.e., non-zero {@link #oldVersion} and/or {@link #newVersion}) will be invoked first.
* </p>
*
* <p><b>Incompatible Schema Changes</b></p>
*
* <p>
* JSimpleDB supports arbitrary Java model schema changes across schema versions, including adding and removing Java types.
* As a result, it's possible for the previous version of an object to contain reference fields whose Java types no longer exist
* in the current Java model. Specifically, this can happen in two ways:
* <ul>
* <li>A reference field refers to an object type that no longer exists; or</li>
* <li>An {@link Enum} field refers to an {@link Enum} type that no longer exists, or whose constants have changed</li>
* </ul>
* </p>
*
* <p>
* In these cases, the old field's value cannot be represented in {@code oldValues} using the original Java types.
* Instead, more generic types are used:
* <ul>
* <li>For a reference field whose type no longer exists, the referenced object will be an {@link org.jsimpledb.UntypedJObject}.
* Note that the fields in the {@link org.jsimpledb.UntypedJObject} may still be accessed by invoking the
* {@link org.jsimpledb.JTransaction} field access methods with {@code upgradeVersion} set to false (otherwise,
* a {@link org.jsimpledb.core.TypeNotInSchemaVersionException} is thrown).
* <li>For {@link Enum} fields whose type no longer exists or has modified constants, the old value
* will be represented as an {@link org.jsimpledb.core.EnumValue} object.</li>
* </ul>
* </p>
*
* <p>
* In addition to Java types disappearing, it's also possible that the type of a reference field is narrower in the current
* Java code than it was in the previous Java code. If an object held a reference in such a field to another object outside
* the new, narrower type, then upgrading the object without change would represent a violation of Java type safety.
* Therefore, when any object is upgraded, all references that would otherwise be illegal are cleared (in the manner of
* {@link org.jsimpledb.core.DeleteAction#UNREFERENCE}); use {@code oldValues} to access the previous field value(s) if needed.
* </p>
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface OnVersionChange {
/**
* Required old schema version.
*
* <p>
* If this property is set to a positive value, only version changes
* for which the previous schema version equals the specified version will result in notification,
* and the annotated method must have the corresponding parameter omitted. Otherwise notifications
* are delivered for any previous schema version and the {@code oldVersion} method parameter is required.
* </p>
*
* <p>
* Negative values are not allowed.
*/
int oldVersion() default 0;
/**
* Required new schema version.
*
* <p>
* If this property is set to a positive value, only version changes
* for which the new schema version equals the specified version will result in notification,
* and the annotated method must have the corresponding parameter omitted. Otherwise notifications
* are delivered for any new schema version and the {@code newVersion} method parameter is required.
* </p>
*
* <p>
* Negative values are not allowed.
*/
int newVersion() default 0;
}
|
src/java/org/jsimpledb/annotation/OnVersionChange.java
|
/*
* Copyright (C) 2014 Archie L. Cobbs. All rights reserved.
*
* $Id$
*/
package org.jsimpledb.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation for methods that are to be invoked whenever an object's schema version has just changed.
*
* <p><b>Method Parameters</b></p>
*
* <p>
* The annotated method must be an instance method (i.e., not static), return void, and
* take one, two, or all three of the following parameters in order:
* <ol>
* <li>{@code int oldVersion} - previous schema version; should be present only if {@link #oldVersion} is zero</li>
* <li>{@code int newVersion} - new schema version; should be present only if {@link #newVersion} is zero</li>
* <li>{@code Map<Integer, Object> oldValues} <i>or</i> {@code Map<String, Object> oldValues} - immutable map containing
* all field values from the previous version of the object, indexed by either storage ID or field name.</li>
* </ol>
* </p>
*
* <p>
* If a class has multiple {@link OnVersionChange @OnVersionChange}-annotated methods, methods with more specific
* constraint(s) (i.e., non-zero {@link #oldVersion} and/or {@link #newVersion}) will be invoked first.
* </p>
*
* <p><b>Incompatible Schema Changes</b></p>
*
* <p>
* JSimpleDB supports arbitrary Java model schema changes across schema versions, including adding and removing Java types.
* As a result, it's possible for the previous version of an object to contain reference fields whose Java types no longer exist
* in the current Java model. Specifically, this can happen in two ways:
* <ul>
* <li>A reference field refers to an object type that no longer exists; or</li>
* <li>An {@link Enum} field refers to an {@link Enum} type taht no longer exists, or whose constants have changed</li>
* </ul>
* </p>
*
* <p>
* In these cases, the old field's value cannot be represented in {@code oldValues} using the original Java types.
* Instead, more generic types are used:
* <ul>
* <li>For a reference field whose type no longer exists, the referenced object will be an {@link org.jsimpledb.UntypedJObject}.
* Note that the fields in the {@link org.jsimpledb.UntypedJObject} may still be accessed by invoking the
* {@link org.jsimpledb.JTransaction} field access methods with {@code upgradeVersion} set to false (otherwise,
* a {@link org.jsimpledb.core.TypeNotInSchemaVersionException} is thrown).
* <li>For {@link Enum} fields whose type no longer exists or has modified constants, the old value
* will be represented as an {@link org.jsimpledb.core.EnumValue} object.</li>
* </ul>
* </p>
*
* <p>
* In addition to Java types disappearing, it's also possible that the type of a reference field is narrower in the current
* Java code than it was in the previous Java code. If an object held a reference in such a field to another object outside
* the new, narrower type, then upgrading the object without change would represent a violation of Java type safety.
* Therefore, when any object is upgraded, all references that would otherwise be illegal are cleared (in the manner of
* {@link org.jsimpledb.core.DeleteAction#UNREFERENCE}); use {@code oldValues} to access the previous field value(s) if needed.
* </p>
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface OnVersionChange {
/**
* Required old schema version.
*
* <p>
* If this property is set to a positive value, only version changes
* for which the previous schema version equals the specified version will result in notification,
* and the annotated method must have the corresponding parameter omitted. Otherwise notifications
* are delivered for any previous schema version and the {@code oldVersion} method parameter is required.
* </p>
*
* <p>
* Negative values are not allowed.
*/
int oldVersion() default 0;
/**
* Required new schema version.
*
* <p>
* If this property is set to a positive value, only version changes
* for which the new schema version equals the specified version will result in notification,
* and the annotated method must have the corresponding parameter omitted. Otherwise notifications
* are delivered for any new schema version and the {@code newVersion} method parameter is required.
* </p>
*
* <p>
* Negative values are not allowed.
*/
int newVersion() default 0;
}
|
Typo fix.
|
src/java/org/jsimpledb/annotation/OnVersionChange.java
|
Typo fix.
|
|
Java
|
apache-2.0
|
c3d36dfbf23db2960b298f7bef15e6a23eae0418
| 0
|
webbukkit/dynmap,webbukkit/dynmap,webbukkit/dynmap,webbukkit/dynmap
|
package org.dynmap.markers.impl;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import javax.imageio.ImageIO;
import org.dynmap.ConfigurationNode;
import org.dynmap.DynmapCore;
import org.dynmap.DynmapLocation;
import org.dynmap.DynmapWorld;
import org.dynmap.Event;
import org.dynmap.Log;
import org.dynmap.MapManager;
import org.dynmap.Client;
import org.dynmap.Client.ComponentMessage;
import org.dynmap.common.DynmapCommandSender;
import org.dynmap.common.DynmapPlayer;
import org.dynmap.hdmap.HDPerspective;
import org.dynmap.markers.AreaMarker;
import org.dynmap.markers.CircleMarker;
import org.dynmap.markers.EnterExitMarker;
import org.dynmap.markers.EnterExitMarker.EnterExitText;
import org.dynmap.markers.Marker;
import org.dynmap.markers.MarkerAPI;
import org.dynmap.markers.MarkerDescription;
import org.dynmap.markers.MarkerIcon;
import org.dynmap.markers.MarkerIcon.MarkerSize;
import org.dynmap.markers.MarkerSet;
import org.dynmap.markers.PlayerSet;
import org.dynmap.markers.PolyLineMarker;
import org.dynmap.utils.BufferOutputStream;
import org.dynmap.web.Json;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Supplier;
/**
* Implementation class for MarkerAPI - should not be called directly
*/
public class MarkerAPIImpl implements MarkerAPI, Event.Listener<DynmapWorld> {
private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
private File markerpersist;
private File markerpersist_old;
private File markerdir; /* Local store for markers (internal) */
private HashMap<String, MarkerIconImpl> markericons = new HashMap<String, MarkerIconImpl>();
private ConcurrentHashMap<String, MarkerSetImpl> markersets = new ConcurrentHashMap<String, MarkerSetImpl>();
private HashMap<String, List<DynmapLocation>> pointaccum = new HashMap<String, List<DynmapLocation>>();
private HashMap<String, PlayerSetImpl> playersets = new HashMap<String, PlayerSetImpl>();
private DynmapCore core;
static MarkerAPIImpl api;
private Map<String, Map<String, Supplier<String[]>>> tabCompletions = null;
/* Built-in icons */
private static final String[] builtin_icons = {
"anchor", "bank", "basket", "bed", "beer", "bighouse", "blueflag", "bomb", "bookshelf", "bricks", "bronzemedal", "bronzestar",
"building", "cake", "camera", "cart", "caution", "chest", "church", "coins", "comment", "compass", "construction",
"cross", "cup", "cutlery", "default", "diamond", "dog", "door", "down", "drink", "exclamation", "factory",
"fire", "flower", "gear", "goldmedal", "goldstar", "greenflag", "hammer", "heart", "house", "key", "king",
"left", "lightbulb", "lighthouse", "lock", "minecart", "orangeflag", "pin", "pinkflag", "pirateflag", "pointdown", "pointleft",
"pointright", "pointup", "portal", "purpleflag", "queen", "redflag", "right", "ruby", "scales", "skull", "shield", "sign",
"silvermedal", "silverstar", "star", "sun", "temple", "theater", "tornado", "tower", "tree", "truck", "up",
"walk", "warning", "world", "wrench", "yellowflag", "offlineuser"
};
/* Component messages for client updates */
public static class MarkerComponentMessage extends ComponentMessage {
public String ctype = "markers";
}
public static class MarkerUpdated extends MarkerComponentMessage {
public String msg;
public double x, y, z;
public String id;
public String label;
public String icon;
public String set;
public boolean markup;
public String desc;
public String dim;
public int minzoom;
public int maxzoom;
public MarkerUpdated(Marker m, boolean deleted) {
this.id = m.getMarkerID();
this.label = Client.sanitizeHTML(m.getLabel());
this.x = m.getX();
this.y = m.getY();
this.z = m.getZ();
this.set = m.getMarkerSet().getMarkerSetID();
this.icon = m.getMarkerIcon().getMarkerIconID();
this.markup = true; // We are markup format all the time now
this.desc = Client.sanitizeHTML(m.getDescription());
this.dim = m.getMarkerIcon().getMarkerIconSize().getSize();
this.minzoom = m.getMinZoom();
this.maxzoom = m.getMaxZoom();
if(deleted)
msg = "markerdeleted";
else
msg = "markerupdated";
}
@Override
public boolean equals(Object o) {
if(o instanceof MarkerUpdated) {
MarkerUpdated m = (MarkerUpdated)o;
return m.id.equals(id) && m.set.equals(set);
}
return false;
}
@Override
public int hashCode() {
return id.hashCode() ^ set.hashCode();
}
}
public static class AreaMarkerUpdated extends MarkerComponentMessage {
public String msg;
public double ytop, ybottom;
public double[] x;
public double[] z;
public int weight;
public double opacity;
public String color;
public double fillopacity;
public String fillcolor;
public String id;
public String label;
public String set;
public String desc;
public int minzoom;
public int maxzoom;
public boolean markup;
public AreaMarkerUpdated(AreaMarker m, boolean deleted) {
this.id = m.getMarkerID();
this.label = Client.sanitizeHTML(m.getLabel());
this.ytop = m.getTopY();
this.ybottom = m.getBottomY();
int cnt = m.getCornerCount();
x = new double[cnt];
z = new double[cnt];
for(int i = 0; i < cnt; i++) {
x[i] = m.getCornerX(i);
z[i] = m.getCornerZ(i);
}
color = String.format("#%06X", m.getLineColor());
weight = m.getLineWeight();
opacity = m.getLineOpacity();
fillcolor = String.format("#%06X", m.getFillColor());
fillopacity = m.getFillOpacity();
desc = Client.sanitizeHTML(m.getDescription());
this.minzoom = m.getMinZoom();
this.maxzoom = m.getMaxZoom();
this.markup = true; // We are markup format all the time now
this.set = m.getMarkerSet().getMarkerSetID();
if(deleted)
msg = "areadeleted";
else
msg = "areaupdated";
}
@Override
public boolean equals(Object o) {
if(o instanceof AreaMarkerUpdated) {
AreaMarkerUpdated m = (AreaMarkerUpdated)o;
return m.id.equals(id) && m.set.equals(set);
}
return false;
}
@Override
public int hashCode() {
return id.hashCode() ^ set.hashCode();
}
}
public static class PolyLineMarkerUpdated extends MarkerComponentMessage {
public String msg;
public double[] x;
public double[] y;
public double[] z;
public int weight;
public double opacity;
public String color;
public String id;
public String label;
public String set;
public String desc;
public int minzoom;
public int maxzoom;
public boolean markup;
public PolyLineMarkerUpdated(PolyLineMarker m, boolean deleted) {
this.id = m.getMarkerID();
this.label = Client.sanitizeHTML(m.getLabel());
this.markup = true; // We are markup format all the time now
int cnt = m.getCornerCount();
x = new double[cnt];
y = new double[cnt];
z = new double[cnt];
for(int i = 0; i < cnt; i++) {
x[i] = m.getCornerX(i);
y[i] = m.getCornerY(i);
z[i] = m.getCornerZ(i);
}
color = String.format("#%06X", m.getLineColor());
weight = m.getLineWeight();
opacity = m.getLineOpacity();
desc = Client.sanitizeHTML(m.getDescription());
this.minzoom = m.getMinZoom();
this.maxzoom = m.getMaxZoom();
this.set = m.getMarkerSet().getMarkerSetID();
if(deleted)
msg = "linedeleted";
else
msg = "lineupdated";
}
@Override
public boolean equals(Object o) {
if(o instanceof PolyLineMarkerUpdated) {
PolyLineMarkerUpdated m = (PolyLineMarkerUpdated)o;
return m.id.equals(id) && m.set.equals(set);
}
return false;
}
@Override
public int hashCode() {
return id.hashCode() ^ set.hashCode();
}
}
public static class CircleMarkerUpdated extends MarkerComponentMessage {
public String msg;
public double x;
public double y;
public double z;
public double xr;
public double zr;
public int weight;
public double opacity;
public String color;
public double fillopacity;
public String fillcolor;
public String id;
public String label;
public String set;
public String desc;
public int minzoom;
public int maxzoom;
public boolean markup;
public CircleMarkerUpdated(CircleMarker m, boolean deleted) {
this.id = m.getMarkerID();
this.label = Client.sanitizeHTML(m.getLabel());
this.x = m.getCenterX();
this.y = m.getCenterY();
this.z = m.getCenterZ();
this.xr = m.getRadiusX();
this.zr = m.getRadiusZ();
this.markup = true; // We are markup format all the time now
color = String.format("#%06X", m.getLineColor());
weight = m.getLineWeight();
opacity = m.getLineOpacity();
fillcolor = String.format("#%06X", m.getFillColor());
fillopacity = m.getFillOpacity();
desc = Client.sanitizeHTML(m.getDescription());
this.minzoom = m.getMinZoom();
this.maxzoom = m.getMaxZoom();
this.set = m.getMarkerSet().getMarkerSetID();
if(deleted)
msg = "circledeleted";
else
msg = "circleupdated";
}
@Override
public boolean equals(Object o) {
if(o instanceof CircleMarkerUpdated) {
CircleMarkerUpdated m = (CircleMarkerUpdated)o;
return m.id.equals(id) && m.set.equals(set);
}
return false;
}
@Override
public int hashCode() {
return id.hashCode() ^ set.hashCode();
}
}
public static class MarkerSetUpdated extends MarkerComponentMessage {
public String msg;
public String id;
public String label;
public int layerprio;
public int minzoom;
public int maxzoom;
public Boolean showlabels;
public MarkerSetUpdated(MarkerSet markerset, boolean deleted) {
this.id = markerset.getMarkerSetID();
this.label = markerset.getMarkerSetLabel();
this.layerprio = markerset.getLayerPriority();
this.minzoom = markerset.getMinZoom();
this.maxzoom = markerset.getMaxZoom();
this.showlabels = markerset.getLabelShow();
if(deleted)
msg = "setdeleted";
else
msg = "setupdated";
}
@Override
public boolean equals(Object o) {
if(o instanceof MarkerSetUpdated) {
MarkerSetUpdated m = (MarkerSetUpdated)o;
return m.id.equals(id);
}
return false;
}
@Override
public int hashCode() {
return id.hashCode();
}
}
private boolean stop = false;
private ConcurrentHashMap<String, String> dirty_worlds = new ConcurrentHashMap<String, String>();
private boolean dirty_markers = false;
private class DoFileWrites implements Runnable {
public void run() {
if(stop)
return;
lock.readLock().lock();
Set<String> dirty = new HashSet<String>(dirty_worlds.keySet());
dirty_worlds.clear();
try {
/* Write markers first - drives JSON updates too */
if (dirty_markers) {
doSaveMarkers();
dirty_markers = false;
}
/* Process any dirty worlds */
if (!dirty.isEmpty()) {
for(String world : dirty) {
writeMarkersFile(world);
}
}
} finally {
lock.readLock().unlock();
}
core.getServer().scheduleServerTask(this, 20);
}
}
/**
* Singleton initializer
* @param core - core object
* @return API object
*/
public static MarkerAPIImpl initializeMarkerAPI(DynmapCore core) {
if(api != null) {
api.cleanup(core);
}
api = new MarkerAPIImpl();
api.core = core;
/* Initialize persistence file name */
api.markerpersist = new File(core.getDataFolder(), "markers.yml");
api.markerpersist_old = new File(core.getDataFolder(), "markers.yml.old");
/* Fill in default icons and sets, if needed */
for(int i = 0; i < builtin_icons.length; i++) {
String id = builtin_icons[i];
api.createBuiltinMarkerIcon(id, id);
}
/* Load persistence */
api.loadMarkers();
/* Initialize default marker set, if needed */
MarkerSet set = api.getMarkerSet(MarkerSet.DEFAULT);
if(set == null) {
set = api.createMarkerSet(MarkerSet.DEFAULT, "Markers", null, true);
}
/* Build paths for markers */
api.markerdir = new File(core.getDataFolder(), "markers");
if(api.markerdir.isDirectory() == false) {
if(api.markerdir.mkdirs() == false) { /* Create directory if needed */
Log.severe("Error creating markers directory - " + api.markerdir.getPath());
}
}
return api;
}
/**
* Singleton initializer complete (after rendder pool available
* @param core - core object
* @return API object
*/
public static void completeInitializeMarkerAPI(MarkerAPIImpl api) {
MapManager.scheduleDelayedJob(new Runnable() {
public void run() {
/* Now publish marker files to the tiles directory */
for(MarkerIcon ico : api.getMarkerIcons()) {
api.publishMarkerIcon(ico);
}
/* Freshen files */
api.freshenMarkerFiles();
/* Add listener so we update marker files for other worlds as they become active */
api.core.events.addListener("worldactivated", api);
api.scheduleWriteJob(); /* Start write job */
Log.info("Finish marker initialization");
}
}, 0);
}
/**
* Generates a map of field:value argument tab completion suggestions for every /dmarker subcommand
* This is quite long as there are a lot of arguments to deal with, and don't have Java 9 map literals
*/
private void initTabCompletions() {
//Static values
String[] emptyValue = new String[]{};
String[] booleanValue = new String[]{"true", "false"};
String[] typeValue = new String[]{"icon", "area", "line", "circle"};
Supplier<String[]> emptySupplier = () -> emptyValue;
Supplier<String[]> booleanSupplier = () -> booleanValue;
//Dynamic values
Supplier<String[]> iconSupplier = () -> markericons.keySet().toArray(new String[0]);
Supplier<String[]> markerSetSupplier = () -> markersets.keySet().toArray(new String[0]);
Supplier<String[]> worldSupplier = () ->
core.mapManager.getWorlds().stream().map(DynmapWorld::getName).toArray(String[]::new);
//Arguments used in multiple commands
Map<String, Supplier<String[]>> labelArg = Collections.singletonMap("label", emptySupplier);
Map<String, Supplier<String[]>> idArg = Collections.singletonMap("id", emptySupplier);
Map<String, Supplier<String[]>> newLabelArg = Collections.singletonMap("newlabel", emptySupplier);
Map<String, Supplier<String[]>> markerSetArg = Collections.singletonMap("set", markerSetSupplier);
Map<String, Supplier<String[]>> newSetArg = Collections.singletonMap("newset", markerSetSupplier);
Map<String, Supplier<String[]>> fileArg = Collections.singletonMap("file", emptySupplier);
//Arguments used in commands taking a location
Map<String, Supplier<String[]>> locationArgs = new LinkedHashMap<>();
locationArgs.put("x", emptySupplier);
locationArgs.put("y", emptySupplier);
locationArgs.put("z", emptySupplier);
locationArgs.put("world", worldSupplier);
//Args shared with all add/update commands
Map<String, Supplier<String[]>> sharedArgs = new LinkedHashMap<>(labelArg);
sharedArgs.putAll(idArg);
//Args shared with all add/update commands affecting objects visible on the map
Map<String, Supplier<String[]>> mapObjectArgs = new LinkedHashMap<>(sharedArgs);
mapObjectArgs.put("minzoom", emptySupplier);
mapObjectArgs.put("maxzoom", emptySupplier);
//Args for marker set add/update commands
Map<String, Supplier<String[]>> setArgs = new LinkedHashMap<>(mapObjectArgs);
setArgs.put("prio", emptySupplier);
setArgs.put("hide", booleanSupplier);
setArgs.put("showlabel", booleanSupplier);
setArgs.put("deficon", iconSupplier);
//Args for marker add/update commands
Map<String, Supplier<String[]>> markerArgs = new LinkedHashMap<>(mapObjectArgs);
markerArgs.putAll(markerSetArg);
markerArgs.put("markup", booleanSupplier);
markerArgs.put("icon", iconSupplier);
markerArgs.putAll(locationArgs);
//Args for area/line/circle add/update commands
Map<String, Supplier<String[]>> shapeArgs = new LinkedHashMap<>(mapObjectArgs);
shapeArgs.putAll(markerSetArg);
shapeArgs.put("markup", booleanSupplier);
shapeArgs.put("weight", emptySupplier);
shapeArgs.put("color", emptySupplier);
shapeArgs.put("opacity", emptySupplier);
//Args for area/circle add/update commands
Map<String, Supplier<String[]>> filledShapeArgs = new LinkedHashMap<>(shapeArgs);
filledShapeArgs.put("fillcolor", emptySupplier);
filledShapeArgs.put("fillopacity", emptySupplier);
filledShapeArgs.put("greeting", emptySupplier);
filledShapeArgs.put("greetingsub", emptySupplier);
filledShapeArgs.put("farewell", emptySupplier);
filledShapeArgs.put("farewellsub", emptySupplier);
filledShapeArgs.put("boost", booleanSupplier);
filledShapeArgs.putAll(locationArgs);
//Args for area add/update commands
Map<String, Supplier<String[]>> areaArgs = new LinkedHashMap<>(filledShapeArgs);
areaArgs.put("ytop", emptySupplier);
areaArgs.put("ybottom", emptySupplier);
//Args for circle add/update commands
Map<String, Supplier<String[]>> circleArgs = new LinkedHashMap<>(filledShapeArgs);
circleArgs.put("radius", emptySupplier);
circleArgs.put("radiusx", emptySupplier);
circleArgs.put("radiusz", emptySupplier);
//Args for icon add/update commands
Map<String, Supplier<String[]>> iconArgs = new LinkedHashMap<>(sharedArgs);
iconArgs.putAll(fileArg);
//Args for updateset command
Map<String, Supplier<String[]>> updateSetArgs = new LinkedHashMap<>(setArgs);
updateSetArgs.putAll(newLabelArg);
//Args for update (marker) command
Map<String, Supplier<String[]>> updateMarkerArgs = new LinkedHashMap<>(markerArgs);
updateMarkerArgs.putAll(newLabelArg);
updateMarkerArgs.putAll(newSetArg);
//Args for updateline command
Map<String, Supplier<String[]>> updateLineArgs = new LinkedHashMap<>(shapeArgs);
updateLineArgs.putAll(newLabelArg);
updateLineArgs.putAll(newSetArg);
//Args for updatearea command
Map<String, Supplier<String[]>> updateAreaArgs = new LinkedHashMap<>(areaArgs);
updateAreaArgs.putAll(newLabelArg);
updateAreaArgs.putAll(newSetArg);
//Args for updatecircle command
Map<String, Supplier<String[]>> updateCircleArgs = new LinkedHashMap<>(circleArgs);
updateCircleArgs.putAll(newLabelArg);
updateCircleArgs.putAll(newSetArg);
//Args for updateicon command
Map<String, Supplier<String[]>> updateIconArgs = new LinkedHashMap<>(iconArgs);
updateIconArgs.putAll(newLabelArg);
//Args for movehere command
Map<String, Supplier<String[]>> moveHereArgs = new LinkedHashMap<>(sharedArgs);
moveHereArgs.putAll(markerSetArg);
//Args for marker/area/circle/line delete commands
Map<String, Supplier<String[]>> deleteArgs = new LinkedHashMap<>(sharedArgs);
deleteArgs.putAll(markerSetArg);
//Args for label/desc commands
Map<String, Supplier<String[]>> descArgs = new LinkedHashMap<>(sharedArgs);
descArgs.putAll(markerSetArg);
descArgs.put("type", () -> typeValue);
//Args for label/desc import commands
Map<String, Supplier<String[]>> importArgs = new LinkedHashMap<>(descArgs);
importArgs.putAll(fileArg);
//Args for appendesc command
Map<String, Supplier<String[]>> appendArgs = new LinkedHashMap<>(descArgs);
appendArgs.put("desc", emptySupplier);
tabCompletions = new HashMap<>();
tabCompletions.put("add", markerArgs);
tabCompletions.put("addicon", iconArgs);
tabCompletions.put("addarea", areaArgs);
tabCompletions.put("addline", shapeArgs); //No unique args
tabCompletions.put("addcircle", circleArgs);
tabCompletions.put("addset", setArgs);
tabCompletions.put("update", updateMarkerArgs);
tabCompletions.put("updateicon", updateIconArgs);
tabCompletions.put("updatearea", updateAreaArgs);
tabCompletions.put("updateline", updateLineArgs);
tabCompletions.put("updatecircle", updateCircleArgs);
tabCompletions.put("updateset", updateSetArgs);
tabCompletions.put("movehere", moveHereArgs);
tabCompletions.put("delete", deleteArgs);
tabCompletions.put("deleteicon", sharedArgs); //Doesn't have set: arg
tabCompletions.put("deletearea", deleteArgs);
tabCompletions.put("deleteline", deleteArgs);
tabCompletions.put("deletecircle", deleteArgs);
tabCompletions.put("deleteset", sharedArgs); //Doesn't have set: arg
tabCompletions.put("list", markerSetArg);
tabCompletions.put("listareas", markerSetArg);
tabCompletions.put("listlines", markerSetArg);
tabCompletions.put("listcircles", markerSetArg);
tabCompletions.put("getdesc", descArgs);
tabCompletions.put("importdesc", importArgs);
tabCompletions.put("resetdesc", descArgs);
tabCompletions.put("getlabel", descArgs);
tabCompletions.put("importlabel", importArgs);
tabCompletions.put("appenddesc", appendArgs);
}
public void scheduleWriteJob() {
core.getServer().scheduleServerTask(new DoFileWrites(), 20);
}
/**
* Cleanup
* @param plugin - core object
*/
public void cleanup(DynmapCore plugin) {
plugin.events.removeListener("worldactivated", api);
stop = true;
lock.readLock().lock();
try {
if(dirty_markers) {
doSaveMarkers();
dirty_markers = false;
}
} finally {
lock.readLock().unlock();
}
lock.writeLock().lock();
try {
for(MarkerIconImpl icn : markericons.values())
icn.cleanup();
markericons.clear();
for(MarkerSetImpl set : markersets.values())
set.cleanup();
markersets.clear();
} finally {
lock.writeLock().unlock();
}
}
private MarkerIcon createBuiltinMarkerIcon(String id, String label) {
if(markericons.containsKey(id)) return null; /* Exists? */
MarkerIconImpl ico = new MarkerIconImpl(id, label, true);
markericons.put(id, ico); /* Add to set */
return ico;
}
void publishMarkerIcon(MarkerIcon ico) {
byte[] buf = new byte[512];
InputStream in = null;
File infile = new File(markerdir, ico.getMarkerIconID() + ".png"); /* Get source file name */
BufferedImage im = null;
if(ico.isBuiltIn()) {
in = getClass().getResourceAsStream("/markers/" + ico.getMarkerIconID() + ".png");
}
else if(infile.canRead()) { /* If it exists and is readable */
try {
im = ImageIO.read(infile);
} catch (IOException e) {
} catch (IndexOutOfBoundsException e) {
}
if(im != null) {
MarkerIconImpl icon = (MarkerIconImpl)ico;
int w = im.getWidth(); /* Get width */
if(w <= 8) { /* Small size? */
icon.setMarkerIconSize(MarkerSize.MARKER_8x8);
}
else if(w > 16) {
icon.setMarkerIconSize(MarkerSize.MARKER_32x32);
}
else {
icon.setMarkerIconSize(MarkerSize.MARKER_16x16);
}
im.flush();
}
try {
in = new FileInputStream(infile);
} catch (IOException iox) {
Log.severe("Error opening marker " + infile.getPath() + " - " + iox);
}
}
if(in == null) { /* Not found, use default marker */
in = getClass().getResourceAsStream("/markers/marker.png");
if(in == null) {
return;
}
}
/* Copy to destination */
try {
BufferOutputStream bos = new BufferOutputStream();
int len;
while((len = in.read(buf)) > 0) {
bos.write(buf, 0, len);
}
core.getDefaultMapStorage().setMarkerImage(ico.getMarkerIconID(), bos);
} catch (IOException iox) {
Log.severe("Error writing marker to tilespath");
} finally {
if(in != null) try { in.close(); } catch (IOException x){}
}
}
@Override
public Set<MarkerSet> getMarkerSets() {
return new HashSet<MarkerSet>(markersets.values());
}
@Override
public MarkerSet getMarkerSet(String id) {
return markersets.get(id);
}
@Override
public MarkerSet createMarkerSet(String id, String lbl, Set<MarkerIcon> iconlimit, boolean persistent) {
if(markersets.containsKey(id)) return null; /* Exists? */
MarkerSetImpl set = new MarkerSetImpl(id, lbl, iconlimit, persistent);
markersets.put(id, set); /* Add to list */
if(persistent) {
saveMarkers();
}
markerSetUpdated(set, MarkerUpdate.CREATED); /* Notify update */
return set;
}
@Override
public Set<MarkerIcon> getMarkerIcons() {
return new HashSet<MarkerIcon>(markericons.values());
}
@Override
public MarkerIcon getMarkerIcon(String id) {
return markericons.get(id);
}
boolean loadMarkerIconStream(String id, InputStream in) {
/* Copy icon resource into marker directory */
File f = new File(markerdir, id + ".png");
FileOutputStream fos = null;
try {
byte[] buf = new byte[512];
int len;
fos = new FileOutputStream(f);
while((len = in.read(buf)) > 0) {
fos.write(buf, 0, len);
}
} catch (IOException iox) {
Log.severe("Error copying marker - " + f.getPath());
return false;
} finally {
if(fos != null) try { fos.close(); } catch (IOException x) {}
}
return true;
}
@Override
public MarkerIcon createMarkerIcon(String id, String label, InputStream marker_png) {
if(markericons.containsKey(id)) return null; /* Exists? */
MarkerIconImpl ico = new MarkerIconImpl(id, label, false);
/* Copy icon resource into marker directory */
if(!loadMarkerIconStream(id, marker_png))
return null;
markericons.put(id, ico); /* Add to set */
/* Publish the marker */
publishMarkerIcon(ico);
saveMarkers(); /* Save results */
return ico;
}
static MarkerIconImpl getMarkerIconImpl(String id) {
if(api != null) {
return api.markericons.get(id);
}
return null;
}
@Override
public Set<PlayerSet> getPlayerSets() {
return new HashSet<PlayerSet>(playersets.values());
}
@Override
public PlayerSet getPlayerSet(String id) {
return playersets.get(id);
}
@Override
public PlayerSet createPlayerSet(String id, boolean symmetric, Set<String> players, boolean persistent) {
if(playersets.containsKey(id)) return null; /* Exists? */
PlayerSetImpl set = new PlayerSetImpl(id, symmetric, players, persistent);
playersets.put(id, set); /* Add to list */
if(persistent) {
saveMarkers();
}
playerSetUpdated(set, MarkerUpdate.CREATED); /* Notify update */
return set;
}
/**
* Save persistence for markers
*/
static void saveMarkers() {
if(api != null) {
api.dirty_markers = true;
}
}
private void doSaveMarkers() {
if(api != null) {
final ConfigurationNode conf = new ConfigurationNode(api.markerpersist); /* Make configuration object */
/* First, save icon definitions */
HashMap<String, Object> icons = new HashMap<String,Object>();
for(String id : api.markericons.keySet()) {
MarkerIconImpl ico = api.markericons.get(id);
Map<String,Object> dat = ico.getPersistentData();
if(dat != null) {
icons.put(id, dat);
}
}
conf.put("icons", icons);
/* Then, save persistent sets */
HashMap<String, Object> sets = new HashMap<String, Object>();
for(String id : api.markersets.keySet()) {
MarkerSetImpl set = api.markersets.get(id);
if(set.isMarkerSetPersistent()) {
Map<String, Object> dat = set.getPersistentData();
if(dat != null) {
sets.put(id, dat);
}
}
}
conf.put("sets", sets);
/* Then, save persistent player sets */
HashMap<String, Object> psets = new HashMap<String, Object>();
for(String id : api.playersets.keySet()) {
PlayerSetImpl set = api.playersets.get(id);
if(set.isPersistentSet()) {
Map<String, Object> dat = set.getPersistentData();
if(dat != null) {
psets.put(id, dat);
}
}
}
conf.put("playersets", psets);
MapManager.scheduleDelayedJob(new Runnable() {
public void run() {
/* And shift old file file out */
if(api.markerpersist_old.exists()) api.markerpersist_old.delete();
if(api.markerpersist.exists()) api.markerpersist.renameTo(api.markerpersist_old);
/* And write it out */
if(!conf.save())
Log.severe("Error writing markers - " + api.markerpersist.getPath());
}
}, 0);
/* Refresh JSON files */
api.freshenMarkerFiles();
}
}
private void freshenMarkerFiles() {
if(MapManager.mapman != null) {
for(DynmapWorld w : MapManager.mapman.worlds) {
dirty_worlds.put(w.getName(),"");
}
}
}
/**
* Load persistence
*/
private boolean loadMarkers() {
ConfigurationNode conf = new ConfigurationNode(api.markerpersist); /* Make configuration object */
conf.load(); /* Load persistence */
lock.writeLock().lock();
try {
/* Get icons */
ConfigurationNode icons = conf.getNode("icons");
if(icons == null) return false;
for(String id : icons.keySet()) {
MarkerIconImpl ico = new MarkerIconImpl(id);
if(ico.loadPersistentData(icons.getNode(id))) {
markericons.put(id, ico);
}
}
/* Get marker sets */
ConfigurationNode sets = conf.getNode("sets");
if(sets != null) {
for(String id: sets.keySet()) {
MarkerSetImpl set = new MarkerSetImpl(id);
if(set.loadPersistentData(sets.getNode(id))) {
markersets.put(id, set);
}
}
}
/* Get player sets */
ConfigurationNode psets = conf.getNode("playersets");
if(psets != null) {
for(String id: psets.keySet()) {
PlayerSetImpl set = new PlayerSetImpl(id);
if(set.loadPersistentData(sets.getNode(id))) {
playersets.put(id, set);
}
}
}
} finally {
lock.writeLock().unlock();
}
return true;
}
enum MarkerUpdate { CREATED, UPDATED, DELETED };
/**
* Signal marker update
* @param marker - updated marker
* @param update - type of update
*/
static void markerUpdated(MarkerImpl marker, MarkerUpdate update) {
/* Freshen marker file for the world for this marker */
if(api != null)
api.dirty_worlds.put(marker.getNormalizedWorld(),"");
/* Enqueue client update */
if(MapManager.mapman != null)
MapManager.mapman.pushUpdate(marker.getNormalizedWorld(), new MarkerUpdated(marker, update == MarkerUpdate.DELETED));
}
/**
* Signal area marker update
* @param marker - updated marker
* @param update - type of update
*/
static void areaMarkerUpdated(AreaMarkerImpl marker, MarkerUpdate update) {
/* Freshen marker file for the world for this marker */
if(api != null)
api.dirty_worlds.put(marker.getNormalizedWorld(),"");
/* Enqueue client update */
if(MapManager.mapman != null)
MapManager.mapman.pushUpdate(marker.getNormalizedWorld(), new AreaMarkerUpdated(marker, update == MarkerUpdate.DELETED));
}
/**
* Signal poly-line marker update
* @param marker - updated marker
* @param update - type of update
*/
static void polyLineMarkerUpdated(PolyLineMarkerImpl marker, MarkerUpdate update) {
/* Freshen marker file for the world for this marker */
if(api != null)
api.dirty_worlds.put(marker.getNormalizedWorld(),"");
/* Enqueue client update */
if(MapManager.mapman != null)
MapManager.mapman.pushUpdate(marker.getNormalizedWorld(), new PolyLineMarkerUpdated(marker, update == MarkerUpdate.DELETED));
}
/**
* Signal circle marker update
* @param marker - updated marker
* @param update - type of update
*/
static void circleMarkerUpdated(CircleMarkerImpl marker, MarkerUpdate update) {
/* Freshen marker file for the world for this marker */
if(api != null)
api.dirty_worlds.put(marker.getNormalizedWorld(),"");
/* Enqueue client update */
if(MapManager.mapman != null)
MapManager.mapman.pushUpdate(marker.getNormalizedWorld(), new CircleMarkerUpdated(marker, update == MarkerUpdate.DELETED));
}
/**
* Signal marker set update
* @param markerset - updated marker set
* @param update - type of update
*/
static void markerSetUpdated(MarkerSetImpl markerset, MarkerUpdate update) {
/* Freshen all marker files */
if(api != null)
api.freshenMarkerFiles();
/* Enqueue client update */
if(MapManager.mapman != null)
MapManager.mapman.pushUpdate(new MarkerSetUpdated(markerset, update == MarkerUpdate.DELETED));
}
/**
* Signal player set update
* @param playerset - updated player set
* @param update - type of update
*/
static void playerSetUpdated(PlayerSetImpl pset, MarkerUpdate update) {
if(api != null)
api.core.events.trigger("playersetupdated", null);
}
/**
* Remove marker set
*/
static void removeMarkerSet(MarkerSetImpl markerset) {
if(api != null) {
api.markersets.remove(markerset.getMarkerSetID()); /* Remove set from list */
if(markerset.isMarkerSetPersistent()) { /* If persistent */
MarkerAPIImpl.saveMarkers(); /* Drive save */
}
markerSetUpdated(markerset, MarkerUpdate.DELETED); /* Signal delete of set */
}
}
/**
* Remove player set
*/
static void removePlayerSet(PlayerSetImpl pset) {
if(api != null) {
api.playersets.remove(pset.getSetID()); /* Remove set from list */
if(pset.isPersistentSet()) { /* If persistent */
MarkerAPIImpl.saveMarkers(); /* Drive save */
}
playerSetUpdated(pset, MarkerUpdate.DELETED); /* Signal delete of set */
}
}
private static boolean processAreaArgs(DynmapCommandSender sender, AreaMarker marker, Map<String,String> parms) {
String val = null;
String val2 = null;
try {
double ytop = marker.getTopY();
double ybottom = marker.getBottomY();
int scolor = marker.getLineColor();
int fcolor = marker.getFillColor();
double sopacity = marker.getLineOpacity();
double fopacity = marker.getFillOpacity();
int sweight = marker.getLineWeight();
boolean boost = marker.getBoostFlag();
int minzoom = marker.getMinZoom();
int maxzoom = marker.getMaxZoom();
EnterExitText greet = marker.getGreetingText();
EnterExitText farew = marker.getFarewellText();
val = parms.get(ARG_STROKECOLOR);
if(val != null)
scolor = Integer.parseInt(val, 16);
val = parms.get(ARG_FILLCOLOR);
if(val != null)
fcolor = Integer.parseInt(val, 16);
val = parms.get(ARG_STROKEOPACITY);
if(val != null)
sopacity = Double.parseDouble(val);
val = parms.get(ARG_FILLOPACITY);
if(val != null)
fopacity = Double.parseDouble(val);
val = parms.get(ARG_STROKEWEIGHT);
if(val != null)
sweight = Integer.parseInt(val);
val = parms.get(ARG_YTOP);
if(val != null)
ytop = Double.parseDouble(val);
val = parms.get(ARG_YBOTTOM);
if(val != null)
ybottom = Double.parseDouble(val);
val = parms.get(ARG_MINZOOM);
if (val != null)
minzoom = Integer.parseInt(val);
val = parms.get(ARG_MAXZOOM);
if (val != null)
maxzoom = Integer.parseInt(val);
val = parms.get(ARG_BOOST);
if(val != null) {
if(api.core.checkPlayerPermission(sender, "marker.boost")) {
boost = val.equals("true");
}
else {
sender.sendMessage("No permission to set boost flag");
return false;
}
}
marker.setLineStyle(sweight, sopacity, scolor);
marker.setFillStyle(fopacity, fcolor);
if(ytop >= ybottom)
marker.setRangeY(ytop, ybottom);
else
marker.setRangeY(ybottom, ytop);
marker.setBoostFlag(boost);
marker.setMinZoom(minzoom);
marker.setMaxZoom(maxzoom);
// Handle greeting
val = parms.get(ARG_GREETING);
val2 = parms.get(ARG_GREETINGSUB);
if ((val != null) || (val2 != null)) {
String title = (val != null) ? ((val.length() > 0) ? val : null) : ((greet != null) ? greet.title : null);
String subtitle = (val2 != null) ? ((val2.length() > 0) ? val2 : null) : ((greet != null) ? greet.subtitle : null);
marker.setGreetingText(title, subtitle);
}
// Handle farewell
val = parms.get(ARG_FAREWELL);
val2 = parms.get(ARG_FAREWELLSUB);
if ((val != null) || (val2 != null)) {
String title = (val != null) ? ((val.length() > 0) ? val : null) : ((farew != null) ? farew.title : null);
String subtitle = (val2 != null) ? ((val2.length() > 0) ? val2 : null) : ((farew != null) ? farew.subtitle : null);
marker.setFarewellText(title, subtitle);
}
} catch (NumberFormatException nfx) {
sender.sendMessage("Invalid parameter format: " + val);
return false;
}
return true;
}
private static boolean processPolyArgs(DynmapCommandSender sender, PolyLineMarker marker, Map<String,String> parms) {
String val = null;
try {
int scolor = marker.getLineColor();
double sopacity = marker.getLineOpacity();
int sweight = marker.getLineWeight();
int minzoom = marker.getMinZoom();
int maxzoom = marker.getMaxZoom();
val = parms.get(ARG_STROKECOLOR);
if(val != null)
scolor = Integer.parseInt(val, 16);
val = parms.get(ARG_STROKEOPACITY);
if(val != null)
sopacity = Double.parseDouble(val);
val = parms.get(ARG_STROKEWEIGHT);
if(val != null)
sweight = Integer.parseInt(val);
val = parms.get(ARG_MINZOOM);
if(val != null)
minzoom = Integer.parseInt(val);
val = parms.get(ARG_MAXZOOM);
if(val != null)
maxzoom = Integer.parseInt(val);
marker.setLineStyle(sweight, sopacity, scolor);
marker.setMinZoom(minzoom);
marker.setMaxZoom(maxzoom);
} catch (NumberFormatException nfx) {
sender.sendMessage("Invalid parameter format: " + val);
return false;
}
return true;
}
private static boolean processCircleArgs(DynmapCommandSender sender, CircleMarker marker, Map<String,String> parms) {
String val = null, val2 = null;
try {
int scolor = marker.getLineColor();
int fcolor = marker.getFillColor();
double sopacity = marker.getLineOpacity();
double fopacity = marker.getFillOpacity();
int sweight = marker.getLineWeight();
double xr = marker.getRadiusX();
double zr = marker.getRadiusZ();
double x = marker.getCenterX();
double y = marker.getCenterY();
double z = marker.getCenterZ();
String world = marker.getWorld();
boolean boost = marker.getBoostFlag();
int minzoom = marker.getMinZoom();
int maxzoom = marker.getMaxZoom();
EnterExitText greet = marker.getGreetingText();
EnterExitText farew = marker.getFarewellText();
val = parms.get(ARG_STROKECOLOR);
if(val != null)
scolor = Integer.parseInt(val, 16);
val = parms.get(ARG_FILLCOLOR);
if(val != null)
fcolor = Integer.parseInt(val, 16);
val = parms.get(ARG_STROKEOPACITY);
if(val != null)
sopacity = Double.parseDouble(val);
val = parms.get(ARG_FILLOPACITY);
if(val != null)
fopacity = Double.parseDouble(val);
val = parms.get(ARG_STROKEWEIGHT);
if(val != null)
sweight = Integer.parseInt(val);
val = parms.get(ARG_X);
if(val != null)
x = Double.parseDouble(val);
val = parms.get(ARG_Y);
if(val != null)
y = Double.parseDouble(val);
val = parms.get(ARG_Z);
if(val != null)
z = Double.parseDouble(val);
val = parms.get(ARG_WORLD);
if(val != null)
world = val;
val = parms.get(ARG_RADIUSX);
if(val != null)
xr = Double.parseDouble(val);
val = parms.get(ARG_RADIUSZ);
if(val != null)
zr = Double.parseDouble(val);
val = parms.get(ARG_RADIUS);
if(val != null)
xr = zr = Double.parseDouble(val);
val = parms.get(ARG_BOOST);
if(val != null) {
if(api.core.checkPlayerPermission(sender, "marker.boost")) {
boost = val.equals("true");
}
else {
sender.sendMessage("No permission to set boost flag");
return false;
}
}
val = parms.get(ARG_MINZOOM);
if (val != null) {
minzoom = Integer.parseInt(val);
}
val = parms.get(ARG_MAXZOOM);
if (val != null) {
maxzoom = Integer.parseInt(val);
}
marker.setCenter(world, x, y, z);
marker.setLineStyle(sweight, sopacity, scolor);
marker.setFillStyle(fopacity, fcolor);
marker.setRadius(xr, zr);
marker.setBoostFlag(boost);
marker.setMinZoom(minzoom);
marker.setMaxZoom(maxzoom);
// Handle greeting
val = parms.get(ARG_GREETING);
val2 = parms.get(ARG_GREETINGSUB);
if ((val != null) || (val2 != null)) {
String title = (val != null) ? ((val.length() > 0) ? val : null) : ((greet != null) ? greet.title : null);
String subtitle = (val2 != null) ? ((val2.length() > 0) ? val2 : null) : ((greet != null) ? greet.subtitle : null);
marker.setGreetingText(title, subtitle);
}
// Handle farewell
val = parms.get(ARG_FAREWELL);
val2 = parms.get(ARG_FAREWELLSUB);
if ((val != null) || (val2 != null)) {
String title = (val != null) ? ((val.length() > 0) ? val : null) : ((farew != null) ? farew.title : null);
String subtitle = (val2 != null) ? ((val2.length() > 0) ? val2 : null) : ((farew != null) ? farew.subtitle : null);
marker.setFarewellText(title, subtitle);
}
} catch (NumberFormatException nfx) {
sender.sendMessage("Invalid parameter format: " + val);
return false;
}
return true;
}
private static final Set<String> commands = new HashSet<String>(Arrays.asList(new String[] {
"add", "movehere", "update", "delete", "list", "icons", "addset", "updateset", "deleteset", "listsets", "addicon", "updateicon",
"deleteicon", "addcorner", "clearcorners", "addarea", "listareas", "deletearea", "updatearea",
"addline", "listlines", "deleteline", "updateline", "addcircle", "listcircles", "deletecircle", "updatecircle",
"getdesc", "resetdesc", "appenddesc", "importdesc", "getlabel", "importlabel"
}));
private static final String ARG_LABEL = "label";
private static final String ARG_MARKUP = "markup";
private static final String ARG_ID = "id";
private static final String ARG_TYPE = "type";
private static final String ARG_NEWLABEL = "newlabel";
private static final String ARG_FILE = "file";
private static final String ARG_HIDE = "hide";
private static final String ARG_ICON = "icon";
private static final String ARG_DEFICON = "deficon";
private static final String ARG_SET = "set";
private static final String ARG_NEWSET = "newset";
private static final String ARG_PRIO = "prio";
private static final String ARG_MINZOOM = "minzoom";
private static final String ARG_MAXZOOM = "maxzoom";
private static final String ARG_STROKEWEIGHT = "weight";
private static final String ARG_STROKECOLOR = "color";
private static final String ARG_STROKEOPACITY = "opacity";
private static final String ARG_FILLCOLOR = "fillcolor";
private static final String ARG_FILLOPACITY = "fillopacity";
private static final String ARG_YTOP = "ytop";
private static final String ARG_YBOTTOM = "ybottom";
private static final String ARG_RADIUSX = "radiusx";
private static final String ARG_RADIUSZ = "radiusz";
private static final String ARG_RADIUS = "radius";
private static final String ARG_SHOWLABEL = "showlabels";
private static final String ARG_X = "x";
private static final String ARG_Y = "y";
private static final String ARG_Z = "z";
private static final String ARG_WORLD = "world";
private static final String ARG_BOOST = "boost";
private static final String ARG_DESC = "desc";
private static final String ARG_GREETING = "greeting";
private static final String ARG_GREETINGSUB = "greetingsub";
private static final String ARG_FAREWELL = "farewell";
private static final String ARG_FAREWELLSUB = "farewellsub";
/* Parse argument strings : handle 'attrib:value' and quoted strings */
private static Map<String,String> parseArgs(String[] args, DynmapCommandSender snd) {
HashMap<String,String> rslt = new HashMap<String,String>();
/* Build command line, so we can parse our way - make sure there is trailing space */
String cmdline = "";
for(int i = 1; i < args.length; i++) {
cmdline += args[i] + " ";
}
boolean inquote = false;
StringBuilder sb = new StringBuilder();
String varid = null;
for(int i = 0; i < cmdline.length(); i++) {
char c = cmdline.charAt(i);
if(inquote) { /* If in quote, accumulate until end or another quote */
if(c == '\"') { /* End quote */
inquote = false;
if(varid == null) { /* No varid? */
rslt.put(ARG_LABEL, sb.toString());
}
else {
rslt.put(varid, sb.toString());
varid = null;
}
sb.setLength(0);
}
else {
sb.append(c);
}
}
else if(c == '\"') { /* Start of quote? */
inquote = true;
}
else if(c == ':') { /* var:value */
varid = sb.toString(); /* Save variable ID */
sb.setLength(0);
}
else if(c == ' ') { /* Ending space? */
if(varid == null) { /* No varid? */
if(sb.length() > 0) {
rslt.put(ARG_LABEL, sb.toString());
}
}
else {
rslt.put(varid, sb.toString());
varid = null;
}
sb.setLength(0);
}
else {
sb.append(c);
}
}
if(inquote) { /* If still in quote, syntax error */
snd.sendMessage("Error: unclosed doublequote");
return null;
}
return rslt;
}
public static boolean onCommand(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
if(api == null) {
sender.sendMessage("Markers component is not enabled.");
return false;
}
if(args.length == 0)
return false;
DynmapPlayer player = null;
if (sender instanceof DynmapPlayer)
player = (DynmapPlayer) sender;
/* Check if valid command */
String c = args[0];
if (!commands.contains(c)) {
return false;
}
/* Process commands read commands */
api.lock.readLock().lock();
try {
/* List markers */
if(c.equals("list") && plugin.checkPlayerPermission(sender, "marker.list")) {
return processListMarker(plugin, sender, cmd, commandLabel, args);
}
/* List icons */
else if(c.equals("icons") && plugin.checkPlayerPermission(sender, "marker.icons")) {
return processListIcon(plugin, sender, cmd, commandLabel, args);
}
/* List sets */
else if(c.equals("listsets") && plugin.checkPlayerPermission(sender, "marker.listsets")) {
return processListSet(plugin, sender, cmd, commandLabel, args);
}
/* List areas */
else if(c.equals("listareas") && plugin.checkPlayerPermission(sender, "marker.listareas")) {
return processListArea(plugin, sender, cmd, commandLabel, args);
}
/* List poly-lines */
else if(c.equals("listlines") && plugin.checkPlayerPermission(sender, "marker.listlines")) {
return processListLine(plugin, sender, cmd, commandLabel, args);
}
/* List circles */
else if(c.equals("listcircles") && plugin.checkPlayerPermission(sender, "marker.listcircles")) {
return processListCircle(plugin, sender, cmd, commandLabel, args);
}
/* Get label for given item - must have ID and type parameter */
else if(c.equals("getlabel") && plugin.checkPlayerPermission(sender, "marker.getlabel")) {
return processGetLabel(plugin, sender, cmd, commandLabel, args);
}
} finally {
api.lock.readLock().unlock();
}
// Handle modify commands
api.lock.writeLock().lock();
try {
if(c.equals("add") && api.core.checkPlayerPermission(sender, "marker.add")) {
return processAddMarker(plugin, sender, cmd, commandLabel, args, player);
}
/* Update position of bookmark - must have ID parameter */
else if(c.equals("movehere") && plugin.checkPlayerPermission(sender, "marker.movehere")) {
return processMoveHere(plugin, sender, cmd, commandLabel, args, player);
}
/* Update other attributes of marker - must have ID parameter */
else if(c.equals("update") && plugin.checkPlayerPermission(sender, "marker.update")) {
return processUpdateMarker(plugin, sender, cmd, commandLabel, args);
}
/* Delete marker - must have ID parameter */
else if(c.equals("delete") && plugin.checkPlayerPermission(sender, "marker.delete")) {
return processDeleteMarker(plugin, sender, cmd, commandLabel, args);
}
else if(c.equals("addset") && plugin.checkPlayerPermission(sender, "marker.addset")) {
return processAddSet(plugin, sender, cmd, commandLabel, args, player);
}
else if(c.equals("updateset") && plugin.checkPlayerPermission(sender, "marker.updateset")) {
return processUpdateSet(plugin, sender, cmd, commandLabel, args);
}
else if(c.equals("deleteset") && plugin.checkPlayerPermission(sender, "marker.deleteset")) {
return processDeleteSet(plugin, sender, cmd, commandLabel, args);
}
/* Add new icon */
else if(c.equals("addicon") && plugin.checkPlayerPermission(sender, "marker.addicon")) {
return processAddIcon(plugin, sender, cmd, commandLabel, args);
}
else if(c.equals("updateicon") && plugin.checkPlayerPermission(sender, "marker.updateicon")) {
return processUpdateIcon(plugin, sender, cmd, commandLabel, args);
}
else if(c.equals("deleteicon") && plugin.checkPlayerPermission(sender, "marker.deleteicon")) {
return processDeleteIcon(plugin, sender, cmd, commandLabel, args);
}
/* Add point to accumulator */
else if(c.equals("addcorner") && plugin.checkPlayerPermission(sender, "marker.addarea")) {
return processAddCorner(plugin, sender, cmd, commandLabel, args, player);
}
else if(c.equals("clearcorners") && plugin.checkPlayerPermission(sender, "marker.addarea")) {
return processClearCorners(plugin, sender, cmd, commandLabel, args, player);
}
else if(c.equals("addarea") && plugin.checkPlayerPermission(sender, "marker.addarea")) {
return processAddArea(plugin, sender, cmd, commandLabel, args, player);
}
/* Delete area - must have ID parameter */
else if(c.equals("deletearea") && plugin.checkPlayerPermission(sender, "marker.deletearea")) {
return processDeleteArea(plugin, sender, cmd, commandLabel, args);
}
/* Update other attributes of area - must have ID parameter */
else if(c.equals("updatearea") && plugin.checkPlayerPermission(sender, "marker.updatearea")) {
return processUpdateArea(plugin, sender, cmd, commandLabel, args);
}
else if(c.equals("addline") && plugin.checkPlayerPermission(sender, "marker.addline")) {
return processAddLine(plugin, sender, cmd, commandLabel, args, player);
}
/* Delete poly-line - must have ID parameter */
else if(c.equals("deleteline") && plugin.checkPlayerPermission(sender, "marker.deleteline")) {
return processDeleteLine(plugin, sender, cmd, commandLabel, args);
}
/* Update other attributes of poly-line - must have ID parameter */
else if(c.equals("updateline") && plugin.checkPlayerPermission(sender, "marker.updateline")) {
return processUpdateLine(plugin, sender, cmd, commandLabel, args);
}
else if(c.equals("addcircle") && plugin.checkPlayerPermission(sender, "marker.addcircle")) {
return processAddCircle(plugin, sender, cmd, commandLabel, args, player);
}
/* Delete circle - must have ID parameter */
else if(c.equals("deletecircle") && plugin.checkPlayerPermission(sender, "marker.deletecircle")) {
return processDeleteCircle(plugin, sender, cmd, commandLabel, args);
}
/* Update other attributes of circle - must have ID parameter */
else if(c.equals("updatecircle") && plugin.checkPlayerPermission(sender, "marker.updatecircle")) {
return processUpdateCircle(plugin, sender, cmd, commandLabel, args);
}
/* Get description for given item - must have ID and type parameter */
else if(c.equals("getdesc") && plugin.checkPlayerPermission(sender, "marker.getdesc")) {
return processGetDesc(plugin, sender, cmd, commandLabel, args);
}
/* Reset description for given item - must have ID and type parameter */
else if(c.equals("resetdesc") && plugin.checkPlayerPermission(sender, "marker.resetdesc")) {
return processResetDesc(plugin, sender, cmd, commandLabel, args);
}
/* Append to description for given item - must have ID and type parameter */
else if(c.equals("appenddesc") && plugin.checkPlayerPermission(sender, "marker.appenddesc")) {
return processAppendDesc(plugin, sender, cmd, commandLabel, args);
}
/* Import description for given item from file - must have ID and type parameter */
else if(c.equals("importdesc") && plugin.checkPlayerPermission(sender, "marker.importdesc")) {
return processImportDesc(plugin, sender, cmd, commandLabel, args);
}
/* Import description for given item from file - must have ID and type parameter */
else if(c.equals("importlabel") && plugin.checkPlayerPermission(sender, "marker.importlabel")) {
return processImportLabel(plugin, sender, cmd, commandLabel, args);
}
else {
return false;
}
} finally {
api.lock.writeLock().unlock();
}
}
public List<String> getTabCompletions(DynmapCommandSender sender, String[] args, DynmapCore core) {
/* Re-parse args - handle doublequotes */
args = DynmapCore.parseArgs(args, sender, true);
if (args == null || args.length <= 1) {
return Collections.emptyList();
}
if (tabCompletions == null) {
initTabCompletions();
}
String cmd = args[0];
if (cmd.equals("addcorner") && core.checkPlayerPermission(sender, "marker.addarea")) {
if (args.length == 5) {
return core.getWorldSuggestions(args[4]);
}
} else if (core.checkPlayerPermission(sender, "marker." + cmd)
&& tabCompletions.containsKey(cmd)) {
return core.getFieldValueSuggestions(args, tabCompletions.get(cmd));
}
return Collections.emptyList();
}
private static boolean processAddMarker(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args, DynmapPlayer player) {
String id, setid, label, iconid, markup;
String x, y, z, world, normalized_world;
if(args.length > 1) {
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
iconid = parms.get(ARG_ICON);
setid = parms.get(ARG_SET);
id = parms.get(ARG_ID);
label = parms.get(ARG_LABEL);
markup = parms.get(ARG_MARKUP);
x = parms.get(ARG_X);
y = parms.get(ARG_Y);
z = parms.get(ARG_Z);
String minzoom = parms.get(ARG_MINZOOM);
int min_zoom = -1;
if (minzoom != null) {
try {
min_zoom = Integer.parseInt(minzoom);
} catch (NumberFormatException nfx) {
sender.sendMessage("Invalid minzoom: " + minzoom);
return true;
}
}
String maxzoom = parms.get(ARG_MAXZOOM);
int max_zoom = -1;
if (maxzoom != null) {
try {
max_zoom = Integer.parseInt(maxzoom);
} catch (NumberFormatException nfx) {
sender.sendMessage("Invalid maxzoom: " + maxzoom);
return true;
}
}
world = DynmapWorld.normalizeWorldName(parms.get(ARG_WORLD));
if(world != null) {
normalized_world = DynmapWorld.normalizeWorldName(world);
if(api.core.getWorld(normalized_world) == null) {
sender.sendMessage("Invalid world ID: " + world);
return true;
}
}
DynmapLocation loc = null;
if((x == null) && (y == null) && (z == null) && (world == null)) {
if(player == null) {
sender.sendMessage("Must be issued by player, or x, y, z, and world parameters are required");
return true;
}
loc = player.getLocation();
}
else if((x != null) && (y != null) && (z != null) && (world != null)) {
try {
loc = new DynmapLocation(world, Double.valueOf(x), Double.valueOf(y), Double.valueOf(z));
} catch (NumberFormatException nfx) {
sender.sendMessage("Coordinates x, y, and z must be numbers");
return true;
}
}
else {
sender.sendMessage("Must be issued by player, or x, y, z, and world parameters are required");
return true;
}
/* Fill in defaults for missing parameters */
if(setid == null) {
setid = MarkerSet.DEFAULT;
}
/* Add new marker */
MarkerSet set = api.getMarkerSet(setid);
if(set == null) {
sender.sendMessage("Error: invalid set - " + setid);
return true;
}
// Prevent adding persistent markers to a non-persistent set
if (!set.isMarkerSetPersistent()) {
sender.sendMessage("Error: cannot add to non-persistent marker set - set is likely plugin owned");
return true;
}
MarkerIcon ico = null;
if(iconid == null) {
ico = set.getDefaultMarkerIcon();
}
if(ico == null) {
if(iconid == null) {
iconid = MarkerIcon.DEFAULT;
}
ico = api.getMarkerIcon(iconid);
}
if(ico == null) {
sender.sendMessage("Error: invalid icon - " + iconid);
return true;
}
if (minzoom != null) {
}
boolean isMarkup = "true".equals(markup);
Marker m = set.createMarker(id, label, isMarkup,
loc.world, loc.x, loc.y, loc.z, ico, true);
if(m == null) {
sender.sendMessage("Error creating marker");
}
else {
if (min_zoom >= 0) {
m.setMinZoom(min_zoom);
}
if (max_zoom >= 0) {
m.setMaxZoom(max_zoom);
}
sender.sendMessage("Added marker id:'" + m.getMarkerID() + "' (" + m.getLabel() + ") to set '" + set.getMarkerSetID() + "'");
}
}
else {
sender.sendMessage("Marker label required");
}
return true;
}
private static boolean processMoveHere(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args, DynmapPlayer player) {
String id, label, setid;
if(player == null) {
sender.sendMessage("Command can only be used by player");
}
else if(args.length > 1) {
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
id = parms.get(ARG_ID);
label = parms.get(ARG_LABEL);
setid = parms.get(ARG_SET);
if((id == null) && (label == null)) {
sender.sendMessage("<label> or id:<marker-id> required");
return true;
}
if(setid == null) {
setid = MarkerSet.DEFAULT;
}
MarkerSet set = api.getMarkerSet(setid);
if(set == null) {
sender.sendMessage("Error: invalid set - " + setid);
return true;
}
Marker marker;
if(id != null) {
marker = set.findMarker(id);
if(marker == null) { /* No marker */
sender.sendMessage("Error: marker not found - " + id);
return true;
}
}
else {
marker = set.findMarkerByLabel(label);
if(marker == null) { /* No marker */
sender.sendMessage("Error: marker not found - " + label);
return true;
}
}
DynmapLocation loc = player.getLocation();
marker.setLocation(loc.world, loc.x, loc.y, loc.z);
sender.sendMessage("Updated location of marker id:" + marker.getMarkerID() + " (" + marker.getLabel() + ")");
}
else {
sender.sendMessage("<label> or id:<marker-id> required");
}
return true;
}
private static boolean processUpdateMarker(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
String id, setid, label, newlabel, iconid, markup;
String x, y, z, world;
String newset;
if(args.length > 1) {
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
id = parms.get(ARG_ID);
label = parms.get(ARG_LABEL);
markup = parms.get(ARG_MARKUP);
setid = parms.get(ARG_SET);
newset = parms.get(ARG_NEWSET);
x = parms.get(ARG_X);
y = parms.get(ARG_Y);
z = parms.get(ARG_Z);
String minzoom = parms.get(ARG_MINZOOM);
int min_zoom = -1;
if (minzoom != null) {
try {
min_zoom = Integer.parseInt(minzoom);
} catch (NumberFormatException nfx) {
sender.sendMessage("Invalid minzoom: " + minzoom);
return true;
}
}
String maxzoom = parms.get(ARG_MAXZOOM);
int max_zoom = -1;
if (maxzoom != null) {
try {
max_zoom = Integer.parseInt(maxzoom);
} catch (NumberFormatException nfx) {
sender.sendMessage("Invalid maxzoom: " + maxzoom);
return true;
}
}
world = parms.get(ARG_WORLD);
if(world != null) {
if(api.core.getWorld(world) == null) {
sender.sendMessage("Invalid world ID: " + world);
return true;
}
}
DynmapLocation loc = null;
if((x != null) && (y != null) && (z != null) && (world != null)) {
try {
loc = new DynmapLocation(world, Double.valueOf(x), Double.valueOf(y), Double.valueOf(z));
} catch (NumberFormatException nfx) {
sender.sendMessage("Coordinates x, y, and z must be numbers");
return true;
}
}
if((id == null) && (label == null)) {
sender.sendMessage("<label> or id:<marker-id> required");
return true;
}
if(setid == null) {
setid = MarkerSet.DEFAULT;
}
MarkerSet set = api.getMarkerSet(setid);
if(set == null) {
sender.sendMessage("Error: invalid set - " + setid);
return true;
}
Marker marker;
if(id != null) {
marker = set.findMarker(id);
if(marker == null) { /* No marker */
sender.sendMessage("Error: marker not found - " + id);
return true;
}
}
else {
marker = set.findMarkerByLabel(label);
if(marker == null) { /* No marker */
sender.sendMessage("Error: marker not found - " + label);
return true;
}
}
newlabel = parms.get(ARG_NEWLABEL);
if(newlabel != null) { /* Label set? */
marker.setLabel(newlabel, "true".equals(markup));
}
else if(markup != null) {
marker.setLabel(marker.getLabel(), "true".equals(markup));
}
iconid = parms.get(ARG_ICON);
if(iconid != null) {
MarkerIcon ico = api.getMarkerIcon(iconid);
if(ico == null) {
sender.sendMessage("Error: invalid icon - " + iconid);
return true;
}
marker.setMarkerIcon(ico);
}
if(loc != null)
marker.setLocation(loc.world, loc.x, loc.y, loc.z);
if (min_zoom >= 0) {
marker.setMinZoom(min_zoom);
}
if (max_zoom >= 0) {
marker.setMaxZoom(max_zoom);
}
if(newset != null) {
MarkerSet ms = api.getMarkerSet(newset);
if(ms == null) {
sender.sendMessage("Error: invalid new marker set - " + newset);
return true;
}
marker.setMarkerSet(ms);
}
sender.sendMessage("Updated marker id:" + marker.getMarkerID() + " (" + marker.getLabel() + ")");
}
else {
sender.sendMessage("<label> or id:<marker-id> required");
}
return true;
}
private static boolean processDeleteMarker(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
String id, label, setid;
if(args.length > 1) {
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
id = parms.get(ARG_ID);
label = parms.get(ARG_LABEL);
setid = parms.get(ARG_SET);
if((id == null) && (label == null)) {
sender.sendMessage("<label> or id:<marker-id> required");
return true;
}
if(setid == null) {
setid = MarkerSet.DEFAULT;
}
MarkerSet set = api.getMarkerSet(setid);
if(set == null) {
sender.sendMessage("Error: invalid set - " + setid);
return true;
}
Marker marker;
if(id != null) {
marker = set.findMarker(id);
if(marker == null) { /* No marker */
sender.sendMessage("Error: marker not found - " + id);
return true;
}
}
else {
marker = set.findMarkerByLabel(label);
if(marker == null) { /* No marker */
sender.sendMessage("Error: marker not found - " + label);
return true;
}
}
marker.deleteMarker();
sender.sendMessage("Deleted marker id:" + marker.getMarkerID() + " (" + marker.getLabel() + ")");
}
else {
sender.sendMessage("<label> or id:<marker-id> required");
}
return true;
}
private static boolean processListMarker(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
String setid;
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
setid = parms.get(ARG_SET);
if(setid == null) {
setid = MarkerSet.DEFAULT;
}
MarkerSet set = api.getMarkerSet(setid);
if(set == null) {
sender.sendMessage("Error: invalid set - " + setid);
return true;
}
Set<Marker> markers = set.getMarkers();
TreeMap<String, Marker> sortmarkers = new TreeMap<String, Marker>();
for(Marker m : markers) {
sortmarkers.put(m.getMarkerID(), m);
}
for(String s : sortmarkers.keySet()) {
Marker m = sortmarkers.get(s);
String msg = m.getMarkerID() + ": label:\"" + m.getLabel() + "\", set:" + m.getMarkerSet().getMarkerSetID() +
", world:" + m.getWorld() + ", x:" + m.getX() + ", y:" + m.getY() + ", z:" + m.getZ() +
", icon:" + m.getMarkerIcon().getMarkerIconID() + ", markup:" + m.isLabelMarkup();
if (m.getMinZoom() >= 0) {
msg += ", minzoom:" + m.getMinZoom();
}
if (m.getMaxZoom() >= 0) {
msg += ", maxzoom:" + m.getMaxZoom();
}
sender.sendMessage(msg);
}
return true;
}
private static boolean processListIcon(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
Set<String> iconids = new TreeSet<String>(api.markericons.keySet());
for(String s : iconids) {
MarkerIcon ico = api.markericons.get(s);
sender.sendMessage(ico.getMarkerIconID() + ": label:\"" + ico.getMarkerIconLabel() + "\", builtin:" + ico.isBuiltIn());
}
return true;
}
private static boolean processAddSet(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args, DynmapPlayer player) {
String id, label, prio, minzoom, maxzoom, deficon;
if(args.length > 1) {
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
id = parms.get(ARG_ID);
label = parms.get(ARG_LABEL);
prio = parms.get(ARG_PRIO);
minzoom = parms.get(ARG_MINZOOM);
maxzoom = parms.get(ARG_MAXZOOM);
deficon = parms.get(ARG_DEFICON);
if(deficon == null) {
deficon = MarkerIcon.DEFAULT;
}
if((id == null) && (label == null)) {
sender.sendMessage("<label> or id:<marker-id> required");
return true;
}
if(label == null)
label = id;
if(id == null)
id = label;
/* See if marker set exists */
MarkerSet set = api.getMarkerSet(id);
if(set != null) {
sender.sendMessage("Error: set already exists - id:" + set.getMarkerSetID());
return true;
}
/* Create new set */
set = api.createMarkerSet(id, label, null, true);
if(set == null) {
sender.sendMessage("Error creating set");
}
else {
String h = parms.get(ARG_HIDE);
if((h != null) && (h.equals("true")))
set.setHideByDefault(true);
String showlabels = parms.get(ARG_SHOWLABEL);
if(showlabels != null) {
if(showlabels.equals("true"))
set.setLabelShow(true);
else if(showlabels.equals("false"))
set.setLabelShow(false);
}
if(prio != null) {
try {
set.setLayerPriority(Integer.valueOf(prio));
} catch (NumberFormatException nfx) {
sender.sendMessage("Invalid priority: " + prio);
}
}
MarkerIcon mi = MarkerAPIImpl.getMarkerIconImpl(deficon);
if(mi != null) {
set.setDefaultMarkerIcon(mi);
}
else {
sender.sendMessage("Invalid default icon: " + deficon);
}
if(minzoom != null) {
try {
set.setMinZoom(Integer.valueOf(minzoom));
} catch (NumberFormatException nfx) {
sender.sendMessage("Invalid min zoom: " + minzoom);
}
}
if(maxzoom != null) {
try {
set.setMaxZoom(Integer.valueOf(maxzoom));
} catch (NumberFormatException nfx) {
sender.sendMessage("Invalid max zoom: " + maxzoom);
}
}
sender.sendMessage("Added set id:'" + set.getMarkerSetID() + "' (" + set.getMarkerSetLabel() + ")");
}
}
else {
sender.sendMessage("<label> or id:<set-id> required");
}
return true;
}
private static boolean processUpdateSet(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
String id, label, prio, minzoom, maxzoom, deficon, newlabel;
if(args.length > 1) {
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
id = parms.get(ARG_ID);
label = parms.get(ARG_LABEL);
prio = parms.get(ARG_PRIO);
minzoom = parms.get(ARG_MINZOOM);
maxzoom = parms.get(ARG_MAXZOOM);
deficon = parms.get(ARG_DEFICON);
if((id == null) && (label == null)) {
sender.sendMessage("<label> or id:<set-id> required");
return true;
}
MarkerSet set = null;
if(id != null) {
set = api.getMarkerSet(id);
if(set == null) {
sender.sendMessage("Error: set does not exist - id:" + id);
return true;
}
}
else {
Set<MarkerSet> sets = api.getMarkerSets();
for(MarkerSet s : sets) {
if(s.getMarkerSetLabel().equals(label)) {
set = s;
break;
}
}
if(set == null) {
sender.sendMessage("Error: matching set not found");
return true;
}
}
newlabel = parms.get(ARG_NEWLABEL);
if(newlabel != null) {
set.setMarkerSetLabel(newlabel);
}
String hide = parms.get(ARG_HIDE);
if(hide != null) {
set.setHideByDefault(hide.equals("true"));
}
String showlabels = parms.get(ARG_SHOWLABEL);
if(showlabels != null) {
if(showlabels.equals("true"))
set.setLabelShow(true);
else if(showlabels.equals("false"))
set.setLabelShow(false);
else
set.setLabelShow(null);
}
if(deficon != null) {
MarkerIcon mi = null;
if(deficon.equals("") == false) {
mi = MarkerAPIImpl.getMarkerIconImpl(deficon);
if(mi == null) {
sender.sendMessage("Error: invalid marker icon - " + deficon);
}
}
set.setDefaultMarkerIcon(mi);
}
if(prio != null) {
try {
set.setLayerPriority(Integer.valueOf(prio));
} catch (NumberFormatException nfx) {
sender.sendMessage("Invalid priority: " + prio);
}
}
if(minzoom != null) {
try {
set.setMinZoom(Integer.valueOf(minzoom));
} catch (NumberFormatException nfx) {
sender.sendMessage("Invalid min zoom: " + minzoom);
}
}
if(maxzoom != null) {
try {
set.setMaxZoom(Integer.valueOf(maxzoom));
} catch (NumberFormatException nfx) {
sender.sendMessage("Invalid max zoom: " + maxzoom);
}
}
sender.sendMessage("Set '" + set.getMarkerSetID() + "' updated");
}
else {
sender.sendMessage("<label> or id:<set-id> required");
}
return true;
}
private static boolean processDeleteSet(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
String id, label;
if(args.length > 1) {
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
id = parms.get(ARG_ID);
label = parms.get(ARG_LABEL);
if((id == null) && (label == null)) {
sender.sendMessage("<label> or id:<set-id> required");
return true;
}
if(id != null) {
MarkerSet set = api.getMarkerSet(id);
if(set == null) {
sender.sendMessage("Error: set does not exist - id:" + id);
return true;
}
set.deleteMarkerSet();
}
else {
Set<MarkerSet> sets = api.getMarkerSets();
MarkerSet set = null;
for(MarkerSet s : sets) {
if(s.getMarkerSetLabel().equals(label)) {
set = s;
break;
}
}
if(set == null) {
sender.sendMessage("Error: matching set not found");
return true;
}
set.deleteMarkerSet();
}
sender.sendMessage("Deleted set");
}
else {
sender.sendMessage("<label> or id:<set-id> required");
}
return true;
}
private static boolean processListSet(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
Set<String> setids = new TreeSet<String>(api.markersets.keySet());
for(String s : setids) {
MarkerSet set = api.markersets.get(s);
Boolean b = set.getLabelShow();
MarkerIcon defi = set.getDefaultMarkerIcon();
String msg = set.getMarkerSetID() + ": label:\"" + set.getMarkerSetLabel() + "\", hide:" + set.getHideByDefault() + ", prio:" + set.getLayerPriority();
if (defi != null) {
msg += ", deficon:" + defi.getMarkerIconID();
}
if (b != null) {
msg += ", showlabels:" + b;
}
if (set.getMinZoom() >= 0) {
msg += ", minzoom:" + set.getMinZoom();
}
if (set.getMaxZoom() >= 0) {
msg += ", maxzoom:" + set.getMaxZoom();
}
if (set.isMarkerSetPersistent()) {
msg += ", persistent=true";
}
sender.sendMessage(msg);
}
return true;
}
private static boolean processAddIcon(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
String id, file, label;
if(args.length > 1) {
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
id = parms.get(ARG_ID);
file = parms.get(ARG_FILE);
label = parms.get(ARG_LABEL);
if(id == null) {
sender.sendMessage("id:<icon-id> required");
return true;
}
if(file == null) {
sender.sendMessage("file:\"filename\" required");
return true;
}
if(label == null)
label = id;
MarkerIcon ico = MarkerAPIImpl.getMarkerIconImpl(id);
if(ico != null) {
sender.sendMessage("Icon '" + id + "' already defined.");
return true;
}
/* Open stream to filename */
File iconf = new File(file);
FileInputStream fis = null;
try {
fis = new FileInputStream(iconf);
/* Create new icon */
MarkerIcon mi = api.createMarkerIcon(id, label, fis);
if(mi == null) {
sender.sendMessage("Error creating icon");
return true;
}
} catch (IOException iox) {
sender.sendMessage("Error loading icon file - " + iox);
} finally {
if(fis != null) {
try { fis.close(); } catch (IOException iox) {}
}
}
}
else {
sender.sendMessage("id:<icon-id> and file:\"filename\" required");
}
return true;
}
private static boolean processUpdateIcon(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
String id, label, newlabel, file;
if(args.length > 1) {
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
id = parms.get(ARG_ID);
label = parms.get(ARG_LABEL);
newlabel = parms.get(ARG_NEWLABEL);
file = parms.get(ARG_FILE);
if((id == null) && (label == null)) {
sender.sendMessage("<label> or id:<icon-id> required");
return true;
}
MarkerIcon ico = null;
if(id != null) {
ico = MarkerAPIImpl.getMarkerIconImpl(id);
if(ico == null) {
sender.sendMessage("Error: icon does not exist - id:" + id);
return true;
}
}
else {
Set<MarkerIcon> icons = api.getMarkerIcons();
for(MarkerIcon ic : icons) {
if(ic.getMarkerIconLabel().equals(label)) {
ico = ic;
break;
}
}
if(ico == null) {
sender.sendMessage("Error: matching icon not found");
return true;
}
}
if(newlabel != null) {
ico.setMarkerIconLabel(newlabel);
}
/* Handle new file */
if(file != null) {
File iconf = new File(file);
FileInputStream fis = null;
try {
fis = new FileInputStream(iconf);
ico.setMarkerIconImage(fis);
} catch (IOException iox) {
sender.sendMessage("Error loading icon file - " + iox);
} finally {
if(fis != null) {
try { fis.close(); } catch (IOException iox) {}
}
}
}
sender.sendMessage("Icon '" + ico.getMarkerIconID() + "' updated");
}
else {
sender.sendMessage("<label> or id:<icon-id> required");
}
return true;
}
private static boolean processDeleteIcon(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
String id, label;
if(args.length > 1) {
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
id = parms.get(ARG_ID);
label = parms.get(ARG_LABEL);
if((id == null) && (label == null)) {
sender.sendMessage("<label> or id:<icon-id> required");
return true;
}
if(id != null) {
MarkerIcon ico = MarkerAPIImpl.getMarkerIconImpl(id);
if(ico == null) {
sender.sendMessage("Error: icon does not exist - id:" + id);
return true;
}
ico.deleteIcon();
}
else {
Set<MarkerIcon> icos = api.getMarkerIcons();
MarkerIcon ico = null;
for(MarkerIcon ic : icos) {
if(ic.getMarkerIconLabel().equals(label)) {
ico = ic;
break;
}
}
if(ico == null) {
sender.sendMessage("Error: matching icon not found");
return true;
}
ico.deleteIcon();
}
sender.sendMessage("Deleted marker icon");
}
else {
sender.sendMessage("<label> or id:<icon-id> required");
}
return true;
}
private static boolean processAddCorner(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args, DynmapPlayer player) {
String id;
DynmapLocation loc = null;
if(player == null) {
id = "-console-";
}
else {
id = player.getName();
loc = player.getLocation();
}
List<DynmapLocation> ll = api.pointaccum.get(id); /* Find list */
if(args.length > 3) { /* Enough for coord */
String w = null;
if(args.length == 4) { /* No world */
if(ll == null) { /* No points? Error */
sender.sendMessage("First added corner needs world ID after coordinates");
return true;
}
else {
w = ll.get(0).world; /* Use same world */
}
}
else { /* Get world ID */
w = args[4];
if(api.core.getWorld(w) == null) {
sender.sendMessage("Invalid world ID: " + args[3]);
return true;
}
}
try {
loc = new DynmapLocation(w, Double.parseDouble(args[1]), Double.parseDouble(args[2]), Double.parseDouble(args[3]));
} catch (NumberFormatException nfx) {
sender.sendMessage("Bad format: /dmarker addcorner <x> <y> <z> <world>");
return true;
}
}
if(loc == null) {
sender.sendMessage("Console must supply corner coordinates: <x> <y> <z> <world>");
return true;
}
if(ll == null) {
ll = new ArrayList<DynmapLocation>();
api.pointaccum.put(id, ll);
}
else { /* Else, if list exists, see if world matches */
if(ll.get(0).world.equals(loc.world) == false) {
ll.clear(); /* Reset list - point on new world */
}
}
ll.add(loc);
sender.sendMessage("Added corner #" + ll.size() + " at {" + loc.x + "," + loc.y + "," + loc.z + "} to list");
return true;
}
private static boolean processClearCorners(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args, DynmapPlayer player) {
String id;
if(player == null) {
id = "-console-";
}
else {
id = player.getName();
}
api.pointaccum.remove(id);
sender.sendMessage("Cleared corner list");
return true;
}
private static boolean processAddArea(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args, DynmapPlayer player) {
String pid, setid, id, label, markup;
if(player == null) {
pid = "-console-";
}
else {
pid = player.getName();
}
List<DynmapLocation> ll = api.pointaccum.get(pid); /* Find list */
if((ll == null) || (ll.size() < 2)) { /* Not enough points? */
sender.sendMessage("At least two corners must be added with /dmarker addcorner before an area can be added");
return true;
}
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
setid = parms.get(ARG_SET);
id = parms.get(ARG_ID);
label = parms.get(ARG_LABEL);
markup = parms.get(ARG_MARKUP);
/* Fill in defaults for missing parameters */
if(setid == null) {
setid = MarkerSet.DEFAULT;
}
/* Add new marker */
MarkerSet set = api.getMarkerSet(setid);
if(set == null) {
sender.sendMessage("Error: invalid set - " + setid);
return true;
}
// Prevent adding persistent markers to a non-persistent set
if (!set.isMarkerSetPersistent()) {
sender.sendMessage("Error: cannot add to non-persistent marker set - set is likely plugin owned");
return true;
}
/* Make coord list */
double[] xx = new double[ll.size()];
double[] zz = new double[ll.size()];
for(int i = 0; i < ll.size(); i++) {
DynmapLocation loc = ll.get(i);
xx[i] = loc.x;
zz[i] = loc.z;
}
/* Make area marker */
AreaMarker m = set.createAreaMarker(id, label, "true".equals(markup), ll.get(0).world, xx, zz, true);
if(m == null) {
sender.sendMessage("Error creating area");
}
else {
/* Process additional attributes, if any */
processAreaArgs(sender, m, parms);
sender.sendMessage("Added area id:'" + m.getMarkerID() + "' (" + m.getLabel() + ") to set '" + set.getMarkerSetID() + "'");
api.pointaccum.remove(pid); /* Clear corner list */
}
return true;
}
private static boolean processListArea(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
String setid;
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
setid = parms.get(ARG_SET);
if(setid == null) {
setid = MarkerSet.DEFAULT;
}
MarkerSet set = api.getMarkerSet(setid);
if(set == null) {
sender.sendMessage("Error: invalid set - " + setid);
return true;
}
Set<AreaMarker> markers = set.getAreaMarkers();
TreeMap<String, AreaMarker> sortmarkers = new TreeMap<String, AreaMarker>();
for(AreaMarker m : markers) {
sortmarkers.put(m.getMarkerID(), m);
}
for(String s : sortmarkers.keySet()) {
AreaMarker m = sortmarkers.get(s);
String msg = m.getMarkerID() + ": label:\"" + m.getLabel() + "\", set:" + m.getMarkerSet().getMarkerSetID() +
", world:" + m.getWorld() +
", weight:" + m.getLineWeight() + ", color:" + String.format("%06x", m.getLineColor()) +
", opacity:" + m.getLineOpacity() + ", fillcolor:" + String.format("%06x", m.getFillColor()) +
", fillopacity:" + m.getFillOpacity() + ", boost:" + m.getBoostFlag() + ", markup:" + m.isLabelMarkup();
if (m.getMinZoom() >= 0) {
msg += ", minzoom:" + m.getMinZoom();
}
if (m.getMaxZoom() >= 0) {
msg += ", maxzoom:" + m.getMaxZoom();
}
EnterExitText t = m.getGreetingText();
if (t != null) {
if (t.title != null) msg += ", greeting:\"" + t.title + "\"";
if (t.subtitle != null) msg += ", greetingsub:\"" + t.subtitle + "\"";
}
t = m.getFarewellText();
if (t != null) {
if (t.title != null) msg += ", farewell:\"" + t.title + "\"";
if (t.subtitle != null) msg += ", farewellsub:\"" + t.subtitle + "\"";
}
sender.sendMessage(msg);
}
return true;
}
private static boolean processDeleteArea(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
String id, label, setid;
if(args.length > 1) {
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
id = parms.get(ARG_ID);
label = parms.get(ARG_LABEL);
setid = parms.get(ARG_SET);
if((id == null) && (label == null)) {
sender.sendMessage("<label> or id:<area-id> required");
return true;
}
if(setid == null) {
setid = MarkerSet.DEFAULT;
}
MarkerSet set = api.getMarkerSet(setid);
if(set == null) {
sender.sendMessage("Error: invalid set - " + setid);
return true;
}
AreaMarker marker;
if(id != null) {
marker = set.findAreaMarker(id);
if(marker == null) { /* No marker */
sender.sendMessage("Error: area not found - " + id);
return true;
}
}
else {
marker = set.findAreaMarkerByLabel(label);
if(marker == null) { /* No marker */
sender.sendMessage("Error: area not found - " + label);
return true;
}
}
marker.deleteMarker();
sender.sendMessage("Deleted area id:" + marker.getMarkerID() + " (" + marker.getLabel() + ")");
}
else {
sender.sendMessage("<label> or id:<area-id> required");
}
return true;
}
private static boolean processUpdateArea(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
String id, label, setid, newlabel, markup, newset;
if(args.length > 1) {
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
id = parms.get(ARG_ID);
label = parms.get(ARG_LABEL);
markup = parms.get(ARG_MARKUP);
setid = parms.get(ARG_SET);
if((id == null) && (label == null)) {
sender.sendMessage("<label> or id:<area-id> required");
return true;
}
if(setid == null) {
setid = MarkerSet.DEFAULT;
}
MarkerSet set = api.getMarkerSet(setid);
if(set == null) {
sender.sendMessage("Error: invalid set - " + setid);
return true;
}
AreaMarker marker;
if(id != null) {
marker = set.findAreaMarker(id);
if(marker == null) { /* No marker */
sender.sendMessage("Error: area not found - " + id);
return true;
}
}
else {
marker = set.findAreaMarkerByLabel(label);
if(marker == null) { /* No marker */
sender.sendMessage("Error: area not found - " + label);
return true;
}
}
newlabel = parms.get(ARG_NEWLABEL);
if(newlabel != null) { /* Label set? */
marker.setLabel(newlabel, "true".equals(markup));
}
else if(markup != null) {
marker.setLabel(marker.getLabel(), "true".equals(markup));
}
newset = parms.get(ARG_NEWSET);
if (newset != null) {
MarkerSet ms = api.getMarkerSet(newset);
if(ms == null) {
sender.sendMessage("Error: invalid new marker set - " + newset);
return true;
}
marker.setMarkerSet(ms);
}
if(!processAreaArgs(sender,marker, parms))
return true;
sender.sendMessage("Updated area id:" + marker.getMarkerID() + " (" + marker.getLabel() + ")");
}
else {
sender.sendMessage("<label> or id:<area-id> required");
}
return true;
}
private static boolean processAddLine(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args, DynmapPlayer player) {
String setid;
String pid, id, label, markup;
if(player == null) {
pid = "-console-";
}
else {
pid = player.getName();
}
List<DynmapLocation> ll = api.pointaccum.get(pid); /* Find list */
if((ll == null) || (ll.size() < 2)) { /* Not enough points? */
sender.sendMessage("At least two corners must be added with /dmarker addcorner before a line can be added");
return true;
}
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
setid = parms.get(ARG_SET);
id = parms.get(ARG_ID);
label = parms.get(ARG_LABEL);
markup = parms.get(ARG_MARKUP);
/* Fill in defaults for missing parameters */
if(setid == null) {
setid = MarkerSet.DEFAULT;
}
/* Add new marker */
MarkerSet set = api.getMarkerSet(setid);
if(set == null) {
sender.sendMessage("Error: invalid set - " + setid);
return true;
}
// Prevent adding persistent markers to a non-persistent set
if (!set.isMarkerSetPersistent()) {
sender.sendMessage("Error: cannot add to non-persistent marker set - set is likely plugin owned");
return true;
}
/* Make coord list */
double[] xx = new double[ll.size()];
double[] yy = new double[ll.size()];
double[] zz = new double[ll.size()];
for(int i = 0; i < ll.size(); i++) {
DynmapLocation loc = ll.get(i);
xx[i] = loc.x;
yy[i] = loc.y;
zz[i] = loc.z;
}
/* Make poly-line marker */
PolyLineMarker m = set.createPolyLineMarker(id, label, "true".equals(markup), ll.get(0).world, xx, yy, zz, true);
if(m == null) {
sender.sendMessage("Error creating line");
}
else {
/* Process additional attributes, if any */
processPolyArgs(sender, m, parms);
sender.sendMessage("Added line id:'" + m.getMarkerID() + "' (" + m.getLabel() + ") to set '" + set.getMarkerSetID() + "'");
api.pointaccum.remove(pid); /* Clear corner list */
}
return true;
}
private static boolean processListLine(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
String setid;
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
setid = parms.get(ARG_SET);
if(setid == null) {
setid = MarkerSet.DEFAULT;
}
MarkerSet set = api.getMarkerSet(setid);
if(set == null) {
sender.sendMessage("Error: invalid set - " + setid);
return true;
}
Set<PolyLineMarker> markers = set.getPolyLineMarkers();
TreeMap<String, PolyLineMarker> sortmarkers = new TreeMap<String, PolyLineMarker>();
for(PolyLineMarker m : markers) {
sortmarkers.put(m.getMarkerID(), m);
}
for(String s : sortmarkers.keySet()) {
PolyLineMarker m = sortmarkers.get(s);
String ptlist = "{ ";
for(int i = 0; i < m.getCornerCount(); i++) {
ptlist += "{" + m.getCornerX(i) + "," + m.getCornerY(i) + "," + m.getCornerZ(i) + "} ";
}
ptlist += "}";
String msg = m.getMarkerID() + ": label:\"" + m.getLabel() + "\", set:" + m.getMarkerSet().getMarkerSetID() +
", world:" + m.getWorld() + ", corners:" + ptlist +
", weight: " + m.getLineWeight() + ", color:" + String.format("%06x", m.getLineColor()) +
", opacity: " + m.getLineOpacity() + ", markup:" + m.isLabelMarkup();
if (m.getMinZoom() >= 0) {
msg += ", minzoom:" + m.getMinZoom();
}
if (m.getMaxZoom() >= 0) {
msg += ", maxzoom:" + m.getMaxZoom();
}
sender.sendMessage(msg);
}
return true;
}
private static boolean processDeleteLine(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
String id, setid, label;
if(args.length > 1) {
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
id = parms.get(ARG_ID);
label = parms.get(ARG_LABEL);
setid = parms.get(ARG_SET);
if((id == null) && (label == null)) {
sender.sendMessage("<label> or id:<line-id> required");
return true;
}
if(setid == null) {
setid = MarkerSet.DEFAULT;
}
MarkerSet set = api.getMarkerSet(setid);
if(set == null) {
sender.sendMessage("Error: invalid set - " + setid);
return true;
}
PolyLineMarker marker;
if(id != null) {
marker = set.findPolyLineMarker(id);
if(marker == null) { /* No marker */
sender.sendMessage("Error: line not found - " + id);
return true;
}
}
else {
marker = set.findPolyLineMarkerByLabel(label);
if(marker == null) { /* No marker */
sender.sendMessage("Error: line not found - " + label);
return true;
}
}
marker.deleteMarker();
sender.sendMessage("Deleted poly-line id:" + marker.getMarkerID() + " (" + marker.getLabel() + ")");
}
else {
sender.sendMessage("<label> or id:<line-id> required");
}
return true;
}
private static boolean processUpdateLine(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
String id, setid, label, newlabel, markup, newset;
if(args.length > 1) {
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
id = parms.get(ARG_ID);
label = parms.get(ARG_LABEL);
markup = parms.get(ARG_MARKUP);
setid = parms.get(ARG_SET);
if((id == null) && (label == null)) {
sender.sendMessage("<label> or id:<line-id> required");
return true;
}
if(setid == null) {
setid = MarkerSet.DEFAULT;
}
MarkerSet set = api.getMarkerSet(setid);
if(set == null) {
sender.sendMessage("Error: invalid set - " + setid);
return true;
}
PolyLineMarker marker;
if(id != null) {
marker = set.findPolyLineMarker(id);
if(marker == null) { /* No marker */
sender.sendMessage("Error: line not found - " + id);
return true;
}
}
else {
marker = set.findPolyLineMarkerByLabel(label);
if(marker == null) { /* No marker */
sender.sendMessage("Error: line not found - " + label);
return true;
}
}
newlabel = parms.get(ARG_NEWLABEL);
if(newlabel != null) { /* Label set? */
marker.setLabel(newlabel, "true".equals(markup));
}
else if(markup != null) {
marker.setLabel(marker.getLabel(), "true".equals(markup));
}
newset = parms.get(ARG_NEWSET);
if (newset != null) {
MarkerSet ms = api.getMarkerSet(newset);
if(ms == null) {
sender.sendMessage("Error: invalid new marker set - " + newset);
return true;
}
marker.setMarkerSet(ms);
}
if(!processPolyArgs(sender,marker, parms))
return true;
sender.sendMessage("Updated line id:" + marker.getMarkerID() + " (" + marker.getLabel() + ")");
}
else {
sender.sendMessage("<label> or id:<line-id> required");
}
return true;
}
private static boolean processAddCircle(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args, DynmapPlayer player) {
String id, setid, label, markup;
String x, y, z, world;
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
setid = parms.get(ARG_SET);
id = parms.get(ARG_ID);
label = parms.get(ARG_LABEL);
markup = parms.get(ARG_MARKUP);
x = parms.get(ARG_X);
y = parms.get(ARG_Y);
z = parms.get(ARG_Z);
world = parms.get(ARG_WORLD);
if(world != null) {
if(api.core.getWorld(world) == null) {
sender.sendMessage("Invalid world ID: " + world);
return true;
}
}
DynmapLocation loc = null;
if((x == null) && (y == null) && (z == null) && (world == null)) {
if(player == null) {
sender.sendMessage("Must be issued by player, or x, y, z, and world parameters are required");
return true;
}
loc = player.getLocation();
}
else if((x != null) && (y != null) && (z != null) && (world != null)) {
try {
loc = new DynmapLocation(world, Double.valueOf(x), Double.valueOf(y), Double.valueOf(z));
} catch (NumberFormatException nfx) {
sender.sendMessage("Coordinates x, y, and z must be numbers");
return true;
}
}
else {
sender.sendMessage("Must be issued by player, or x, y, z, and world parameters are required");
return true;
}
/* Fill in defaults for missing parameters */
if(setid == null) {
setid = MarkerSet.DEFAULT;
}
/* Add new marker */
MarkerSet set = api.getMarkerSet(setid);
if(set == null) {
sender.sendMessage("Error: invalid set - " + setid);
return true;
}
// Prevent adding persistent markers to a non-persistent set
if (!set.isMarkerSetPersistent()) {
sender.sendMessage("Error: cannot add to non-persistent marker set - set is likely plugin owned");
return true;
}
/* Make circle marker */
CircleMarker m = set.createCircleMarker(id, label, "true".equals(markup), loc.world, loc.x, loc.y, loc.z, 1, 1, true);
if(m == null) {
sender.sendMessage("Error creating circle");
}
else {
/* Process additional attributes, if any */
if(!processCircleArgs(sender, m, parms)) {
return true;
}
sender.sendMessage("Added circle id:'" + m.getMarkerID() + "' (" + m.getLabel() + ") to set '" + set.getMarkerSetID() + "'");
}
return true;
}
private static boolean processListCircle(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
String setid;
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
setid = parms.get(ARG_SET);
if(setid == null) {
setid = MarkerSet.DEFAULT;
}
MarkerSet set = api.getMarkerSet(setid);
if(set == null) {
sender.sendMessage("Error: invalid set - " + setid);
return true;
}
Set<CircleMarker> markers = set.getCircleMarkers();
TreeMap<String, CircleMarker> sortmarkers = new TreeMap<String, CircleMarker>();
for(CircleMarker m : markers) {
sortmarkers.put(m.getMarkerID(), m);
}
for(String s : sortmarkers.keySet()) {
CircleMarker m = sortmarkers.get(s);
String msg = m.getMarkerID() + ": label:\"" + m.getLabel() + "\", set:" + m.getMarkerSet().getMarkerSetID() +
", world:" + m.getWorld() + ", center:" + m.getCenterX() + "/" + m.getCenterY() + "/" + m.getCenterZ() +
", radiusx:" + m.getRadiusX() + ", radiusz:" + m.getRadiusZ() +
", weight: " + m.getLineWeight() + ", color:" + String.format("%06x", m.getLineColor()) +
", opacity: " + m.getLineOpacity() + ", fillcolor: " + String.format("%06x", m.getFillColor()) +
", fillopacity: " + m.getFillOpacity() + ", boost:" + m.getBoostFlag() + ", markup:" + m.isLabelMarkup();
if (m.getMinZoom() >= 0) {
msg += ", minzoom:" + m.getMinZoom();
}
if (m.getMaxZoom() >= 0) {
msg += ", maxzoom:" + m.getMaxZoom();
}
EnterExitText t = m.getGreetingText();
if (t != null) {
if (t.title != null) msg += ", greeting:\"" + t.title + "\"";
if (t.subtitle != null) msg += ", greetingsub:\"" + t.subtitle + "\"";
}
t = m.getFarewellText();
if (t != null) {
if (t.title != null) msg += ", farewell:\"" + t.title + "\"";
if (t.subtitle != null) msg += ", farewellsub:\"" + t.subtitle + "\"";
}
sender.sendMessage(msg);
}
return true;
}
private static boolean processDeleteCircle(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
String id, setid, label;
if(args.length > 1) {
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
id = parms.get(ARG_ID);
label = parms.get(ARG_LABEL);
setid = parms.get(ARG_SET);
if((id == null) && (label == null)) {
sender.sendMessage("<label> or id:<circle-id> required");
return true;
}
if(setid == null) {
setid = MarkerSet.DEFAULT;
}
MarkerSet set = api.getMarkerSet(setid);
if(set == null) {
sender.sendMessage("Error: invalid set - " + setid);
return true;
}
CircleMarker marker;
if(id != null) {
marker = set.findCircleMarker(id);
if(marker == null) { /* No marker */
sender.sendMessage("Error: circle not found - " + id);
return true;
}
}
else {
marker = set.findCircleMarkerByLabel(label);
if(marker == null) { /* No marker */
sender.sendMessage("Error: circle not found - " + label);
return true;
}
}
marker.deleteMarker();
sender.sendMessage("Deleted circle id:" + marker.getMarkerID() + " (" + marker.getLabel() + ")");
}
else {
sender.sendMessage("<label> or id:<circle-id> required");
}
return true;
}
private static boolean processUpdateCircle(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
String id, setid, label, newlabel, markup, newset;
if(args.length > 1) {
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
id = parms.get(ARG_ID);
label = parms.get(ARG_LABEL);
markup = parms.get(ARG_MARKUP);
setid = parms.get(ARG_SET);
if((id == null) && (label == null)) {
sender.sendMessage("<label> or id:<area-id> required");
return true;
}
if(setid == null) {
setid = MarkerSet.DEFAULT;
}
MarkerSet set = api.getMarkerSet(setid);
if(set == null) {
sender.sendMessage("Error: invalid set - " + setid);
return true;
}
CircleMarker marker;
if(id != null) {
marker = set.findCircleMarker(id);
if(marker == null) { /* No marker */
sender.sendMessage("Error: circle not found - " + id);
return true;
}
}
else {
marker = set.findCircleMarkerByLabel(label);
if(marker == null) { /* No marker */
sender.sendMessage("Error: circle not found - " + label);
return true;
}
}
newlabel = parms.get(ARG_NEWLABEL);
if(newlabel != null) { /* Label set? */
marker.setLabel(newlabel, "true".equals(markup));
}
else if(markup != null) {
marker.setLabel(marker.getLabel(), "true".equals(markup));
}
newset = parms.get(ARG_NEWSET);
if (newset != null) {
MarkerSet ms = api.getMarkerSet(newset);
if(ms == null) {
sender.sendMessage("Error: invalid new marker set - " + newset);
return true;
}
marker.setMarkerSet(ms);
}
if(!processCircleArgs(sender,marker, parms))
return true;
sender.sendMessage("Updated circle id:" + marker.getMarkerID() + " (" + marker.getLabel() + ")");
}
else {
sender.sendMessage("<label> or id:<circle-id> required");
}
return true;
}
private static MarkerDescription findMarkerDescription(DynmapCommandSender sender, Map<String, String> parms) {
MarkerDescription md = null;
String id, setid, label, type;
id = parms.get(ARG_ID);
label = parms.get(ARG_LABEL);
setid = parms.get(ARG_SET);
if((id == null) && (label == null)) {
sender.sendMessage("<label> or id:<area-id> required");
return null;
}
type = parms.get(ARG_TYPE);
if (type == null) type = "icon";
if(setid == null) {
setid = MarkerSet.DEFAULT;
}
MarkerSet set = api.getMarkerSet(setid);
if(set == null) {
sender.sendMessage("Error: invalid set - " + setid);
return null;
}
if (id != null) {
if (type.equals("icon")) {
md = set.findMarker(id);
}
else if (type.equals("area")) {
md = set.findAreaMarker(id);
}
else if (type.equals("circle")) {
md = set.findCircleMarker(id);
}
else if (type.equals("line")) {
md = set.findPolyLineMarker(id);
}
else {
sender.sendMessage("Error: invalid type - " + type);
return null;
}
if(md == null) { /* No marker */
sender.sendMessage("Error: marker not found - " + id);
return null;
}
}
else {
if (type.equals("icon")) {
md = set.findMarkerByLabel(label);
}
else if (type.equals("area")) {
md = set.findAreaMarkerByLabel(label);
}
else if (type.equals("circle")) {
md = set.findCircleMarkerByLabel(label);
}
else if (type.equals("line")) {
md = set.findPolyLineMarkerByLabel(label);
}
else {
sender.sendMessage("Error: invalid type - " + type);
return null;
}
if(md == null) { /* No marker */
sender.sendMessage("Error: marker not found - " + label);
return null;
}
}
return md;
}
/** Process getdesc for given item */
private static boolean processGetDesc(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
if(args.length > 1) {
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
MarkerDescription md = findMarkerDescription(sender, parms);
if (md == null) {
return true;
}
String desc = md.getDescription();
if (desc == null) {
sender.sendMessage("<null>");
}
else {
sender.sendMessage(desc);
}
}
else {
sender.sendMessage("<label> or id:<id> required");
}
return true;
}
/** Process resetdesc for given item */
private static boolean processResetDesc(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
if(args.length > 1) {
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
MarkerDescription md = findMarkerDescription(sender, parms);
if (md == null) {
return true;
}
md.setDescription(null);
sender.sendMessage("Description cleared");
}
else {
sender.sendMessage("<label> or id:<id> required");
}
return true;
}
/** Process appenddesc for given item */
private static boolean processAppendDesc(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
if(args.length > 1) {
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
MarkerDescription md = findMarkerDescription(sender, parms);
if (md == null) {
return true;
}
String desc = parms.get(ARG_DESC);
if (desc == null) {
sender.sendMessage("Error: no 'desc:' parameter");
return true;
}
String d = md.getDescription();
if (d == null) {
d = desc + "\n";
}
else {
d = d + desc + "\n";
}
md.setDescription(d);
sender.sendMessage(md.getDescription());
}
else {
sender.sendMessage("<label> or id:<id> required");
}
return true;
}
/** Process getlabel for given item */
private static boolean processGetLabel(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
if(args.length > 1) {
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
MarkerDescription md = findMarkerDescription(sender, parms);
if (md == null) {
return true;
}
String desc = md.getLabel();
if (desc == null) {
sender.sendMessage("<null>");
}
else {
sender.sendMessage(desc);
}
}
else {
sender.sendMessage("<label> or id:<id> required");
}
return true;
}
/** Process importdesc for given item */
private static boolean processImportDesc(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
if(args.length > 1) {
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
MarkerDescription md = findMarkerDescription(sender, parms);
if (md == null) {
return true;
}
String f = parms.get(ARG_FILE);
if (f == null) {
sender.sendMessage("Error: no '" + ARG_FILE + "' parameter");
return true;
}
FileReader fr = null;
String val = null;
try {
fr = new FileReader(f);
StringBuilder sb = new StringBuilder();
char[] buf = new char[512];
int len;
while ((len = fr.read(buf)) > 0) {
sb.append(buf, 0, len);
}
val = sb.toString();
} catch (FileNotFoundException fnfx) {
sender.sendMessage("Error: file '" + f + "' not found");
return true;
} catch (IOException iox) {
sender.sendMessage("Error reading file '" + f + "'");
return true;
} finally {
if (fr != null) {
try { fr.close(); } catch (IOException iox) {}
}
}
md.setDescription(val);
sender.sendMessage("Description imported from '" + f + "'");
}
else {
sender.sendMessage("<label> or id:<id> required");
}
return true;
}
/** Process importlabel for given item */
private static boolean processImportLabel(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
if(args.length > 1) {
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
MarkerDescription md = findMarkerDescription(sender, parms);
if (md == null) {
return true;
}
String f = parms.get(ARG_FILE);
if (f == null) {
sender.sendMessage("Error: no '" + ARG_FILE + "' parameter");
return true;
}
FileReader fr = null;
String val = null;
try {
fr = new FileReader(f);
StringBuilder sb = new StringBuilder();
char[] buf = new char[512];
int len;
while ((len = fr.read(buf)) > 0) {
sb.append(buf, 0, len);
}
val = sb.toString();
} catch (FileNotFoundException fnfx) {
sender.sendMessage("Error: file '" + f + "' not found");
return true;
} catch (IOException iox) {
sender.sendMessage("Error reading file '" + f + "'");
return true;
} finally {
if (fr != null) {
try { fr.close(); } catch (IOException iox) {}
}
}
md.setLabel(val, true);
sender.sendMessage("Label with markup imported from '" + f + "'");
}
else {
sender.sendMessage("<label> or id:<id> required");
}
return true;
}
/**
* Write markers file for given world
*/
private void writeMarkersFile(final String wname) {
Map<String, Object> markerdata = new HashMap<String, Object>();
final Map<String, Object> worlddata = new HashMap<String, Object>();
worlddata.put("timestamp", Long.valueOf(System.currentTimeMillis())); /* Add timestamp */
for(MarkerSet ms : markersets.values()) {
HashMap<String, Object> msdata = new HashMap<String, Object>();
msdata.put("label", ms.getMarkerSetLabel());
msdata.put("hide", ms.getHideByDefault());
msdata.put("layerprio", ms.getLayerPriority());
if (ms.getMinZoom() >= 0) {
msdata.put("minzoom", ms.getMinZoom());
}
if (ms.getMaxZoom() >= 0) {
msdata.put("maxzoom", ms.getMaxZoom());
}
if(ms.getLabelShow() != null) {
msdata.put("showlabels", ms.getLabelShow());
}
HashMap<String, Object> markers = new HashMap<String, Object>();
for(Marker m : ms.getMarkers()) {
if(m.getWorld().equals(wname) == false) continue;
HashMap<String, Object> mdata = new HashMap<String, Object>();
mdata.put("x", m.getX());
mdata.put("y", m.getY());
mdata.put("z", m.getZ());
MarkerIcon mi = m.getMarkerIcon();
if(mi == null)
mi = MarkerAPIImpl.getMarkerIconImpl(MarkerIcon.DEFAULT);
mdata.put("icon", mi.getMarkerIconID());
mdata.put("dim", mi.getMarkerIconSize().getSize());
mdata.put("label", Client.sanitizeHTML(m.getLabel()));
mdata.put("markup", m.isLabelMarkup());
if(m.getDescription() != null)
mdata.put("desc", Client.sanitizeHTML(m.getDescription()));
if (m.getMinZoom() >= 0) {
mdata.put("minzoom", m.getMinZoom());
}
if (m.getMaxZoom() >= 0) {
mdata.put("maxzoom", m.getMaxZoom());
}
/* Add to markers */
markers.put(m.getMarkerID(), mdata);
}
msdata.put("markers", markers); /* Add markers to set data */
HashMap<String, Object> areas = new HashMap<String, Object>();
for(AreaMarker m : ms.getAreaMarkers()) {
if(m.getWorld().equals(wname) == false) continue;
HashMap<String, Object> mdata = new HashMap<String, Object>();
int cnt = m.getCornerCount();
List<Double> xx = new ArrayList<Double>();
List<Double> zz = new ArrayList<Double>();
for(int i = 0; i < cnt; i++) {
xx.add(m.getCornerX(i));
zz.add(m.getCornerZ(i));
}
mdata.put("x", xx);
mdata.put("ytop", m.getTopY());
mdata.put("ybottom", m.getBottomY());
mdata.put("z", zz);
mdata.put("color", String.format("#%06X", m.getLineColor()));
mdata.put("fillcolor", String.format("#%06X", m.getFillColor()));
mdata.put("opacity", m.getLineOpacity());
mdata.put("fillopacity", m.getFillOpacity());
mdata.put("weight", m.getLineWeight());
mdata.put("label", Client.sanitizeHTML(m.getLabel()));
mdata.put("markup", m.isLabelMarkup());
if(m.getDescription() != null)
mdata.put("desc", Client.sanitizeHTML(m.getDescription()));
if (m.getMinZoom() >= 0) {
mdata.put("minzoom", m.getMinZoom());
}
if (m.getMaxZoom() >= 0) {
mdata.put("maxzoom", m.getMaxZoom());
}
/* Add to markers */
areas.put(m.getMarkerID(), mdata);
}
msdata.put("areas", areas); /* Add areamarkers to set data */
HashMap<String, Object> lines = new HashMap<String, Object>();
for(PolyLineMarker m : ms.getPolyLineMarkers()) {
if(m.getWorld().equals(wname) == false) continue;
HashMap<String, Object> mdata = new HashMap<String, Object>();
int cnt = m.getCornerCount();
List<Double> xx = new ArrayList<Double>();
List<Double> yy = new ArrayList<Double>();
List<Double> zz = new ArrayList<Double>();
for(int i = 0; i < cnt; i++) {
xx.add(m.getCornerX(i));
yy.add(m.getCornerY(i));
zz.add(m.getCornerZ(i));
}
mdata.put("x", xx);
mdata.put("y", yy);
mdata.put("z", zz);
mdata.put("color", String.format("#%06X", m.getLineColor()));
mdata.put("opacity", m.getLineOpacity());
mdata.put("weight", m.getLineWeight());
mdata.put("label", Client.sanitizeHTML(m.getLabel()));
mdata.put("markup", m.isLabelMarkup());
if(m.getDescription() != null)
mdata.put("desc", Client.sanitizeHTML(m.getDescription()));
if (m.getMinZoom() >= 0) {
mdata.put("minzoom", m.getMinZoom());
}
if (m.getMaxZoom() >= 0) {
mdata.put("maxzoom", m.getMaxZoom());
}
/* Add to markers */
lines.put(m.getMarkerID(), mdata);
}
msdata.put("lines", lines); /* Add polylinemarkers to set data */
HashMap<String, Object> circles = new HashMap<String, Object>();
for(CircleMarker m : ms.getCircleMarkers()) {
if(m.getWorld().equals(wname) == false) continue;
HashMap<String, Object> mdata = new HashMap<String, Object>();
mdata.put("x", m.getCenterX());
mdata.put("y", m.getCenterY());
mdata.put("z", m.getCenterZ());
mdata.put("xr", m.getRadiusX());
mdata.put("zr", m.getRadiusZ());
mdata.put("color", String.format("#%06X", m.getLineColor()));
mdata.put("fillcolor", String.format("#%06X", m.getFillColor()));
mdata.put("opacity", m.getLineOpacity());
mdata.put("fillopacity", m.getFillOpacity());
mdata.put("weight", m.getLineWeight());
mdata.put("label", Client.sanitizeHTML(m.getLabel()));
mdata.put("markup", m.isLabelMarkup());
if(m.getDescription() != null)
mdata.put("desc", Client.sanitizeHTML(m.getDescription()));
if (m.getMinZoom() >= 0) {
mdata.put("minzoom", m.getMinZoom());
}
if (m.getMaxZoom() >= 0) {
mdata.put("maxzoom", m.getMaxZoom());
}
/* Add to markers */
circles.put(m.getMarkerID(), mdata);
}
msdata.put("circles", circles); /* Add circle markers to set data */
markerdata.put(ms.getMarkerSetID(), msdata); /* Add marker set data to world marker data */
}
worlddata.put("sets", markerdata);
MapManager.scheduleDelayedJob(new Runnable() {
public void run() {
core.getDefaultMapStorage().setMarkerFile(wname, Json.stringifyJson(worlddata));
}
}, 0);
}
@Override
public void triggered(DynmapWorld t) {
/* Update markers for now-active world */
dirty_worlds.put(t.getName(),"");
}
/* Remove icon */
static void removeIcon(MarkerIcon ico) {
MarkerIcon def = api.getMarkerIcon(MarkerIcon.DEFAULT);
/* Need to scrub all uses of this icon from markers */
for(MarkerSet s : api.markersets.values()) {
for(Marker m : s.getMarkers()) {
if(m.getMarkerIcon() == ico) {
m.setMarkerIcon(def); /* Set to default */
}
}
Set<MarkerIcon> allowed = s.getAllowedMarkerIcons();
if((allowed != null) && (allowed.contains(ico))) {
s.removeAllowedMarkerIcon(ico);
}
}
/* Remove files */
File f = new File(api.markerdir, ico.getMarkerIconID() + ".png");
f.delete();
api.core.getDefaultMapStorage().setMarkerImage(ico.getMarkerIconID(), null);
/* Remove from marker icons */
api.markericons.remove(ico.getMarkerIconID());
saveMarkers();
}
/**
* Test if given player can see another player on the map (based on player sets and privileges).
* @param player - player attempting to observe
* @param player_to_see - player to be observed by 'player'
* @return true if can be seen on map, false if cannot be seen
*/
public boolean testIfPlayerVisible(String player, String player_to_see)
{
if(api == null) return false;
/* Go through player sets - see if any are applicable */
for(Entry<String, PlayerSetImpl> s : playersets.entrySet()) {
PlayerSetImpl ps = s.getValue();
if(!ps.isPlayerInSet(player_to_see)) { /* Is in set? */
continue;
}
if(ps.isSymmetricSet() && ps.isPlayerInSet(player)) { /* If symmetric, and observer is there */
return true;
}
if(core.checkPermission(player, "playerset." + s.getKey())) { /* If player has privilege */
return true;
}
}
return false;
}
/**
* Get set of player visible to given player
* @param player - player to check
* @return set of visible players
*/
public Set<String> getPlayersVisibleToPlayer(String player) {
player = player.toLowerCase();
HashSet<String> pset = new HashSet<String>();
pset.add(player);
/* Go through player sets - see if any are applicable */
for(Entry<String, PlayerSetImpl> s : playersets.entrySet()) {
PlayerSetImpl ps = s.getValue();
if(ps.isSymmetricSet() && ps.isPlayerInSet(player)) { /* If symmetric, and observer is there */
pset.addAll(ps.getPlayers());
}
else if(core.checkPermission(player, "playerset." + s.getKey())) { /* If player has privilege */
pset.addAll(ps.getPlayers());
}
}
return pset;
}
/**
* Test if any markers with 'boost=true' intersect given map tile
* @param w - world
* @param perspective - perspective for transforming world to tile coordinates
* @param tile_x - X coordinate of tile corner, in map coords
* @param tile_y - Y coordinate of tile corner, in map coords
* @param tile_dim - Tile dimension, in map units
* @return true if intersected, false if not
*/
public static boolean testTileForBoostMarkers(DynmapWorld w, HDPerspective perspective, double tile_x, double tile_y, double tile_dim) {
if (api == null) return false;
for(MarkerSetImpl ms : api.markersets.values()) {
if(ms.testTileForBoostMarkers(w, perspective, tile_x, tile_y, tile_dim)) {
return true;
}
}
return false;
}
/**
* Build entered marker set based on given location
* @param worldid - world
* @param x
* @param y
* @param z
* @param entered
*/
public static void getEnteredMarkers(String worldid, double x, double y, double z, Set<EnterExitMarker> entered) {
if (api == null) return;
for(MarkerSetImpl ms : api.markersets.values()) {
ms.addEnteredMarkers(entered, worldid, x, y, z);
}
}
/**
* Check if loaded string needs to be escaped (if non-markup)
*/
public static String escapeForHTMLIfNeeded(String txt, boolean markup) {
if (markup) return txt; // Not needed for markup
// If escaped properly, these characters aren't present (all but ampersand of HTML active characrers
if (txt != null) {
if ((txt.indexOf('<') >= 0) || (txt.indexOf('>') >= 0) || (txt.indexOf('\'') >= 0) || (txt.indexOf('"') >= 0)) {
return Client.encodeForHTML(txt);
}
// If ampersand without semicolon after (simplistic check for ampersand without being escape sequence)
int idx = txt.lastIndexOf('&');
if ((idx >= 0) && (txt.indexOf(';', idx) < 0)) {
return Client.encodeForHTML(txt);
}
}
return txt;
}
}
|
DynmapCore/src/main/java/org/dynmap/markers/impl/MarkerAPIImpl.java
|
package org.dynmap.markers.impl;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import javax.imageio.ImageIO;
import org.dynmap.ConfigurationNode;
import org.dynmap.DynmapCore;
import org.dynmap.DynmapLocation;
import org.dynmap.DynmapWorld;
import org.dynmap.Event;
import org.dynmap.Log;
import org.dynmap.MapManager;
import org.dynmap.Client;
import org.dynmap.Client.ComponentMessage;
import org.dynmap.common.DynmapCommandSender;
import org.dynmap.common.DynmapPlayer;
import org.dynmap.hdmap.HDPerspective;
import org.dynmap.markers.AreaMarker;
import org.dynmap.markers.CircleMarker;
import org.dynmap.markers.EnterExitMarker;
import org.dynmap.markers.EnterExitMarker.EnterExitText;
import org.dynmap.markers.Marker;
import org.dynmap.markers.MarkerAPI;
import org.dynmap.markers.MarkerDescription;
import org.dynmap.markers.MarkerIcon;
import org.dynmap.markers.MarkerIcon.MarkerSize;
import org.dynmap.markers.MarkerSet;
import org.dynmap.markers.PlayerSet;
import org.dynmap.markers.PolyLineMarker;
import org.dynmap.utils.BufferOutputStream;
import org.dynmap.web.Json;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Supplier;
/**
* Implementation class for MarkerAPI - should not be called directly
*/
public class MarkerAPIImpl implements MarkerAPI, Event.Listener<DynmapWorld> {
private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
private File markerpersist;
private File markerpersist_old;
private File markerdir; /* Local store for markers (internal) */
private HashMap<String, MarkerIconImpl> markericons = new HashMap<String, MarkerIconImpl>();
private ConcurrentHashMap<String, MarkerSetImpl> markersets = new ConcurrentHashMap<String, MarkerSetImpl>();
private HashMap<String, List<DynmapLocation>> pointaccum = new HashMap<String, List<DynmapLocation>>();
private HashMap<String, PlayerSetImpl> playersets = new HashMap<String, PlayerSetImpl>();
private DynmapCore core;
static MarkerAPIImpl api;
private Map<String, Map<String, Supplier<String[]>>> tabCompletions = null;
/* Built-in icons */
private static final String[] builtin_icons = {
"anchor", "bank", "basket", "bed", "beer", "bighouse", "blueflag", "bomb", "bookshelf", "bricks", "bronzemedal", "bronzestar",
"building", "cake", "camera", "cart", "caution", "chest", "church", "coins", "comment", "compass", "construction",
"cross", "cup", "cutlery", "default", "diamond", "dog", "door", "down", "drink", "exclamation", "factory",
"fire", "flower", "gear", "goldmedal", "goldstar", "greenflag", "hammer", "heart", "house", "key", "king",
"left", "lightbulb", "lighthouse", "lock", "minecart", "orangeflag", "pin", "pinkflag", "pirateflag", "pointdown", "pointleft",
"pointright", "pointup", "portal", "purpleflag", "queen", "redflag", "right", "ruby", "scales", "skull", "shield", "sign",
"silvermedal", "silverstar", "star", "sun", "temple", "theater", "tornado", "tower", "tree", "truck", "up",
"walk", "warning", "world", "wrench", "yellowflag", "offlineuser"
};
/* Component messages for client updates */
public static class MarkerComponentMessage extends ComponentMessage {
public String ctype = "markers";
}
public static class MarkerUpdated extends MarkerComponentMessage {
public String msg;
public double x, y, z;
public String id;
public String label;
public String icon;
public String set;
public boolean markup;
public String desc;
public String dim;
public int minzoom;
public int maxzoom;
public MarkerUpdated(Marker m, boolean deleted) {
this.id = m.getMarkerID();
this.label = Client.sanitizeHTML(m.getLabel());
this.x = m.getX();
this.y = m.getY();
this.z = m.getZ();
this.set = m.getMarkerSet().getMarkerSetID();
this.icon = m.getMarkerIcon().getMarkerIconID();
this.markup = true; // We are markup format all the time now
this.desc = Client.sanitizeHTML(m.getDescription());
this.dim = m.getMarkerIcon().getMarkerIconSize().getSize();
this.minzoom = m.getMinZoom();
this.maxzoom = m.getMaxZoom();
if(deleted)
msg = "markerdeleted";
else
msg = "markerupdated";
}
@Override
public boolean equals(Object o) {
if(o instanceof MarkerUpdated) {
MarkerUpdated m = (MarkerUpdated)o;
return m.id.equals(id) && m.set.equals(set);
}
return false;
}
@Override
public int hashCode() {
return id.hashCode() ^ set.hashCode();
}
}
public static class AreaMarkerUpdated extends MarkerComponentMessage {
public String msg;
public double ytop, ybottom;
public double[] x;
public double[] z;
public int weight;
public double opacity;
public String color;
public double fillopacity;
public String fillcolor;
public String id;
public String label;
public String set;
public String desc;
public int minzoom;
public int maxzoom;
public boolean markup;
public AreaMarkerUpdated(AreaMarker m, boolean deleted) {
this.id = m.getMarkerID();
this.label = Client.sanitizeHTML(m.getLabel());
this.ytop = m.getTopY();
this.ybottom = m.getBottomY();
int cnt = m.getCornerCount();
x = new double[cnt];
z = new double[cnt];
for(int i = 0; i < cnt; i++) {
x[i] = m.getCornerX(i);
z[i] = m.getCornerZ(i);
}
color = String.format("#%06X", m.getLineColor());
weight = m.getLineWeight();
opacity = m.getLineOpacity();
fillcolor = String.format("#%06X", m.getFillColor());
fillopacity = m.getFillOpacity();
desc = Client.sanitizeHTML(m.getDescription());
this.minzoom = m.getMinZoom();
this.maxzoom = m.getMaxZoom();
this.markup = true; // We are markup format all the time now
this.set = m.getMarkerSet().getMarkerSetID();
if(deleted)
msg = "areadeleted";
else
msg = "areaupdated";
}
@Override
public boolean equals(Object o) {
if(o instanceof AreaMarkerUpdated) {
AreaMarkerUpdated m = (AreaMarkerUpdated)o;
return m.id.equals(id) && m.set.equals(set);
}
return false;
}
@Override
public int hashCode() {
return id.hashCode() ^ set.hashCode();
}
}
public static class PolyLineMarkerUpdated extends MarkerComponentMessage {
public String msg;
public double[] x;
public double[] y;
public double[] z;
public int weight;
public double opacity;
public String color;
public String id;
public String label;
public String set;
public String desc;
public int minzoom;
public int maxzoom;
public boolean markup;
public PolyLineMarkerUpdated(PolyLineMarker m, boolean deleted) {
this.id = m.getMarkerID();
this.label = Client.sanitizeHTML(m.getLabel());
this.markup = true; // We are markup format all the time now
int cnt = m.getCornerCount();
x = new double[cnt];
y = new double[cnt];
z = new double[cnt];
for(int i = 0; i < cnt; i++) {
x[i] = m.getCornerX(i);
y[i] = m.getCornerY(i);
z[i] = m.getCornerZ(i);
}
color = String.format("#%06X", m.getLineColor());
weight = m.getLineWeight();
opacity = m.getLineOpacity();
desc = Client.sanitizeHTML(m.getDescription());
this.minzoom = m.getMinZoom();
this.maxzoom = m.getMaxZoom();
this.set = m.getMarkerSet().getMarkerSetID();
if(deleted)
msg = "linedeleted";
else
msg = "lineupdated";
}
@Override
public boolean equals(Object o) {
if(o instanceof PolyLineMarkerUpdated) {
PolyLineMarkerUpdated m = (PolyLineMarkerUpdated)o;
return m.id.equals(id) && m.set.equals(set);
}
return false;
}
@Override
public int hashCode() {
return id.hashCode() ^ set.hashCode();
}
}
public static class CircleMarkerUpdated extends MarkerComponentMessage {
public String msg;
public double x;
public double y;
public double z;
public double xr;
public double zr;
public int weight;
public double opacity;
public String color;
public double fillopacity;
public String fillcolor;
public String id;
public String label;
public String set;
public String desc;
public int minzoom;
public int maxzoom;
public boolean markup;
public CircleMarkerUpdated(CircleMarker m, boolean deleted) {
this.id = m.getMarkerID();
this.label = Client.sanitizeHTML(m.getLabel());
this.x = m.getCenterX();
this.y = m.getCenterY();
this.z = m.getCenterZ();
this.xr = m.getRadiusX();
this.zr = m.getRadiusZ();
this.markup = true; // We are markup format all the time now
color = String.format("#%06X", m.getLineColor());
weight = m.getLineWeight();
opacity = m.getLineOpacity();
fillcolor = String.format("#%06X", m.getFillColor());
fillopacity = m.getFillOpacity();
desc = Client.sanitizeHTML(m.getDescription());
this.minzoom = m.getMinZoom();
this.maxzoom = m.getMaxZoom();
this.set = m.getMarkerSet().getMarkerSetID();
if(deleted)
msg = "circledeleted";
else
msg = "circleupdated";
}
@Override
public boolean equals(Object o) {
if(o instanceof CircleMarkerUpdated) {
CircleMarkerUpdated m = (CircleMarkerUpdated)o;
return m.id.equals(id) && m.set.equals(set);
}
return false;
}
@Override
public int hashCode() {
return id.hashCode() ^ set.hashCode();
}
}
public static class MarkerSetUpdated extends MarkerComponentMessage {
public String msg;
public String id;
public String label;
public int layerprio;
public int minzoom;
public int maxzoom;
public Boolean showlabels;
public MarkerSetUpdated(MarkerSet markerset, boolean deleted) {
this.id = markerset.getMarkerSetID();
this.label = markerset.getMarkerSetLabel();
this.layerprio = markerset.getLayerPriority();
this.minzoom = markerset.getMinZoom();
this.maxzoom = markerset.getMaxZoom();
this.showlabels = markerset.getLabelShow();
if(deleted)
msg = "setdeleted";
else
msg = "setupdated";
}
@Override
public boolean equals(Object o) {
if(o instanceof MarkerSetUpdated) {
MarkerSetUpdated m = (MarkerSetUpdated)o;
return m.id.equals(id);
}
return false;
}
@Override
public int hashCode() {
return id.hashCode();
}
}
private boolean stop = false;
private Set<String> dirty_worlds = new HashSet<String>();
private boolean dirty_markers = false;
private class DoFileWrites implements Runnable {
public void run() {
if(stop)
return;
lock.readLock().lock();
try {
/* Write markers first - drives JSON updates too */
if(dirty_markers) {
doSaveMarkers();
dirty_markers = false;
}
/* Process any dirty worlds */
if(!dirty_worlds.isEmpty()) {
for(String world : dirty_worlds) {
writeMarkersFile(world);
}
dirty_worlds.clear();
}
} finally {
lock.readLock().unlock();
}
core.getServer().scheduleServerTask(this, 20);
}
}
/**
* Singleton initializer
* @param core - core object
* @return API object
*/
public static MarkerAPIImpl initializeMarkerAPI(DynmapCore core) {
if(api != null) {
api.cleanup(core);
}
api = new MarkerAPIImpl();
api.core = core;
/* Initialize persistence file name */
api.markerpersist = new File(core.getDataFolder(), "markers.yml");
api.markerpersist_old = new File(core.getDataFolder(), "markers.yml.old");
/* Fill in default icons and sets, if needed */
for(int i = 0; i < builtin_icons.length; i++) {
String id = builtin_icons[i];
api.createBuiltinMarkerIcon(id, id);
}
/* Load persistence */
api.loadMarkers();
/* Initialize default marker set, if needed */
MarkerSet set = api.getMarkerSet(MarkerSet.DEFAULT);
if(set == null) {
set = api.createMarkerSet(MarkerSet.DEFAULT, "Markers", null, true);
}
/* Build paths for markers */
api.markerdir = new File(core.getDataFolder(), "markers");
if(api.markerdir.isDirectory() == false) {
if(api.markerdir.mkdirs() == false) { /* Create directory if needed */
Log.severe("Error creating markers directory - " + api.markerdir.getPath());
}
}
return api;
}
/**
* Singleton initializer complete (after rendder pool available
* @param core - core object
* @return API object
*/
public static void completeInitializeMarkerAPI(MarkerAPIImpl api) {
MapManager.scheduleDelayedJob(new Runnable() {
public void run() {
/* Now publish marker files to the tiles directory */
for(MarkerIcon ico : api.getMarkerIcons()) {
api.publishMarkerIcon(ico);
}
/* Freshen files */
api.freshenMarkerFiles();
/* Add listener so we update marker files for other worlds as they become active */
api.core.events.addListener("worldactivated", api);
api.scheduleWriteJob(); /* Start write job */
Log.info("Finish marker initialization");
}
}, 0);
}
/**
* Generates a map of field:value argument tab completion suggestions for every /dmarker subcommand
* This is quite long as there are a lot of arguments to deal with, and don't have Java 9 map literals
*/
private void initTabCompletions() {
//Static values
String[] emptyValue = new String[]{};
String[] booleanValue = new String[]{"true", "false"};
String[] typeValue = new String[]{"icon", "area", "line", "circle"};
Supplier<String[]> emptySupplier = () -> emptyValue;
Supplier<String[]> booleanSupplier = () -> booleanValue;
//Dynamic values
Supplier<String[]> iconSupplier = () -> markericons.keySet().toArray(new String[0]);
Supplier<String[]> markerSetSupplier = () -> markersets.keySet().toArray(new String[0]);
Supplier<String[]> worldSupplier = () ->
core.mapManager.getWorlds().stream().map(DynmapWorld::getName).toArray(String[]::new);
//Arguments used in multiple commands
Map<String, Supplier<String[]>> labelArg = Collections.singletonMap("label", emptySupplier);
Map<String, Supplier<String[]>> idArg = Collections.singletonMap("id", emptySupplier);
Map<String, Supplier<String[]>> newLabelArg = Collections.singletonMap("newlabel", emptySupplier);
Map<String, Supplier<String[]>> markerSetArg = Collections.singletonMap("set", markerSetSupplier);
Map<String, Supplier<String[]>> newSetArg = Collections.singletonMap("newset", markerSetSupplier);
Map<String, Supplier<String[]>> fileArg = Collections.singletonMap("file", emptySupplier);
//Arguments used in commands taking a location
Map<String, Supplier<String[]>> locationArgs = new LinkedHashMap<>();
locationArgs.put("x", emptySupplier);
locationArgs.put("y", emptySupplier);
locationArgs.put("z", emptySupplier);
locationArgs.put("world", worldSupplier);
//Args shared with all add/update commands
Map<String, Supplier<String[]>> sharedArgs = new LinkedHashMap<>(labelArg);
sharedArgs.putAll(idArg);
//Args shared with all add/update commands affecting objects visible on the map
Map<String, Supplier<String[]>> mapObjectArgs = new LinkedHashMap<>(sharedArgs);
mapObjectArgs.put("minzoom", emptySupplier);
mapObjectArgs.put("maxzoom", emptySupplier);
//Args for marker set add/update commands
Map<String, Supplier<String[]>> setArgs = new LinkedHashMap<>(mapObjectArgs);
setArgs.put("prio", emptySupplier);
setArgs.put("hide", booleanSupplier);
setArgs.put("showlabel", booleanSupplier);
setArgs.put("deficon", iconSupplier);
//Args for marker add/update commands
Map<String, Supplier<String[]>> markerArgs = new LinkedHashMap<>(mapObjectArgs);
markerArgs.putAll(markerSetArg);
markerArgs.put("markup", booleanSupplier);
markerArgs.put("icon", iconSupplier);
markerArgs.putAll(locationArgs);
//Args for area/line/circle add/update commands
Map<String, Supplier<String[]>> shapeArgs = new LinkedHashMap<>(mapObjectArgs);
shapeArgs.putAll(markerSetArg);
shapeArgs.put("markup", booleanSupplier);
shapeArgs.put("weight", emptySupplier);
shapeArgs.put("color", emptySupplier);
shapeArgs.put("opacity", emptySupplier);
//Args for area/circle add/update commands
Map<String, Supplier<String[]>> filledShapeArgs = new LinkedHashMap<>(shapeArgs);
filledShapeArgs.put("fillcolor", emptySupplier);
filledShapeArgs.put("fillopacity", emptySupplier);
filledShapeArgs.put("greeting", emptySupplier);
filledShapeArgs.put("greetingsub", emptySupplier);
filledShapeArgs.put("farewell", emptySupplier);
filledShapeArgs.put("farewellsub", emptySupplier);
filledShapeArgs.put("boost", booleanSupplier);
filledShapeArgs.putAll(locationArgs);
//Args for area add/update commands
Map<String, Supplier<String[]>> areaArgs = new LinkedHashMap<>(filledShapeArgs);
areaArgs.put("ytop", emptySupplier);
areaArgs.put("ybottom", emptySupplier);
//Args for circle add/update commands
Map<String, Supplier<String[]>> circleArgs = new LinkedHashMap<>(filledShapeArgs);
circleArgs.put("radius", emptySupplier);
circleArgs.put("radiusx", emptySupplier);
circleArgs.put("radiusz", emptySupplier);
//Args for icon add/update commands
Map<String, Supplier<String[]>> iconArgs = new LinkedHashMap<>(sharedArgs);
iconArgs.putAll(fileArg);
//Args for updateset command
Map<String, Supplier<String[]>> updateSetArgs = new LinkedHashMap<>(setArgs);
updateSetArgs.putAll(newLabelArg);
//Args for update (marker) command
Map<String, Supplier<String[]>> updateMarkerArgs = new LinkedHashMap<>(markerArgs);
updateMarkerArgs.putAll(newLabelArg);
updateMarkerArgs.putAll(newSetArg);
//Args for updateline command
Map<String, Supplier<String[]>> updateLineArgs = new LinkedHashMap<>(shapeArgs);
updateLineArgs.putAll(newLabelArg);
updateLineArgs.putAll(newSetArg);
//Args for updatearea command
Map<String, Supplier<String[]>> updateAreaArgs = new LinkedHashMap<>(areaArgs);
updateAreaArgs.putAll(newLabelArg);
updateAreaArgs.putAll(newSetArg);
//Args for updatecircle command
Map<String, Supplier<String[]>> updateCircleArgs = new LinkedHashMap<>(circleArgs);
updateCircleArgs.putAll(newLabelArg);
updateCircleArgs.putAll(newSetArg);
//Args for updateicon command
Map<String, Supplier<String[]>> updateIconArgs = new LinkedHashMap<>(iconArgs);
updateIconArgs.putAll(newLabelArg);
//Args for movehere command
Map<String, Supplier<String[]>> moveHereArgs = new LinkedHashMap<>(sharedArgs);
moveHereArgs.putAll(markerSetArg);
//Args for marker/area/circle/line delete commands
Map<String, Supplier<String[]>> deleteArgs = new LinkedHashMap<>(sharedArgs);
deleteArgs.putAll(markerSetArg);
//Args for label/desc commands
Map<String, Supplier<String[]>> descArgs = new LinkedHashMap<>(sharedArgs);
descArgs.putAll(markerSetArg);
descArgs.put("type", () -> typeValue);
//Args for label/desc import commands
Map<String, Supplier<String[]>> importArgs = new LinkedHashMap<>(descArgs);
importArgs.putAll(fileArg);
//Args for appendesc command
Map<String, Supplier<String[]>> appendArgs = new LinkedHashMap<>(descArgs);
appendArgs.put("desc", emptySupplier);
tabCompletions = new HashMap<>();
tabCompletions.put("add", markerArgs);
tabCompletions.put("addicon", iconArgs);
tabCompletions.put("addarea", areaArgs);
tabCompletions.put("addline", shapeArgs); //No unique args
tabCompletions.put("addcircle", circleArgs);
tabCompletions.put("addset", setArgs);
tabCompletions.put("update", updateMarkerArgs);
tabCompletions.put("updateicon", updateIconArgs);
tabCompletions.put("updatearea", updateAreaArgs);
tabCompletions.put("updateline", updateLineArgs);
tabCompletions.put("updatecircle", updateCircleArgs);
tabCompletions.put("updateset", updateSetArgs);
tabCompletions.put("movehere", moveHereArgs);
tabCompletions.put("delete", deleteArgs);
tabCompletions.put("deleteicon", sharedArgs); //Doesn't have set: arg
tabCompletions.put("deletearea", deleteArgs);
tabCompletions.put("deleteline", deleteArgs);
tabCompletions.put("deletecircle", deleteArgs);
tabCompletions.put("deleteset", sharedArgs); //Doesn't have set: arg
tabCompletions.put("list", markerSetArg);
tabCompletions.put("listareas", markerSetArg);
tabCompletions.put("listlines", markerSetArg);
tabCompletions.put("listcircles", markerSetArg);
tabCompletions.put("getdesc", descArgs);
tabCompletions.put("importdesc", importArgs);
tabCompletions.put("resetdesc", descArgs);
tabCompletions.put("getlabel", descArgs);
tabCompletions.put("importlabel", importArgs);
tabCompletions.put("appenddesc", appendArgs);
}
public void scheduleWriteJob() {
core.getServer().scheduleServerTask(new DoFileWrites(), 20);
}
/**
* Cleanup
* @param plugin - core object
*/
public void cleanup(DynmapCore plugin) {
plugin.events.removeListener("worldactivated", api);
stop = true;
lock.readLock().lock();
try {
if(dirty_markers) {
doSaveMarkers();
dirty_markers = false;
}
} finally {
lock.readLock().unlock();
}
lock.writeLock().lock();
try {
for(MarkerIconImpl icn : markericons.values())
icn.cleanup();
markericons.clear();
for(MarkerSetImpl set : markersets.values())
set.cleanup();
markersets.clear();
} finally {
lock.writeLock().unlock();
}
}
private MarkerIcon createBuiltinMarkerIcon(String id, String label) {
if(markericons.containsKey(id)) return null; /* Exists? */
MarkerIconImpl ico = new MarkerIconImpl(id, label, true);
markericons.put(id, ico); /* Add to set */
return ico;
}
void publishMarkerIcon(MarkerIcon ico) {
byte[] buf = new byte[512];
InputStream in = null;
File infile = new File(markerdir, ico.getMarkerIconID() + ".png"); /* Get source file name */
BufferedImage im = null;
if(ico.isBuiltIn()) {
in = getClass().getResourceAsStream("/markers/" + ico.getMarkerIconID() + ".png");
}
else if(infile.canRead()) { /* If it exists and is readable */
try {
im = ImageIO.read(infile);
} catch (IOException e) {
} catch (IndexOutOfBoundsException e) {
}
if(im != null) {
MarkerIconImpl icon = (MarkerIconImpl)ico;
int w = im.getWidth(); /* Get width */
if(w <= 8) { /* Small size? */
icon.setMarkerIconSize(MarkerSize.MARKER_8x8);
}
else if(w > 16) {
icon.setMarkerIconSize(MarkerSize.MARKER_32x32);
}
else {
icon.setMarkerIconSize(MarkerSize.MARKER_16x16);
}
im.flush();
}
try {
in = new FileInputStream(infile);
} catch (IOException iox) {
Log.severe("Error opening marker " + infile.getPath() + " - " + iox);
}
}
if(in == null) { /* Not found, use default marker */
in = getClass().getResourceAsStream("/markers/marker.png");
if(in == null) {
return;
}
}
/* Copy to destination */
try {
BufferOutputStream bos = new BufferOutputStream();
int len;
while((len = in.read(buf)) > 0) {
bos.write(buf, 0, len);
}
core.getDefaultMapStorage().setMarkerImage(ico.getMarkerIconID(), bos);
} catch (IOException iox) {
Log.severe("Error writing marker to tilespath");
} finally {
if(in != null) try { in.close(); } catch (IOException x){}
}
}
@Override
public Set<MarkerSet> getMarkerSets() {
return new HashSet<MarkerSet>(markersets.values());
}
@Override
public MarkerSet getMarkerSet(String id) {
return markersets.get(id);
}
@Override
public MarkerSet createMarkerSet(String id, String lbl, Set<MarkerIcon> iconlimit, boolean persistent) {
if(markersets.containsKey(id)) return null; /* Exists? */
MarkerSetImpl set = new MarkerSetImpl(id, lbl, iconlimit, persistent);
markersets.put(id, set); /* Add to list */
if(persistent) {
saveMarkers();
}
markerSetUpdated(set, MarkerUpdate.CREATED); /* Notify update */
return set;
}
@Override
public Set<MarkerIcon> getMarkerIcons() {
return new HashSet<MarkerIcon>(markericons.values());
}
@Override
public MarkerIcon getMarkerIcon(String id) {
return markericons.get(id);
}
boolean loadMarkerIconStream(String id, InputStream in) {
/* Copy icon resource into marker directory */
File f = new File(markerdir, id + ".png");
FileOutputStream fos = null;
try {
byte[] buf = new byte[512];
int len;
fos = new FileOutputStream(f);
while((len = in.read(buf)) > 0) {
fos.write(buf, 0, len);
}
} catch (IOException iox) {
Log.severe("Error copying marker - " + f.getPath());
return false;
} finally {
if(fos != null) try { fos.close(); } catch (IOException x) {}
}
return true;
}
@Override
public MarkerIcon createMarkerIcon(String id, String label, InputStream marker_png) {
if(markericons.containsKey(id)) return null; /* Exists? */
MarkerIconImpl ico = new MarkerIconImpl(id, label, false);
/* Copy icon resource into marker directory */
if(!loadMarkerIconStream(id, marker_png))
return null;
markericons.put(id, ico); /* Add to set */
/* Publish the marker */
publishMarkerIcon(ico);
saveMarkers(); /* Save results */
return ico;
}
static MarkerIconImpl getMarkerIconImpl(String id) {
if(api != null) {
return api.markericons.get(id);
}
return null;
}
@Override
public Set<PlayerSet> getPlayerSets() {
return new HashSet<PlayerSet>(playersets.values());
}
@Override
public PlayerSet getPlayerSet(String id) {
return playersets.get(id);
}
@Override
public PlayerSet createPlayerSet(String id, boolean symmetric, Set<String> players, boolean persistent) {
if(playersets.containsKey(id)) return null; /* Exists? */
PlayerSetImpl set = new PlayerSetImpl(id, symmetric, players, persistent);
playersets.put(id, set); /* Add to list */
if(persistent) {
saveMarkers();
}
playerSetUpdated(set, MarkerUpdate.CREATED); /* Notify update */
return set;
}
/**
* Save persistence for markers
*/
static void saveMarkers() {
if(api != null) {
api.dirty_markers = true;
}
}
private void doSaveMarkers() {
if(api != null) {
final ConfigurationNode conf = new ConfigurationNode(api.markerpersist); /* Make configuration object */
/* First, save icon definitions */
HashMap<String, Object> icons = new HashMap<String,Object>();
for(String id : api.markericons.keySet()) {
MarkerIconImpl ico = api.markericons.get(id);
Map<String,Object> dat = ico.getPersistentData();
if(dat != null) {
icons.put(id, dat);
}
}
conf.put("icons", icons);
/* Then, save persistent sets */
HashMap<String, Object> sets = new HashMap<String, Object>();
for(String id : api.markersets.keySet()) {
MarkerSetImpl set = api.markersets.get(id);
if(set.isMarkerSetPersistent()) {
Map<String, Object> dat = set.getPersistentData();
if(dat != null) {
sets.put(id, dat);
}
}
}
conf.put("sets", sets);
/* Then, save persistent player sets */
HashMap<String, Object> psets = new HashMap<String, Object>();
for(String id : api.playersets.keySet()) {
PlayerSetImpl set = api.playersets.get(id);
if(set.isPersistentSet()) {
Map<String, Object> dat = set.getPersistentData();
if(dat != null) {
psets.put(id, dat);
}
}
}
conf.put("playersets", psets);
MapManager.scheduleDelayedJob(new Runnable() {
public void run() {
/* And shift old file file out */
if(api.markerpersist_old.exists()) api.markerpersist_old.delete();
if(api.markerpersist.exists()) api.markerpersist.renameTo(api.markerpersist_old);
/* And write it out */
if(!conf.save())
Log.severe("Error writing markers - " + api.markerpersist.getPath());
}
}, 0);
/* Refresh JSON files */
api.freshenMarkerFiles();
}
}
private void freshenMarkerFiles() {
if(MapManager.mapman != null) {
for(DynmapWorld w : MapManager.mapman.worlds) {
dirty_worlds.add(w.getName());
}
}
}
/**
* Load persistence
*/
private boolean loadMarkers() {
ConfigurationNode conf = new ConfigurationNode(api.markerpersist); /* Make configuration object */
conf.load(); /* Load persistence */
lock.writeLock().lock();
try {
/* Get icons */
ConfigurationNode icons = conf.getNode("icons");
if(icons == null) return false;
for(String id : icons.keySet()) {
MarkerIconImpl ico = new MarkerIconImpl(id);
if(ico.loadPersistentData(icons.getNode(id))) {
markericons.put(id, ico);
}
}
/* Get marker sets */
ConfigurationNode sets = conf.getNode("sets");
if(sets != null) {
for(String id: sets.keySet()) {
MarkerSetImpl set = new MarkerSetImpl(id);
if(set.loadPersistentData(sets.getNode(id))) {
markersets.put(id, set);
}
}
}
/* Get player sets */
ConfigurationNode psets = conf.getNode("playersets");
if(psets != null) {
for(String id: psets.keySet()) {
PlayerSetImpl set = new PlayerSetImpl(id);
if(set.loadPersistentData(sets.getNode(id))) {
playersets.put(id, set);
}
}
}
} finally {
lock.writeLock().unlock();
}
return true;
}
enum MarkerUpdate { CREATED, UPDATED, DELETED };
/**
* Signal marker update
* @param marker - updated marker
* @param update - type of update
*/
static void markerUpdated(MarkerImpl marker, MarkerUpdate update) {
/* Freshen marker file for the world for this marker */
if(api != null)
api.dirty_worlds.add(marker.getNormalizedWorld());
/* Enqueue client update */
if(MapManager.mapman != null)
MapManager.mapman.pushUpdate(marker.getNormalizedWorld(), new MarkerUpdated(marker, update == MarkerUpdate.DELETED));
}
/**
* Signal area marker update
* @param marker - updated marker
* @param update - type of update
*/
static void areaMarkerUpdated(AreaMarkerImpl marker, MarkerUpdate update) {
/* Freshen marker file for the world for this marker */
if(api != null)
api.dirty_worlds.add(marker.getNormalizedWorld());
/* Enqueue client update */
if(MapManager.mapman != null)
MapManager.mapman.pushUpdate(marker.getNormalizedWorld(), new AreaMarkerUpdated(marker, update == MarkerUpdate.DELETED));
}
/**
* Signal poly-line marker update
* @param marker - updated marker
* @param update - type of update
*/
static void polyLineMarkerUpdated(PolyLineMarkerImpl marker, MarkerUpdate update) {
/* Freshen marker file for the world for this marker */
if(api != null)
api.dirty_worlds.add(marker.getNormalizedWorld());
/* Enqueue client update */
if(MapManager.mapman != null)
MapManager.mapman.pushUpdate(marker.getNormalizedWorld(), new PolyLineMarkerUpdated(marker, update == MarkerUpdate.DELETED));
}
/**
* Signal circle marker update
* @param marker - updated marker
* @param update - type of update
*/
static void circleMarkerUpdated(CircleMarkerImpl marker, MarkerUpdate update) {
/* Freshen marker file for the world for this marker */
if(api != null)
api.dirty_worlds.add(marker.getNormalizedWorld());
/* Enqueue client update */
if(MapManager.mapman != null)
MapManager.mapman.pushUpdate(marker.getNormalizedWorld(), new CircleMarkerUpdated(marker, update == MarkerUpdate.DELETED));
}
/**
* Signal marker set update
* @param markerset - updated marker set
* @param update - type of update
*/
static void markerSetUpdated(MarkerSetImpl markerset, MarkerUpdate update) {
/* Freshen all marker files */
if(api != null)
api.freshenMarkerFiles();
/* Enqueue client update */
if(MapManager.mapman != null)
MapManager.mapman.pushUpdate(new MarkerSetUpdated(markerset, update == MarkerUpdate.DELETED));
}
/**
* Signal player set update
* @param playerset - updated player set
* @param update - type of update
*/
static void playerSetUpdated(PlayerSetImpl pset, MarkerUpdate update) {
if(api != null)
api.core.events.trigger("playersetupdated", null);
}
/**
* Remove marker set
*/
static void removeMarkerSet(MarkerSetImpl markerset) {
if(api != null) {
api.markersets.remove(markerset.getMarkerSetID()); /* Remove set from list */
if(markerset.isMarkerSetPersistent()) { /* If persistent */
MarkerAPIImpl.saveMarkers(); /* Drive save */
}
markerSetUpdated(markerset, MarkerUpdate.DELETED); /* Signal delete of set */
}
}
/**
* Remove player set
*/
static void removePlayerSet(PlayerSetImpl pset) {
if(api != null) {
api.playersets.remove(pset.getSetID()); /* Remove set from list */
if(pset.isPersistentSet()) { /* If persistent */
MarkerAPIImpl.saveMarkers(); /* Drive save */
}
playerSetUpdated(pset, MarkerUpdate.DELETED); /* Signal delete of set */
}
}
private static boolean processAreaArgs(DynmapCommandSender sender, AreaMarker marker, Map<String,String> parms) {
String val = null;
String val2 = null;
try {
double ytop = marker.getTopY();
double ybottom = marker.getBottomY();
int scolor = marker.getLineColor();
int fcolor = marker.getFillColor();
double sopacity = marker.getLineOpacity();
double fopacity = marker.getFillOpacity();
int sweight = marker.getLineWeight();
boolean boost = marker.getBoostFlag();
int minzoom = marker.getMinZoom();
int maxzoom = marker.getMaxZoom();
EnterExitText greet = marker.getGreetingText();
EnterExitText farew = marker.getFarewellText();
val = parms.get(ARG_STROKECOLOR);
if(val != null)
scolor = Integer.parseInt(val, 16);
val = parms.get(ARG_FILLCOLOR);
if(val != null)
fcolor = Integer.parseInt(val, 16);
val = parms.get(ARG_STROKEOPACITY);
if(val != null)
sopacity = Double.parseDouble(val);
val = parms.get(ARG_FILLOPACITY);
if(val != null)
fopacity = Double.parseDouble(val);
val = parms.get(ARG_STROKEWEIGHT);
if(val != null)
sweight = Integer.parseInt(val);
val = parms.get(ARG_YTOP);
if(val != null)
ytop = Double.parseDouble(val);
val = parms.get(ARG_YBOTTOM);
if(val != null)
ybottom = Double.parseDouble(val);
val = parms.get(ARG_MINZOOM);
if (val != null)
minzoom = Integer.parseInt(val);
val = parms.get(ARG_MAXZOOM);
if (val != null)
maxzoom = Integer.parseInt(val);
val = parms.get(ARG_BOOST);
if(val != null) {
if(api.core.checkPlayerPermission(sender, "marker.boost")) {
boost = val.equals("true");
}
else {
sender.sendMessage("No permission to set boost flag");
return false;
}
}
marker.setLineStyle(sweight, sopacity, scolor);
marker.setFillStyle(fopacity, fcolor);
if(ytop >= ybottom)
marker.setRangeY(ytop, ybottom);
else
marker.setRangeY(ybottom, ytop);
marker.setBoostFlag(boost);
marker.setMinZoom(minzoom);
marker.setMaxZoom(maxzoom);
// Handle greeting
val = parms.get(ARG_GREETING);
val2 = parms.get(ARG_GREETINGSUB);
if ((val != null) || (val2 != null)) {
String title = (val != null) ? ((val.length() > 0) ? val : null) : ((greet != null) ? greet.title : null);
String subtitle = (val2 != null) ? ((val2.length() > 0) ? val2 : null) : ((greet != null) ? greet.subtitle : null);
marker.setGreetingText(title, subtitle);
}
// Handle farewell
val = parms.get(ARG_FAREWELL);
val2 = parms.get(ARG_FAREWELLSUB);
if ((val != null) || (val2 != null)) {
String title = (val != null) ? ((val.length() > 0) ? val : null) : ((farew != null) ? farew.title : null);
String subtitle = (val2 != null) ? ((val2.length() > 0) ? val2 : null) : ((farew != null) ? farew.subtitle : null);
marker.setFarewellText(title, subtitle);
}
} catch (NumberFormatException nfx) {
sender.sendMessage("Invalid parameter format: " + val);
return false;
}
return true;
}
private static boolean processPolyArgs(DynmapCommandSender sender, PolyLineMarker marker, Map<String,String> parms) {
String val = null;
try {
int scolor = marker.getLineColor();
double sopacity = marker.getLineOpacity();
int sweight = marker.getLineWeight();
int minzoom = marker.getMinZoom();
int maxzoom = marker.getMaxZoom();
val = parms.get(ARG_STROKECOLOR);
if(val != null)
scolor = Integer.parseInt(val, 16);
val = parms.get(ARG_STROKEOPACITY);
if(val != null)
sopacity = Double.parseDouble(val);
val = parms.get(ARG_STROKEWEIGHT);
if(val != null)
sweight = Integer.parseInt(val);
val = parms.get(ARG_MINZOOM);
if(val != null)
minzoom = Integer.parseInt(val);
val = parms.get(ARG_MAXZOOM);
if(val != null)
maxzoom = Integer.parseInt(val);
marker.setLineStyle(sweight, sopacity, scolor);
marker.setMinZoom(minzoom);
marker.setMaxZoom(maxzoom);
} catch (NumberFormatException nfx) {
sender.sendMessage("Invalid parameter format: " + val);
return false;
}
return true;
}
private static boolean processCircleArgs(DynmapCommandSender sender, CircleMarker marker, Map<String,String> parms) {
String val = null, val2 = null;
try {
int scolor = marker.getLineColor();
int fcolor = marker.getFillColor();
double sopacity = marker.getLineOpacity();
double fopacity = marker.getFillOpacity();
int sweight = marker.getLineWeight();
double xr = marker.getRadiusX();
double zr = marker.getRadiusZ();
double x = marker.getCenterX();
double y = marker.getCenterY();
double z = marker.getCenterZ();
String world = marker.getWorld();
boolean boost = marker.getBoostFlag();
int minzoom = marker.getMinZoom();
int maxzoom = marker.getMaxZoom();
EnterExitText greet = marker.getGreetingText();
EnterExitText farew = marker.getFarewellText();
val = parms.get(ARG_STROKECOLOR);
if(val != null)
scolor = Integer.parseInt(val, 16);
val = parms.get(ARG_FILLCOLOR);
if(val != null)
fcolor = Integer.parseInt(val, 16);
val = parms.get(ARG_STROKEOPACITY);
if(val != null)
sopacity = Double.parseDouble(val);
val = parms.get(ARG_FILLOPACITY);
if(val != null)
fopacity = Double.parseDouble(val);
val = parms.get(ARG_STROKEWEIGHT);
if(val != null)
sweight = Integer.parseInt(val);
val = parms.get(ARG_X);
if(val != null)
x = Double.parseDouble(val);
val = parms.get(ARG_Y);
if(val != null)
y = Double.parseDouble(val);
val = parms.get(ARG_Z);
if(val != null)
z = Double.parseDouble(val);
val = parms.get(ARG_WORLD);
if(val != null)
world = val;
val = parms.get(ARG_RADIUSX);
if(val != null)
xr = Double.parseDouble(val);
val = parms.get(ARG_RADIUSZ);
if(val != null)
zr = Double.parseDouble(val);
val = parms.get(ARG_RADIUS);
if(val != null)
xr = zr = Double.parseDouble(val);
val = parms.get(ARG_BOOST);
if(val != null) {
if(api.core.checkPlayerPermission(sender, "marker.boost")) {
boost = val.equals("true");
}
else {
sender.sendMessage("No permission to set boost flag");
return false;
}
}
val = parms.get(ARG_MINZOOM);
if (val != null) {
minzoom = Integer.parseInt(val);
}
val = parms.get(ARG_MAXZOOM);
if (val != null) {
maxzoom = Integer.parseInt(val);
}
marker.setCenter(world, x, y, z);
marker.setLineStyle(sweight, sopacity, scolor);
marker.setFillStyle(fopacity, fcolor);
marker.setRadius(xr, zr);
marker.setBoostFlag(boost);
marker.setMinZoom(minzoom);
marker.setMaxZoom(maxzoom);
// Handle greeting
val = parms.get(ARG_GREETING);
val2 = parms.get(ARG_GREETINGSUB);
if ((val != null) || (val2 != null)) {
String title = (val != null) ? ((val.length() > 0) ? val : null) : ((greet != null) ? greet.title : null);
String subtitle = (val2 != null) ? ((val2.length() > 0) ? val2 : null) : ((greet != null) ? greet.subtitle : null);
marker.setGreetingText(title, subtitle);
}
// Handle farewell
val = parms.get(ARG_FAREWELL);
val2 = parms.get(ARG_FAREWELLSUB);
if ((val != null) || (val2 != null)) {
String title = (val != null) ? ((val.length() > 0) ? val : null) : ((farew != null) ? farew.title : null);
String subtitle = (val2 != null) ? ((val2.length() > 0) ? val2 : null) : ((farew != null) ? farew.subtitle : null);
marker.setFarewellText(title, subtitle);
}
} catch (NumberFormatException nfx) {
sender.sendMessage("Invalid parameter format: " + val);
return false;
}
return true;
}
private static final Set<String> commands = new HashSet<String>(Arrays.asList(new String[] {
"add", "movehere", "update", "delete", "list", "icons", "addset", "updateset", "deleteset", "listsets", "addicon", "updateicon",
"deleteicon", "addcorner", "clearcorners", "addarea", "listareas", "deletearea", "updatearea",
"addline", "listlines", "deleteline", "updateline", "addcircle", "listcircles", "deletecircle", "updatecircle",
"getdesc", "resetdesc", "appenddesc", "importdesc", "getlabel", "importlabel"
}));
private static final String ARG_LABEL = "label";
private static final String ARG_MARKUP = "markup";
private static final String ARG_ID = "id";
private static final String ARG_TYPE = "type";
private static final String ARG_NEWLABEL = "newlabel";
private static final String ARG_FILE = "file";
private static final String ARG_HIDE = "hide";
private static final String ARG_ICON = "icon";
private static final String ARG_DEFICON = "deficon";
private static final String ARG_SET = "set";
private static final String ARG_NEWSET = "newset";
private static final String ARG_PRIO = "prio";
private static final String ARG_MINZOOM = "minzoom";
private static final String ARG_MAXZOOM = "maxzoom";
private static final String ARG_STROKEWEIGHT = "weight";
private static final String ARG_STROKECOLOR = "color";
private static final String ARG_STROKEOPACITY = "opacity";
private static final String ARG_FILLCOLOR = "fillcolor";
private static final String ARG_FILLOPACITY = "fillopacity";
private static final String ARG_YTOP = "ytop";
private static final String ARG_YBOTTOM = "ybottom";
private static final String ARG_RADIUSX = "radiusx";
private static final String ARG_RADIUSZ = "radiusz";
private static final String ARG_RADIUS = "radius";
private static final String ARG_SHOWLABEL = "showlabels";
private static final String ARG_X = "x";
private static final String ARG_Y = "y";
private static final String ARG_Z = "z";
private static final String ARG_WORLD = "world";
private static final String ARG_BOOST = "boost";
private static final String ARG_DESC = "desc";
private static final String ARG_GREETING = "greeting";
private static final String ARG_GREETINGSUB = "greetingsub";
private static final String ARG_FAREWELL = "farewell";
private static final String ARG_FAREWELLSUB = "farewellsub";
/* Parse argument strings : handle 'attrib:value' and quoted strings */
private static Map<String,String> parseArgs(String[] args, DynmapCommandSender snd) {
HashMap<String,String> rslt = new HashMap<String,String>();
/* Build command line, so we can parse our way - make sure there is trailing space */
String cmdline = "";
for(int i = 1; i < args.length; i++) {
cmdline += args[i] + " ";
}
boolean inquote = false;
StringBuilder sb = new StringBuilder();
String varid = null;
for(int i = 0; i < cmdline.length(); i++) {
char c = cmdline.charAt(i);
if(inquote) { /* If in quote, accumulate until end or another quote */
if(c == '\"') { /* End quote */
inquote = false;
if(varid == null) { /* No varid? */
rslt.put(ARG_LABEL, sb.toString());
}
else {
rslt.put(varid, sb.toString());
varid = null;
}
sb.setLength(0);
}
else {
sb.append(c);
}
}
else if(c == '\"') { /* Start of quote? */
inquote = true;
}
else if(c == ':') { /* var:value */
varid = sb.toString(); /* Save variable ID */
sb.setLength(0);
}
else if(c == ' ') { /* Ending space? */
if(varid == null) { /* No varid? */
if(sb.length() > 0) {
rslt.put(ARG_LABEL, sb.toString());
}
}
else {
rslt.put(varid, sb.toString());
varid = null;
}
sb.setLength(0);
}
else {
sb.append(c);
}
}
if(inquote) { /* If still in quote, syntax error */
snd.sendMessage("Error: unclosed doublequote");
return null;
}
return rslt;
}
public static boolean onCommand(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
if(api == null) {
sender.sendMessage("Markers component is not enabled.");
return false;
}
if(args.length == 0)
return false;
DynmapPlayer player = null;
if (sender instanceof DynmapPlayer)
player = (DynmapPlayer) sender;
/* Check if valid command */
String c = args[0];
if (!commands.contains(c)) {
return false;
}
/* Process commands read commands */
api.lock.readLock().lock();
try {
/* List markers */
if(c.equals("list") && plugin.checkPlayerPermission(sender, "marker.list")) {
return processListMarker(plugin, sender, cmd, commandLabel, args);
}
/* List icons */
else if(c.equals("icons") && plugin.checkPlayerPermission(sender, "marker.icons")) {
return processListIcon(plugin, sender, cmd, commandLabel, args);
}
/* List sets */
else if(c.equals("listsets") && plugin.checkPlayerPermission(sender, "marker.listsets")) {
return processListSet(plugin, sender, cmd, commandLabel, args);
}
/* List areas */
else if(c.equals("listareas") && plugin.checkPlayerPermission(sender, "marker.listareas")) {
return processListArea(plugin, sender, cmd, commandLabel, args);
}
/* List poly-lines */
else if(c.equals("listlines") && plugin.checkPlayerPermission(sender, "marker.listlines")) {
return processListLine(plugin, sender, cmd, commandLabel, args);
}
/* List circles */
else if(c.equals("listcircles") && plugin.checkPlayerPermission(sender, "marker.listcircles")) {
return processListCircle(plugin, sender, cmd, commandLabel, args);
}
/* Get label for given item - must have ID and type parameter */
else if(c.equals("getlabel") && plugin.checkPlayerPermission(sender, "marker.getlabel")) {
return processGetLabel(plugin, sender, cmd, commandLabel, args);
}
} finally {
api.lock.readLock().unlock();
}
// Handle modify commands
api.lock.writeLock().lock();
try {
if(c.equals("add") && api.core.checkPlayerPermission(sender, "marker.add")) {
return processAddMarker(plugin, sender, cmd, commandLabel, args, player);
}
/* Update position of bookmark - must have ID parameter */
else if(c.equals("movehere") && plugin.checkPlayerPermission(sender, "marker.movehere")) {
return processMoveHere(plugin, sender, cmd, commandLabel, args, player);
}
/* Update other attributes of marker - must have ID parameter */
else if(c.equals("update") && plugin.checkPlayerPermission(sender, "marker.update")) {
return processUpdateMarker(plugin, sender, cmd, commandLabel, args);
}
/* Delete marker - must have ID parameter */
else if(c.equals("delete") && plugin.checkPlayerPermission(sender, "marker.delete")) {
return processDeleteMarker(plugin, sender, cmd, commandLabel, args);
}
else if(c.equals("addset") && plugin.checkPlayerPermission(sender, "marker.addset")) {
return processAddSet(plugin, sender, cmd, commandLabel, args, player);
}
else if(c.equals("updateset") && plugin.checkPlayerPermission(sender, "marker.updateset")) {
return processUpdateSet(plugin, sender, cmd, commandLabel, args);
}
else if(c.equals("deleteset") && plugin.checkPlayerPermission(sender, "marker.deleteset")) {
return processDeleteSet(plugin, sender, cmd, commandLabel, args);
}
/* Add new icon */
else if(c.equals("addicon") && plugin.checkPlayerPermission(sender, "marker.addicon")) {
return processAddIcon(plugin, sender, cmd, commandLabel, args);
}
else if(c.equals("updateicon") && plugin.checkPlayerPermission(sender, "marker.updateicon")) {
return processUpdateIcon(plugin, sender, cmd, commandLabel, args);
}
else if(c.equals("deleteicon") && plugin.checkPlayerPermission(sender, "marker.deleteicon")) {
return processDeleteIcon(plugin, sender, cmd, commandLabel, args);
}
/* Add point to accumulator */
else if(c.equals("addcorner") && plugin.checkPlayerPermission(sender, "marker.addarea")) {
return processAddCorner(plugin, sender, cmd, commandLabel, args, player);
}
else if(c.equals("clearcorners") && plugin.checkPlayerPermission(sender, "marker.addarea")) {
return processClearCorners(plugin, sender, cmd, commandLabel, args, player);
}
else if(c.equals("addarea") && plugin.checkPlayerPermission(sender, "marker.addarea")) {
return processAddArea(plugin, sender, cmd, commandLabel, args, player);
}
/* Delete area - must have ID parameter */
else if(c.equals("deletearea") && plugin.checkPlayerPermission(sender, "marker.deletearea")) {
return processDeleteArea(plugin, sender, cmd, commandLabel, args);
}
/* Update other attributes of area - must have ID parameter */
else if(c.equals("updatearea") && plugin.checkPlayerPermission(sender, "marker.updatearea")) {
return processUpdateArea(plugin, sender, cmd, commandLabel, args);
}
else if(c.equals("addline") && plugin.checkPlayerPermission(sender, "marker.addline")) {
return processAddLine(plugin, sender, cmd, commandLabel, args, player);
}
/* Delete poly-line - must have ID parameter */
else if(c.equals("deleteline") && plugin.checkPlayerPermission(sender, "marker.deleteline")) {
return processDeleteLine(plugin, sender, cmd, commandLabel, args);
}
/* Update other attributes of poly-line - must have ID parameter */
else if(c.equals("updateline") && plugin.checkPlayerPermission(sender, "marker.updateline")) {
return processUpdateLine(plugin, sender, cmd, commandLabel, args);
}
else if(c.equals("addcircle") && plugin.checkPlayerPermission(sender, "marker.addcircle")) {
return processAddCircle(plugin, sender, cmd, commandLabel, args, player);
}
/* Delete circle - must have ID parameter */
else if(c.equals("deletecircle") && plugin.checkPlayerPermission(sender, "marker.deletecircle")) {
return processDeleteCircle(plugin, sender, cmd, commandLabel, args);
}
/* Update other attributes of circle - must have ID parameter */
else if(c.equals("updatecircle") && plugin.checkPlayerPermission(sender, "marker.updatecircle")) {
return processUpdateCircle(plugin, sender, cmd, commandLabel, args);
}
/* Get description for given item - must have ID and type parameter */
else if(c.equals("getdesc") && plugin.checkPlayerPermission(sender, "marker.getdesc")) {
return processGetDesc(plugin, sender, cmd, commandLabel, args);
}
/* Reset description for given item - must have ID and type parameter */
else if(c.equals("resetdesc") && plugin.checkPlayerPermission(sender, "marker.resetdesc")) {
return processResetDesc(plugin, sender, cmd, commandLabel, args);
}
/* Append to description for given item - must have ID and type parameter */
else if(c.equals("appenddesc") && plugin.checkPlayerPermission(sender, "marker.appenddesc")) {
return processAppendDesc(plugin, sender, cmd, commandLabel, args);
}
/* Import description for given item from file - must have ID and type parameter */
else if(c.equals("importdesc") && plugin.checkPlayerPermission(sender, "marker.importdesc")) {
return processImportDesc(plugin, sender, cmd, commandLabel, args);
}
/* Import description for given item from file - must have ID and type parameter */
else if(c.equals("importlabel") && plugin.checkPlayerPermission(sender, "marker.importlabel")) {
return processImportLabel(plugin, sender, cmd, commandLabel, args);
}
else {
return false;
}
} finally {
api.lock.writeLock().unlock();
}
}
public List<String> getTabCompletions(DynmapCommandSender sender, String[] args, DynmapCore core) {
/* Re-parse args - handle doublequotes */
args = DynmapCore.parseArgs(args, sender, true);
if (args == null || args.length <= 1) {
return Collections.emptyList();
}
if (tabCompletions == null) {
initTabCompletions();
}
String cmd = args[0];
if (cmd.equals("addcorner") && core.checkPlayerPermission(sender, "marker.addarea")) {
if (args.length == 5) {
return core.getWorldSuggestions(args[4]);
}
} else if (core.checkPlayerPermission(sender, "marker." + cmd)
&& tabCompletions.containsKey(cmd)) {
return core.getFieldValueSuggestions(args, tabCompletions.get(cmd));
}
return Collections.emptyList();
}
private static boolean processAddMarker(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args, DynmapPlayer player) {
String id, setid, label, iconid, markup;
String x, y, z, world, normalized_world;
if(args.length > 1) {
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
iconid = parms.get(ARG_ICON);
setid = parms.get(ARG_SET);
id = parms.get(ARG_ID);
label = parms.get(ARG_LABEL);
markup = parms.get(ARG_MARKUP);
x = parms.get(ARG_X);
y = parms.get(ARG_Y);
z = parms.get(ARG_Z);
String minzoom = parms.get(ARG_MINZOOM);
int min_zoom = -1;
if (minzoom != null) {
try {
min_zoom = Integer.parseInt(minzoom);
} catch (NumberFormatException nfx) {
sender.sendMessage("Invalid minzoom: " + minzoom);
return true;
}
}
String maxzoom = parms.get(ARG_MAXZOOM);
int max_zoom = -1;
if (maxzoom != null) {
try {
max_zoom = Integer.parseInt(maxzoom);
} catch (NumberFormatException nfx) {
sender.sendMessage("Invalid maxzoom: " + maxzoom);
return true;
}
}
world = DynmapWorld.normalizeWorldName(parms.get(ARG_WORLD));
if(world != null) {
normalized_world = DynmapWorld.normalizeWorldName(world);
if(api.core.getWorld(normalized_world) == null) {
sender.sendMessage("Invalid world ID: " + world);
return true;
}
}
DynmapLocation loc = null;
if((x == null) && (y == null) && (z == null) && (world == null)) {
if(player == null) {
sender.sendMessage("Must be issued by player, or x, y, z, and world parameters are required");
return true;
}
loc = player.getLocation();
}
else if((x != null) && (y != null) && (z != null) && (world != null)) {
try {
loc = new DynmapLocation(world, Double.valueOf(x), Double.valueOf(y), Double.valueOf(z));
} catch (NumberFormatException nfx) {
sender.sendMessage("Coordinates x, y, and z must be numbers");
return true;
}
}
else {
sender.sendMessage("Must be issued by player, or x, y, z, and world parameters are required");
return true;
}
/* Fill in defaults for missing parameters */
if(setid == null) {
setid = MarkerSet.DEFAULT;
}
/* Add new marker */
MarkerSet set = api.getMarkerSet(setid);
if(set == null) {
sender.sendMessage("Error: invalid set - " + setid);
return true;
}
// Prevent adding persistent markers to a non-persistent set
if (!set.isMarkerSetPersistent()) {
sender.sendMessage("Error: cannot add to non-persistent marker set - set is likely plugin owned");
return true;
}
MarkerIcon ico = null;
if(iconid == null) {
ico = set.getDefaultMarkerIcon();
}
if(ico == null) {
if(iconid == null) {
iconid = MarkerIcon.DEFAULT;
}
ico = api.getMarkerIcon(iconid);
}
if(ico == null) {
sender.sendMessage("Error: invalid icon - " + iconid);
return true;
}
if (minzoom != null) {
}
boolean isMarkup = "true".equals(markup);
Marker m = set.createMarker(id, label, isMarkup,
loc.world, loc.x, loc.y, loc.z, ico, true);
if(m == null) {
sender.sendMessage("Error creating marker");
}
else {
if (min_zoom >= 0) {
m.setMinZoom(min_zoom);
}
if (max_zoom >= 0) {
m.setMaxZoom(max_zoom);
}
sender.sendMessage("Added marker id:'" + m.getMarkerID() + "' (" + m.getLabel() + ") to set '" + set.getMarkerSetID() + "'");
}
}
else {
sender.sendMessage("Marker label required");
}
return true;
}
private static boolean processMoveHere(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args, DynmapPlayer player) {
String id, label, setid;
if(player == null) {
sender.sendMessage("Command can only be used by player");
}
else if(args.length > 1) {
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
id = parms.get(ARG_ID);
label = parms.get(ARG_LABEL);
setid = parms.get(ARG_SET);
if((id == null) && (label == null)) {
sender.sendMessage("<label> or id:<marker-id> required");
return true;
}
if(setid == null) {
setid = MarkerSet.DEFAULT;
}
MarkerSet set = api.getMarkerSet(setid);
if(set == null) {
sender.sendMessage("Error: invalid set - " + setid);
return true;
}
Marker marker;
if(id != null) {
marker = set.findMarker(id);
if(marker == null) { /* No marker */
sender.sendMessage("Error: marker not found - " + id);
return true;
}
}
else {
marker = set.findMarkerByLabel(label);
if(marker == null) { /* No marker */
sender.sendMessage("Error: marker not found - " + label);
return true;
}
}
DynmapLocation loc = player.getLocation();
marker.setLocation(loc.world, loc.x, loc.y, loc.z);
sender.sendMessage("Updated location of marker id:" + marker.getMarkerID() + " (" + marker.getLabel() + ")");
}
else {
sender.sendMessage("<label> or id:<marker-id> required");
}
return true;
}
private static boolean processUpdateMarker(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
String id, setid, label, newlabel, iconid, markup;
String x, y, z, world;
String newset;
if(args.length > 1) {
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
id = parms.get(ARG_ID);
label = parms.get(ARG_LABEL);
markup = parms.get(ARG_MARKUP);
setid = parms.get(ARG_SET);
newset = parms.get(ARG_NEWSET);
x = parms.get(ARG_X);
y = parms.get(ARG_Y);
z = parms.get(ARG_Z);
String minzoom = parms.get(ARG_MINZOOM);
int min_zoom = -1;
if (minzoom != null) {
try {
min_zoom = Integer.parseInt(minzoom);
} catch (NumberFormatException nfx) {
sender.sendMessage("Invalid minzoom: " + minzoom);
return true;
}
}
String maxzoom = parms.get(ARG_MAXZOOM);
int max_zoom = -1;
if (maxzoom != null) {
try {
max_zoom = Integer.parseInt(maxzoom);
} catch (NumberFormatException nfx) {
sender.sendMessage("Invalid maxzoom: " + maxzoom);
return true;
}
}
world = parms.get(ARG_WORLD);
if(world != null) {
if(api.core.getWorld(world) == null) {
sender.sendMessage("Invalid world ID: " + world);
return true;
}
}
DynmapLocation loc = null;
if((x != null) && (y != null) && (z != null) && (world != null)) {
try {
loc = new DynmapLocation(world, Double.valueOf(x), Double.valueOf(y), Double.valueOf(z));
} catch (NumberFormatException nfx) {
sender.sendMessage("Coordinates x, y, and z must be numbers");
return true;
}
}
if((id == null) && (label == null)) {
sender.sendMessage("<label> or id:<marker-id> required");
return true;
}
if(setid == null) {
setid = MarkerSet.DEFAULT;
}
MarkerSet set = api.getMarkerSet(setid);
if(set == null) {
sender.sendMessage("Error: invalid set - " + setid);
return true;
}
Marker marker;
if(id != null) {
marker = set.findMarker(id);
if(marker == null) { /* No marker */
sender.sendMessage("Error: marker not found - " + id);
return true;
}
}
else {
marker = set.findMarkerByLabel(label);
if(marker == null) { /* No marker */
sender.sendMessage("Error: marker not found - " + label);
return true;
}
}
newlabel = parms.get(ARG_NEWLABEL);
if(newlabel != null) { /* Label set? */
marker.setLabel(newlabel, "true".equals(markup));
}
else if(markup != null) {
marker.setLabel(marker.getLabel(), "true".equals(markup));
}
iconid = parms.get(ARG_ICON);
if(iconid != null) {
MarkerIcon ico = api.getMarkerIcon(iconid);
if(ico == null) {
sender.sendMessage("Error: invalid icon - " + iconid);
return true;
}
marker.setMarkerIcon(ico);
}
if(loc != null)
marker.setLocation(loc.world, loc.x, loc.y, loc.z);
if (min_zoom >= 0) {
marker.setMinZoom(min_zoom);
}
if (max_zoom >= 0) {
marker.setMaxZoom(max_zoom);
}
if(newset != null) {
MarkerSet ms = api.getMarkerSet(newset);
if(ms == null) {
sender.sendMessage("Error: invalid new marker set - " + newset);
return true;
}
marker.setMarkerSet(ms);
}
sender.sendMessage("Updated marker id:" + marker.getMarkerID() + " (" + marker.getLabel() + ")");
}
else {
sender.sendMessage("<label> or id:<marker-id> required");
}
return true;
}
private static boolean processDeleteMarker(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
String id, label, setid;
if(args.length > 1) {
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
id = parms.get(ARG_ID);
label = parms.get(ARG_LABEL);
setid = parms.get(ARG_SET);
if((id == null) && (label == null)) {
sender.sendMessage("<label> or id:<marker-id> required");
return true;
}
if(setid == null) {
setid = MarkerSet.DEFAULT;
}
MarkerSet set = api.getMarkerSet(setid);
if(set == null) {
sender.sendMessage("Error: invalid set - " + setid);
return true;
}
Marker marker;
if(id != null) {
marker = set.findMarker(id);
if(marker == null) { /* No marker */
sender.sendMessage("Error: marker not found - " + id);
return true;
}
}
else {
marker = set.findMarkerByLabel(label);
if(marker == null) { /* No marker */
sender.sendMessage("Error: marker not found - " + label);
return true;
}
}
marker.deleteMarker();
sender.sendMessage("Deleted marker id:" + marker.getMarkerID() + " (" + marker.getLabel() + ")");
}
else {
sender.sendMessage("<label> or id:<marker-id> required");
}
return true;
}
private static boolean processListMarker(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
String setid;
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
setid = parms.get(ARG_SET);
if(setid == null) {
setid = MarkerSet.DEFAULT;
}
MarkerSet set = api.getMarkerSet(setid);
if(set == null) {
sender.sendMessage("Error: invalid set - " + setid);
return true;
}
Set<Marker> markers = set.getMarkers();
TreeMap<String, Marker> sortmarkers = new TreeMap<String, Marker>();
for(Marker m : markers) {
sortmarkers.put(m.getMarkerID(), m);
}
for(String s : sortmarkers.keySet()) {
Marker m = sortmarkers.get(s);
String msg = m.getMarkerID() + ": label:\"" + m.getLabel() + "\", set:" + m.getMarkerSet().getMarkerSetID() +
", world:" + m.getWorld() + ", x:" + m.getX() + ", y:" + m.getY() + ", z:" + m.getZ() +
", icon:" + m.getMarkerIcon().getMarkerIconID() + ", markup:" + m.isLabelMarkup();
if (m.getMinZoom() >= 0) {
msg += ", minzoom:" + m.getMinZoom();
}
if (m.getMaxZoom() >= 0) {
msg += ", maxzoom:" + m.getMaxZoom();
}
sender.sendMessage(msg);
}
return true;
}
private static boolean processListIcon(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
Set<String> iconids = new TreeSet<String>(api.markericons.keySet());
for(String s : iconids) {
MarkerIcon ico = api.markericons.get(s);
sender.sendMessage(ico.getMarkerIconID() + ": label:\"" + ico.getMarkerIconLabel() + "\", builtin:" + ico.isBuiltIn());
}
return true;
}
private static boolean processAddSet(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args, DynmapPlayer player) {
String id, label, prio, minzoom, maxzoom, deficon;
if(args.length > 1) {
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
id = parms.get(ARG_ID);
label = parms.get(ARG_LABEL);
prio = parms.get(ARG_PRIO);
minzoom = parms.get(ARG_MINZOOM);
maxzoom = parms.get(ARG_MAXZOOM);
deficon = parms.get(ARG_DEFICON);
if(deficon == null) {
deficon = MarkerIcon.DEFAULT;
}
if((id == null) && (label == null)) {
sender.sendMessage("<label> or id:<marker-id> required");
return true;
}
if(label == null)
label = id;
if(id == null)
id = label;
/* See if marker set exists */
MarkerSet set = api.getMarkerSet(id);
if(set != null) {
sender.sendMessage("Error: set already exists - id:" + set.getMarkerSetID());
return true;
}
/* Create new set */
set = api.createMarkerSet(id, label, null, true);
if(set == null) {
sender.sendMessage("Error creating set");
}
else {
String h = parms.get(ARG_HIDE);
if((h != null) && (h.equals("true")))
set.setHideByDefault(true);
String showlabels = parms.get(ARG_SHOWLABEL);
if(showlabels != null) {
if(showlabels.equals("true"))
set.setLabelShow(true);
else if(showlabels.equals("false"))
set.setLabelShow(false);
}
if(prio != null) {
try {
set.setLayerPriority(Integer.valueOf(prio));
} catch (NumberFormatException nfx) {
sender.sendMessage("Invalid priority: " + prio);
}
}
MarkerIcon mi = MarkerAPIImpl.getMarkerIconImpl(deficon);
if(mi != null) {
set.setDefaultMarkerIcon(mi);
}
else {
sender.sendMessage("Invalid default icon: " + deficon);
}
if(minzoom != null) {
try {
set.setMinZoom(Integer.valueOf(minzoom));
} catch (NumberFormatException nfx) {
sender.sendMessage("Invalid min zoom: " + minzoom);
}
}
if(maxzoom != null) {
try {
set.setMaxZoom(Integer.valueOf(maxzoom));
} catch (NumberFormatException nfx) {
sender.sendMessage("Invalid max zoom: " + maxzoom);
}
}
sender.sendMessage("Added set id:'" + set.getMarkerSetID() + "' (" + set.getMarkerSetLabel() + ")");
}
}
else {
sender.sendMessage("<label> or id:<set-id> required");
}
return true;
}
private static boolean processUpdateSet(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
String id, label, prio, minzoom, maxzoom, deficon, newlabel;
if(args.length > 1) {
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
id = parms.get(ARG_ID);
label = parms.get(ARG_LABEL);
prio = parms.get(ARG_PRIO);
minzoom = parms.get(ARG_MINZOOM);
maxzoom = parms.get(ARG_MAXZOOM);
deficon = parms.get(ARG_DEFICON);
if((id == null) && (label == null)) {
sender.sendMessage("<label> or id:<set-id> required");
return true;
}
MarkerSet set = null;
if(id != null) {
set = api.getMarkerSet(id);
if(set == null) {
sender.sendMessage("Error: set does not exist - id:" + id);
return true;
}
}
else {
Set<MarkerSet> sets = api.getMarkerSets();
for(MarkerSet s : sets) {
if(s.getMarkerSetLabel().equals(label)) {
set = s;
break;
}
}
if(set == null) {
sender.sendMessage("Error: matching set not found");
return true;
}
}
newlabel = parms.get(ARG_NEWLABEL);
if(newlabel != null) {
set.setMarkerSetLabel(newlabel);
}
String hide = parms.get(ARG_HIDE);
if(hide != null) {
set.setHideByDefault(hide.equals("true"));
}
String showlabels = parms.get(ARG_SHOWLABEL);
if(showlabels != null) {
if(showlabels.equals("true"))
set.setLabelShow(true);
else if(showlabels.equals("false"))
set.setLabelShow(false);
else
set.setLabelShow(null);
}
if(deficon != null) {
MarkerIcon mi = null;
if(deficon.equals("") == false) {
mi = MarkerAPIImpl.getMarkerIconImpl(deficon);
if(mi == null) {
sender.sendMessage("Error: invalid marker icon - " + deficon);
}
}
set.setDefaultMarkerIcon(mi);
}
if(prio != null) {
try {
set.setLayerPriority(Integer.valueOf(prio));
} catch (NumberFormatException nfx) {
sender.sendMessage("Invalid priority: " + prio);
}
}
if(minzoom != null) {
try {
set.setMinZoom(Integer.valueOf(minzoom));
} catch (NumberFormatException nfx) {
sender.sendMessage("Invalid min zoom: " + minzoom);
}
}
if(maxzoom != null) {
try {
set.setMaxZoom(Integer.valueOf(maxzoom));
} catch (NumberFormatException nfx) {
sender.sendMessage("Invalid max zoom: " + maxzoom);
}
}
sender.sendMessage("Set '" + set.getMarkerSetID() + "' updated");
}
else {
sender.sendMessage("<label> or id:<set-id> required");
}
return true;
}
private static boolean processDeleteSet(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
String id, label;
if(args.length > 1) {
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
id = parms.get(ARG_ID);
label = parms.get(ARG_LABEL);
if((id == null) && (label == null)) {
sender.sendMessage("<label> or id:<set-id> required");
return true;
}
if(id != null) {
MarkerSet set = api.getMarkerSet(id);
if(set == null) {
sender.sendMessage("Error: set does not exist - id:" + id);
return true;
}
set.deleteMarkerSet();
}
else {
Set<MarkerSet> sets = api.getMarkerSets();
MarkerSet set = null;
for(MarkerSet s : sets) {
if(s.getMarkerSetLabel().equals(label)) {
set = s;
break;
}
}
if(set == null) {
sender.sendMessage("Error: matching set not found");
return true;
}
set.deleteMarkerSet();
}
sender.sendMessage("Deleted set");
}
else {
sender.sendMessage("<label> or id:<set-id> required");
}
return true;
}
private static boolean processListSet(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
Set<String> setids = new TreeSet<String>(api.markersets.keySet());
for(String s : setids) {
MarkerSet set = api.markersets.get(s);
Boolean b = set.getLabelShow();
MarkerIcon defi = set.getDefaultMarkerIcon();
String msg = set.getMarkerSetID() + ": label:\"" + set.getMarkerSetLabel() + "\", hide:" + set.getHideByDefault() + ", prio:" + set.getLayerPriority();
if (defi != null) {
msg += ", deficon:" + defi.getMarkerIconID();
}
if (b != null) {
msg += ", showlabels:" + b;
}
if (set.getMinZoom() >= 0) {
msg += ", minzoom:" + set.getMinZoom();
}
if (set.getMaxZoom() >= 0) {
msg += ", maxzoom:" + set.getMaxZoom();
}
if (set.isMarkerSetPersistent()) {
msg += ", persistent=true";
}
sender.sendMessage(msg);
}
return true;
}
private static boolean processAddIcon(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
String id, file, label;
if(args.length > 1) {
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
id = parms.get(ARG_ID);
file = parms.get(ARG_FILE);
label = parms.get(ARG_LABEL);
if(id == null) {
sender.sendMessage("id:<icon-id> required");
return true;
}
if(file == null) {
sender.sendMessage("file:\"filename\" required");
return true;
}
if(label == null)
label = id;
MarkerIcon ico = MarkerAPIImpl.getMarkerIconImpl(id);
if(ico != null) {
sender.sendMessage("Icon '" + id + "' already defined.");
return true;
}
/* Open stream to filename */
File iconf = new File(file);
FileInputStream fis = null;
try {
fis = new FileInputStream(iconf);
/* Create new icon */
MarkerIcon mi = api.createMarkerIcon(id, label, fis);
if(mi == null) {
sender.sendMessage("Error creating icon");
return true;
}
} catch (IOException iox) {
sender.sendMessage("Error loading icon file - " + iox);
} finally {
if(fis != null) {
try { fis.close(); } catch (IOException iox) {}
}
}
}
else {
sender.sendMessage("id:<icon-id> and file:\"filename\" required");
}
return true;
}
private static boolean processUpdateIcon(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
String id, label, newlabel, file;
if(args.length > 1) {
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
id = parms.get(ARG_ID);
label = parms.get(ARG_LABEL);
newlabel = parms.get(ARG_NEWLABEL);
file = parms.get(ARG_FILE);
if((id == null) && (label == null)) {
sender.sendMessage("<label> or id:<icon-id> required");
return true;
}
MarkerIcon ico = null;
if(id != null) {
ico = MarkerAPIImpl.getMarkerIconImpl(id);
if(ico == null) {
sender.sendMessage("Error: icon does not exist - id:" + id);
return true;
}
}
else {
Set<MarkerIcon> icons = api.getMarkerIcons();
for(MarkerIcon ic : icons) {
if(ic.getMarkerIconLabel().equals(label)) {
ico = ic;
break;
}
}
if(ico == null) {
sender.sendMessage("Error: matching icon not found");
return true;
}
}
if(newlabel != null) {
ico.setMarkerIconLabel(newlabel);
}
/* Handle new file */
if(file != null) {
File iconf = new File(file);
FileInputStream fis = null;
try {
fis = new FileInputStream(iconf);
ico.setMarkerIconImage(fis);
} catch (IOException iox) {
sender.sendMessage("Error loading icon file - " + iox);
} finally {
if(fis != null) {
try { fis.close(); } catch (IOException iox) {}
}
}
}
sender.sendMessage("Icon '" + ico.getMarkerIconID() + "' updated");
}
else {
sender.sendMessage("<label> or id:<icon-id> required");
}
return true;
}
private static boolean processDeleteIcon(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
String id, label;
if(args.length > 1) {
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
id = parms.get(ARG_ID);
label = parms.get(ARG_LABEL);
if((id == null) && (label == null)) {
sender.sendMessage("<label> or id:<icon-id> required");
return true;
}
if(id != null) {
MarkerIcon ico = MarkerAPIImpl.getMarkerIconImpl(id);
if(ico == null) {
sender.sendMessage("Error: icon does not exist - id:" + id);
return true;
}
ico.deleteIcon();
}
else {
Set<MarkerIcon> icos = api.getMarkerIcons();
MarkerIcon ico = null;
for(MarkerIcon ic : icos) {
if(ic.getMarkerIconLabel().equals(label)) {
ico = ic;
break;
}
}
if(ico == null) {
sender.sendMessage("Error: matching icon not found");
return true;
}
ico.deleteIcon();
}
sender.sendMessage("Deleted marker icon");
}
else {
sender.sendMessage("<label> or id:<icon-id> required");
}
return true;
}
private static boolean processAddCorner(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args, DynmapPlayer player) {
String id;
DynmapLocation loc = null;
if(player == null) {
id = "-console-";
}
else {
id = player.getName();
loc = player.getLocation();
}
List<DynmapLocation> ll = api.pointaccum.get(id); /* Find list */
if(args.length > 3) { /* Enough for coord */
String w = null;
if(args.length == 4) { /* No world */
if(ll == null) { /* No points? Error */
sender.sendMessage("First added corner needs world ID after coordinates");
return true;
}
else {
w = ll.get(0).world; /* Use same world */
}
}
else { /* Get world ID */
w = args[4];
if(api.core.getWorld(w) == null) {
sender.sendMessage("Invalid world ID: " + args[3]);
return true;
}
}
try {
loc = new DynmapLocation(w, Double.parseDouble(args[1]), Double.parseDouble(args[2]), Double.parseDouble(args[3]));
} catch (NumberFormatException nfx) {
sender.sendMessage("Bad format: /dmarker addcorner <x> <y> <z> <world>");
return true;
}
}
if(loc == null) {
sender.sendMessage("Console must supply corner coordinates: <x> <y> <z> <world>");
return true;
}
if(ll == null) {
ll = new ArrayList<DynmapLocation>();
api.pointaccum.put(id, ll);
}
else { /* Else, if list exists, see if world matches */
if(ll.get(0).world.equals(loc.world) == false) {
ll.clear(); /* Reset list - point on new world */
}
}
ll.add(loc);
sender.sendMessage("Added corner #" + ll.size() + " at {" + loc.x + "," + loc.y + "," + loc.z + "} to list");
return true;
}
private static boolean processClearCorners(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args, DynmapPlayer player) {
String id;
if(player == null) {
id = "-console-";
}
else {
id = player.getName();
}
api.pointaccum.remove(id);
sender.sendMessage("Cleared corner list");
return true;
}
private static boolean processAddArea(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args, DynmapPlayer player) {
String pid, setid, id, label, markup;
if(player == null) {
pid = "-console-";
}
else {
pid = player.getName();
}
List<DynmapLocation> ll = api.pointaccum.get(pid); /* Find list */
if((ll == null) || (ll.size() < 2)) { /* Not enough points? */
sender.sendMessage("At least two corners must be added with /dmarker addcorner before an area can be added");
return true;
}
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
setid = parms.get(ARG_SET);
id = parms.get(ARG_ID);
label = parms.get(ARG_LABEL);
markup = parms.get(ARG_MARKUP);
/* Fill in defaults for missing parameters */
if(setid == null) {
setid = MarkerSet.DEFAULT;
}
/* Add new marker */
MarkerSet set = api.getMarkerSet(setid);
if(set == null) {
sender.sendMessage("Error: invalid set - " + setid);
return true;
}
// Prevent adding persistent markers to a non-persistent set
if (!set.isMarkerSetPersistent()) {
sender.sendMessage("Error: cannot add to non-persistent marker set - set is likely plugin owned");
return true;
}
/* Make coord list */
double[] xx = new double[ll.size()];
double[] zz = new double[ll.size()];
for(int i = 0; i < ll.size(); i++) {
DynmapLocation loc = ll.get(i);
xx[i] = loc.x;
zz[i] = loc.z;
}
/* Make area marker */
AreaMarker m = set.createAreaMarker(id, label, "true".equals(markup), ll.get(0).world, xx, zz, true);
if(m == null) {
sender.sendMessage("Error creating area");
}
else {
/* Process additional attributes, if any */
processAreaArgs(sender, m, parms);
sender.sendMessage("Added area id:'" + m.getMarkerID() + "' (" + m.getLabel() + ") to set '" + set.getMarkerSetID() + "'");
api.pointaccum.remove(pid); /* Clear corner list */
}
return true;
}
private static boolean processListArea(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
String setid;
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
setid = parms.get(ARG_SET);
if(setid == null) {
setid = MarkerSet.DEFAULT;
}
MarkerSet set = api.getMarkerSet(setid);
if(set == null) {
sender.sendMessage("Error: invalid set - " + setid);
return true;
}
Set<AreaMarker> markers = set.getAreaMarkers();
TreeMap<String, AreaMarker> sortmarkers = new TreeMap<String, AreaMarker>();
for(AreaMarker m : markers) {
sortmarkers.put(m.getMarkerID(), m);
}
for(String s : sortmarkers.keySet()) {
AreaMarker m = sortmarkers.get(s);
String msg = m.getMarkerID() + ": label:\"" + m.getLabel() + "\", set:" + m.getMarkerSet().getMarkerSetID() +
", world:" + m.getWorld() +
", weight:" + m.getLineWeight() + ", color:" + String.format("%06x", m.getLineColor()) +
", opacity:" + m.getLineOpacity() + ", fillcolor:" + String.format("%06x", m.getFillColor()) +
", fillopacity:" + m.getFillOpacity() + ", boost:" + m.getBoostFlag() + ", markup:" + m.isLabelMarkup();
if (m.getMinZoom() >= 0) {
msg += ", minzoom:" + m.getMinZoom();
}
if (m.getMaxZoom() >= 0) {
msg += ", maxzoom:" + m.getMaxZoom();
}
EnterExitText t = m.getGreetingText();
if (t != null) {
if (t.title != null) msg += ", greeting:\"" + t.title + "\"";
if (t.subtitle != null) msg += ", greetingsub:\"" + t.subtitle + "\"";
}
t = m.getFarewellText();
if (t != null) {
if (t.title != null) msg += ", farewell:\"" + t.title + "\"";
if (t.subtitle != null) msg += ", farewellsub:\"" + t.subtitle + "\"";
}
sender.sendMessage(msg);
}
return true;
}
private static boolean processDeleteArea(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
String id, label, setid;
if(args.length > 1) {
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
id = parms.get(ARG_ID);
label = parms.get(ARG_LABEL);
setid = parms.get(ARG_SET);
if((id == null) && (label == null)) {
sender.sendMessage("<label> or id:<area-id> required");
return true;
}
if(setid == null) {
setid = MarkerSet.DEFAULT;
}
MarkerSet set = api.getMarkerSet(setid);
if(set == null) {
sender.sendMessage("Error: invalid set - " + setid);
return true;
}
AreaMarker marker;
if(id != null) {
marker = set.findAreaMarker(id);
if(marker == null) { /* No marker */
sender.sendMessage("Error: area not found - " + id);
return true;
}
}
else {
marker = set.findAreaMarkerByLabel(label);
if(marker == null) { /* No marker */
sender.sendMessage("Error: area not found - " + label);
return true;
}
}
marker.deleteMarker();
sender.sendMessage("Deleted area id:" + marker.getMarkerID() + " (" + marker.getLabel() + ")");
}
else {
sender.sendMessage("<label> or id:<area-id> required");
}
return true;
}
private static boolean processUpdateArea(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
String id, label, setid, newlabel, markup, newset;
if(args.length > 1) {
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
id = parms.get(ARG_ID);
label = parms.get(ARG_LABEL);
markup = parms.get(ARG_MARKUP);
setid = parms.get(ARG_SET);
if((id == null) && (label == null)) {
sender.sendMessage("<label> or id:<area-id> required");
return true;
}
if(setid == null) {
setid = MarkerSet.DEFAULT;
}
MarkerSet set = api.getMarkerSet(setid);
if(set == null) {
sender.sendMessage("Error: invalid set - " + setid);
return true;
}
AreaMarker marker;
if(id != null) {
marker = set.findAreaMarker(id);
if(marker == null) { /* No marker */
sender.sendMessage("Error: area not found - " + id);
return true;
}
}
else {
marker = set.findAreaMarkerByLabel(label);
if(marker == null) { /* No marker */
sender.sendMessage("Error: area not found - " + label);
return true;
}
}
newlabel = parms.get(ARG_NEWLABEL);
if(newlabel != null) { /* Label set? */
marker.setLabel(newlabel, "true".equals(markup));
}
else if(markup != null) {
marker.setLabel(marker.getLabel(), "true".equals(markup));
}
newset = parms.get(ARG_NEWSET);
if (newset != null) {
MarkerSet ms = api.getMarkerSet(newset);
if(ms == null) {
sender.sendMessage("Error: invalid new marker set - " + newset);
return true;
}
marker.setMarkerSet(ms);
}
if(!processAreaArgs(sender,marker, parms))
return true;
sender.sendMessage("Updated area id:" + marker.getMarkerID() + " (" + marker.getLabel() + ")");
}
else {
sender.sendMessage("<label> or id:<area-id> required");
}
return true;
}
private static boolean processAddLine(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args, DynmapPlayer player) {
String setid;
String pid, id, label, markup;
if(player == null) {
pid = "-console-";
}
else {
pid = player.getName();
}
List<DynmapLocation> ll = api.pointaccum.get(pid); /* Find list */
if((ll == null) || (ll.size() < 2)) { /* Not enough points? */
sender.sendMessage("At least two corners must be added with /dmarker addcorner before a line can be added");
return true;
}
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
setid = parms.get(ARG_SET);
id = parms.get(ARG_ID);
label = parms.get(ARG_LABEL);
markup = parms.get(ARG_MARKUP);
/* Fill in defaults for missing parameters */
if(setid == null) {
setid = MarkerSet.DEFAULT;
}
/* Add new marker */
MarkerSet set = api.getMarkerSet(setid);
if(set == null) {
sender.sendMessage("Error: invalid set - " + setid);
return true;
}
// Prevent adding persistent markers to a non-persistent set
if (!set.isMarkerSetPersistent()) {
sender.sendMessage("Error: cannot add to non-persistent marker set - set is likely plugin owned");
return true;
}
/* Make coord list */
double[] xx = new double[ll.size()];
double[] yy = new double[ll.size()];
double[] zz = new double[ll.size()];
for(int i = 0; i < ll.size(); i++) {
DynmapLocation loc = ll.get(i);
xx[i] = loc.x;
yy[i] = loc.y;
zz[i] = loc.z;
}
/* Make poly-line marker */
PolyLineMarker m = set.createPolyLineMarker(id, label, "true".equals(markup), ll.get(0).world, xx, yy, zz, true);
if(m == null) {
sender.sendMessage("Error creating line");
}
else {
/* Process additional attributes, if any */
processPolyArgs(sender, m, parms);
sender.sendMessage("Added line id:'" + m.getMarkerID() + "' (" + m.getLabel() + ") to set '" + set.getMarkerSetID() + "'");
api.pointaccum.remove(pid); /* Clear corner list */
}
return true;
}
private static boolean processListLine(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
String setid;
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
setid = parms.get(ARG_SET);
if(setid == null) {
setid = MarkerSet.DEFAULT;
}
MarkerSet set = api.getMarkerSet(setid);
if(set == null) {
sender.sendMessage("Error: invalid set - " + setid);
return true;
}
Set<PolyLineMarker> markers = set.getPolyLineMarkers();
TreeMap<String, PolyLineMarker> sortmarkers = new TreeMap<String, PolyLineMarker>();
for(PolyLineMarker m : markers) {
sortmarkers.put(m.getMarkerID(), m);
}
for(String s : sortmarkers.keySet()) {
PolyLineMarker m = sortmarkers.get(s);
String ptlist = "{ ";
for(int i = 0; i < m.getCornerCount(); i++) {
ptlist += "{" + m.getCornerX(i) + "," + m.getCornerY(i) + "," + m.getCornerZ(i) + "} ";
}
ptlist += "}";
String msg = m.getMarkerID() + ": label:\"" + m.getLabel() + "\", set:" + m.getMarkerSet().getMarkerSetID() +
", world:" + m.getWorld() + ", corners:" + ptlist +
", weight: " + m.getLineWeight() + ", color:" + String.format("%06x", m.getLineColor()) +
", opacity: " + m.getLineOpacity() + ", markup:" + m.isLabelMarkup();
if (m.getMinZoom() >= 0) {
msg += ", minzoom:" + m.getMinZoom();
}
if (m.getMaxZoom() >= 0) {
msg += ", maxzoom:" + m.getMaxZoom();
}
sender.sendMessage(msg);
}
return true;
}
private static boolean processDeleteLine(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
String id, setid, label;
if(args.length > 1) {
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
id = parms.get(ARG_ID);
label = parms.get(ARG_LABEL);
setid = parms.get(ARG_SET);
if((id == null) && (label == null)) {
sender.sendMessage("<label> or id:<line-id> required");
return true;
}
if(setid == null) {
setid = MarkerSet.DEFAULT;
}
MarkerSet set = api.getMarkerSet(setid);
if(set == null) {
sender.sendMessage("Error: invalid set - " + setid);
return true;
}
PolyLineMarker marker;
if(id != null) {
marker = set.findPolyLineMarker(id);
if(marker == null) { /* No marker */
sender.sendMessage("Error: line not found - " + id);
return true;
}
}
else {
marker = set.findPolyLineMarkerByLabel(label);
if(marker == null) { /* No marker */
sender.sendMessage("Error: line not found - " + label);
return true;
}
}
marker.deleteMarker();
sender.sendMessage("Deleted poly-line id:" + marker.getMarkerID() + " (" + marker.getLabel() + ")");
}
else {
sender.sendMessage("<label> or id:<line-id> required");
}
return true;
}
private static boolean processUpdateLine(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
String id, setid, label, newlabel, markup, newset;
if(args.length > 1) {
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
id = parms.get(ARG_ID);
label = parms.get(ARG_LABEL);
markup = parms.get(ARG_MARKUP);
setid = parms.get(ARG_SET);
if((id == null) && (label == null)) {
sender.sendMessage("<label> or id:<line-id> required");
return true;
}
if(setid == null) {
setid = MarkerSet.DEFAULT;
}
MarkerSet set = api.getMarkerSet(setid);
if(set == null) {
sender.sendMessage("Error: invalid set - " + setid);
return true;
}
PolyLineMarker marker;
if(id != null) {
marker = set.findPolyLineMarker(id);
if(marker == null) { /* No marker */
sender.sendMessage("Error: line not found - " + id);
return true;
}
}
else {
marker = set.findPolyLineMarkerByLabel(label);
if(marker == null) { /* No marker */
sender.sendMessage("Error: line not found - " + label);
return true;
}
}
newlabel = parms.get(ARG_NEWLABEL);
if(newlabel != null) { /* Label set? */
marker.setLabel(newlabel, "true".equals(markup));
}
else if(markup != null) {
marker.setLabel(marker.getLabel(), "true".equals(markup));
}
newset = parms.get(ARG_NEWSET);
if (newset != null) {
MarkerSet ms = api.getMarkerSet(newset);
if(ms == null) {
sender.sendMessage("Error: invalid new marker set - " + newset);
return true;
}
marker.setMarkerSet(ms);
}
if(!processPolyArgs(sender,marker, parms))
return true;
sender.sendMessage("Updated line id:" + marker.getMarkerID() + " (" + marker.getLabel() + ")");
}
else {
sender.sendMessage("<label> or id:<line-id> required");
}
return true;
}
private static boolean processAddCircle(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args, DynmapPlayer player) {
String id, setid, label, markup;
String x, y, z, world;
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
setid = parms.get(ARG_SET);
id = parms.get(ARG_ID);
label = parms.get(ARG_LABEL);
markup = parms.get(ARG_MARKUP);
x = parms.get(ARG_X);
y = parms.get(ARG_Y);
z = parms.get(ARG_Z);
world = parms.get(ARG_WORLD);
if(world != null) {
if(api.core.getWorld(world) == null) {
sender.sendMessage("Invalid world ID: " + world);
return true;
}
}
DynmapLocation loc = null;
if((x == null) && (y == null) && (z == null) && (world == null)) {
if(player == null) {
sender.sendMessage("Must be issued by player, or x, y, z, and world parameters are required");
return true;
}
loc = player.getLocation();
}
else if((x != null) && (y != null) && (z != null) && (world != null)) {
try {
loc = new DynmapLocation(world, Double.valueOf(x), Double.valueOf(y), Double.valueOf(z));
} catch (NumberFormatException nfx) {
sender.sendMessage("Coordinates x, y, and z must be numbers");
return true;
}
}
else {
sender.sendMessage("Must be issued by player, or x, y, z, and world parameters are required");
return true;
}
/* Fill in defaults for missing parameters */
if(setid == null) {
setid = MarkerSet.DEFAULT;
}
/* Add new marker */
MarkerSet set = api.getMarkerSet(setid);
if(set == null) {
sender.sendMessage("Error: invalid set - " + setid);
return true;
}
// Prevent adding persistent markers to a non-persistent set
if (!set.isMarkerSetPersistent()) {
sender.sendMessage("Error: cannot add to non-persistent marker set - set is likely plugin owned");
return true;
}
/* Make circle marker */
CircleMarker m = set.createCircleMarker(id, label, "true".equals(markup), loc.world, loc.x, loc.y, loc.z, 1, 1, true);
if(m == null) {
sender.sendMessage("Error creating circle");
}
else {
/* Process additional attributes, if any */
if(!processCircleArgs(sender, m, parms)) {
return true;
}
sender.sendMessage("Added circle id:'" + m.getMarkerID() + "' (" + m.getLabel() + ") to set '" + set.getMarkerSetID() + "'");
}
return true;
}
private static boolean processListCircle(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
String setid;
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
setid = parms.get(ARG_SET);
if(setid == null) {
setid = MarkerSet.DEFAULT;
}
MarkerSet set = api.getMarkerSet(setid);
if(set == null) {
sender.sendMessage("Error: invalid set - " + setid);
return true;
}
Set<CircleMarker> markers = set.getCircleMarkers();
TreeMap<String, CircleMarker> sortmarkers = new TreeMap<String, CircleMarker>();
for(CircleMarker m : markers) {
sortmarkers.put(m.getMarkerID(), m);
}
for(String s : sortmarkers.keySet()) {
CircleMarker m = sortmarkers.get(s);
String msg = m.getMarkerID() + ": label:\"" + m.getLabel() + "\", set:" + m.getMarkerSet().getMarkerSetID() +
", world:" + m.getWorld() + ", center:" + m.getCenterX() + "/" + m.getCenterY() + "/" + m.getCenterZ() +
", radiusx:" + m.getRadiusX() + ", radiusz:" + m.getRadiusZ() +
", weight: " + m.getLineWeight() + ", color:" + String.format("%06x", m.getLineColor()) +
", opacity: " + m.getLineOpacity() + ", fillcolor: " + String.format("%06x", m.getFillColor()) +
", fillopacity: " + m.getFillOpacity() + ", boost:" + m.getBoostFlag() + ", markup:" + m.isLabelMarkup();
if (m.getMinZoom() >= 0) {
msg += ", minzoom:" + m.getMinZoom();
}
if (m.getMaxZoom() >= 0) {
msg += ", maxzoom:" + m.getMaxZoom();
}
EnterExitText t = m.getGreetingText();
if (t != null) {
if (t.title != null) msg += ", greeting:\"" + t.title + "\"";
if (t.subtitle != null) msg += ", greetingsub:\"" + t.subtitle + "\"";
}
t = m.getFarewellText();
if (t != null) {
if (t.title != null) msg += ", farewell:\"" + t.title + "\"";
if (t.subtitle != null) msg += ", farewellsub:\"" + t.subtitle + "\"";
}
sender.sendMessage(msg);
}
return true;
}
private static boolean processDeleteCircle(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
String id, setid, label;
if(args.length > 1) {
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
id = parms.get(ARG_ID);
label = parms.get(ARG_LABEL);
setid = parms.get(ARG_SET);
if((id == null) && (label == null)) {
sender.sendMessage("<label> or id:<circle-id> required");
return true;
}
if(setid == null) {
setid = MarkerSet.DEFAULT;
}
MarkerSet set = api.getMarkerSet(setid);
if(set == null) {
sender.sendMessage("Error: invalid set - " + setid);
return true;
}
CircleMarker marker;
if(id != null) {
marker = set.findCircleMarker(id);
if(marker == null) { /* No marker */
sender.sendMessage("Error: circle not found - " + id);
return true;
}
}
else {
marker = set.findCircleMarkerByLabel(label);
if(marker == null) { /* No marker */
sender.sendMessage("Error: circle not found - " + label);
return true;
}
}
marker.deleteMarker();
sender.sendMessage("Deleted circle id:" + marker.getMarkerID() + " (" + marker.getLabel() + ")");
}
else {
sender.sendMessage("<label> or id:<circle-id> required");
}
return true;
}
private static boolean processUpdateCircle(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
String id, setid, label, newlabel, markup, newset;
if(args.length > 1) {
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
id = parms.get(ARG_ID);
label = parms.get(ARG_LABEL);
markup = parms.get(ARG_MARKUP);
setid = parms.get(ARG_SET);
if((id == null) && (label == null)) {
sender.sendMessage("<label> or id:<area-id> required");
return true;
}
if(setid == null) {
setid = MarkerSet.DEFAULT;
}
MarkerSet set = api.getMarkerSet(setid);
if(set == null) {
sender.sendMessage("Error: invalid set - " + setid);
return true;
}
CircleMarker marker;
if(id != null) {
marker = set.findCircleMarker(id);
if(marker == null) { /* No marker */
sender.sendMessage("Error: circle not found - " + id);
return true;
}
}
else {
marker = set.findCircleMarkerByLabel(label);
if(marker == null) { /* No marker */
sender.sendMessage("Error: circle not found - " + label);
return true;
}
}
newlabel = parms.get(ARG_NEWLABEL);
if(newlabel != null) { /* Label set? */
marker.setLabel(newlabel, "true".equals(markup));
}
else if(markup != null) {
marker.setLabel(marker.getLabel(), "true".equals(markup));
}
newset = parms.get(ARG_NEWSET);
if (newset != null) {
MarkerSet ms = api.getMarkerSet(newset);
if(ms == null) {
sender.sendMessage("Error: invalid new marker set - " + newset);
return true;
}
marker.setMarkerSet(ms);
}
if(!processCircleArgs(sender,marker, parms))
return true;
sender.sendMessage("Updated circle id:" + marker.getMarkerID() + " (" + marker.getLabel() + ")");
}
else {
sender.sendMessage("<label> or id:<circle-id> required");
}
return true;
}
private static MarkerDescription findMarkerDescription(DynmapCommandSender sender, Map<String, String> parms) {
MarkerDescription md = null;
String id, setid, label, type;
id = parms.get(ARG_ID);
label = parms.get(ARG_LABEL);
setid = parms.get(ARG_SET);
if((id == null) && (label == null)) {
sender.sendMessage("<label> or id:<area-id> required");
return null;
}
type = parms.get(ARG_TYPE);
if (type == null) type = "icon";
if(setid == null) {
setid = MarkerSet.DEFAULT;
}
MarkerSet set = api.getMarkerSet(setid);
if(set == null) {
sender.sendMessage("Error: invalid set - " + setid);
return null;
}
if (id != null) {
if (type.equals("icon")) {
md = set.findMarker(id);
}
else if (type.equals("area")) {
md = set.findAreaMarker(id);
}
else if (type.equals("circle")) {
md = set.findCircleMarker(id);
}
else if (type.equals("line")) {
md = set.findPolyLineMarker(id);
}
else {
sender.sendMessage("Error: invalid type - " + type);
return null;
}
if(md == null) { /* No marker */
sender.sendMessage("Error: marker not found - " + id);
return null;
}
}
else {
if (type.equals("icon")) {
md = set.findMarkerByLabel(label);
}
else if (type.equals("area")) {
md = set.findAreaMarkerByLabel(label);
}
else if (type.equals("circle")) {
md = set.findCircleMarkerByLabel(label);
}
else if (type.equals("line")) {
md = set.findPolyLineMarkerByLabel(label);
}
else {
sender.sendMessage("Error: invalid type - " + type);
return null;
}
if(md == null) { /* No marker */
sender.sendMessage("Error: marker not found - " + label);
return null;
}
}
return md;
}
/** Process getdesc for given item */
private static boolean processGetDesc(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
if(args.length > 1) {
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
MarkerDescription md = findMarkerDescription(sender, parms);
if (md == null) {
return true;
}
String desc = md.getDescription();
if (desc == null) {
sender.sendMessage("<null>");
}
else {
sender.sendMessage(desc);
}
}
else {
sender.sendMessage("<label> or id:<id> required");
}
return true;
}
/** Process resetdesc for given item */
private static boolean processResetDesc(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
if(args.length > 1) {
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
MarkerDescription md = findMarkerDescription(sender, parms);
if (md == null) {
return true;
}
md.setDescription(null);
sender.sendMessage("Description cleared");
}
else {
sender.sendMessage("<label> or id:<id> required");
}
return true;
}
/** Process appenddesc for given item */
private static boolean processAppendDesc(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
if(args.length > 1) {
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
MarkerDescription md = findMarkerDescription(sender, parms);
if (md == null) {
return true;
}
String desc = parms.get(ARG_DESC);
if (desc == null) {
sender.sendMessage("Error: no 'desc:' parameter");
return true;
}
String d = md.getDescription();
if (d == null) {
d = desc + "\n";
}
else {
d = d + desc + "\n";
}
md.setDescription(d);
sender.sendMessage(md.getDescription());
}
else {
sender.sendMessage("<label> or id:<id> required");
}
return true;
}
/** Process getlabel for given item */
private static boolean processGetLabel(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
if(args.length > 1) {
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
MarkerDescription md = findMarkerDescription(sender, parms);
if (md == null) {
return true;
}
String desc = md.getLabel();
if (desc == null) {
sender.sendMessage("<null>");
}
else {
sender.sendMessage(desc);
}
}
else {
sender.sendMessage("<label> or id:<id> required");
}
return true;
}
/** Process importdesc for given item */
private static boolean processImportDesc(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
if(args.length > 1) {
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
MarkerDescription md = findMarkerDescription(sender, parms);
if (md == null) {
return true;
}
String f = parms.get(ARG_FILE);
if (f == null) {
sender.sendMessage("Error: no '" + ARG_FILE + "' parameter");
return true;
}
FileReader fr = null;
String val = null;
try {
fr = new FileReader(f);
StringBuilder sb = new StringBuilder();
char[] buf = new char[512];
int len;
while ((len = fr.read(buf)) > 0) {
sb.append(buf, 0, len);
}
val = sb.toString();
} catch (FileNotFoundException fnfx) {
sender.sendMessage("Error: file '" + f + "' not found");
return true;
} catch (IOException iox) {
sender.sendMessage("Error reading file '" + f + "'");
return true;
} finally {
if (fr != null) {
try { fr.close(); } catch (IOException iox) {}
}
}
md.setDescription(val);
sender.sendMessage("Description imported from '" + f + "'");
}
else {
sender.sendMessage("<label> or id:<id> required");
}
return true;
}
/** Process importlabel for given item */
private static boolean processImportLabel(DynmapCore plugin, DynmapCommandSender sender, String cmd, String commandLabel, String[] args) {
if(args.length > 1) {
/* Parse arguements */
Map<String,String> parms = parseArgs(args, sender);
if(parms == null) return true;
MarkerDescription md = findMarkerDescription(sender, parms);
if (md == null) {
return true;
}
String f = parms.get(ARG_FILE);
if (f == null) {
sender.sendMessage("Error: no '" + ARG_FILE + "' parameter");
return true;
}
FileReader fr = null;
String val = null;
try {
fr = new FileReader(f);
StringBuilder sb = new StringBuilder();
char[] buf = new char[512];
int len;
while ((len = fr.read(buf)) > 0) {
sb.append(buf, 0, len);
}
val = sb.toString();
} catch (FileNotFoundException fnfx) {
sender.sendMessage("Error: file '" + f + "' not found");
return true;
} catch (IOException iox) {
sender.sendMessage("Error reading file '" + f + "'");
return true;
} finally {
if (fr != null) {
try { fr.close(); } catch (IOException iox) {}
}
}
md.setLabel(val, true);
sender.sendMessage("Label with markup imported from '" + f + "'");
}
else {
sender.sendMessage("<label> or id:<id> required");
}
return true;
}
/**
* Write markers file for given world
*/
private void writeMarkersFile(final String wname) {
Map<String, Object> markerdata = new HashMap<String, Object>();
final Map<String, Object> worlddata = new HashMap<String, Object>();
worlddata.put("timestamp", Long.valueOf(System.currentTimeMillis())); /* Add timestamp */
for(MarkerSet ms : markersets.values()) {
HashMap<String, Object> msdata = new HashMap<String, Object>();
msdata.put("label", ms.getMarkerSetLabel());
msdata.put("hide", ms.getHideByDefault());
msdata.put("layerprio", ms.getLayerPriority());
if (ms.getMinZoom() >= 0) {
msdata.put("minzoom", ms.getMinZoom());
}
if (ms.getMaxZoom() >= 0) {
msdata.put("maxzoom", ms.getMaxZoom());
}
if(ms.getLabelShow() != null) {
msdata.put("showlabels", ms.getLabelShow());
}
HashMap<String, Object> markers = new HashMap<String, Object>();
for(Marker m : ms.getMarkers()) {
if(m.getWorld().equals(wname) == false) continue;
HashMap<String, Object> mdata = new HashMap<String, Object>();
mdata.put("x", m.getX());
mdata.put("y", m.getY());
mdata.put("z", m.getZ());
MarkerIcon mi = m.getMarkerIcon();
if(mi == null)
mi = MarkerAPIImpl.getMarkerIconImpl(MarkerIcon.DEFAULT);
mdata.put("icon", mi.getMarkerIconID());
mdata.put("dim", mi.getMarkerIconSize().getSize());
mdata.put("label", Client.sanitizeHTML(m.getLabel()));
mdata.put("markup", m.isLabelMarkup());
if(m.getDescription() != null)
mdata.put("desc", Client.sanitizeHTML(m.getDescription()));
if (m.getMinZoom() >= 0) {
mdata.put("minzoom", m.getMinZoom());
}
if (m.getMaxZoom() >= 0) {
mdata.put("maxzoom", m.getMaxZoom());
}
/* Add to markers */
markers.put(m.getMarkerID(), mdata);
}
msdata.put("markers", markers); /* Add markers to set data */
HashMap<String, Object> areas = new HashMap<String, Object>();
for(AreaMarker m : ms.getAreaMarkers()) {
if(m.getWorld().equals(wname) == false) continue;
HashMap<String, Object> mdata = new HashMap<String, Object>();
int cnt = m.getCornerCount();
List<Double> xx = new ArrayList<Double>();
List<Double> zz = new ArrayList<Double>();
for(int i = 0; i < cnt; i++) {
xx.add(m.getCornerX(i));
zz.add(m.getCornerZ(i));
}
mdata.put("x", xx);
mdata.put("ytop", m.getTopY());
mdata.put("ybottom", m.getBottomY());
mdata.put("z", zz);
mdata.put("color", String.format("#%06X", m.getLineColor()));
mdata.put("fillcolor", String.format("#%06X", m.getFillColor()));
mdata.put("opacity", m.getLineOpacity());
mdata.put("fillopacity", m.getFillOpacity());
mdata.put("weight", m.getLineWeight());
mdata.put("label", Client.sanitizeHTML(m.getLabel()));
mdata.put("markup", m.isLabelMarkup());
if(m.getDescription() != null)
mdata.put("desc", Client.sanitizeHTML(m.getDescription()));
if (m.getMinZoom() >= 0) {
mdata.put("minzoom", m.getMinZoom());
}
if (m.getMaxZoom() >= 0) {
mdata.put("maxzoom", m.getMaxZoom());
}
/* Add to markers */
areas.put(m.getMarkerID(), mdata);
}
msdata.put("areas", areas); /* Add areamarkers to set data */
HashMap<String, Object> lines = new HashMap<String, Object>();
for(PolyLineMarker m : ms.getPolyLineMarkers()) {
if(m.getWorld().equals(wname) == false) continue;
HashMap<String, Object> mdata = new HashMap<String, Object>();
int cnt = m.getCornerCount();
List<Double> xx = new ArrayList<Double>();
List<Double> yy = new ArrayList<Double>();
List<Double> zz = new ArrayList<Double>();
for(int i = 0; i < cnt; i++) {
xx.add(m.getCornerX(i));
yy.add(m.getCornerY(i));
zz.add(m.getCornerZ(i));
}
mdata.put("x", xx);
mdata.put("y", yy);
mdata.put("z", zz);
mdata.put("color", String.format("#%06X", m.getLineColor()));
mdata.put("opacity", m.getLineOpacity());
mdata.put("weight", m.getLineWeight());
mdata.put("label", Client.sanitizeHTML(m.getLabel()));
mdata.put("markup", m.isLabelMarkup());
if(m.getDescription() != null)
mdata.put("desc", Client.sanitizeHTML(m.getDescription()));
if (m.getMinZoom() >= 0) {
mdata.put("minzoom", m.getMinZoom());
}
if (m.getMaxZoom() >= 0) {
mdata.put("maxzoom", m.getMaxZoom());
}
/* Add to markers */
lines.put(m.getMarkerID(), mdata);
}
msdata.put("lines", lines); /* Add polylinemarkers to set data */
HashMap<String, Object> circles = new HashMap<String, Object>();
for(CircleMarker m : ms.getCircleMarkers()) {
if(m.getWorld().equals(wname) == false) continue;
HashMap<String, Object> mdata = new HashMap<String, Object>();
mdata.put("x", m.getCenterX());
mdata.put("y", m.getCenterY());
mdata.put("z", m.getCenterZ());
mdata.put("xr", m.getRadiusX());
mdata.put("zr", m.getRadiusZ());
mdata.put("color", String.format("#%06X", m.getLineColor()));
mdata.put("fillcolor", String.format("#%06X", m.getFillColor()));
mdata.put("opacity", m.getLineOpacity());
mdata.put("fillopacity", m.getFillOpacity());
mdata.put("weight", m.getLineWeight());
mdata.put("label", Client.sanitizeHTML(m.getLabel()));
mdata.put("markup", m.isLabelMarkup());
if(m.getDescription() != null)
mdata.put("desc", Client.sanitizeHTML(m.getDescription()));
if (m.getMinZoom() >= 0) {
mdata.put("minzoom", m.getMinZoom());
}
if (m.getMaxZoom() >= 0) {
mdata.put("maxzoom", m.getMaxZoom());
}
/* Add to markers */
circles.put(m.getMarkerID(), mdata);
}
msdata.put("circles", circles); /* Add circle markers to set data */
markerdata.put(ms.getMarkerSetID(), msdata); /* Add marker set data to world marker data */
}
worlddata.put("sets", markerdata);
MapManager.scheduleDelayedJob(new Runnable() {
public void run() {
core.getDefaultMapStorage().setMarkerFile(wname, Json.stringifyJson(worlddata));
}
}, 0);
}
@Override
public void triggered(DynmapWorld t) {
/* Update markers for now-active world */
dirty_worlds.add(t.getName());
}
/* Remove icon */
static void removeIcon(MarkerIcon ico) {
MarkerIcon def = api.getMarkerIcon(MarkerIcon.DEFAULT);
/* Need to scrub all uses of this icon from markers */
for(MarkerSet s : api.markersets.values()) {
for(Marker m : s.getMarkers()) {
if(m.getMarkerIcon() == ico) {
m.setMarkerIcon(def); /* Set to default */
}
}
Set<MarkerIcon> allowed = s.getAllowedMarkerIcons();
if((allowed != null) && (allowed.contains(ico))) {
s.removeAllowedMarkerIcon(ico);
}
}
/* Remove files */
File f = new File(api.markerdir, ico.getMarkerIconID() + ".png");
f.delete();
api.core.getDefaultMapStorage().setMarkerImage(ico.getMarkerIconID(), null);
/* Remove from marker icons */
api.markericons.remove(ico.getMarkerIconID());
saveMarkers();
}
/**
* Test if given player can see another player on the map (based on player sets and privileges).
* @param player - player attempting to observe
* @param player_to_see - player to be observed by 'player'
* @return true if can be seen on map, false if cannot be seen
*/
public boolean testIfPlayerVisible(String player, String player_to_see)
{
if(api == null) return false;
/* Go through player sets - see if any are applicable */
for(Entry<String, PlayerSetImpl> s : playersets.entrySet()) {
PlayerSetImpl ps = s.getValue();
if(!ps.isPlayerInSet(player_to_see)) { /* Is in set? */
continue;
}
if(ps.isSymmetricSet() && ps.isPlayerInSet(player)) { /* If symmetric, and observer is there */
return true;
}
if(core.checkPermission(player, "playerset." + s.getKey())) { /* If player has privilege */
return true;
}
}
return false;
}
/**
* Get set of player visible to given player
* @param player - player to check
* @return set of visible players
*/
public Set<String> getPlayersVisibleToPlayer(String player) {
player = player.toLowerCase();
HashSet<String> pset = new HashSet<String>();
pset.add(player);
/* Go through player sets - see if any are applicable */
for(Entry<String, PlayerSetImpl> s : playersets.entrySet()) {
PlayerSetImpl ps = s.getValue();
if(ps.isSymmetricSet() && ps.isPlayerInSet(player)) { /* If symmetric, and observer is there */
pset.addAll(ps.getPlayers());
}
else if(core.checkPermission(player, "playerset." + s.getKey())) { /* If player has privilege */
pset.addAll(ps.getPlayers());
}
}
return pset;
}
/**
* Test if any markers with 'boost=true' intersect given map tile
* @param w - world
* @param perspective - perspective for transforming world to tile coordinates
* @param tile_x - X coordinate of tile corner, in map coords
* @param tile_y - Y coordinate of tile corner, in map coords
* @param tile_dim - Tile dimension, in map units
* @return true if intersected, false if not
*/
public static boolean testTileForBoostMarkers(DynmapWorld w, HDPerspective perspective, double tile_x, double tile_y, double tile_dim) {
if (api == null) return false;
for(MarkerSetImpl ms : api.markersets.values()) {
if(ms.testTileForBoostMarkers(w, perspective, tile_x, tile_y, tile_dim)) {
return true;
}
}
return false;
}
/**
* Build entered marker set based on given location
* @param worldid - world
* @param x
* @param y
* @param z
* @param entered
*/
public static void getEnteredMarkers(String worldid, double x, double y, double z, Set<EnterExitMarker> entered) {
if (api == null) return;
for(MarkerSetImpl ms : api.markersets.values()) {
ms.addEnteredMarkers(entered, worldid, x, y, z);
}
}
/**
* Check if loaded string needs to be escaped (if non-markup)
*/
public static String escapeForHTMLIfNeeded(String txt, boolean markup) {
if (markup) return txt; // Not needed for markup
// If escaped properly, these characters aren't present (all but ampersand of HTML active characrers
if (txt != null) {
if ((txt.indexOf('<') >= 0) || (txt.indexOf('>') >= 0) || (txt.indexOf('\'') >= 0) || (txt.indexOf('"') >= 0)) {
return Client.encodeForHTML(txt);
}
// If ampersand without semicolon after (simplistic check for ampersand without being escape sequence)
int idx = txt.lastIndexOf('&');
if ((idx >= 0) && (txt.indexOf(';', idx) < 0)) {
return Client.encodeForHTML(txt);
}
}
return txt;
}
}
|
Use concurrentmap for dirty_worlds
|
DynmapCore/src/main/java/org/dynmap/markers/impl/MarkerAPIImpl.java
|
Use concurrentmap for dirty_worlds
|
|
Java
|
apache-2.0
|
9d1319a9d72f15352bdac57c2419d8cd562b9e0b
| 0
|
nus-ncl/service-web,nus-ncl/service-web,nus-ncl/service-web,nus-ncl/service-web
|
package sg.ncl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.tomcat.util.codec.binary.Base64;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.support.RequestContextUtils;
import sg.ncl.domain.*;
import sg.ncl.exceptions.*;
import sg.ncl.testbed_interface.*;
import sg.ncl.testbed_interface.Image;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.text.DecimalFormat;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.List;
import java.util.regex.Pattern;
import static java.time.temporal.TemporalAdjusters.firstDayOfMonth;
import static java.time.temporal.TemporalAdjusters.lastDayOfMonth;
import static sg.ncl.domain.ExceptionState.*;
/**
*
* Spring Controller
* Direct the views to appropriate locations and invoke the respective REST API
*
* @author Cassie, Desmond, Te Ye, Vu
*/
@Controller
@Slf4j
public class MainController {
public static final String CONTENT_DISPOSITION = "Content-Disposition";
public static final String APPLICATION_FORCE_DOWNLOAD = "application/force-download";
private static final String SESSION_LOGGED_IN_USER_ID = "loggedInUserId";
private TeamManager teamManager = TeamManager.getInstance();
// private UserManager userManager = UserManager.getInstance();
// private ExperimentManager experimentManager = ExperimentManager.getInstance();
// private DomainManager domainManager = DomainManager.getInstance();
// private DatasetManager datasetManager = DatasetManager.getInstance();
// private NodeManager nodeManager = NodeManager.getInstance();
private static final String CONTACT_EMAIL = "support@ncl.sg";
private static final String UNKNOWN = "?";
private static final String MESSAGE = "message";
private static final String MESSAGE_SUCCESS = "messageSuccess";
private static final String EXPERIMENT_MESSAGE = "exp_message";
private static final String ERROR_PREFIX = "Error: ";
// error messages
private static final String ERROR_CONNECTING_TO_SERVICE_TELEMETRY = "Error connecting to service-telemetry: {}";
private static final String ERR_SERVER_OVERLOAD = "There is a problem with your request. Please contact " + CONTACT_EMAIL;
private static final String CONNECTION_ERROR = "Connection Error";
private final String permissionDeniedMessage = "Permission denied. If the error persists, please contact " + CONTACT_EMAIL;
private static final String ERR_START_DATE_AFTER_END_DATE = "End date must be after start date";
// for user dashboard hashmap key values
private static final String USER_DASHBOARD_APPROVED_TEAMS = "numberOfApprovedTeam";
private static final String USER_DASHBOARD_RUNNING_EXPERIMENTS = "numberOfRunningExperiments";
private static final String USER_DASHBOARD_FREE_NODES = "freeNodes";
private static final String USER_DASHBOARD_TOTAL_NODES = "totalNodes";
private static final String USER_DASHBOARD_GLOBAL_IMAGES = "globalImagesMap";
private static final String USER_DASHBOARD_LOGGED_IN_USERS_COUNT = "loggedInUsersCount";
private static final String USER_DASHBOARD_RUNNING_EXPERIMENTS_COUNT = "runningExperimentsCount";
private static final String DETER_UID = "deterUid";
private static final Pattern VALID_EMAIL_ADDRESS_REGEX =
Pattern.compile("(?:(?:\\r\\n)?[ \\t])*(?:(?:(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*\\<(?:(?:\\r\\n)?[ \\t])*(?:@(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*(?:,@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*)*:(?:(?:\\r\\n)?[ \\t])*)?(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\>(?:(?:\\r\\n)?[ \\t])*)|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*:(?:(?:\\r\\n)?[ \\t])*(?:(?:(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*\\<(?:(?:\\r\\n)?[ \\t])*(?:@(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*(?:,@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*)*:(?:(?:\\r\\n)?[ \\t])*)?(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\>(?:(?:\\r\\n)?[ \\t])*)(?:,\\s*(?:(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*\\<(?:(?:\\r\\n)?[ \\t])*(?:@(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*(?:,@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*)*:(?:(?:\\r\\n)?[ \\t])*)?(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\>(?:(?:\\r\\n)?[ \\t])*))*)?;\\s*)");
private static final String FORGET_PSWD_PAGE = "password_reset_email";
private static final String FORGET_PSWD_NEW_PSWD_PAGE = "password_reset_new_password";
private static final String NO_PERMISSION_PAGE = "nopermission";
private static final String EXPERIMENTS = "experiments";
private static final String APPLICATION_DATE = "applicationDate";
private static final String TEAM_NAME = "teamName";
private static final String TEAM_ID = "teamId";
private static final String NODE_ID = "nodeId";
private static final String PERMISSION_DENIED = "Permission denied";
private static final String TEAM_NOT_FOUND = "Team not found";
private static final String NOT_FOUND = " not found.";
private static final String EDIT_BUDGET = "editBudget";
private static final String ORIGINAL_BUDGET = "originalBudget";
private static final String REDIRECT_TEAM_PROFILE_TEAM_ID = "redirect:/team_profile/{teamId}";
private static final String REDIRECT_TEAM_PROFILE = "redirect:/team_profile/";
private static final String REDIRECT_INDEX_PAGE = "redirect:/";
private static final String REDIRECT_ENERGY_USAGE = "redirect:/energy_usage";
// remove members from team profile; to display the list of experiments created by user
private static final String REMOVE_MEMBER_UID = "removeMemberUid";
private static final String REMOVE_MEMBER_NAME = "removeMemberName";
private static final String MEMBER_TYPE = "memberType";
// admin update data resource to track what fields have been updated
private static final String ORIGINAL_DATARESOURCE = "original_dataresource";
private static final String NOT_APPLICABLE = "N.A.";
@Autowired
protected RestTemplate restTemplate;
@Inject
protected ObjectMapper objectMapper;
@Inject
protected ConnectionProperties properties;
@Inject
protected WebProperties webProperties;
@Inject
protected AccountingProperties accountingProperties;
@Inject
protected HttpSession httpScopedSession;
@RequestMapping("/")
public String index() {
return "index";
}
@RequestMapping("/overview")
public String overview() {
return "overview";
}
@RequestMapping("/community")
public String community() {
return "community";
}
@RequestMapping("/about")
public String about() {
return "about";
}
@RequestMapping("/event")
public String event() {
return "event";
}
@RequestMapping("/plan")
public String plan() {
return "plan";
}
@RequestMapping("/career")
public String career() {
return "career";
}
@RequestMapping("/pricing")
public String pricing() {
return "pricing";
}
@RequestMapping("/resources")
public String resources() {
return "resources";
}
@RequestMapping("/research")
public String research() {
return "research";
}
@RequestMapping("/calendar")
public String calendar() {
return "calendar";
}
@RequestMapping("/tutorials/createaccount")
public String createAccount() {
return "createaccount";
}
@RequestMapping("/tutorials/createexperiment")
public String createExperimentTutorial() {
return "createexperiment";
}
@RequestMapping("/tutorials/loadimage")
public String loadimage() {
return "loadimage";
}
@RequestMapping("/tutorials/saveimage")
public String saveimage() {
return "saveimage";
}
@RequestMapping("/tutorials/applyteam")
public String applyteam() {
return "applyteam";
}
@RequestMapping("/tutorials/jointeam")
public String jointeam() {
return "jointeam";
}
@RequestMapping("/tutorials/usenode")
public String usenode() {
return "usenode";
}
@RequestMapping("/tutorials/usessh")
public String usessh() {
return "usessh";
}
@RequestMapping("/tutorials/usescp")
public String usescp() {
return "usescp";
}
@RequestMapping("/tutorials/usegui")
public String usegui() {
return "usegui";
}
@RequestMapping("/tutorials/manageresource")
public String manageresource() {
return "manageresource";
}
@RequestMapping("/tutorials/testbedinfo")
public String testbedinfo() {
return "testbedinfo";
}
@RequestMapping("/tutorials/createcustom")
public String createcustom() {
return "createcustom";
}
@RequestMapping("/error_openstack")
public String error_openstack() {
return "error_openstack";
}
@RequestMapping("/accessexperiment")
public String accessexperiment() {
return "accessexperiment";
}
@RequestMapping("/resource2")
public String resource2() {
return "resource2";
}
@RequestMapping("/tutorials")
public String tutorials() {
return "tutorials";
}
@RequestMapping("/maintainance")
public String maintainance() {
return "maintainance";
}
@RequestMapping("/testbedInformation")
public String testbedInformation(Model model) throws IOException {
model.addAttribute(USER_DASHBOARD_GLOBAL_IMAGES, getGlobalImages());
return "testbed_information";
}
// get all the nodes' status
// there are three types of status
// "free" : node is free
// "in_use" : node is in use
// "reload" : node is in process of freeing or unknown status
// "reserved" : node is pre-reserved for a project
@RequestMapping("/testbedNodesStatus")
public String testbedNodesStatus(Model model) throws IOException {
// get number of active users and running experiments
Map<String, String> testbedStatsMap = getTestbedStats();
testbedStatsMap.put(USER_DASHBOARD_FREE_NODES, "0");
testbedStatsMap.put(USER_DASHBOARD_TOTAL_NODES, "0");
Map<String, List<Map<String, String>>> nodesStatus = getNodesStatus();
Map<String, Map<String, Long>> nodesStatusCount = new HashMap<>();
/* loop through each of the machine type
tabulate the different nodes type
count the number of different nodes status, e.g. SYSTEMX = { FREE = 10, IN_USE = 11, ... }
*/
nodesStatus.entrySet().forEach(machineTypeListEntry -> {
Map<String, Long> nodesCountMap = new HashMap<>();
long free = machineTypeListEntry.getValue().stream().filter(stringStringMap -> "free".equalsIgnoreCase(stringStringMap.get("status"))).count();
long inUse = machineTypeListEntry.getValue().stream().filter(stringStringMap -> "in_use".equalsIgnoreCase(stringStringMap.get("status"))).count();
long reserved = machineTypeListEntry.getValue().stream().filter(stringStringMap -> "reserved".equalsIgnoreCase(stringStringMap.get("status"))).count();
long reload = machineTypeListEntry.getValue().stream().filter(stringStringMap -> "reload".equalsIgnoreCase(stringStringMap.get("status"))).count();
long total = free + inUse + reserved + reload;
long currentTotal = Long.parseLong(testbedStatsMap.get(USER_DASHBOARD_TOTAL_NODES)) + total;
long currentFree = Long.parseLong(testbedStatsMap.get(USER_DASHBOARD_FREE_NODES)) + free;
nodesCountMap.put(NodeType.FREE.name(), free);
nodesCountMap.put(NodeType.IN_USE.name(), inUse);
nodesCountMap.put(NodeType.RESERVED.name(), reserved);
nodesCountMap.put(NodeType.RELOADING.name(), reload);
nodesStatusCount.put(machineTypeListEntry.getKey(), nodesCountMap);
testbedStatsMap.put(USER_DASHBOARD_FREE_NODES, Long.toString(currentFree));
testbedStatsMap.put(USER_DASHBOARD_TOTAL_NODES, Long.toString(currentTotal));
});
model.addAttribute("nodesStatus", nodesStatus);
model.addAttribute("nodesStatusCount", nodesStatusCount);
model.addAttribute(USER_DASHBOARD_LOGGED_IN_USERS_COUNT, testbedStatsMap.get(USER_DASHBOARD_LOGGED_IN_USERS_COUNT));
model.addAttribute(USER_DASHBOARD_RUNNING_EXPERIMENTS_COUNT, testbedStatsMap.get(USER_DASHBOARD_RUNNING_EXPERIMENTS_COUNT));
model.addAttribute(USER_DASHBOARD_FREE_NODES, testbedStatsMap.get(USER_DASHBOARD_FREE_NODES));
model.addAttribute(USER_DASHBOARD_TOTAL_NODES, testbedStatsMap.get(USER_DASHBOARD_TOTAL_NODES));
return "testbed_nodes_status";
}
@RequestMapping(value = "/orderform/download", method = RequestMethod.GET)
public void OrderForm_v1Download(HttpServletResponse response) throws OrderFormDownloadException, IOException {
InputStream stream = null;
response.setContentType(MediaType.APPLICATION_PDF_VALUE);
try {
stream = getClass().getClassLoader().getResourceAsStream("downloads/order_form.pdf");
response.setContentType(APPLICATION_FORCE_DOWNLOAD);
response.setHeader(CONTENT_DISPOSITION, "attachment; filename=order_form.pdf");
IOUtils.copy(stream, response.getOutputStream());
response.flushBuffer();
} catch (IOException ex) {
log.info("Error for download orderform.");
throw new OrderFormDownloadException("Error for download orderform.");
} finally {
if (stream != null) {
stream.close();
}
}
}
@RequestMapping("/contactus")
public String contactus() {
return "contactus";
}
@RequestMapping("/notfound")
public String redirectNotFound(HttpSession session) {
if (session.getAttribute("id") != null && !session.getAttribute("id").toString().isEmpty()) {
// user is already logged on and has encountered an error
// redirect to dashboard
return "redirect:/dashboard";
} else {
// user have not logged on before
// redirect to home page
return REDIRECT_INDEX_PAGE;
}
}
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(Model model) {
model.addAttribute("loginForm", new LoginForm());
return "login";
}
@RequestMapping(value = "/emailVerification", params = {"id", "email", "key"})
public String verifyEmail(
@NotNull @RequestParam("id") final String id,
@NotNull @RequestParam("email") final String emailBase64,
@NotNull @RequestParam("key") final String key
) throws UnsupportedEncodingException {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
ObjectNode keyObject = objectMapper.createObjectNode();
keyObject.put("key", key);
HttpEntity<String> request = new HttpEntity<>(keyObject.toString(), headers);
restTemplate.setErrorHandler(new MyResponseErrorHandler());
final String link = properties.getSioRegUrl() + "/users/" + id + "/emails/" + emailBase64;
log.info("Activation link: {}, verification key {}", link, key);
ResponseEntity response = restTemplate.exchange(link, HttpMethod.PUT, request, String.class);
if (RestUtil.isError(response.getStatusCode())) {
log.error("Activation of user {} failed.", id);
return "email_validation_failed";
} else {
log.info("Activation of user {} completed.", id);
return "email_validation_ok";
}
}
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String loginSubmit(
@Valid
@ModelAttribute("loginForm") LoginForm loginForm,
BindingResult bindingResult,
Model model,
HttpSession session, final RedirectAttributes redirectAttributes) throws WebServiceRuntimeException {
if (bindingResult.hasErrors()) {
loginForm.setErrorMsg("Login failed: Invalid email/password.");
return "login";
}
String inputEmail = loginForm.getLoginEmail();
String inputPwd = loginForm.getLoginPassword();
if (inputEmail.trim().isEmpty() || inputPwd.trim().isEmpty()) {
loginForm.setErrorMsg("Email or Password cannot be empty!");
return "login";
}
String plainCreds = inputEmail + ":" + inputPwd;
byte[] plainCredsBytes = plainCreds.getBytes();
byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
String base64Creds = new String(base64CredsBytes);
ResponseEntity response;
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Basic " + base64Creds);
HttpEntity<String> request = new HttpEntity<>(headers);
restTemplate.setErrorHandler(new MyResponseErrorHandler());
try {
response = restTemplate.exchange(properties.getSioAuthUrl(), HttpMethod.POST, request, String.class);
} catch (RestClientException e) {
log.warn("Error connecting to sio authentication service: {}", e);
loginForm.setErrorMsg(ERR_SERVER_OVERLOAD);
return "login";
}
String jwtTokenString = response.getBody().toString();
log.info("token string {}", jwtTokenString);
if (jwtTokenString == null || jwtTokenString.isEmpty()) {
log.warn("login failed for {}: unknown response code", loginForm.getLoginEmail());
loginForm.setErrorMsg("Login failed: Invalid email/password.");
return "login";
}
if (RestUtil.isError(response.getStatusCode())) {
try {
MyErrorResource error = objectMapper.readValue(jwtTokenString, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
if (exceptionState == ExceptionState.CREDENTIALS_NOT_FOUND_EXCEPTION) {
log.warn("login failed for {}: credentials not found", loginForm.getLoginEmail());
loginForm.setErrorMsg("Login failed: Account does not exist. Please register.");
return "login";
}
log.warn("login failed for {}: {}", loginForm.getLoginEmail(), error.getError());
loginForm.setErrorMsg("Login failed: Invalid email/password.");
return "login";
} catch (IOException ioe) {
log.warn("IOException {}", ioe);
throw new WebServiceRuntimeException(ioe.getMessage());
}
}
JSONObject tokenObject = new JSONObject(jwtTokenString);
String token = tokenObject.getString("token");
String id = tokenObject.getString("id");
String role = "";
if (tokenObject.getJSONArray("roles") != null) {
role = tokenObject.getJSONArray("roles").get(0).toString();
}
if (token.trim().isEmpty() || id.trim().isEmpty() || role.trim().isEmpty()) {
log.warn("login failed for {}: empty id {} or token {} or role {}", loginForm.getLoginEmail(), id, token, role);
loginForm.setErrorMsg("Login failed: Invalid email/password.");
return "login";
}
// now check user status to decide what to show to the user
User2 user = invokeAndExtractUserInfo(id);
try {
String userStatus = user.getStatus();
boolean emailVerified = user.getEmailVerified();
if (UserStatus.FROZEN.toString().equals(userStatus)) {
log.warn("User {} login failed: account has been frozen", id);
loginForm.setErrorMsg("Login Failed: Account Frozen. Please contact " + CONTACT_EMAIL);
return "login";
} else if (!emailVerified || (UserStatus.CREATED.toString()).equals(userStatus)) {
redirectAttributes.addAttribute("statuschecklist", userStatus);
log.info("User {} not validated, redirected to email verification page", id);
return "redirect:/email_checklist";
} else if ((UserStatus.PENDING.toString()).equals(userStatus)) {
redirectAttributes.addAttribute("statuschecklist", userStatus);
log.info("User {} not approved, redirected to application pending page", id);
return "redirect:/email_checklist";
} else if ((UserStatus.APPROVED.toString()).equals(userStatus)) {
// set session variables
setSessionVariables(session, loginForm.getLoginEmail(), id, user.getFirstName(), role, token);
log.info("login success for {}, id: {}", loginForm.getLoginEmail(), id);
return "redirect:/dashboard";
} else {
log.warn("login failed for user {}: account is rejected or closed", id);
loginForm.setErrorMsg("Login Failed: Account Rejected/Closed.");
return "login";
}
} catch (Exception e) {
log.warn("Error parsing json object for user: {}", e.getMessage());
loginForm.setErrorMsg(ERR_SERVER_OVERLOAD);
return "login";
}
}
// triggered when user clicks "Forget Password?"
@RequestMapping("/password_reset_email")
public String passwordResetEmail(Model model) {
model.addAttribute("passwordResetRequestForm", new PasswordResetRequestForm());
return FORGET_PSWD_PAGE;
}
// triggered when user clicks "Send Reset Email" button
@PostMapping("/password_reset_request")
public String sendPasswordResetRequest(
@ModelAttribute("passwordResetRequestForm") PasswordResetRequestForm passwordResetRequestForm
) throws WebServiceRuntimeException {
String email = passwordResetRequestForm.getEmail();
if (!VALID_EMAIL_ADDRESS_REGEX.matcher(email).matches()) {
passwordResetRequestForm.setErrMsg("Please provide a valid email address");
return FORGET_PSWD_PAGE;
}
JSONObject obj = new JSONObject();
obj.put("username", email);
log.info("Connecting to sio for password reset email: {}", email);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(obj.toString(), headers);
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = null;
try {
response = restTemplate.exchange(properties.getPasswordResetRequestURI(), HttpMethod.POST, request, String.class);
} catch (RestClientException e) {
log.warn("Cannot connect to sio for password reset email: {}", e);
passwordResetRequestForm.setErrMsg("Cannot connect. Server may be down!");
return FORGET_PSWD_PAGE;
}
if (RestUtil.isError(response.getStatusCode())) {
log.warn("Server responded error for password reset email: {}", response.getStatusCode());
passwordResetRequestForm.setErrMsg("Email not registered. Please use a different email address.");
return FORGET_PSWD_PAGE;
}
log.info("Password reset email sent for {}", email);
return "password_reset_email_sent";
}
// triggered when user clicks password reset link in the email
@RequestMapping(path = "/passwordReset", params = {"key"})
public String passwordResetNewPassword(@NotNull @RequestParam("key") final String key, Model model) {
PasswordResetForm form = new PasswordResetForm();
form.setKey(key);
model.addAttribute("passwordResetForm", form);
// redirect to the page for user to enter new password
return FORGET_PSWD_NEW_PSWD_PAGE;
}
// actual call to sio to reset password
@RequestMapping(path = "/password_reset")
public String resetPassword(@ModelAttribute("passwordResetForm") PasswordResetForm passwordResetForm) throws IOException {
if (!passwordResetForm.isPasswordOk()) {
return FORGET_PSWD_NEW_PSWD_PAGE;
}
JSONObject obj = new JSONObject();
obj.put("key", passwordResetForm.getKey());
obj.put("new", passwordResetForm.getPassword1());
log.info("Connecting to sio for password reset, key = {}", passwordResetForm.getKey());
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(obj.toString(), headers);
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = null;
try {
response = restTemplate.exchange(properties.getPasswordResetURI(), HttpMethod.PUT, request, String.class);
} catch (RestClientException e) {
log.warn("Error connecting to sio for password reset! {}", e);
passwordResetForm.setErrMsg("Cannot connect to server! Please try again later.");
return FORGET_PSWD_NEW_PSWD_PAGE;
}
if (RestUtil.isError(response.getStatusCode())) {
EnumMap<ExceptionState, String> exceptionMessageMap = new EnumMap<>(ExceptionState.class);
exceptionMessageMap.put(PASSWORD_RESET_REQUEST_TIMEOUT_EXCEPTION, "Password reset request timed out. Please request a new reset email.");
exceptionMessageMap.put(PASSWORD_RESET_REQUEST_NOT_FOUND_EXCEPTION, "Invalid password reset request. Please request a new reset email.");
exceptionMessageMap.put(ADAPTER_CONNECTION_EXCEPTION, "Server-side error. Please contact " + CONTACT_EMAIL);
MyErrorResource error = objectMapper.readValue(response.getBody().toString(), MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
final String errMsg = exceptionMessageMap.get(exceptionState) == null ? ERR_SERVER_OVERLOAD : exceptionMessageMap.get(exceptionState);
passwordResetForm.setErrMsg(errMsg);
log.warn("Server responded error for password reset: {}", exceptionState.toString());
return FORGET_PSWD_NEW_PSWD_PAGE;
}
log.info("Password was reset, key = {}", passwordResetForm.getKey());
return "password_reset_success";
}
@RequestMapping("/dashboard")
public String dashboard(Model model, HttpSession session) throws WebServiceRuntimeException {
HttpEntity<String> request = createHttpEntityHeaderOnly();
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = restTemplate.exchange(properties.getDeterUid(session.getAttribute(webProperties.getSessionUserId()).toString()), HttpMethod.GET, request, String.class);
String responseBody = response.getBody().toString();
try {
if (RestUtil.isError(response.getStatusCode())) {
log.error("No user exists : {}", session.getAttribute(webProperties.getSessionUserId()));
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
model.addAttribute(DETER_UID, CONNECTION_ERROR);
} else {
log.info("Show the deter user id: {}", responseBody);
model.addAttribute(DETER_UID, responseBody);
}
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
// retrieve user dashboard stats
Map<String, Integer> userDashboardMap = getUserDashboardStats(session.getAttribute(webProperties.getSessionUserId()).toString());
List<TeamUsageInfo> usageInfoList = getTeamsUsageStatisticsForUser(session.getAttribute(webProperties.getSessionUserId()).toString());
model.addAttribute("userDashboardMap", userDashboardMap);
model.addAttribute("usageInfoList", usageInfoList);
return "dashboard";
}
@RequestMapping(value = "/logout", method = RequestMethod.GET)
public String logout(HttpSession session) {
removeSessionVariables(session);
return REDIRECT_INDEX_PAGE;
}
//--------------------------Sign Up Page--------------------------
@RequestMapping(value = "/signup2", method = RequestMethod.GET)
public String signup2(Model model, HttpServletRequest request) {
Map<String, ?> inputFlashMap = RequestContextUtils.getInputFlashMap(request);
if (inputFlashMap != null) {
log.debug((String) inputFlashMap.get(MESSAGE));
model.addAttribute("signUpMergedForm", (SignUpMergedForm) inputFlashMap.get("signUpMergedForm"));
} else {
log.debug("InputFlashMap is null");
model.addAttribute("signUpMergedForm", new SignUpMergedForm());
}
return "signup2";
}
@RequestMapping(value = "/signup2", method = RequestMethod.POST)
public String validateDetails(
@Valid
@ModelAttribute("signUpMergedForm") SignUpMergedForm signUpMergedForm,
BindingResult bindingResult,
final RedirectAttributes redirectAttributes) throws WebServiceRuntimeException {
if (bindingResult.hasErrors() || signUpMergedForm.getIsValid() == false) {
log.warn("Register form has errors {}", signUpMergedForm.toString());
return "signup2";
}
if (!signUpMergedForm.getHasAcceptTeamOwnerPolicy()) {
signUpMergedForm.setErrorTeamOwnerPolicy("Please accept the team owner policy");
log.warn("Policy not accepted");
return "signup2";
}
// get form fields
// craft the registration json
JSONObject mainObject = new JSONObject();
JSONObject credentialsFields = new JSONObject();
credentialsFields.put("username", signUpMergedForm.getEmail().trim());
credentialsFields.put("password", signUpMergedForm.getPassword());
// create the user JSON
JSONObject userFields = new JSONObject();
JSONObject userDetails = new JSONObject();
JSONObject addressDetails = new JSONObject();
userDetails.put("firstName", signUpMergedForm.getFirstName().trim());
userDetails.put("lastName", signUpMergedForm.getLastName().trim());
userDetails.put("jobTitle", signUpMergedForm.getJobTitle().trim());
userDetails.put("email", signUpMergedForm.getEmail().trim());
userDetails.put("phone", signUpMergedForm.getPhone().trim());
userDetails.put("institution", signUpMergedForm.getInstitution().trim());
userDetails.put("institutionAbbreviation", signUpMergedForm.getInstitutionAbbreviation().trim());
userDetails.put("institutionWeb", signUpMergedForm.getWebsite().trim());
userDetails.put("address", addressDetails);
addressDetails.put("address1", signUpMergedForm.getAddress1().trim());
addressDetails.put("address2", signUpMergedForm.getAddress2().trim());
addressDetails.put("country", signUpMergedForm.getCountry().trim());
addressDetails.put("region", signUpMergedForm.getProvince().trim());
addressDetails.put("city", signUpMergedForm.getCity().trim());
addressDetails.put("zipCode", signUpMergedForm.getPostalCode().trim());
userFields.put("userDetails", userDetails);
userFields.put(APPLICATION_DATE, ZonedDateTime.now());
JSONObject teamFields = new JSONObject();
// add all to main json
mainObject.put("credentials", credentialsFields);
mainObject.put("user", userFields);
mainObject.put("team", teamFields);
// check if user chose create new team or join existing team by checking team name
String createNewTeamName = signUpMergedForm.getTeamName().trim();
String joinNewTeamName = signUpMergedForm.getJoinTeamName().trim();
if (createNewTeamName != null && !createNewTeamName.isEmpty()) {
log.info("Signup new team name {}", createNewTeamName);
boolean errorsFound = false;
if (createNewTeamName.length() < 2 || createNewTeamName.length() > 12) {
errorsFound = true;
signUpMergedForm.setErrorTeamName("Team name must be 2 to 12 alphabetic/numeric characters");
}
if (signUpMergedForm.getTeamDescription() == null || signUpMergedForm.getTeamDescription().isEmpty()) {
errorsFound = true;
signUpMergedForm.setErrorTeamDescription("Team description cannot be empty");
}
if (signUpMergedForm.getTeamWebsite() == null || signUpMergedForm.getTeamWebsite().isEmpty()) {
errorsFound = true;
signUpMergedForm.setErrorTeamWebsite("Team website cannot be empty");
}
if (errorsFound) {
log.warn("Signup new team error {}", signUpMergedForm.toString());
// clear join team name first before submitting the form
signUpMergedForm.setJoinTeamName(null);
return "signup2";
} else {
teamFields.put("name", signUpMergedForm.getTeamName().trim());
teamFields.put("description", signUpMergedForm.getTeamDescription().trim());
teamFields.put("website", signUpMergedForm.getTeamWebsite().trim());
teamFields.put("organisationType", signUpMergedForm.getTeamOrganizationType());
teamFields.put("visibility", signUpMergedForm.getIsPublic());
mainObject.put("isJoinTeam", false);
try {
registerUserToDeter(mainObject);
} catch (
TeamNotFoundException |
TeamNameAlreadyExistsException |
UsernameAlreadyExistsException |
EmailAlreadyExistsException |
InvalidTeamNameException |
InvalidPasswordException |
DeterLabOperationFailedException e) {
redirectAttributes.addFlashAttribute(MESSAGE, e.getMessage());
redirectAttributes.addFlashAttribute("signUpMergedForm", signUpMergedForm);
return "redirect:/signup2";
} catch (Exception e) {
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
redirectAttributes.addFlashAttribute("signUpMergedForm", signUpMergedForm);
return "redirect:/signup2";
}
log.info("Signup new team success");
return "redirect:/team_application_submitted";
}
} else if (joinNewTeamName != null && !joinNewTeamName.isEmpty()) {
log.info("Signup join team name {}", joinNewTeamName);
// get the team JSON from team name
Team2 joinTeamInfo;
try {
joinTeamInfo = getTeamIdByName(signUpMergedForm.getJoinTeamName().trim());
} catch (TeamNotFoundException | AdapterConnectionException e) {
redirectAttributes.addFlashAttribute(MESSAGE, e.getMessage());
redirectAttributes.addFlashAttribute("signUpMergedForm", signUpMergedForm);
return "redirect:/signup2";
}
teamFields.put("id", joinTeamInfo.getId());
// set the flag to indicate to controller that it is joining an existing team
mainObject.put("isJoinTeam", true);
try {
registerUserToDeter(mainObject);
} catch (
TeamNotFoundException |
AdapterConnectionException |
TeamNameAlreadyExistsException |
UsernameAlreadyExistsException |
EmailAlreadyExistsException |
InvalidTeamNameException |
InvalidPasswordException |
DeterLabOperationFailedException e) {
redirectAttributes.addFlashAttribute(MESSAGE, e.getMessage());
redirectAttributes.addFlashAttribute("signUpMergedForm", signUpMergedForm);
return "redirect:/signup2";
} catch (Exception e) {
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
redirectAttributes.addFlashAttribute("signUpMergedForm", signUpMergedForm);
return "redirect:/signup2";
}
log.info("Signup join team success");
log.info("jointeam info: {}", joinTeamInfo);
redirectAttributes.addFlashAttribute("team", joinTeamInfo);
return "redirect:/join_application_submitted";
} else {
log.warn("Signup unreachable statement");
// logic error not suppose to reach here
// possible if user fill up create new team but without the team name
redirectAttributes.addFlashAttribute("signupError", "There is a problem when submitting your form. Please re-enter and submit the details again.");
redirectAttributes.addFlashAttribute("signUpMergedForm", signUpMergedForm);
return "redirect:/signup2";
}
}
/**
* Use when registering new accounts
*
* @param mainObject A JSONObject that contains user's credentials, personal details and team application details
*/
private void registerUserToDeter(JSONObject mainObject) throws
WebServiceRuntimeException,
TeamNotFoundException,
AdapterConnectionException,
TeamNameAlreadyExistsException,
UsernameAlreadyExistsException,
EmailAlreadyExistsException,
InvalidTeamNameException,
InvalidPasswordException,
DeterLabOperationFailedException {
HttpEntity<String> request = createHttpEntityWithBodyNoAuthHeader(mainObject.toString());
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = restTemplate.exchange(properties.getSioRegUrl(), HttpMethod.POST, request, String.class);
String responseBody = response.getBody().toString();
log.info("Register user to deter response: {}", responseBody);
try {
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
log.warn("Register user exception error: {}", error.getError());
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case DETERLAB_OPERATION_FAILED_EXCEPTION:
log.warn("Register new user failed on DeterLab: {}", error.getMessage());
throw new DeterLabOperationFailedException(ERROR_PREFIX + (error.getMessage().contains("unknown error") ? ERR_SERVER_OVERLOAD : error.getMessage()));
case TEAM_NAME_ALREADY_EXISTS_EXCEPTION:
log.warn("Register new users new team request : team name already exists");
throw new TeamNameAlreadyExistsException("Team name already exists");
case INVALID_TEAM_NAME_EXCEPTION:
log.warn("Register new users new team request : team name invalid");
throw new InvalidTeamNameException("Invalid team name: must be 6-12 alphanumeric characters only");
case INVALID_PASSWORD_EXCEPTION:
log.warn("Register new users new team request : invalid password");
throw new InvalidPasswordException("Password is too simple");
case USERNAME_ALREADY_EXISTS_EXCEPTION:
// throw from user service
{
String email = mainObject.getJSONObject("user").getJSONObject("userDetails").getString("email");
log.warn("Register new users : email already exists: {}", email);
throw new UsernameAlreadyExistsException(ERROR_PREFIX + email + " already in use.");
}
case EMAIL_ALREADY_EXISTS_EXCEPTION:
// throw from adapter deterlab
{
String email = mainObject.getJSONObject("user").getJSONObject("userDetails").getString("email");
log.warn("Register new users : email already exists: {}", email);
throw new EmailAlreadyExistsException(ERROR_PREFIX + email + " already in use.");
}
default:
log.warn("Registration or adapter connection fail");
// possible sio or adapter connection fail
throw new AdapterConnectionException(ERR_SERVER_OVERLOAD);
}
} else {
// do nothing
log.info("Not an error for status code: {}", response.getStatusCode());
}
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
}
/**
* Use when users register a new account for joining existing team
*
* @param teamName The team name to join
* @return the team id from sio
*/
private Team2 getTeamIdByName(String teamName) throws WebServiceRuntimeException, TeamNotFoundException, AdapterConnectionException {
// FIXME check if team name exists
// FIXME check for general exception?
HttpEntity<String> request = createHttpEntityHeaderOnlyNoAuthHeader();
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = restTemplate.exchange(properties.getTeamByName(teamName), HttpMethod.GET, request, String.class);
String responseBody = response.getBody().toString();
try {
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
if (exceptionState == ExceptionState.TEAM_NOT_FOUND_EXCEPTION) {
log.warn("Get team by name : team name error");
throw new TeamNotFoundException("Team name " + teamName + " does not exists");
} else {
log.warn("Team service or adapter connection fail");
// possible sio or adapter connection fail
throw new AdapterConnectionException(ERR_SERVER_OVERLOAD);
}
} else {
return extractTeamInfo(responseBody);
}
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
}
//--------------------------Account Settings Page--------------------------
@RequestMapping(value = "/account_settings", method = RequestMethod.GET)
public String accountDetails(Model model, HttpSession session) throws WebServiceRuntimeException {
String userId_uri = properties.getSioUsersUrl() + session.getAttribute("id");
HttpEntity<String> request = createHttpEntityHeaderOnly();
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = restTemplate.exchange(userId_uri, HttpMethod.GET, request, String.class);
String responseBody = response.getBody().toString();
try {
if (RestUtil.isError(response.getStatusCode())) {
log.error("No user to edit : {}", session.getAttribute("id"));
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
throw new RestClientException("[" + error.getError() + "] ");
} else {
User2 user2 = extractUserInfo(responseBody);
// need to do this so that we can compare after submitting the form
session.setAttribute(webProperties.getSessionUserAccount(), user2);
model.addAttribute("editUser", user2);
return "account_settings";
}
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
}
@RequestMapping(value = "/account_settings", method = RequestMethod.POST)
public String editAccountDetails(
@ModelAttribute("editUser") User2 editUser,
final RedirectAttributes redirectAttributes,
HttpSession session) throws WebServiceRuntimeException {
boolean errorsFound = false;
String editPhrase = "editPhrase";
// check fields first
if (errorsFound == false && editUser.getFirstName().isEmpty()) {
redirectAttributes.addFlashAttribute("editFirstName", "fail");
errorsFound = true;
}
if (errorsFound == false && editUser.getLastName().isEmpty()) {
redirectAttributes.addFlashAttribute("editLastName", "fail");
errorsFound = true;
}
if (errorsFound == false && editUser.getPhone().isEmpty()) {
redirectAttributes.addFlashAttribute("editPhone", "fail");
errorsFound = true;
}
if (errorsFound == false && (editUser.getPhone().matches("(.*)[a-zA-Z](.*)") || editUser.getPhone().length() < 6)) {
// previously already check if phone is empty
// now check phone must contain only digits
redirectAttributes.addFlashAttribute("editPhone", "fail");
errorsFound = true;
}
if (errorsFound == false && !editUser.getConfirmPassword().isEmpty() && !editUser.isPasswordValid()) {
redirectAttributes.addFlashAttribute(editPhrase, "invalid");
errorsFound = true;
}
if (errorsFound == false && editUser.getJobTitle().isEmpty()) {
redirectAttributes.addFlashAttribute("editJobTitle", "fail");
errorsFound = true;
}
if (errorsFound == false && editUser.getInstitution().isEmpty()) {
redirectAttributes.addFlashAttribute("editInstitution", "fail");
errorsFound = true;
}
if (errorsFound == false && editUser.getCountry().isEmpty()) {
redirectAttributes.addFlashAttribute("editCountry", "fail");
errorsFound = true;
}
if (errorsFound) {
session.removeAttribute(webProperties.getSessionUserAccount());
return "redirect:/account_settings";
} else {
// used to compare original and edited User2 objects
User2 originalUser = (User2) session.getAttribute(webProperties.getSessionUserAccount());
JSONObject userObject = new JSONObject();
JSONObject userDetails = new JSONObject();
JSONObject address = new JSONObject();
userDetails.put("firstName", editUser.getFirstName());
userDetails.put("lastName", editUser.getLastName());
userDetails.put("email", editUser.getEmail());
userDetails.put("phone", editUser.getPhone());
userDetails.put("jobTitle", editUser.getJobTitle());
userDetails.put("address", address);
userDetails.put("institution", editUser.getInstitution());
userDetails.put("institutionAbbreviation", originalUser.getInstitutionAbbreviation());
userDetails.put("institutionWeb", originalUser.getInstitutionWeb());
address.put("address1", originalUser.getAddress1());
address.put("address2", originalUser.getAddress2());
address.put("country", editUser.getCountry());
address.put("city", originalUser.getCity());
address.put("region", originalUser.getRegion());
address.put("zipCode", originalUser.getPostalCode());
userObject.put("userDetails", userDetails);
String userId_uri = properties.getSioUsersUrl() + session.getAttribute(webProperties.getSessionUserId());
HttpEntity<String> request = createHttpEntityWithBody(userObject.toString());
restTemplate.exchange(userId_uri, HttpMethod.PUT, request, String.class);
if (!originalUser.getFirstName().equals(editUser.getFirstName())) {
redirectAttributes.addFlashAttribute("editFirstName", "success");
}
if (!originalUser.getLastName().equals(editUser.getLastName())) {
redirectAttributes.addFlashAttribute("editLastName", "success");
}
if (!originalUser.getPhone().equals(editUser.getPhone())) {
redirectAttributes.addFlashAttribute("editPhone", "success");
}
if (!originalUser.getJobTitle().equals(editUser.getJobTitle())) {
redirectAttributes.addFlashAttribute("editJobTitle", "success");
}
if (!originalUser.getInstitution().equals(editUser.getInstitution())) {
redirectAttributes.addFlashAttribute("editInstitution", "success");
}
if (!originalUser.getCountry().equals(editUser.getCountry())) {
redirectAttributes.addFlashAttribute("editCountry", "success");
}
// credential service change password
if (editUser.isPasswordMatch()) {
JSONObject credObject = new JSONObject();
credObject.put("password", editUser.getPassword());
HttpEntity<String> credRequest = createHttpEntityWithBody(credObject.toString());
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = restTemplate.exchange(properties.getUpdateCredentials(session.getAttribute("id").toString()), HttpMethod.PUT, credRequest, String.class);
String responseBody = response.getBody().toString();
try {
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
redirectAttributes.addFlashAttribute(editPhrase, "fail");
} else {
redirectAttributes.addFlashAttribute(editPhrase, "success");
}
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
} finally {
session.removeAttribute(webProperties.getSessionUserAccount());
}
}
}
return "redirect:/account_settings";
}
//--------------------User Side Approve Members Page------------
@RequestMapping("/approve_new_user")
public String approveNewUser(Model model, HttpSession session) throws Exception {
// HashMap<Integer, Team> rv = new HashMap<Integer, Team>();
// rv = teamManager.getTeamMapByTeamOwner(getSessionIdOfLoggedInUser(session));
// boolean userHasAnyJoinRequest = hasAnyJoinRequest(rv);
// model.addAttribute("teamMapOwnedByUser", rv);
// model.addAttribute("userHasAnyJoinRequest", userHasAnyJoinRequest);
List<JoinRequestApproval> rv = new ArrayList<>();
List<JoinRequestApproval> temp;
// get list of teamids
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response = restTemplate.exchange(properties.getUser(session.getAttribute("id").toString()), HttpMethod.GET, request, String.class);
String responseBody = response.getBody().toString();
JSONObject object = new JSONObject(responseBody);
JSONArray teamIdsJsonArray = object.getJSONArray("teams");
for (int i = 0; i < teamIdsJsonArray.length(); i++) {
String teamId = teamIdsJsonArray.get(i).toString();
HttpEntity<String> teamRequest = createHttpEntityHeaderOnly();
ResponseEntity teamResponse = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, teamRequest, String.class);
String teamResponseBody = teamResponse.getBody().toString();
Team2 team2 = new Team2();
JSONObject teamObject = new JSONObject(teamResponseBody);
JSONArray membersArray = teamObject.getJSONArray("members");
team2.setId(teamObject.getString("id"));
team2.setName(teamObject.getString("name"));
boolean isTeamLeader = false;
temp = new ArrayList<>();
for (int j = 0; j < membersArray.length(); j++) {
JSONObject memberObject = membersArray.getJSONObject(j);
String userId = memberObject.getString("userId");
String teamMemberType = memberObject.getString(MEMBER_TYPE);
String teamMemberStatus = memberObject.getString("memberStatus");
String teamJoinedDate = formatZonedDateTime(memberObject.get("joinedDate").toString());
JoinRequestApproval joinRequestApproval = new JoinRequestApproval();
if (userId.equals(session.getAttribute("id").toString()) && teamMemberType.equals(MemberType.OWNER.toString())) {
isTeamLeader = true;
}
if (teamMemberStatus.equals(MemberStatus.PENDING.toString()) && teamMemberType.equals(MemberType.MEMBER.toString())) {
User2 myUser = invokeAndExtractUserInfo(userId);
joinRequestApproval.setUserId(myUser.getId());
joinRequestApproval.setUserEmail(myUser.getEmail());
joinRequestApproval.setUserName(myUser.getFirstName() + " " + myUser.getLastName());
joinRequestApproval.setApplicationDate(teamJoinedDate);
joinRequestApproval.setTeamId(team2.getId());
joinRequestApproval.setTeamName(team2.getName());
joinRequestApproval.setVerified(myUser.getEmailVerified());
temp.add(joinRequestApproval);
log.info("Join request: UserId: {}, UserEmail: {}", myUser.getId(), myUser.getEmail());
}
}
if (isTeamLeader) {
if (!temp.isEmpty()) {
rv.addAll(temp);
}
}
}
model.addAttribute("joinApprovalList", rv);
return "approve_new_user";
}
@RequestMapping("/approve_new_user/accept/{teamId}/{userId}")
public String userSideAcceptJoinRequest(
@PathVariable String teamId,
@PathVariable String userId,
HttpSession session,
RedirectAttributes redirectAttributes) throws WebServiceRuntimeException {
log.info("Approve join request: User {}, Team {}, Approver {}",
userId, teamId, session.getAttribute("id").toString());
JSONObject mainObject = new JSONObject();
JSONObject userFields = new JSONObject();
userFields.put("id", session.getAttribute("id").toString());
mainObject.put("user", userFields);
HttpEntity<String> request = createHttpEntityWithBody(mainObject.toString());
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getApproveJoinRequest(teamId, userId), HttpMethod.POST, request, String.class);
} catch (RestClientException e) {
log.warn("Error connecting to sio team service: {}", e);
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
return "redirect:/approve_new_user";
}
String responseBody = response.getBody().toString();
if (RestUtil.isError(response.getStatusCode())) {
try {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case EMAIL_NOT_VERIFIED_EXCEPTION:
log.warn("Approve join request: User {} email not verified", userId);
redirectAttributes.addFlashAttribute(MESSAGE, "User email has not been verified");
break;
case DETERLAB_OPERATION_FAILED_EXCEPTION:
log.warn("Approve join request: User {}, Team {} fail", userId, teamId);
redirectAttributes.addFlashAttribute(MESSAGE, "Approve join request fail");
break;
default:
log.warn("Server side error: {}", error.getError());
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
break;
}
return "redirect:/approve_new_user";
} catch (IOException ioe) {
log.warn("IOException {}", ioe);
throw new WebServiceRuntimeException(ioe.getMessage());
}
}
// everything looks OK?
log.info("Join request has been APPROVED, User {}, Team {}", userId, teamId);
redirectAttributes.addFlashAttribute(MESSAGE_SUCCESS, "Join request has been APPROVED.");
return "redirect:/approve_new_user";
}
@RequestMapping("/approve_new_user/reject/{teamId}/{userId}")
public String userSideRejectJoinRequest(
@PathVariable String teamId,
@PathVariable String userId,
HttpSession session,
RedirectAttributes redirectAttributes) throws WebServiceRuntimeException {
log.info("Reject join request: User {}, Team {}, Approver {}",
userId, teamId, session.getAttribute("id").toString());
JSONObject mainObject = new JSONObject();
JSONObject userFields = new JSONObject();
userFields.put("id", session.getAttribute("id").toString());
mainObject.put("user", userFields);
HttpEntity<String> request = createHttpEntityWithBody(mainObject.toString());
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getRejectJoinRequest(teamId, userId), HttpMethod.DELETE, request, String.class);
} catch (RestClientException e) {
log.warn("Error connecting to sio team service: {}", e);
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
return "redirect:/approve_new_user";
}
String responseBody = response.getBody().toString();
if (RestUtil.isError(response.getStatusCode())) {
try {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case DETERLAB_OPERATION_FAILED_EXCEPTION:
log.warn("Reject join request: User {}, Team {} fail", userId, teamId);
redirectAttributes.addFlashAttribute(MESSAGE, "Reject join request fail");
break;
default:
log.warn("Server side error: {}", error.getError());
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
break;
}
return "redirect:/approve_new_user";
} catch (IOException ioe) {
log.warn("IOException {}", ioe);
throw new WebServiceRuntimeException(ioe.getMessage());
}
}
// everything looks OK?
log.info("Join request has been REJECTED, User {}, Team {}", userId, teamId);
redirectAttributes.addFlashAttribute(MESSAGE, "Join request has been REJECTED.");
return "redirect:/approve_new_user";
}
//--------------------------Teams Page--------------------------
@RequestMapping("/public_teams")
public String publicTeamsBeforeLogin(Model model) {
TeamManager2 teamManager2 = new TeamManager2();
// get public teams
HttpEntity<String> teamRequest = createHttpEntityHeaderOnlyNoAuthHeader();
ResponseEntity teamResponse = restTemplate.exchange(properties.getTeamsByVisibility(TeamVisibility.PUBLIC.toString()), HttpMethod.GET, teamRequest, String.class);
String teamResponseBody = teamResponse.getBody().toString();
JSONArray teamPublicJsonArray = new JSONArray(teamResponseBody);
for (int i = 0; i < teamPublicJsonArray.length(); i++) {
JSONObject teamInfoObject = teamPublicJsonArray.getJSONObject(i);
Team2 team2 = extractTeamInfo(teamInfoObject.toString());
teamManager2.addTeamToPublicTeamMap(team2);
}
model.addAttribute("publicTeamMap2", teamManager2.getPublicTeamMap());
return "public_teams";
}
@RequestMapping("/teams")
public String teams(Model model, HttpSession session) {
// int currentLoggedInUserId = getSessionIdOfLoggedInUser(session);
// model.addAttribute("infoMsg", teamManager.getInfoMsg());
// model.addAttribute("currentLoggedInUserId", currentLoggedInUserId);
// model.addAttribute("teamMap", teamManager.getTeamMap(currentLoggedInUserId));
// model.addAttribute("publicTeamMap", teamManager.getPublicTeamMap());
// model.addAttribute("invitedToParticipateMap2", teamManager.getInvitedToParticipateMap2(currentLoggedInUserId));
// model.addAttribute("joinRequestMap2", teamManager.getJoinRequestTeamMap2(currentLoggedInUserId));
TeamManager2 teamManager2 = new TeamManager2();
// stores the list of images created or in progress of creation by teams
// e.g. teamNameA : "created" : [imageA, imageB], "inProgress" : [imageC, imageD]
Map<String, Map<String, List<Image>>> imageMap = new HashMap<>();
// get list of teamids
String userId = session.getAttribute("id").toString();
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response = restTemplate.exchange(properties.getUser(userId), HttpMethod.GET, request, String.class);
String responseBody = response.getBody().toString();
JSONObject object = new JSONObject(responseBody);
JSONArray teamIdsJsonArray = object.getJSONArray("teams");
String userEmail = object.getJSONObject("userDetails").getString("email");
for (int i = 0; i < teamIdsJsonArray.length(); i++) {
String teamId = teamIdsJsonArray.get(i).toString();
HttpEntity<String> teamRequest = createHttpEntityHeaderOnly();
ResponseEntity teamResponse = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, teamRequest, String.class);
String teamResponseBody = teamResponse.getBody().toString();
//Tran: check if team is approved for userId
Team2 joinRequestTeam = extractTeamInfoUserJoinRequest(userId, teamResponseBody);
if (joinRequestTeam != null) {
teamManager2.addTeamToUserJoinRequestTeamMap(joinRequestTeam);
} else {
Team2 team2 = extractTeamInfo(teamResponseBody);
teamManager2.addTeamToTeamMap(team2);
imageMap.put(team2.getName(), invokeAndGetImageList(teamId)); //Tran : only retrieve images of approved teams
}
}
// check if inner image map is empty, have to do it via this manner
// returns true if the team contains an image list
boolean isInnerImageMapPresent = imageMap.values().stream().filter(perTeamImageMap -> !perTeamImageMap.isEmpty()).findFirst().isPresent();
model.addAttribute("userEmail", userEmail);
model.addAttribute("teamMap2", teamManager2.getTeamMap());
model.addAttribute("userJoinRequestMap", teamManager2.getUserJoinRequestMap());
model.addAttribute("isInnerImageMapPresent", isInnerImageMapPresent);
model.addAttribute("imageMap", imageMap);
return "teams";
}
/**
* Exectues the service-image and returns a Map containing the list of images in two partitions.
* One partition contains the list of already created images.
* The other partition contains the list of currently saving in progress images.
*
* @param teamId The ncl team id to retrieve the list of images from.
* @return Returns a Map containing the list of images in two partitions.
*/
private Map<String, List<Image>> invokeAndGetImageList(String teamId) {
log.info("Getting list of saved images for team {}", teamId);
Map<String, List<Image>> resultMap = new HashMap<>();
List<Image> createdImageList = new ArrayList<>();
List<Image> inProgressImageList = new ArrayList<>();
HttpEntity<String> imageRequest = createHttpEntityHeaderOnly();
ResponseEntity imageResponse;
try {
imageResponse = restTemplate.exchange(properties.getTeamSavedImages(teamId), HttpMethod.GET, imageRequest, String.class);
} catch (ResourceAccessException e) {
log.warn("Error connecting to image service: {}", e);
return new HashMap<>();
}
String imageResponseBody = imageResponse.getBody().toString();
String osImageList = new JSONObject(imageResponseBody).getString(teamId);
JSONObject osImageObject = new JSONObject(osImageList);
log.debug("osImageList: {}", osImageList);
log.debug("osImageObject: {}", osImageObject);
if (osImageObject == JSONObject.NULL || osImageObject.length() == 0) {
log.info("List of saved images for team {} is empty.", teamId);
return resultMap;
}
for (int k = 0; k < osImageObject.names().length(); k++) {
String imageName = osImageObject.names().getString(k);
String imageStatus = osImageObject.getString(imageName);
log.info("Image list for team {}: image name {}, status {}", teamId, imageName, imageStatus);
Image image = new Image();
image.setImageName(imageName);
image.setDescription("-");
image.setTeamId(teamId);
if ("created".equals(imageStatus)) {
createdImageList.add(image);
} else if ("notfound".equals(imageStatus)) {
inProgressImageList.add(image);
}
}
resultMap.put("created", createdImageList);
resultMap.put("inProgress", inProgressImageList);
return resultMap;
}
// @RequestMapping("/accept_participation/{teamId}")
// public String acceptParticipationRequest(@PathVariable Integer teamId, Model model, HttpSession session) {
// int currentLoggedInUserId = getSessionIdOfLoggedInUser(session);
// // get user's participation request list
// // add this user id to the requested list
// teamManager.acceptParticipationRequest(currentLoggedInUserId, teamId);
// // remove participation request since accepted
// teamManager.removeParticipationRequest(currentLoggedInUserId, teamId);
//
// // must get team name
// String teamName = teamManager.getTeamNameByTeamId(teamId);
// teamManager.setInfoMsg("You have just joined Team " + teamName + " !");
//
// return "redirect:/teams";
// }
// @RequestMapping("/ignore_participation/{teamId}")
// public String ignoreParticipationRequest(@PathVariable Integer teamId, Model model, HttpSession session) {
// // get user's participation request list
// // remove this user id from the requested list
// String teamName = teamManager.getTeamNameByTeamId(teamId);
// teamManager.ignoreParticipationRequest2(getSessionIdOfLoggedInUser(session), teamId);
// teamManager.setInfoMsg("You have just ignored a team request from Team " + teamName + " !");
//
// return "redirect:/teams";
// }
// @RequestMapping("/withdraw/{teamId}")
public String withdrawnJoinRequest(@PathVariable Integer teamId, HttpSession session) {
// get user team request
// remove this user id from the user's request list
String teamName = teamManager.getTeamNameByTeamId(teamId);
teamManager.removeUserJoinRequest2(getSessionIdOfLoggedInUser(session), teamId);
teamManager.setInfoMsg("You have withdrawn your join request for Team " + teamName);
return "redirect:/teams";
}
// @RequestMapping(value="/teams/invite_members/{teamId}", method=RequestMethod.GET)
// public String inviteMember(@PathVariable Integer teamId, Model model) {
// model.addAttribute("teamIdVar", teamId);
// model.addAttribute("teamPageInviteMemberForm", new TeamPageInviteMemberForm());
// return "team_page_invite_members";
// }
// @RequestMapping(value="/teams/invite_members/{teamId}", method=RequestMethod.POST)
// public String sendInvitation(@PathVariable Integer teamId, @ModelAttribute TeamPageInviteMemberForm teamPageInviteMemberForm,Model model) {
// int userId = userManager.getUserIdByEmail(teamPageInviteMemberForm.getInviteUserEmail());
// teamManager.addInvitedToParticipateMap(userId, teamId);
// return "redirect:/teams";
// }
@RequestMapping(value = "/teams/members_approval/{teamId}", method = RequestMethod.GET)
public String membersApproval(@PathVariable Integer teamId, Model model) {
model.addAttribute("team", teamManager.getTeamByTeamId(teamId));
return "team_page_approve_members";
}
@RequestMapping("/teams/members_approval/accept/{teamId}/{userId}")
public String acceptJoinRequest(@PathVariable Integer teamId, @PathVariable Integer userId) {
teamManager.acceptJoinRequest(userId, teamId);
return "redirect:/teams/members_approval/{teamId}";
}
@RequestMapping("/teams/members_approval/reject/{teamId}/{userId}")
public String rejectJoinRequest(@PathVariable Integer teamId, @PathVariable Integer userId) {
teamManager.rejectJoinRequest(userId, teamId);
return "redirect:/teams/members_approval/{teamId}";
}
//--------------------------Team Profile Page--------------------------
@RequestMapping(value = "/team_profile/{teamId}", method = RequestMethod.GET)
public String teamProfile(@PathVariable String teamId, Model model, final RedirectAttributes redirectAttributes, HttpSession session) throws IOException {
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, request, String.class);
String responseBody = response.getBody().toString();
Team2 team = extractTeamInfo(responseBody);
model.addAttribute("team", team);
model.addAttribute("owner", team.getOwner());
model.addAttribute("membersList", team.getMembersStatusMap().get(MemberStatus.APPROVED));
session.setAttribute("originalTeam", team);
request = createHttpEntityHeaderOnly();
response = restTemplate.exchange(properties.getExpListByTeamId(teamId), HttpMethod.GET, request, String.class);
JSONArray experimentsArray = new JSONArray(response.getBody().toString());
List<Experiment2> experimentList = new ArrayList<>();
Map<Long, Realization> realizationMap = new HashMap<>();
for (int k = 0; k < experimentsArray.length(); k++) {
Experiment2 experiment2 = extractExperiment(experimentsArray.getJSONObject(k).toString());
Realization realization = invokeAndExtractRealization(experiment2.getTeamName(), experiment2.getId());
realizationMap.put(experiment2.getId(), realization);
experimentList.add(experiment2);
}
model.addAttribute("teamExperimentList", experimentList);
model.addAttribute("teamRealizationMap", realizationMap);
//Starting to get quota
try {
response = restTemplate.exchange(properties.getQuotaByTeamId(teamId), HttpMethod.GET, request, String.class);
} catch (RestClientException e) {
log.warn("Error connecting to sio team service for display team quota: {}", e);
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
return REDIRECT_TEAM_PROFILE_TEAM_ID;
}
responseBody = response.getBody().toString();
// handling exceptions from SIO
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case TEAM_NOT_FOUND_EXCEPTION:
log.warn("Get team quota: Team {} not found", teamId);
return REDIRECT_INDEX_PAGE;
default:
log.warn("Get team quota : sio or deterlab adapter connection error");
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
break;
}
} else {
log.info("Get team quota info : {}", responseBody);
}
TeamQuota teamQuota = extractTeamQuotaInfo(responseBody);
model.addAttribute("teamQuota", teamQuota);
session.setAttribute(ORIGINAL_BUDGET, teamQuota.getBudget()); // this is to check if budget changed later
return "team_profile";
}
@RequestMapping(value = "/team_profile/{teamId}", method = RequestMethod.POST)
public String editTeamProfile(
@PathVariable String teamId,
@ModelAttribute("team") Team2 editTeam,
final RedirectAttributes redirectAttributes,
HttpSession session) {
boolean errorsFound = false;
if (editTeam.getDescription().isEmpty()) {
errorsFound = true;
redirectAttributes.addFlashAttribute("editDesc", "fail");
}
if (errorsFound) {
// safer to remove
session.removeAttribute("originalTeam");
return REDIRECT_TEAM_PROFILE + editTeam.getId();
}
// can edit team description and team website for now
JSONObject teamfields = new JSONObject();
teamfields.put("id", teamId);
teamfields.put("name", editTeam.getName());
teamfields.put("description", editTeam.getDescription());
teamfields.put("website", "http://default.com");
teamfields.put("organisationType", editTeam.getOrganisationType());
teamfields.put("privacy", "OPEN");
teamfields.put("status", editTeam.getStatus());
teamfields.put("members", editTeam.getMembersList());
HttpEntity<String> request = createHttpEntityWithBody(teamfields.toString());
ResponseEntity response = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.PUT, request, String.class);
Team2 originalTeam = (Team2) session.getAttribute("originalTeam");
if (!originalTeam.getDescription().equals(editTeam.getDescription())) {
redirectAttributes.addFlashAttribute("editDesc", "success");
}
// safer to remove
session.removeAttribute("originalTeam");
return REDIRECT_TEAM_PROFILE + teamId;
}
@RequestMapping(value = "/team_quota/{teamId}", method = RequestMethod.POST)
public String editTeamQuota(
@PathVariable String teamId,
@ModelAttribute("teamQuota") TeamQuota editTeamQuota,
final RedirectAttributes redirectAttributes,
HttpSession session) throws IOException {
final String QUOTA = "#quota";
JSONObject teamQuotaJSONObject = new JSONObject();
teamQuotaJSONObject.put(TEAM_ID, teamId);
// check if budget is negative or exceeding limit
if (!editTeamQuota.getBudget().equals("")) {
if (Double.parseDouble(editTeamQuota.getBudget()) < 0) {
redirectAttributes.addFlashAttribute(EDIT_BUDGET, "negativeError");
return REDIRECT_TEAM_PROFILE + teamId + QUOTA;
} else if(Double.parseDouble(editTeamQuota.getBudget()) > 99999999.99) {
redirectAttributes.addFlashAttribute(EDIT_BUDGET, "exceedingLimit");
return REDIRECT_TEAM_PROFILE + teamId + QUOTA;
}
}
teamQuotaJSONObject.put("quota", editTeamQuota.getBudget());
HttpEntity<String> request = createHttpEntityWithBody(teamQuotaJSONObject.toString());
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getQuotaByTeamId(teamId), HttpMethod.PUT, request, String.class);
} catch (RestClientException e) {
log.warn("Error connecting to sio team service for display team quota: {}", e);
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
return REDIRECT_TEAM_PROFILE_TEAM_ID;
}
String responseBody = response.getBody().toString();
// handling exceptions from SIO
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case TEAM_NOT_FOUND_EXCEPTION:
log.warn("Get team quota: Team {} not found", teamId);
return REDIRECT_INDEX_PAGE;
case TEAM_QUOTA_OUT_OF_RANGE_EXCEPTION:
log.warn("Get team quota: Budget is out of range");
return REDIRECT_TEAM_PROFILE + teamId + QUOTA;
case FORBIDDEN_EXCEPTION:
log.warn("Get team quota: Budget can only be updated by team owner.");
redirectAttributes.addFlashAttribute(EDIT_BUDGET, "editDeny");
return REDIRECT_TEAM_PROFILE + teamId + QUOTA;
default:
log.warn("Get team quota : sio or deterlab adapter connection error");
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
return REDIRECT_TEAM_PROFILE + teamId + QUOTA;
}
} else {
log.info("Edit team quota info : {}", responseBody);
}
//check if new budget is different in order to display successful message to user
String originalBudget = (String) session.getAttribute(ORIGINAL_BUDGET);
if (!originalBudget.equals(editTeamQuota.getBudget())) {
redirectAttributes.addFlashAttribute(EDIT_BUDGET, "success");
}
// safer to remove
session.removeAttribute(ORIGINAL_BUDGET);
return REDIRECT_TEAM_PROFILE + teamId + QUOTA;
}
@RequestMapping("/remove_member/{teamId}/{userId}")
public String removeMember(@PathVariable String teamId, @PathVariable String userId, final RedirectAttributes redirectAttributes) throws IOException {
JSONObject teamMemberFields = new JSONObject();
teamMemberFields.put("userId", userId);
teamMemberFields.put(MEMBER_TYPE, MemberType.MEMBER.name());
teamMemberFields.put("memberStatus", MemberStatus.APPROVED.name());
HttpEntity<String> request = createHttpEntityWithBody(teamMemberFields.toString());
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response;
try {
response = restTemplate.exchange(properties.removeUserFromTeam(teamId), HttpMethod.DELETE, request, String.class);
} catch (RestClientException e) {
log.warn("Error connecting to sio team service for remove user: {}", e);
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
return REDIRECT_TEAM_PROFILE_TEAM_ID;
}
String responseBody = response.getBody().toString();
User2 user = invokeAndExtractUserInfo(userId);
String name = user.getFirstName() + " " + user.getLastName();
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case DETERLAB_OPERATION_FAILED_EXCEPTION:
// two subcases when fail to remove users from team
log.warn("Remove member from team: User {}, Team {} fail - {}", userId, teamId, error.getMessage());
if ("user has experiments".equals(error.getMessage())) {
// case 1 - user has experiments
// display the list of experiments that have to be terminated first
// since the team profile page has experiments already, we don't have to retrieve them again
// use the userid to filter out the experiment list at the web pages
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + " Member " + name + " has experiments.");
redirectAttributes.addFlashAttribute(REMOVE_MEMBER_UID, userId);
redirectAttributes.addFlashAttribute(REMOVE_MEMBER_NAME, name);
break;
} else {
// case 2 - deterlab operation failure
log.warn("Remove member from team: deterlab operation failed");
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + " Member " + name + " cannot be removed.");
break;
}
default:
log.warn("Server side error for remove members: {}", error.getError());
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
break;
}
} else {
log.info("Remove member: {}", response.getBody().toString());
// add success message
redirectAttributes.addFlashAttribute(MESSAGE_SUCCESS, "Member " + name + " has been removed.");
}
return REDIRECT_TEAM_PROFILE_TEAM_ID;
}
// @RequestMapping("/team_profile/{teamId}/start_experiment/{expId}")
// public String startExperimentFromTeamProfile(@PathVariable Integer teamId, @PathVariable Integer expId, Model model, HttpSession session) {
// // start experiment
// // ensure experiment is stopped first before starting
// experimentManager.startExperiment(getSessionIdOfLoggedInUser(session), expId);
// return "redirect:/team_profile/{teamId}";
// }
// @RequestMapping("/team_profile/{teamId}/stop_experiment/{expId}")
// public String stopExperimentFromTeamProfile(@PathVariable Integer teamId, @PathVariable Integer expId, Model model, HttpSession session) {
// // stop experiment
// // ensure experiment is in ready mode before stopping
// experimentManager.stopExperiment(getSessionIdOfLoggedInUser(session), expId);
// return "redirect:/team_profile/{teamId}";
// }
// @RequestMapping("/team_profile/{teamId}/remove_experiment/{expId}")
// public String removeExperimentFromTeamProfile(@PathVariable Integer teamId, @PathVariable Integer expId, Model model, HttpSession session) {
// // remove experiment
// // TODO check userid is indeed the experiment owner or team owner
// // ensure experiment is stopped first
// if (experimentManager.removeExperiment(getSessionIdOfLoggedInUser(session), expId) == true) {
// // decrease exp count to be display on Teams page
// teamManager.decrementExperimentCount(teamId);
// }
// model.addAttribute("experimentList", experimentManager.getExperimentListByExperimentOwner(getSessionIdOfLoggedInUser(session)));
// return "redirect:/team_profile/{teamId}";
// }
// @RequestMapping(value="/team_profile/invite_user/{teamId}", method=RequestMethod.GET)
// public String inviteUserFromTeamProfile(@PathVariable Integer teamId, Model model) {
// model.addAttribute("teamIdVar", teamId);
// model.addAttribute("teamPageInviteMemberForm", new TeamPageInviteMemberForm());
// return "team_profile_invite_members";
// }
// @RequestMapping(value="/team_profile/invite_user/{teamId}", method=RequestMethod.POST)
// public String sendInvitationFromTeamProfile(@PathVariable Integer teamId, @ModelAttribute TeamPageInviteMemberForm teamPageInviteMemberForm, Model model) {
// int userId = userManager.getUserIdByEmail(teamPageInviteMemberForm.getInviteUserEmail());
// teamManager.addInvitedToParticipateMap(userId, teamId);
// return "redirect:/team_profile/{teamId}";
// }
//--------------------------Apply for New Team Page--------------------------
@RequestMapping(value = "/teams/apply_team", method = RequestMethod.GET)
public String teamPageApplyTeam(Model model) {
model.addAttribute("teamPageApplyTeamForm", new TeamPageApplyTeamForm());
return "team_page_apply_team";
}
@RequestMapping(value = "/teams/apply_team", method = RequestMethod.POST)
public String checkApplyTeamInfo(
@Valid TeamPageApplyTeamForm teamPageApplyTeamForm,
BindingResult bindingResult,
HttpSession session,
final RedirectAttributes redirectAttributes) throws WebServiceRuntimeException {
final String LOG_PREFIX = "Existing user apply for new team: {}";
if (bindingResult.hasErrors()) {
log.warn(LOG_PREFIX, "Application form error " + teamPageApplyTeamForm.toString());
return "team_page_apply_team";
}
// log data to ensure data has been parsed
log.debug(LOG_PREFIX, properties.getRegisterRequestToApplyTeam(session.getAttribute("id").toString()));
log.info(LOG_PREFIX, teamPageApplyTeamForm.toString());
JSONObject mainObject = new JSONObject();
JSONObject teamFields = new JSONObject();
mainObject.put("team", teamFields);
teamFields.put("name", teamPageApplyTeamForm.getTeamName());
teamFields.put("description", teamPageApplyTeamForm.getTeamDescription());
teamFields.put("website", teamPageApplyTeamForm.getTeamWebsite());
teamFields.put("organisationType", teamPageApplyTeamForm.getTeamOrganizationType());
teamFields.put("visibility", teamPageApplyTeamForm.getIsPublic());
String nclUserId = session.getAttribute("id").toString();
HttpEntity<String> request = createHttpEntityWithBody(mainObject.toString());
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getRegisterRequestToApplyTeam(nclUserId), HttpMethod.POST, request, String.class);
String responseBody = response.getBody().toString();
if (RestUtil.isError(response.getStatusCode())) {
// prepare the exception mapping
EnumMap<ExceptionState, String> exceptionMessageMap = new EnumMap<>(ExceptionState.class);
exceptionMessageMap.put(USER_ID_NULL_OR_EMPTY_EXCEPTION, "User id is null or empty ");
exceptionMessageMap.put(TEAM_NAME_NULL_OR_EMPTY_EXCEPTION, "Team name is null or empty ");
exceptionMessageMap.put(USER_NOT_FOUND_EXCEPTION, "User not found");
exceptionMessageMap.put(TEAM_NAME_ALREADY_EXISTS_EXCEPTION, "Team name already exists");
exceptionMessageMap.put(INVALID_TEAM_NAME_EXCEPTION, "Team name contains invalid characters");
exceptionMessageMap.put(TEAM_MEMBER_ALREADY_EXISTS_EXCEPTION, "Team member already exists");
exceptionMessageMap.put(ADAPTER_CONNECTION_EXCEPTION, "Connection to adapter failed");
exceptionMessageMap.put(ADAPTER_INTERNAL_ERROR_EXCEPTION, "Internal server error on adapter");
exceptionMessageMap.put(DETERLAB_OPERATION_FAILED_EXCEPTION, "Operation failed on DeterLab");
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
final String errorMessage = exceptionMessageMap.containsKey(exceptionState) ? error.getMessage() : ERR_SERVER_OVERLOAD;
log.warn(LOG_PREFIX, responseBody);
redirectAttributes.addFlashAttribute("message", errorMessage);
return "redirect:/teams/apply_team";
} else {
// no errors, everything ok
log.info(LOG_PREFIX, "Application for team " + teamPageApplyTeamForm.getTeamName() + " submitted");
return "redirect:/teams/team_application_submitted";
}
} catch (ResourceAccessException | IOException e) {
log.error(LOG_PREFIX, e);
throw new WebServiceRuntimeException(e.getMessage());
}
}
@RequestMapping(value = "/acceptable_usage_policy", method = RequestMethod.GET)
public String teamOwnerPolicy() {
return "acceptable_usage_policy";
}
@RequestMapping(value = "/terms_and_conditions", method = RequestMethod.GET)
public String termsAndConditions() {
return "terms_and_conditions";
}
//--------------------------Join Team Page--------------------------
@RequestMapping(value = "/teams/join_team", method = RequestMethod.GET)
public String teamPageJoinTeam(Model model) {
model.addAttribute("teamPageJoinTeamForm", new TeamPageJoinTeamForm());
return "team_page_join_team";
}
@RequestMapping(value = "/teams/join_team", method = RequestMethod.POST)
public String checkJoinTeamInfo(
@Valid TeamPageJoinTeamForm teamPageJoinForm,
BindingResult bindingResult,
Model model,
HttpSession session,
final RedirectAttributes redirectAttributes) throws WebServiceRuntimeException {
final String LOG_PREFIX = "Existing user join team: {}";
if (bindingResult.hasErrors()) {
log.warn(LOG_PREFIX, "Application form error " + teamPageJoinForm.toString());
return "team_page_join_team";
}
JSONObject mainObject = new JSONObject();
JSONObject teamFields = new JSONObject();
JSONObject userFields = new JSONObject();
mainObject.put("team", teamFields);
mainObject.put("user", userFields);
userFields.put("id", session.getAttribute("id")); // ncl-id
teamFields.put("name", teamPageJoinForm.getTeamName());
log.info(LOG_PREFIX, "User " + session.getAttribute("id") + ", team " + teamPageJoinForm.getTeamName());
HttpEntity<String> request = createHttpEntityWithBody(mainObject.toString());
ResponseEntity response;
try {
restTemplate.setErrorHandler(new MyResponseErrorHandler());
response = restTemplate.exchange(properties.getJoinRequestExistingUser(), HttpMethod.POST, request, String.class);
String responseBody = response.getBody().toString();
if (RestUtil.isError(response.getStatusCode())) {
// prepare the exception mapping
EnumMap<ExceptionState, String> exceptionMessageMap = new EnumMap<>(ExceptionState.class);
exceptionMessageMap.put(USER_NOT_FOUND_EXCEPTION, "User not found");
exceptionMessageMap.put(USER_ID_NULL_OR_EMPTY_EXCEPTION, "User id is null or empty");
exceptionMessageMap.put(TEAM_NOT_FOUND_EXCEPTION, "Team name not found");
exceptionMessageMap.put(TEAM_NAME_NULL_OR_EMPTY_EXCEPTION, "Team name is null or empty");
exceptionMessageMap.put(USER_ALREADY_IN_TEAM_EXCEPTION, "User already in team");
exceptionMessageMap.put(TEAM_MEMBER_ALREADY_EXISTS_EXCEPTION, "Team member already exists");
exceptionMessageMap.put(ADAPTER_CONNECTION_EXCEPTION, "Connection to adapter failed");
exceptionMessageMap.put(ADAPTER_INTERNAL_ERROR_EXCEPTION, "Internal server error on adapter");
exceptionMessageMap.put(DETERLAB_OPERATION_FAILED_EXCEPTION, "Operation failed on DeterLab");
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
final String errorMessage = exceptionMessageMap.containsKey(exceptionState) ? error.getMessage() : ERR_SERVER_OVERLOAD;
log.warn(LOG_PREFIX, responseBody);
redirectAttributes.addFlashAttribute("message", errorMessage);
return "redirect:/teams/join_team";
} else {
log.info(LOG_PREFIX, "Application for join team " + teamPageJoinForm.getTeamName() + " submitted");
return "redirect:/teams/join_application_submitted/" + teamPageJoinForm.getTeamName();
}
} catch (ResourceAccessException | IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
}
//--------------------------Experiment Page--------------------------
@RequestMapping(value = "/experiments", method = RequestMethod.GET)
public String experiments(Model model, HttpSession session) throws WebServiceRuntimeException {
// long start = System.currentTimeMillis();
List<Experiment2> experimentList = new ArrayList<>();
Map<Long, Realization> realizationMap = new HashMap<>();
HttpEntity<String> request = createHttpEntityHeaderOnly();
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = restTemplate.exchange(properties.getDeterUid(session.getAttribute("id").toString()), HttpMethod.GET, request, String.class);
String responseBody = response.getBody().toString();
try {
if (RestUtil.isError(response.getStatusCode())) {
log.error("No user to get experiment: {}", session.getAttribute("id"));
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
log.info("experiment error: {} - {} - {} - user token:{}", error.getError(), error.getMessage(), error.getLocalizedMessage(), httpScopedSession.getAttribute(webProperties.getSessionJwtToken()));
model.addAttribute(DETER_UID, CONNECTION_ERROR);
} else {
log.info("Show the deter user id: {}", responseBody);
model.addAttribute(DETER_UID, responseBody);
}
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
// get list of teamids
ResponseEntity userRespEntity = restTemplate.exchange(properties.getUser(session.getAttribute("id").toString()), HttpMethod.GET, request, String.class);
JSONObject object = new JSONObject(userRespEntity.getBody().toString());
JSONArray teamIdsJsonArray = object.getJSONArray("teams");
for (int i = 0; i < teamIdsJsonArray.length(); i++) {
String teamId = teamIdsJsonArray.get(i).toString();
HttpEntity<String> teamRequest = createHttpEntityHeaderOnly();
ResponseEntity teamResponse = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, teamRequest, String.class);
String teamResponseBody = teamResponse.getBody().toString();
if (!isMemberJoinRequestPending(session.getAttribute("id").toString(), teamResponseBody)) {
// get experiments lists of the teams
HttpEntity<String> expRequest = createHttpEntityHeaderOnly();
ResponseEntity expRespEntity = restTemplate.exchange(properties.getExpListByTeamId(teamId), HttpMethod.GET, expRequest, String.class);
JSONArray experimentsArray = new JSONArray(expRespEntity.getBody().toString());
for (int k = 0; k < experimentsArray.length(); k++) {
Experiment2 experiment2 = extractExperiment(experimentsArray.getJSONObject(k).toString());
Realization realization = invokeAndExtractRealization(experiment2.getTeamName(), experiment2.getId());
realizationMap.put(experiment2.getId(), realization);
experimentList.add(experiment2);
}
}
}
model.addAttribute("experimentList", experimentList);
model.addAttribute("realizationMap", realizationMap);
// System.out.println("Elapsed time to get experiment page:" + (System.currentTimeMillis() - start));
return EXPERIMENTS;
}
@RequestMapping(value = "/experiments/create", method = RequestMethod.GET)
public String createExperiment(Model model, HttpSession session) throws WebServiceRuntimeException {
log.info("Loading create experiment page");
// a list of teams that the logged in user is in
List<String> scenarioFileNameList = getScenarioFileNameList();
List<Team2> userTeamsList = new ArrayList<>();
// get list of teamids
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response = restTemplate.exchange(properties.getUser(session.getAttribute("id").toString()), HttpMethod.GET, request, String.class);
String responseBody = response.getBody().toString();
JSONObject object = new JSONObject(responseBody);
JSONArray teamIdsJsonArray = object.getJSONArray("teams");
for (int i = 0; i < teamIdsJsonArray.length(); i++) {
String teamId = teamIdsJsonArray.get(i).toString();
HttpEntity<String> teamRequest = createHttpEntityHeaderOnly();
ResponseEntity teamResponse = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, teamRequest, String.class);
String teamResponseBody = teamResponse.getBody().toString();
Team2 team2 = extractTeamInfo(teamResponseBody);
userTeamsList.add(team2);
}
model.addAttribute("scenarioFileNameList", scenarioFileNameList);
model.addAttribute("experimentForm", new ExperimentForm());
model.addAttribute("userTeamsList", userTeamsList);
return "experiment_page_create_experiment";
}
@RequestMapping(value = "/experiments/create", method = RequestMethod.POST)
public String validateExperiment(
@ModelAttribute("experimentForm") ExperimentForm experimentForm,
HttpSession session,
BindingResult bindingResult,
final RedirectAttributes redirectAttributes) throws WebServiceRuntimeException {
if (bindingResult.hasErrors()) {
log.info("Create experiment - form has errors");
return "redirect:/experiments/create";
}
if (experimentForm.getName() == null || experimentForm.getName().isEmpty()) {
redirectAttributes.addFlashAttribute(MESSAGE, "Experiment Name cannot be empty");
return "redirect:/experiments/create";
}
if (experimentForm.getDescription() == null || experimentForm.getDescription().isEmpty()) {
redirectAttributes.addFlashAttribute(MESSAGE, "Description cannot be empty");
return "redirect:/experiments/create";
}
experimentForm.setScenarioContents(getScenarioContentsFromFile(experimentForm.getScenarioFileName()));
JSONObject experimentObject = new JSONObject();
experimentObject.put("userId", session.getAttribute("id").toString());
experimentObject.put(TEAM_ID, experimentForm.getTeamId());
experimentObject.put(TEAM_NAME, experimentForm.getTeamName());
experimentObject.put("name", experimentForm.getName().replaceAll("\\s+", "")); // truncate whitespaces and non-visible characters like \n
experimentObject.put("description", experimentForm.getDescription());
experimentObject.put("nsFile", "file");
experimentObject.put("nsFileContent", experimentForm.getNsFileContent());
experimentObject.put("idleSwap", "240");
experimentObject.put("maxDuration", "960");
log.info("Calling service to create experiment");
HttpEntity<String> request = createHttpEntityWithBody(experimentObject.toString());
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = restTemplate.exchange(properties.getSioExpUrl(), HttpMethod.POST, request, String.class);
String responseBody = response.getBody().toString();
try {
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case NS_FILE_PARSE_EXCEPTION:
log.warn("Ns file error");
redirectAttributes.addFlashAttribute(MESSAGE, "There is an error when parsing the NS File.");
break;
case EXPERIMENT_NAME_ALREADY_EXISTS_EXCEPTION:
log.warn("Exp name already exists");
redirectAttributes.addFlashAttribute(MESSAGE, "Experiment name already exists.");
break;
default:
log.warn("Exp service or adapter fail");
// possible sio or adapter connection fail
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
break;
}
log.info("Experiment {} created", experimentForm);
return "redirect:/experiments/create";
}
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
//
// TODO Uploaded function for network configuration and optional dataset
// if (!networkFile.isEmpty()) {
// try {
// String networkFileName = getSessionIdOfLoggedInUser(session) + "-networkconfig-" + networkFile.getOriginalFilename();
// BufferedOutputStream stream = new BufferedOutputStream(
// new FileOutputStream(new File(App.EXP_CONFIG_DIR + "/" + networkFileName)));
// FileCopyUtils.copy(networkFile.getInputStream(), stream);
// stream.close();
// redirectAttributes.addFlashAttribute(MESSAGE,
// "You successfully uploaded " + networkFile.getOriginalFilename() + "!");
// // remember network file name here
// }
// catch (Exception e) {
// redirectAttributes.addFlashAttribute(MESSAGE,
// "You failed to upload " + networkFile.getOriginalFilename() + " => " + e.getMessage());
// return "redirect:/experiments/create";
// }
// }
//
// if (!dataFile.isEmpty()) {
// try {
// String dataFileName = getSessionIdOfLoggedInUser(session) + "-data-" + dataFile.getOriginalFilename();
// BufferedOutputStream stream = new BufferedOutputStream(
// new FileOutputStream(new File(App.EXP_CONFIG_DIR + "/" + dataFileName)));
// FileCopyUtils.copy(dataFile.getInputStream(), stream);
// stream.close();
// redirectAttributes.addFlashAttribute("message2",
// "You successfully uploaded " + dataFile.getOriginalFilename() + "!");
// // remember data file name here
// }
// catch (Exception e) {
// redirectAttributes.addFlashAttribute("message2",
// "You failed to upload " + dataFile.getOriginalFilename() + " => " + e.getMessage());
// }
// }
//
// // add current experiment to experiment manager
// experimentManager.addExperiment(getSessionIdOfLoggedInUser(session), experiment);
// // increase exp count to be display on Teams page
// teamManager.incrementExperimentCount(experiment.getTeamId());
return "redirect:/experiments";
}
@RequestMapping(value = "/experiments/save_image/{teamId}/{expId}/{nodeId}", method = RequestMethod.GET)
public String saveExperimentImage(@PathVariable String teamId, @PathVariable String expId, @PathVariable String nodeId, Model model) {
Map<String, Map<String, String>> singleNodeInfoMap = new HashMap<>();
Image saveImageForm = new Image();
String teamName = invokeAndExtractTeamInfo(teamId).getName();
Realization realization = invokeAndExtractRealization(teamName, Long.parseLong(expId));
// experiment may have many nodes
// extract just the particular node details to display
for (Map.Entry<String, Map<String, String>> nodesInfo : realization.getNodesInfoMap().entrySet()) {
String nodeName = nodesInfo.getKey();
Map<String, String> singleNodeDetailsMap = nodesInfo.getValue();
if (singleNodeDetailsMap.get(NODE_ID).equals(nodeId)) {
singleNodeInfoMap.put(nodeName, singleNodeDetailsMap);
// store the current os of the node into the form also
// have to pass the the services
saveImageForm.setCurrentOS(singleNodeDetailsMap.get("os"));
}
}
saveImageForm.setTeamId(teamId);
saveImageForm.setNodeId(nodeId);
model.addAttribute("teamName", teamName);
model.addAttribute("singleNodeInfoMap", singleNodeInfoMap);
model.addAttribute("pathTeamId", teamId);
model.addAttribute("pathExperimentId", expId);
model.addAttribute("pathNodeId", nodeId);
model.addAttribute("experimentName", realization.getExperimentName());
model.addAttribute("saveImageForm", saveImageForm);
return "save_experiment_image";
}
// bindingResult is required in the method signature to perform the JSR303 validation for Image object
@RequestMapping(value = "/experiments/save_image/{teamId}/{expId}/{nodeId}", method = RequestMethod.POST)
public String saveExperimentImage(
@Valid @ModelAttribute("saveImageForm") Image saveImageForm,
BindingResult bindingResult,
RedirectAttributes redirectAttributes,
@PathVariable String teamId,
@PathVariable String expId,
@PathVariable String nodeId) throws IOException {
if (saveImageForm.getImageName().length() < 2) {
log.warn("Save image form has errors {}", saveImageForm);
redirectAttributes.addFlashAttribute("message", "Image name too short, minimum 2 characters");
return "redirect:/experiments/save_image/" + teamId + "/" + expId + "/" + nodeId;
}
log.info("Saving image: team {}, experiment {}, node {}", teamId, expId, nodeId);
ObjectMapper mapper = new ObjectMapper();
HttpEntity<String> request = createHttpEntityWithBody(mapper.writeValueAsString(saveImageForm));
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = restTemplate.exchange(properties.saveImage(), HttpMethod.POST, request, String.class);
String responseBody = response.getBody().toString();
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
log.warn("Save image: error with exception {}", exceptionState);
switch (exceptionState) {
case DETERLAB_OPERATION_FAILED_EXCEPTION:
log.warn("Save image: error, operation failed on DeterLab");
redirectAttributes.addFlashAttribute("message", error.getMessage());
break;
case ADAPTER_CONNECTION_EXCEPTION:
log.warn("Save image: error, cannot connect to adapter");
redirectAttributes.addFlashAttribute("message", "connection to adapter failed");
break;
case ADAPTER_INTERNAL_ERROR_EXCEPTION:
log.warn("Save image: error, adapter internal server error");
redirectAttributes.addFlashAttribute("message", "internal error was found on the adapter");
break;
default:
log.warn("Save image: other error");
redirectAttributes.addFlashAttribute("message", ERR_SERVER_OVERLOAD);
}
return "redirect:/experiments/save_image/" + teamId + "/" + expId + "/" + nodeId;
}
// everything looks ok
log.info("Save image in progress: team {}, experiment {}, node {}, image {}", teamId, expId, nodeId, saveImageForm.getImageName());
return "redirect:/experiments";
}
/*
private String processSaveImageRequest(@Valid @ModelAttribute("saveImageForm") Image saveImageForm, RedirectAttributes redirectAttributes, @PathVariable String teamId, @PathVariable String expId, @PathVariable String nodeId, ResponseEntity response, String responseBody) throws IOException {
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
log.warn("Save image exception: {}", exceptionState);
switch (exceptionState) {
case DETERLAB_OPERATION_FAILED_EXCEPTION:
log.warn("adapter deterlab operation failed exception");
redirectAttributes.addFlashAttribute("message", error.getMessage());
break;
default:
log.warn("Image service or adapter fail");
// possible sio or adapter connection fail
redirectAttributes.addFlashAttribute("message", ERR_SERVER_OVERLOAD);
break;
}
return "redirect:/experiments/save_image/" + teamId + "/" + expId + "/" + nodeId;
} else {
// everything ok
log.info("Image service in progress for Team: {}, Exp: {}, Node: {}, Image: {}", teamId, expId, nodeId, saveImageForm.getImageName());
return "redirect:/experiments";
}
}
*/
// @RequestMapping("/experiments/configuration/{expId}")
// public String viewExperimentConfiguration(@PathVariable Integer expId, Model model) {
// // get experiment from expid
// // retrieve the scenario contents to be displayed
// Experiment currExp = experimentManager.getExperimentByExpId(expId);
// model.addAttribute("scenarioContents", currExp.getScenarioContents());
// return "experiment_scenario_contents";
// }
@RequestMapping("/remove_experiment/{teamName}/{teamId}/{expId}")
public String removeExperiment(@PathVariable String teamName, @PathVariable String teamId, @PathVariable String expId, final RedirectAttributes redirectAttributes, HttpSession session) throws WebServiceRuntimeException {
// ensure experiment is stopped first
Realization realization = invokeAndExtractRealization(teamName, Long.parseLong(expId));
Team2 team = invokeAndExtractTeamInfo(teamId);
// check valid authentication to remove experiments
// either admin, experiment creator or experiment owner
if (!validateIfAdmin(session) && !realization.getUserId().equals(session.getAttribute("id").toString()) && !team.getOwner().getId().equals(session.getAttribute(webProperties.getSessionUserId()))) {
log.warn("Permission denied when remove Team:{}, Experiment: {} with User: {}, Role:{}", teamId, expId, session.getAttribute("id"), session.getAttribute(webProperties.getSessionRoles()));
redirectAttributes.addFlashAttribute(MESSAGE, "An error occurred while trying to remove experiment;" + permissionDeniedMessage);
return "redirect:/experiments";
}
if (!realization.getState().equals(RealizationState.NOT_RUNNING.toString())) {
log.warn("Trying to remove Team: {}, Experiment: {} with State: {} that is still in progress?", teamId, expId, realization.getState());
redirectAttributes.addFlashAttribute(MESSAGE, "An error occurred while trying to remove Exp: " + realization.getExperimentName() + ". Please refresh the page again. If the error persists, please contact " + CONTACT_EMAIL);
return "redirect:/experiments";
}
log.info("Removing experiment: at " + properties.getDeleteExperiment(teamId, expId));
HttpEntity<String> request = createHttpEntityHeaderOnly();
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getDeleteExperiment(teamId, expId), HttpMethod.DELETE, request, String.class);
} catch (Exception e) {
log.warn("Error connecting to experiment service to remove experiment", e.getMessage());
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
return "redirect:/experiments";
}
String responseBody = response.getBody().toString();
try {
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case EXPERIMENT_DELETE_EXCEPTION:
case FORBIDDEN_EXCEPTION:
log.warn("remove experiment failed for Team: {}, Exp: {}", teamId, expId);
redirectAttributes.addFlashAttribute(MESSAGE, error.getMessage());
break;
case OBJECT_OPTIMISTIC_LOCKING_FAILURE_EXCEPTION:
// do nothing
log.info("remove experiment database locking failure");
break;
default:
// do nothing
break;
}
return "redirect:/experiments";
} else {
// everything ok
log.info("remove experiment success for Team: {}, Exp: {}", teamId, expId);
redirectAttributes.addFlashAttribute("exp_remove_message", "Team: " + teamName + " has removed Exp: " + realization.getExperimentName());
return "redirect:/experiments";
}
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
}
@RequestMapping("/start_experiment/{teamName}/{expId}")
public String startExperiment(
@PathVariable String teamName,
@PathVariable String expId,
final RedirectAttributes redirectAttributes, Model model, HttpSession session) throws WebServiceRuntimeException {
// ensure experiment is stopped first before starting
Realization realization = invokeAndExtractRealization(teamName, Long.parseLong(expId));
if (!checkPermissionRealizeExperiment(realization, session)) {
log.warn("Permission denied to start experiment: {} for team: {}", realization.getExperimentName(), teamName);
redirectAttributes.addFlashAttribute(MESSAGE, permissionDeniedMessage);
return "redirect:/experiments";
}
String teamId = realization.getTeamId();
String teamStatus = getTeamStatus(teamId);
if (!teamStatus.equals(TeamStatus.APPROVED.name())) {
log.warn("Error: trying to realize an experiment {} on team {} with status {}", realization.getExperimentName(), teamId, teamStatus);
redirectAttributes.addFlashAttribute(MESSAGE, teamName + " is in " + teamStatus + " status and does not have permission to start experiment. Please contact " + CONTACT_EMAIL);
return "redirect:/experiments";
}
if (!realization.getState().equals(RealizationState.NOT_RUNNING.toString())) {
log.warn("Trying to start Team: {}, Experiment: {} with State: {} that is not running?", teamName, expId, realization.getState());
redirectAttributes.addFlashAttribute(MESSAGE, "An error occurred while trying to start Exp: " + realization.getExperimentName() + ". Please refresh the page again. If the error persists, please contact " + CONTACT_EMAIL);
return "redirect:/experiments";
}
//start experiment
log.info("Starting experiment: at " + properties.getStartExperiment(teamName, expId));
HttpEntity<String> request = createHttpEntityHeaderOnly();
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getStartExperiment(teamName, expId), HttpMethod.POST, request, String.class);
} catch (Exception e) {
log.warn("Error connecting to experiment service to start experiment", e.getMessage());
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
return "redirect:/experiments";
}
String responseBody = response.getBody().toString();
try {
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case EXPERIMENT_START_EXCEPTION:
case FORBIDDEN_EXCEPTION:
log.warn("start experiment failed for Team: {}, Exp: {}", teamName, expId);
redirectAttributes.addFlashAttribute(MESSAGE, error.getMessage());
return "redirect:/experiments";
case TEAM_NOT_FOUND_EXCEPTION:
log.warn("Check team quota to start experiment: Team {} not found", teamName);
return REDIRECT_INDEX_PAGE;
case INSUFFICIENT_QUOTA_EXCEPTION:
log.warn("Check team quota to start experiment: Team {} do not have sufficient quota", teamName);
redirectAttributes.addFlashAttribute(MESSAGE, "There is insufficient quota for you to start this experiment. Please contact your team leader for more details.");
return "redirect:/experiments";
case OBJECT_OPTIMISTIC_LOCKING_FAILURE_EXCEPTION:
// do nothing
log.info("start experiment database locking failure");
break;
default:
// do nothing
break;
}
log.warn("start experiment some other error occurred exception: {}", exceptionState);
// possible for it to be error but experiment has started up finish
// if user clicks on start but reloads the page
// model.addAttribute(EXPERIMENT_MESSAGE, "Team: " + teamName + " has started Exp: " + realization.getExperimentName());
return EXPERIMENTS;
} else {
// everything ok
log.info("start experiment success for Team: {}, Exp: {}", teamName, expId);
redirectAttributes.addFlashAttribute(EXPERIMENT_MESSAGE, "Experiment " + realization.getExperimentName() + " in team " + teamName + " is starting. This may take up to 10 minutes depending on the scale of your experiment. Please refresh this page later.");
return "redirect:/experiments";
}
} catch (IOException e) {
log.warn("start experiment error: {]", e.getMessage());
throw new WebServiceRuntimeException(e.getMessage());
}
}
@RequestMapping("/stop_experiment/{teamName}/{expId}")
public String stopExperiment(@PathVariable String teamName, @PathVariable String expId, Model model, final RedirectAttributes redirectAttributes, HttpSession session) throws WebServiceRuntimeException {
// ensure experiment is active first before stopping
Realization realization = invokeAndExtractRealization(teamName, Long.parseLong(expId));
if (isNotAdminAndNotInTeam(session, realization)) {
log.warn("Permission denied to stop experiment: {} for team: {}", realization.getExperimentName(), teamName);
redirectAttributes.addFlashAttribute(MESSAGE, permissionDeniedMessage);
return "redirect:/experiments";
}
if (!realization.getState().equals(RealizationState.RUNNING.toString())) {
log.warn("Trying to stop Team: {}, Experiment: {} with State: {} that is still in progress?", teamName, expId, realization.getState());
redirectAttributes.addFlashAttribute(MESSAGE, "An error occurred while trying to stop Exp: " + realization.getExperimentName() + ". Please refresh the page again. If the error persists, please contact " + CONTACT_EMAIL);
return "redirect:/experiments";
}
log.info("Stopping experiment: at " + properties.getStopExperiment(teamName, expId));
HttpEntity<String> request = createHttpEntityHeaderOnly();
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response;
return abc(teamName, expId, redirectAttributes, realization, request);
}
@RequestMapping("/get_topology/{teamName}/{expId}")
@ResponseBody
public String getTopology(@PathVariable String teamName, @PathVariable String expId) {
try {
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response = restTemplate.exchange(properties.getTopology(teamName, expId), HttpMethod.GET, request, String.class);
log.info("Retrieve experiment topo success");
return "data:image/png;base64," + response.getBody();
} catch (Exception e) {
log.error("Error getting topology thumbnail", e.getMessage());
return "";
}
}
private String abc(@PathVariable String teamName, @PathVariable String expId, RedirectAttributes redirectAttributes, Realization realization, HttpEntity<String> request) throws WebServiceRuntimeException {
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getStopExperiment(teamName, expId), HttpMethod.POST, request, String.class);
} catch (Exception e) {
log.warn("Error connecting to experiment service to stop experiment", e.getMessage());
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
return "redirect:/experiments";
}
String responseBody = response.getBody().toString();
try {
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
if (exceptionState == ExceptionState.FORBIDDEN_EXCEPTION) {
log.warn("Permission denied to stop experiment: {} for team: {}", realization.getExperimentName(), teamName);
redirectAttributes.addFlashAttribute(MESSAGE, permissionDeniedMessage);
}
if (exceptionState == ExceptionState.OBJECT_OPTIMISTIC_LOCKING_FAILURE_EXCEPTION) {
log.info("stop experiment database locking failure");
}
} else {
// everything ok
log.info("stop experiment success for Team: {}, Exp: {}", teamName, expId);
redirectAttributes.addFlashAttribute(EXPERIMENT_MESSAGE, "Experiment " + realization.getExperimentName() + " in team " + teamName + " is stopping. Please refresh this page in a few minutes.");
}
return "redirect:/experiments";
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
}
private boolean isNotAdminAndNotInTeam(HttpSession session, Realization realization) {
return !validateIfAdmin(session) && !checkPermissionRealizeExperiment(realization, session);
}
//-----------------------------------------------------------------------
//--------------------------Admin Revamp---------------------------------
//-----------------------------------------------------------------------
//---------------------------------Admin---------------------------------
@RequestMapping("/admin")
public String admin(Model model, HttpSession session) {
if (!validateIfAdmin(session)) {
return NO_PERMISSION_PAGE;
}
List<Team2> pendingApprovalTeamsList = new ArrayList<>();
//------------------------------------
// get list of teams pending for approval
//------------------------------------
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity responseEntity = restTemplate.exchange(properties.getSioTeamsUrl(), HttpMethod.GET, request, String.class);
JSONArray jsonArray = new JSONArray(responseEntity.getBody().toString());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Team2 one = extractTeamInfo(jsonObject.toString());
if (one.getStatus().equals(TeamStatus.PENDING.name())) {
pendingApprovalTeamsList.add(one);
}
}
model.addAttribute("pendingApprovalTeamsList", pendingApprovalTeamsList);
return "admin3";
}
@RequestMapping("/admin/data")
public String adminDataManagement(Model model, HttpSession session) {
if (!validateIfAdmin(session)) {
return NO_PERMISSION_PAGE;
}
//------------------------------------
// get list of datasets
//------------------------------------
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response = restTemplate.exchange(properties.getData(), HttpMethod.GET, request, String.class);
String responseBody = response.getBody().toString();
List<Dataset> datasetsList = new ArrayList<>();
JSONArray dataJsonArray = new JSONArray(responseBody);
for (int i = 0; i < dataJsonArray.length(); i++) {
JSONObject dataInfoObject = dataJsonArray.getJSONObject(i);
Dataset dataset = extractDataInfo(dataInfoObject.toString());
datasetsList.add(dataset);
}
ResponseEntity response4 = restTemplate.exchange(properties.getDownloadStat(), HttpMethod.GET, request, String.class);
String responseBody4 = response4.getBody().toString();
Map<Integer, Long> dataDownloadStats = new HashMap<>();
JSONArray statJsonArray = new JSONArray(responseBody4);
for (int i = 0; i < statJsonArray.length(); i++) {
JSONObject statInfoObject = statJsonArray.getJSONObject(i);
dataDownloadStats.put(statInfoObject.getInt("dataId"), statInfoObject.getLong("count"));
}
model.addAttribute("dataList", datasetsList);
model.addAttribute("downloadStats", dataDownloadStats);
return "data_dashboard";
}
@RequestMapping("/admin/data/{datasetId}/resources")
public String adminViewDataResources(@PathVariable String datasetId, Model model, HttpSession session) {
if (!validateIfAdmin(session)) {
return NO_PERMISSION_PAGE;
}
//----------------------------------------
// get list of data resources in a dataset
//----------------------------------------
Dataset dataset = invokeAndExtractDataInfo(Long.parseLong(datasetId));
model.addAttribute("dataset", dataset);
return "admin_data_resources";
}
@RequestMapping(value = "/admin/data/{datasetId}/resources/{resourceId}/update", method = RequestMethod.GET)
public String adminUpdateResource(@PathVariable String datasetId, @PathVariable String resourceId, Model model, HttpSession session) {
if (!validateIfAdmin(session)) {
return NO_PERMISSION_PAGE;
}
Dataset dataset = invokeAndExtractDataInfo(Long.parseLong(datasetId));
DataResource currentDataResource = new DataResource();
for (DataResource dataResource : dataset.getDataResources()) {
if (dataResource.getId() == Long.parseLong(resourceId)) {
currentDataResource = dataResource;
break;
}
}
model.addAttribute("did", dataset.getId());
model.addAttribute("dataresource", currentDataResource);
session.setAttribute(ORIGINAL_DATARESOURCE, currentDataResource);
return "admin_data_resources_update";
}
// updates the malicious status of a data resource
@RequestMapping(value = "/admin/data/{datasetId}/resources/{resourceId}/update", method = RequestMethod.POST)
public String adminUpdateResourceFormSubmit(@PathVariable String datasetId, @PathVariable String resourceId, @ModelAttribute DataResource dataResource, Model model, HttpSession session, RedirectAttributes redirectAttributes) throws IOException {
if (!validateIfAdmin(session)) {
return NO_PERMISSION_PAGE;
}
DataResource original = (DataResource) session.getAttribute(ORIGINAL_DATARESOURCE);
Dataset dataset = invokeAndExtractDataInfo(Long.parseLong(datasetId));
updateDataset(dataset, dataResource);
// add redirect attributes variable to notify what has been modified
if (!original.getMaliciousFlag().equalsIgnoreCase(dataResource.getMaliciousFlag())) {
redirectAttributes.addFlashAttribute("editMaliciousFlag", "success");
}
log.info("Data updated... {}", dataset.getName());
model.addAttribute("did", dataset.getId());
model.addAttribute("dataresource", dataResource);
session.removeAttribute(ORIGINAL_DATARESOURCE);
return "redirect:/admin/data/" + datasetId + "/resources/" + resourceId + "/update";
}
private Dataset updateDataset(Dataset dataset, DataResource dataResource) throws IOException {
log.info("Data resource updating... {}", dataResource);
HttpEntity<String> request = createHttpEntityWithBody(objectMapper.writeValueAsString(dataResource));
ResponseEntity response = restTemplate.exchange(properties.getResource(dataset.getId().toString(), dataResource.getId().toString()), HttpMethod.PUT, request, String.class);
Dataset updatedDataset = extractDataInfo(response.getBody().toString());
log.info("Data resource updated... {}", dataResource.getUri());
return updatedDataset;
}
@RequestMapping("/admin/experiments")
public String adminExperimentsManagement(Model model, HttpSession session) {
if (!validateIfAdmin(session)) {
return NO_PERMISSION_PAGE;
}
//------------------------------------
// get list of experiments
//------------------------------------
HttpEntity<String> expRequest = createHttpEntityHeaderOnly();
ResponseEntity expResponseEntity = restTemplate.exchange(properties.getSioExpUrl(), HttpMethod.GET, expRequest, String.class);
//------------------------------------
// get list of realizations
//------------------------------------
HttpEntity<String> realizationRequest = createHttpEntityHeaderOnly();
ResponseEntity realizationResponseEntity = restTemplate.exchange(properties.getAllRealizations(), HttpMethod.GET, realizationRequest, String.class);
JSONArray jsonExpArray = new JSONArray(expResponseEntity.getBody().toString());
JSONArray jsonRealizationArray = new JSONArray(realizationResponseEntity.getBody().toString());
Map<Experiment2, Realization> experiment2Map = new HashMap<>(); // exp id, experiment
Map<Long, Realization> realizationMap = new HashMap<>(); // exp id, realization
for (int k = 0; k < jsonRealizationArray.length(); k++) {
Realization realization;
try {
realization = extractRealization(jsonRealizationArray.getJSONObject(k).toString());
} catch (JSONException e) {
log.debug("Admin extract realization {}", e);
realization = getCleanRealization();
}
if (realization.getState().equals(RealizationState.RUNNING.name())) {
realizationMap.put(realization.getExperimentId(), realization);
}
}
for (int i = 0; i < jsonExpArray.length(); i++) {
Experiment2 experiment2 = extractExperiment(jsonExpArray.getJSONObject(i).toString());
if (realizationMap.containsKey(experiment2.getId())) {
experiment2Map.put(experiment2, realizationMap.get(experiment2.getId()));
}
}
model.addAttribute("runningExpMap", experiment2Map);
return "experiment_dashboard";
}
@RequestMapping("/admin/teams")
public String adminTeamsManagement(Model model, HttpSession session) {
if (!validateIfAdmin(session)) {
return NO_PERMISSION_PAGE;
}
//------------------------------------
// get list of teams
//------------------------------------
TeamManager2 teamManager2 = new TeamManager2();
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity responseEntity = restTemplate.exchange(properties.getSioTeamsUrl(), HttpMethod.GET, request, String.class);
JSONArray jsonArray = new JSONArray(responseEntity.getBody().toString());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Team2 one = extractTeamInfo(jsonObject.toString());
teamManager2.addTeamToTeamMap(one);
}
model.addAttribute("teamsMap", teamManager2.getTeamMap());
return "team_dashboard";
}
@RequestMapping("/admin/users")
public String adminUsersManagement(Model model, HttpSession session) {
if (!validateIfAdmin(session)) {
return NO_PERMISSION_PAGE;
}
//------------------------------------
// get list of users
//------------------------------------
Map<String, List<String>> userToTeamMap = new HashMap<>(); // userId : list of team names
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response2 = restTemplate.exchange(properties.getSioUsersUrl(), HttpMethod.GET, request, String.class);
String responseBody2 = response2.getBody().toString();
JSONArray jsonUserArray = new JSONArray(responseBody2);
List<User2> usersList = new ArrayList<>();
for (int i = 0; i < jsonUserArray.length(); i++) {
JSONObject userObject = jsonUserArray.getJSONObject(i);
User2 user = extractUserInfo(userObject.toString());
usersList.add(user);
// get list of teams' names for each user
List<String> perUserTeamList = new ArrayList<>();
if (userObject.get("teams") != null) {
JSONArray teamJsonArray = userObject.getJSONArray("teams");
for (int k = 0; k < teamJsonArray.length(); k++) {
Team2 team = invokeAndExtractTeamInfo(teamJsonArray.get(k).toString());
perUserTeamList.add(team.getName());
}
userToTeamMap.put(user.getId(), perUserTeamList);
}
}
model.addAttribute("usersList", usersList);
model.addAttribute("userToTeamMap", userToTeamMap);
return "user_dashboard";
}
@RequestMapping("/admin/usage")
public String adminTeamUsage(Model model,
@RequestParam(value = "team", required = false) String team,
@RequestParam(value = "start", required = false) String start,
@RequestParam(value = "end", required = false) String end,
HttpSession session) {
if (!validateIfAdmin(session)) {
return NO_PERMISSION_PAGE;
}
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
ZonedDateTime now = ZonedDateTime.now();
if (start == null) {
ZonedDateTime startDate = now.with(firstDayOfMonth());
start = startDate.format(formatter);
}
if (end == null) {
ZonedDateTime endDate = now.with(lastDayOfMonth());
end = endDate.format(formatter);
}
// get list of teamids
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity responseEntity = restTemplate.exchange(properties.getSioTeamsUrl(), HttpMethod.GET, request, String.class);
JSONArray jsonArray = new JSONArray(responseEntity.getBody().toString());
TeamManager2 teamManager2 = new TeamManager2();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Team2 one = extractTeamInfo(jsonObject.toString());
teamManager2.addTeamToTeamMap(one);
}
if (team != null) {
responseEntity = restTemplate.exchange(properties.getUsageStat(team, "startDate=" + start, "endDate=" + end), HttpMethod.GET, request, String.class);
String usage = responseEntity.getBody().toString();
model.addAttribute("usage", usage);
}
model.addAttribute("teamsMap", teamManager2.getTeamMap());
model.addAttribute("start", start);
model.addAttribute("end", end);
model.addAttribute("team", team);
return "usage_statistics";
}
@RequestMapping(value = "/admin/energy", method = RequestMethod.GET)
public String adminEnergy(Model model,
@RequestParam(value = "start", required = false) String start,
@RequestParam(value = "end", required = false) String end,
final RedirectAttributes redirectAttributes,
HttpSession session) throws IOException {
if (!validateIfAdmin(session)) {
return NO_PERMISSION_PAGE;
}
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
ZonedDateTime now = ZonedDateTime.now();
if (start == null) {
ZonedDateTime startDate = now.with(firstDayOfMonth());
start = startDate.format(formatter);
}
if (end == null) {
ZonedDateTime endDate = now.with(lastDayOfMonth());
end = endDate.format(formatter);
}
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity responseEntity;
try {
responseEntity = restTemplate.exchange(properties.getEnergyStatistics("startDate=" + start, "endDate=" + end), HttpMethod.GET, request, String.class);
} catch (RestClientException e) {
log.warn("Error connecting to sio analytics service for energy usage: {}", e);
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
return REDIRECT_ENERGY_USAGE;
}
String responseBody = responseEntity.getBody().toString();
JSONArray jsonArray = new JSONArray(responseBody);
// handling exceptions from SIO
if (RestUtil.isError(responseEntity.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case START_DATE_AFTER_END_DATE_EXCEPTION:
log.warn("Get energy usage : Start date after end date error");
redirectAttributes.addFlashAttribute(MESSAGE, ERR_START_DATE_AFTER_END_DATE);
return REDIRECT_ENERGY_USAGE;
default:
log.warn("Get energy usage : sio or deterlab adapter connection error");
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
return REDIRECT_ENERGY_USAGE;
}
} else {
log.info("Get energy usage info : {}", responseBody);
}
DecimalFormat df2 = new DecimalFormat(".##");
double sumEnergy = 0.00;
List<String> listOfDate = new ArrayList<>();
List<Double> listOfEnergy = new ArrayList<>();
ZonedDateTime currentZonedDateTime = convertToZonedDateTime(start);
String currentDate = null;
for (int i = 0; i < jsonArray.length(); i++) {
sumEnergy += jsonArray.getDouble(i);
// add into listOfDate to display graph
currentDate = currentZonedDateTime.format(formatter);
listOfDate.add(currentDate);
// add into listOfEnergy to display graph
double energy = Double.valueOf(df2.format(jsonArray.getDouble(i)));
listOfEnergy.add(energy);
currentZonedDateTime = convertToZonedDateTime(currentDate).plusDays(1);
}
sumEnergy = Double.valueOf(df2.format(sumEnergy));
model.addAttribute("listOfDate", listOfDate);
model.addAttribute("listOfEnergy", listOfEnergy);
model.addAttribute("start", start);
model.addAttribute("end", end);
model.addAttribute("energy", sumEnergy);
return "energy_usage";
}
@RequestMapping("/admin/nodesStatus")
public String adminNodesStatus(Model model, HttpSession session) throws IOException {
if (!validateIfAdmin(session)) {
return NO_PERMISSION_PAGE;
}
// get number of active users and running experiments
Map<String, String> testbedStatsMap = getTestbedStats();
testbedStatsMap.put(USER_DASHBOARD_FREE_NODES, "0");
testbedStatsMap.put(USER_DASHBOARD_TOTAL_NODES, "0");
Map<String, List<Map<String, String>>> nodesStatus = getNodesStatus();
Map<String, Map<String, Long>> nodesStatusCount = new HashMap<>();
// loop through each of the machine type
// tabulate the different nodes type
// count the number of different nodes status, e.g. SYSTEMX = { FREE = 10, IN_USE = 11, ... }
nodesStatus.entrySet().forEach(machineTypeListEntry -> {
Map<String, Long> nodesCountMap = new HashMap<>();
long free = machineTypeListEntry.getValue().stream().filter(stringStringMap -> "free".equalsIgnoreCase(stringStringMap.get("status"))).count();
long inUse = machineTypeListEntry.getValue().stream().filter(stringStringMap -> "in_use".equalsIgnoreCase(stringStringMap.get("status"))).count();
long reserved = machineTypeListEntry.getValue().stream().filter(stringStringMap -> "reserved".equalsIgnoreCase(stringStringMap.get("status"))).count();
long reload = machineTypeListEntry.getValue().stream().filter(stringStringMap -> "reload".equalsIgnoreCase(stringStringMap.get("status"))).count();
long total = free + inUse + reserved + reload;
long currentTotal = Long.parseLong(testbedStatsMap.get(USER_DASHBOARD_TOTAL_NODES)) + total;
long currentFree = Long.parseLong(testbedStatsMap.get(USER_DASHBOARD_FREE_NODES)) + free;
nodesCountMap.put(NodeType.FREE.name(), free);
nodesCountMap.put(NodeType.IN_USE.name(), inUse);
nodesCountMap.put(NodeType.RESERVED.name(), reserved);
nodesCountMap.put(NodeType.RELOADING.name(), reload);
nodesStatusCount.put(machineTypeListEntry.getKey(), nodesCountMap);
testbedStatsMap.put(USER_DASHBOARD_FREE_NODES, Long.toString(currentFree));
testbedStatsMap.put(USER_DASHBOARD_TOTAL_NODES, Long.toString(currentTotal));
});
model.addAttribute("nodesStatus", nodesStatus);
model.addAttribute("nodesStatusCount", nodesStatusCount);
model.addAttribute(USER_DASHBOARD_LOGGED_IN_USERS_COUNT, testbedStatsMap.get(USER_DASHBOARD_LOGGED_IN_USERS_COUNT));
model.addAttribute(USER_DASHBOARD_RUNNING_EXPERIMENTS_COUNT, testbedStatsMap.get(USER_DASHBOARD_RUNNING_EXPERIMENTS_COUNT));
model.addAttribute(USER_DASHBOARD_FREE_NODES, testbedStatsMap.get(USER_DASHBOARD_FREE_NODES));
model.addAttribute(USER_DASHBOARD_TOTAL_NODES, testbedStatsMap.get(USER_DASHBOARD_TOTAL_NODES));
return "node_status";
}
/**
* Get simple ZonedDateTime from date string in the format 'YYYY-MM-DD'.
* @param date date string to convert
* @return ZonedDateTime of
*/
private ZonedDateTime convertToZonedDateTime(String date) {
String[] result = date.split("-");
return ZonedDateTime.of(
Integer.parseInt(result[0]),
Integer.parseInt(result[1]),
Integer.parseInt(result[2]),
0, 0, 0, 0, ZoneId.of("Asia/Singapore"));
}
// @RequestMapping(value="/admin/domains/add", method=RequestMethod.POST)
// public String addDomain(@Valid Domain domain, BindingResult bindingResult) {
// if (bindingResult.hasErrors()) {
// return "redirect:/admin";
// } else {
// domainManager.addDomains(domain.getDomainName());
// }
// return "redirect:/admin";
// }
// @RequestMapping("/admin/domains/remove/{domainKey}")
// public String removeDomain(@PathVariable String domainKey) {
// domainManager.removeDomains(domainKey);
// return "redirect:/admin";
// }
@RequestMapping("/admin/teams/accept/{teamId}/{teamOwnerId}")
public String approveTeam(
@PathVariable String teamId,
@PathVariable String teamOwnerId,
final RedirectAttributes redirectAttributes,
HttpSession session
) throws WebServiceRuntimeException {
if (!validateIfAdmin(session)) {
return NO_PERMISSION_PAGE;
}
//FIXME require approver info
log.info("Approving new team {}, team owner {}", teamId, teamOwnerId);
HttpEntity<String> request = createHttpEntityHeaderOnly();
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = restTemplate.exchange(
properties.getApproveTeam(teamId, teamOwnerId, TeamStatus.APPROVED), HttpMethod.POST, request, String.class);
String responseBody = response.getBody().toString();
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error;
try {
error = objectMapper.readValue(responseBody, MyErrorResource.class);
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case TEAM_ID_NULL_OR_EMPTY_EXCEPTION:
log.warn("Approve team: TeamId cannot be null or empty: {}",
teamId);
redirectAttributes.addFlashAttribute(MESSAGE, "TeamId cannot be null or empty");
break;
case USER_ID_NULL_OR_EMPTY_EXCEPTION:
log.warn("Approve team: UserId cannot be null or empty: {}",
teamOwnerId);
redirectAttributes.addFlashAttribute(MESSAGE, "UserId cannot be null or empty");
break;
case EMAIL_NOT_VERIFIED_EXCEPTION:
log.warn("Approve team: User {} email not verified", teamOwnerId);
redirectAttributes.addFlashAttribute(MESSAGE, "User email has not been verified");
break;
case INVALID_TEAM_STATUS_EXCEPTION:
log.warn("Approve team: TeamStatus is invalid");
redirectAttributes.addFlashAttribute(MESSAGE, "Team status is invalid");
break;
case TEAM_NOT_FOUND_EXCEPTION:
log.warn("Approve team: Team {} not found", teamId);
redirectAttributes.addFlashAttribute(MESSAGE, "Team does not exist");
break;
case DETERLAB_OPERATION_FAILED_EXCEPTION:
log.warn("Approve team: Team {} fail", teamId);
redirectAttributes.addFlashAttribute(MESSAGE, "Approve team request fail on Deterlab");
break;
default:
log.warn("Approve team : sio or deterlab adapter connection error");
// possible sio or adapter connection fail
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
break;
}
return "redirect:/admin";
}
// http status code is OK, then need to check the response message
String msg = new JSONObject(responseBody).getString("msg");
if ("approve project OK".equals(msg)) {
log.info("Approve team {} OK", teamId);
} else {
log.warn("Approve team {} FAIL", teamId);
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
}
return "redirect:/admin";
}
@RequestMapping("/admin/teams/reject/{teamId}/{teamOwnerId}")
public String rejectTeam(
@PathVariable String teamId,
@PathVariable String teamOwnerId,
@RequestParam("reason") String reason,
final RedirectAttributes redirectAttributes,
HttpSession session
) throws WebServiceRuntimeException {
if (!validateIfAdmin(session)) {
return NO_PERMISSION_PAGE;
}
//FIXME require approver info
log.info("Rejecting new team {}, team owner {}, reason {}", teamId, teamOwnerId, reason);
HttpEntity<String> request = createHttpEntityWithBody(reason);
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = restTemplate.exchange(
properties.getApproveTeam(teamId, teamOwnerId, TeamStatus.REJECTED), HttpMethod.POST, request, String.class);
String responseBody = response.getBody().toString();
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error;
try {
error = objectMapper.readValue(responseBody, MyErrorResource.class);
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case TEAM_ID_NULL_OR_EMPTY_EXCEPTION:
log.warn("Reject team: TeamId cannot be null or empty: {}",
teamId);
redirectAttributes.addFlashAttribute(MESSAGE, "TeamId cannot be null or empty");
break;
case USER_ID_NULL_OR_EMPTY_EXCEPTION:
log.warn("Reject team: UserId cannot be null or empty: {}",
teamOwnerId);
redirectAttributes.addFlashAttribute(MESSAGE, "UserId cannot be null or empty");
break;
case INVALID_TEAM_STATUS_EXCEPTION:
log.warn("Reject team: TeamStatus is invalid");
redirectAttributes.addFlashAttribute(MESSAGE, "Team status is invalid");
break;
case TEAM_NOT_FOUND_EXCEPTION:
log.warn("Reject team: Team {} not found", teamId);
redirectAttributes.addFlashAttribute(MESSAGE, "Team does not exist");
break;
case DETERLAB_OPERATION_FAILED_EXCEPTION:
log.warn("Reject team: Team {} fail", teamId);
redirectAttributes.addFlashAttribute(MESSAGE, "Reject team request fail on Deterlab");
break;
default:
log.warn("Reject team : sio or deterlab adapter connection error");
// possible sio or adapter connection fail
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
break;
}
return "redirect:/admin";
}
// http status code is OK, then need to check the response message
String msg = new JSONObject(responseBody).getString("msg");
if ("reject project OK".equals(msg)) {
log.info("Reject team {} OK", teamId);
} else {
log.warn("Reject team {} FAIL", teamId);
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
}
return "redirect:/admin";
}
@RequestMapping("/admin/teams/{teamId}")
public String setupTeamRestriction(
@PathVariable final String teamId,
@RequestParam(value = "action", required = true) final String action,
final RedirectAttributes redirectAttributes,
HttpSession session) throws IOException {
final String LOG_MESSAGE = "Updating restriction settings for team {}: {}";
// check if admin
if (!validateIfAdmin(session)) {
log.warn(LOG_MESSAGE, teamId, PERMISSION_DENIED);
return NO_PERMISSION_PAGE;
}
Team2 team = invokeAndExtractTeamInfo(teamId);
// check if team is approved before restricted
if ("restrict".equals(action) && team.getStatus().equals(TeamStatus.APPROVED.name())) {
return restrictTeam(team, redirectAttributes);
}
// check if team is restricted before freeing it back to approved
else if ("free".equals(action) && team.getStatus().equals(TeamStatus.RESTRICTED.name())) {
return freeTeam(team, redirectAttributes);
} else {
log.warn(LOG_MESSAGE, teamId, "Cannot " + action + " team with status " + team.getStatus());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + "Cannot " + action + " team " + team.getName() + " with status " + team.getStatus());
return "redirect:/admin/teams";
}
}
private String restrictTeam(final Team2 team, RedirectAttributes redirectAttributes) throws IOException {
log.info("Restricting team {}", team.getId());
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response = restTemplate.exchange(
properties.getSioTeamsStatusUrl(team.getId(), TeamStatus.RESTRICTED),
HttpMethod.PUT, request, String.class);
String responseBody = response.getBody().toString();
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
String logMessage = "Failed to restrict team {}: {}";
switch (exceptionState) {
case TEAM_NOT_FOUND_EXCEPTION:
log.warn(logMessage, team.getId(), TEAM_NOT_FOUND);
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + TEAM_NOT_FOUND);
break;
case INVALID_STATUS_TRANSITION_EXCEPTION:
log.warn(logMessage, team.getId(), error.getMessage());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage());
break;
case INVALID_TEAM_STATUS_EXCEPTION:
log.warn(logMessage, team.getId(), error.getMessage());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage());
break;
case FORBIDDEN_EXCEPTION:
log.warn(logMessage, team.getId(), PERMISSION_DENIED);
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + PERMISSION_DENIED);
break;
default:
log.warn(logMessage, team.getId(), exceptionState.getExceptionName());
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
}
return "redirect:/admin";
} else {
// good
log.info("Team {} has been restricted", team.getId());
redirectAttributes.addFlashAttribute(MESSAGE_SUCCESS, "Team " + team.getName() + " status has been changed to " + TeamStatus.RESTRICTED.name());
return "redirect:/admin";
}
}
private String freeTeam(final Team2 team, RedirectAttributes redirectAttributes) throws IOException {
log.info("Freeing team {}", team.getId());
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response = restTemplate.exchange(
properties.getSioTeamsStatusUrl(team.getId(), TeamStatus.APPROVED),
HttpMethod.PUT, request, String.class);
String responseBody = response.getBody().toString();
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
String logMessage = "Failed to free team {}: {}";
switch (exceptionState) {
case TEAM_NOT_FOUND_EXCEPTION:
log.warn(logMessage, team.getId(), TEAM_NOT_FOUND);
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + TEAM_NOT_FOUND);
break;
case INVALID_STATUS_TRANSITION_EXCEPTION:
log.warn(logMessage, team.getId(), error.getMessage());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage());
break;
case INVALID_TEAM_STATUS_EXCEPTION:
log.warn(logMessage, team.getId(), error.getMessage());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage());
break;
case FORBIDDEN_EXCEPTION:
log.warn(logMessage, team.getId(), PERMISSION_DENIED);
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + PERMISSION_DENIED);
break;
default:
log.warn(logMessage, team.getId(), exceptionState.getExceptionName());
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
}
return "redirect:/admin";
} else {
// good
log.info("Team {} has been freed", team.getId());
redirectAttributes.addFlashAttribute(MESSAGE_SUCCESS, "Team " + team.getName() + " status has been changed to " + TeamStatus.APPROVED.name());
return "redirect:/admin";
}
}
@RequestMapping("/admin/users/{userId}")
public String freezeUnfreezeUsers(
@PathVariable final String userId,
@RequestParam(value = "action", required = true) final String action,
final RedirectAttributes redirectAttributes,
HttpSession session) throws IOException {
User2 user = invokeAndExtractUserInfo(userId);
// check if admin
if (!validateIfAdmin(session)) {
log.warn("Access denied when trying to freeze/unfreeze user {}: must be admin!", userId);
return NO_PERMISSION_PAGE;
}
// check if user status is approved before freeze
if ("freeze".equals(action) && user.getStatus().equals(UserStatus.APPROVED.toString())) {
return freezeUser(user, redirectAttributes);
}
// check if user status is frozen before unfreeze
else if ("unfreeze".equals(action) && user.getStatus().equals(UserStatus.FROZEN.toString())) {
return unfreezeUser(user, redirectAttributes);
} else {
log.warn("Error in freeze/unfreeze user {}: failed to {} user with status {}", userId, action, user.getStatus());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + "failed to " + action + " user " + user.getEmail() + " with status " + user.getStatus());
return "redirect:/admin/users";
}
}
private String freezeUser(final User2 user, RedirectAttributes redirectAttributes) throws IOException {
log.info("Freezing user {}, email {}", user.getId(), user.getEmail());
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response = restTemplate.exchange(
properties.getSioUsersStatusUrl(user.getId(), UserStatus.FROZEN.toString()),
HttpMethod.PUT, request, String.class);
String responseBody = response.getBody().toString();
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case USER_NOT_FOUND_EXCEPTION:
log.warn("Failed to freeze user {}: user not found", user.getId());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + " user " + user.getEmail() + NOT_FOUND);
break;
case INVALID_STATUS_TRANSITION_EXCEPTION:
log.warn("Failed to freeze user {}: invalid status transition {}", user.getId(), error.getMessage());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage() + " is not allowed.");
break;
case INVALID_USER_STATUS_EXCEPTION:
log.warn("Failed to freeze user {}: invalid user status {}", user.getId(), error.getMessage());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage() + " is not a valid status.");
break;
case FORBIDDEN_EXCEPTION:
log.warn("Failed to freeze user {}: must be an Admin", user.getId());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + " permission denied.");
break;
default:
log.warn("Failed to freeze user {}: {}", user.getId(), exceptionState.getExceptionName());
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
break;
}
return "redirect:/admin";
} else {
// good
log.info("User {} has been frozen", user.getId());
redirectAttributes.addFlashAttribute(MESSAGE_SUCCESS, "User " + user.getEmail() + " has been banned.");
return "redirect:/admin";
}
}
private String unfreezeUser(final User2 user, RedirectAttributes redirectAttributes) throws IOException {
log.info("Unfreezing user {}, email {}", user.getId(), user.getEmail());
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response = restTemplate.exchange(
properties.getSioUsersStatusUrl(user.getId(), UserStatus.APPROVED.toString()),
HttpMethod.PUT, request, String.class);
String responseBody = response.getBody().toString();
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case USER_NOT_FOUND_EXCEPTION:
log.warn("Failed to unfreeze user {}: user not found", user.getId());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + " user " + user.getEmail() + NOT_FOUND);
break;
case INVALID_STATUS_TRANSITION_EXCEPTION:
log.warn("Failed to unfreeze user {}: invalid status transition {}", user.getId(), error.getMessage());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage() + " is not allowed.");
break;
case INVALID_USER_STATUS_EXCEPTION:
log.warn("Failed to unfreeze user {}: invalid user status {}", user.getId(), error.getMessage());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage() + " is not a valid status.");
break;
case FORBIDDEN_EXCEPTION:
log.warn("Failed to unfreeze user {}: must be an Admin", user.getId());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + " permission denied.");
break;
default:
log.warn("Failed to unfreeze user {}: {}", user.getId(), exceptionState.getExceptionName());
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
break;
}
return "redirect:/admin";
} else {
// good
log.info("User {} has been unfrozen", user.getId());
redirectAttributes.addFlashAttribute(MESSAGE_SUCCESS, "User " + user.getEmail() + " has been unbanned.");
return "redirect:/admin";
}
}
@RequestMapping("/admin/users/{userId}/remove")
public String removeUser(@PathVariable final String userId, final RedirectAttributes redirectAttributes, HttpSession session) throws IOException {
// check if admin
if (!validateIfAdmin(session)) {
log.warn("Access denied when trying to remove user {}: must be admin!", userId);
return NO_PERMISSION_PAGE;
}
User2 user = invokeAndExtractUserInfo(userId);
HttpEntity<String> request = createHttpEntityHeaderOnly();
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = restTemplate.exchange(properties.getUser(user.getId()), HttpMethod.DELETE, request, String.class);
String responseBody = response.getBody().toString();
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case USER_NOT_FOUND_EXCEPTION:
log.warn("Failed to remove user {}: user not found", user.getId());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + " user " + user.getEmail() + NOT_FOUND);
break;
case USER_IS_NOT_DELETABLE_EXCEPTION:
log.warn("Failed to remove user {}: user is not deletable", user.getId());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + " user " + user.getEmail() + " is not deletable.");
break;
case CREDENTIALS_NOT_FOUND_EXCEPTION:
log.warn("Failed to remove user {}: unable to find credentials", user.getId());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + " user " + user.getEmail() + " is not found.");
break;
default:
log.warn("Failed to remove user {}: {}", user.getId(), exceptionState.getExceptionName());
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
break;
}
} else {
log.info("User {} has been removed", userId);
redirectAttributes.addFlashAttribute(MESSAGE_SUCCESS, "User " + user.getEmail() + " has been removed.");
}
return "redirect:/admin/users";
}
// @RequestMapping("/admin/experiments/remove/{expId}")
// public String adminRemoveExp(@PathVariable Integer expId) {
// int teamId = experimentManager.getExperimentByExpId(expId).getTeamId();
// experimentManager.adminRemoveExperiment(expId);
//
// // decrease exp count to be display on Teams page
// teamManager.decrementExperimentCount(teamId);
// return "redirect:/admin";
// }
// @RequestMapping(value="/admin/data/contribute", method=RequestMethod.GET)
// public String adminContributeDataset(Model model) {
// model.addAttribute("dataset", new Dataset());
//
// File rootFolder = new File(App.ROOT);
// List<String> fileNames = Arrays.stream(rootFolder.listFiles())
// .map(f -> f.getError())
// .collect(Collectors.toList());
//
// model.addAttribute("files",
// Arrays.stream(rootFolder.listFiles())
// .sorted(Comparator.comparingLong(f -> -1 * f.lastModified()))
// .map(f -> f.getError())
// .collect(Collectors.toList())
// );
//
// return "admin_contribute_data";
// }
// @RequestMapping(value="/admin/data/contribute", method=RequestMethod.POST)
// public String validateAdminContributeDataset(@ModelAttribute("dataset") Dataset dataset, HttpSession session, @RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) throws IOException {
// BufferedOutputStream stream = null;
// FileOutputStream fileOutputStream = null;
// // TODO
// // validation
// // get file from user upload to server
// if (!file.isEmpty()) {
// try {
// String fileName = getSessionIdOfLoggedInUser(session) + "-" + file.getOriginalFilename();
// fileOutputStream = new FileOutputStream(new File(App.ROOT + "/" + fileName));
// stream = new BufferedOutputStream(fileOutputStream);
// FileCopyUtils.copy(file.getInputStream(), stream);
// redirectAttributes.addFlashAttribute(MESSAGE,
// "You successfully uploaded " + file.getOriginalFilename() + "!");
// datasetManager.addDataset(getSessionIdOfLoggedInUser(session), dataset, file.getOriginalFilename());
// }
// catch (Exception e) {
// redirectAttributes.addFlashAttribute(MESSAGE,
// "You failed to upload " + file.getOriginalFilename() + " => " + e.getMessage());
// } finally {
// if (stream != null) {
// stream.close();
// }
// if (fileOutputStream != null) {
// fileOutputStream.close();
// }
// }
// }
// else {
// redirectAttributes.addFlashAttribute(MESSAGE,
// "You failed to upload " + file.getOriginalFilename() + " because the file was empty");
// }
// return "redirect:/admin";
// }
// @RequestMapping("/admin/data/remove/{datasetId}")
// public String adminRemoveDataset(@PathVariable Integer datasetId) {
// datasetManager.removeDataset(datasetId);
// return "redirect:/admin";
// }
// @RequestMapping(value="/admin/node/add", method=RequestMethod.GET)
// public String adminAddNode(Model model) {
// model.addAttribute("node", new Node());
// return "admin_add_node";
// }
// @RequestMapping(value="/admin/node/add", method=RequestMethod.POST)
// public String adminAddNode(@ModelAttribute("node") Node node) {
// // TODO
// // validate fields, eg should be integer
// nodeManager.addNode(node);
// return "redirect:/admin";
// }
//--------------------------Static pages for teams--------------------------
@RequestMapping("/teams/team_application_submitted")
public String teamAppSubmitFromTeamsPage() {
return "team_page_application_submitted";
}
@RequestMapping("/teams/join_application_submitted/{teamName}")
public String teamAppJoinFromTeamsPage(@PathVariable String teamName, Model model) throws WebServiceRuntimeException {
log.info("Redirecting to join application submitted page");
HttpEntity<String> request = createHttpEntityHeaderOnly();
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = restTemplate.exchange(properties.getTeamByName(teamName), HttpMethod.GET, request, String.class);
String responseBody = response.getBody().toString();
try {
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case TEAM_NOT_FOUND_EXCEPTION:
log.warn("submitted join team request : team name error");
break;
default:
log.warn("submitted join team request : some other failure");
// possible sio or adapter connection fail
break;
}
return "redirect:/teams/join_team";
}
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
Team2 one = extractTeamInfo(responseBody);
model.addAttribute("team", one);
return "team_page_join_application_submitted";
}
//--------------------------Static pages for sign up--------------------------
@RequestMapping("/team_application_submitted")
public String teamAppSubmit() {
return "team_application_submitted";
}
/**
* A page to show new users has successfully registered to apply to join an existing team
* The page contains the team owner information which the users requested to join
*
* @param model The model which is passed from signup
* @return A success page otherwise an error page if the user tries to access this page directly
*/
@RequestMapping("/join_application_submitted")
public String joinTeamAppSubmit(Model model) {
// model attribute should be passed from /signup2
// team is required to display the team owner details
if (model.containsAttribute("team")) {
return "join_team_application_submitted";
}
return "error";
}
@RequestMapping("/email_not_validated")
public String emailNotValidated() {
return "email_not_validated";
}
@RequestMapping("/team_application_under_review")
public String teamAppUnderReview() {
return "team_application_under_review";
}
// model attribute name come from /login
@RequestMapping("/email_checklist")
public String emailChecklist(@ModelAttribute("statuschecklist") String status) {
return "email_checklist";
}
@RequestMapping("/join_application_awaiting_approval")
public String joinTeamAppAwaitingApproval(Model model) {
model.addAttribute("loginForm", new LoginForm());
model.addAttribute("signUpMergedForm", new SignUpMergedForm());
return "join_team_application_awaiting_approval";
}
//--------------------------Get List of scenarios filenames--------------------------
private List<String> getScenarioFileNameList() throws WebServiceRuntimeException {
log.info("Retrieving scenario file names");
// List<String> scenarioFileNameList = null;
// try {
// scenarioFileNameList = IOUtils.readLines(getClass().getClassLoader().getResourceAsStream("scenarios"), StandardCharsets.UTF_8);
// } catch (IOException e) {
// throw new WebServiceRuntimeException(e.getMessage());
// }
// File folder = null;
// try {
// folder = new ClassPathResource("scenarios").getFile();
// } catch (IOException e) {
// throw new WebServiceRuntimeException(e.getMessage());
// }
// List<String> scenarioFileNameList = new ArrayList<>();
// File[] files = folder.listFiles();
// for (File file : files) {
// if (file.isFile()) {
// scenarioFileNameList.add(file.getError());
// }
// }
// FIXME: hardcode list of filenames for now
List<String> scenarioFileNameList = new ArrayList<>();
scenarioFileNameList.add("Scenario 1 - Experiment with a single node");
scenarioFileNameList.add("Scenario 2 - Experiment with 2 nodes and 10Gb link");
scenarioFileNameList.add("Scenario 3 - Experiment with 3 nodes in a LAN");
scenarioFileNameList.add("Scenario 4 - Experiment with 2 nodes and customized link property");
scenarioFileNameList.add("Scenario 5 - Single SDN switch connected to two nodes");
scenarioFileNameList.add("Scenario 6 - Tree Topology with configurable SDN switches");
// scenarioFileNameList.add("Scenario 4 - Two nodes linked with a 10Gbps SDN switch");
// scenarioFileNameList.add("Scenario 5 - Three nodes with Blockchain capabilities");
log.info("Scenario file list: {}", scenarioFileNameList);
return scenarioFileNameList;
}
private String getScenarioContentsFromFile(String scenarioFileName) throws WebServiceRuntimeException {
// FIXME: switch to better way of referencing scenario descriptions to actual filenames
String actualScenarioFileName;
if (scenarioFileName.contains("Scenario 1")) {
actualScenarioFileName = "basic1.ns";
} else if (scenarioFileName.contains("Scenario 2")) {
actualScenarioFileName = "basic2.ns";
} else if (scenarioFileName.contains("Scenario 3")) {
actualScenarioFileName = "basic3.ns";
} else if (scenarioFileName.contains("Scenario 4")) {
actualScenarioFileName = "basic4.ns";
} else if (scenarioFileName.contains("Scenario 5")) {
actualScenarioFileName = "basic5.ns";
} else if (scenarioFileName.contains("Scenario 6")) {
actualScenarioFileName = "basic6.ns";
} else {
// defaults to basic single node
actualScenarioFileName = "basic1.ns";
}
try {
log.info("Retrieving scenario files {}", getClass().getClassLoader().getResourceAsStream("scenarios/" + actualScenarioFileName));
List<String> lines = IOUtils.readLines(getClass().getClassLoader().getResourceAsStream("scenarios/" + actualScenarioFileName), StandardCharsets.UTF_8);
StringBuilder sb = new StringBuilder();
for (String line : lines) {
sb.append(line);
sb.append(System.getProperty("line.separator"));
}
log.info("Experiment ns file contents: {}", sb);
return sb.toString();
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
}
//---Check if user is a team owner and has any join request waiting for approval----
private boolean hasAnyJoinRequest(HashMap<Integer, Team> teamMapOwnedByUser) {
for (Map.Entry<Integer, Team> entry : teamMapOwnedByUser.entrySet()) {
Team currTeam = entry.getValue();
if (currTeam.isUserJoinRequestEmpty() == false) {
// at least one team has join user request
return true;
}
}
// loop through all teams but never return a single true
// therefore, user's controlled teams has no join request
return false;
}
//--------------------------MISC--------------------------
private int getSessionIdOfLoggedInUser(HttpSession session) {
return Integer.parseInt(session.getAttribute(SESSION_LOGGED_IN_USER_ID).toString());
}
private User2 extractUserInfo(String userJson) {
User2 user2 = new User2();
if (userJson == null) {
// return empty user
return user2;
}
JSONObject object = new JSONObject(userJson);
JSONObject userDetails = object.getJSONObject("userDetails");
JSONObject address = userDetails.getJSONObject("address");
user2.setId(object.getString("id"));
user2.setFirstName(getJSONStr(userDetails.getString("firstName")));
user2.setLastName(getJSONStr(userDetails.getString("lastName")));
user2.setJobTitle(userDetails.getString("jobTitle"));
user2.setEmail(userDetails.getString("email"));
user2.setPhone(userDetails.getString("phone"));
user2.setAddress1(address.getString("address1"));
user2.setAddress2(address.getString("address2"));
user2.setCountry(address.getString("country"));
user2.setRegion(address.getString("region"));
user2.setPostalCode(address.getString("zipCode"));
user2.setCity(address.getString("city"));
user2.setInstitution(userDetails.getString("institution"));
user2.setInstitutionAbbreviation(userDetails.getString("institutionAbbreviation"));
user2.setInstitutionWeb(userDetails.getString("institutionWeb"));
user2.setStatus(object.getString("status"));
user2.setEmailVerified(object.getBoolean("emailVerified"));
// applicationDate is ZonedDateTime
try {
user2.setApplicationDate(object.get(APPLICATION_DATE).toString());
} catch (Exception e) {
// since applicationDate date is a ZonedDateTime and not String
// set to '?' at the html page
log.warn("Error getting user application date {}", e);
}
return user2;
}
private Team2 extractTeamInfo(String json) {
Team2 team2 = new Team2();
JSONObject object = new JSONObject(json);
JSONArray membersArray = object.getJSONArray("members");
// createdDate is ZonedDateTime
// processedDate is ZonedDateTime
try {
team2.setApplicationDate(object.get(APPLICATION_DATE).toString());
team2.setProcessedDate(object.get("processedDate").toString());
} catch (Exception e) {
log.warn("Error getting team application date and/or processedDate {}", e);
// created date is a ZonedDateTime
// since created date and proccessed date is a ZonedDateTime and not String
// both is set to '?' at the html page if exception
}
team2.setId(object.getString("id"));
team2.setName(object.getString("name"));
team2.setDescription(object.getString("description"));
team2.setWebsite(object.getString("website"));
team2.setOrganisationType(object.getString("organisationType"));
team2.setStatus(object.getString("status"));
team2.setVisibility(object.getString("visibility"));
for (int i = 0; i < membersArray.length(); i++) {
JSONObject memberObject = membersArray.getJSONObject(i);
String userId = memberObject.getString("userId");
String teamMemberType = memberObject.getString(MEMBER_TYPE);
String teamMemberStatus = memberObject.getString("memberStatus");
User2 myUser = invokeAndExtractUserInfo(userId);
if (teamMemberType.equals(MemberType.MEMBER.name())) {
// add to pending members list for Members Awaiting Approval function
if (teamMemberStatus.equals(MemberStatus.PENDING.name())) {
team2.addPendingMembers(myUser);
}
} else if (teamMemberType.equals(MemberType.OWNER.name())) {
// explicit safer check
team2.setOwner(myUser);
}
team2.addMembersToStatusMap(MemberStatus.valueOf(teamMemberStatus), myUser);
}
team2.setMembersCount(team2.getMembersStatusMap().get(MemberStatus.APPROVED).size());
return team2;
}
// use to extract JSON Strings from services
// in the case where the JSON Strings are null, return "Connection Error"
private String getJSONStr(String jsonString) {
if (jsonString == null || jsonString.isEmpty()) {
return CONNECTION_ERROR;
}
return jsonString;
}
/**
* Checks if user is pending for join request approval from team leader
* Use for fixing bug for view experiment page where users previously can view the experiments just by issuing a join request
*
* @param json the response body after calling team service
* @param loginUserId the current logged in user id
* @return True if the user is anything but APPROVED, false otherwise
*/
private boolean isMemberJoinRequestPending(String loginUserId, String json) {
if (json == null) {
return true;
}
JSONObject object = new JSONObject(json);
JSONArray membersArray = object.getJSONArray("members");
for (int i = 0; i < membersArray.length(); i++) {
JSONObject memberObject = membersArray.getJSONObject(i);
String userId = memberObject.getString("userId");
String teamMemberStatus = memberObject.getString("memberStatus");
if (userId.equals(loginUserId) && !teamMemberStatus.equals(MemberStatus.APPROVED.toString())) {
return true;
}
}
log.info("User: {} is viewing experiment page", loginUserId);
return false;
}
private Team2 extractTeamInfoUserJoinRequest(String userId, String json) {
Team2 team2 = new Team2();
JSONObject object = new JSONObject(json);
JSONArray membersArray = object.getJSONArray("members");
for (int i = 0; i < membersArray.length(); i++) {
JSONObject memberObject = membersArray.getJSONObject(i);
String uid = memberObject.getString("userId");
String teamMemberStatus = memberObject.getString("memberStatus");
if (uid.equals(userId) && teamMemberStatus.equals(MemberStatus.PENDING.toString())) {
team2.setId(object.getString("id"));
team2.setName(object.getString("name"));
team2.setDescription(object.getString("description"));
team2.setWebsite(object.getString("website"));
team2.setOrganisationType(object.getString("organisationType"));
team2.setStatus(object.getString("status"));
team2.setVisibility(object.getString("visibility"));
team2.setMembersCount(membersArray.length());
return team2;
}
}
// no such member in the team found
return null;
}
protected Dataset invokeAndExtractDataInfo(Long dataId) {
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response = restTemplate.exchange(properties.getDataset(dataId.toString()), HttpMethod.GET, request, String.class);
return extractDataInfo(response.getBody().toString());
}
protected Dataset extractDataInfo(String json) {
log.debug(json);
JSONObject object = new JSONObject(json);
Dataset dataset = new Dataset();
dataset.setId(object.getInt("id"));
dataset.setName(object.getString("name"));
dataset.setDescription(object.getString("description"));
dataset.setContributorId(object.getString("contributorId"));
dataset.addVisibility(object.getString("visibility"));
dataset.addAccessibility(object.getString("accessibility"));
try {
dataset.setReleasedDate(getZonedDateTime(object.get("releasedDate").toString()));
} catch (IOException e) {
log.warn("Error getting released date {}", e);
dataset.setReleasedDate(null);
}
dataset.setCategoryId(object.getInt("categoryId"));
dataset.setLicenseId(object.getInt("licenseId"));
dataset.setContributor(invokeAndExtractUserInfo(dataset.getContributorId()));
dataset.setCategory(invokeAndExtractCategoryInfo(dataset.getCategoryId()));
dataset.setLicense(invokeAndExtractLicenseInfo(dataset.getLicenseId()));
JSONArray resources = object.getJSONArray("resources");
for (int i = 0; i < resources.length(); i++) {
JSONObject resource = resources.getJSONObject(i);
DataResource dataResource = new DataResource();
dataResource.setId(resource.getLong("id"));
dataResource.setUri(resource.getString("uri"));
dataResource.setMalicious(resource.getBoolean("malicious"));
dataResource.setScanned(resource.getBoolean("scanned"));
dataset.addResource(dataResource);
}
JSONArray approvedUsers = object.getJSONArray("approvedUsers");
for (int i = 0; i < approvedUsers.length(); i++) {
dataset.addApprovedUser(approvedUsers.getString(i));
}
JSONArray keywords = object.getJSONArray("keywords");
List<String> keywordList = new ArrayList<>();
for (int i = 0; i < keywords.length(); i++) {
keywordList.add(keywords.getString(i));
}
dataset.setKeywordList(keywordList);
return dataset;
}
protected DataCategory extractCategoryInfo(String json) {
log.debug(json);
DataCategory dataCategory = new DataCategory();
JSONObject object = new JSONObject(json);
dataCategory.setId(object.getLong("id"));
dataCategory.setName(object.getString("name"));
dataCategory.setDescription(object.getString("description"));
return dataCategory;
}
protected DataLicense extractLicenseInfo(String json) {
log.debug(json);
DataLicense dataLicense = new DataLicense();
JSONObject object = new JSONObject(json);
dataLicense.setId(object.getLong("id"));
dataLicense.setName(object.getString("name"));
dataLicense.setAcronym(object.getString("acronym"));
dataLicense.setDescription(object.getString("description"));
dataLicense.setLink(object.getString("link"));
return dataLicense;
}
protected DataCategory invokeAndExtractCategoryInfo(Integer categoryId) {
HttpEntity<String> request = createHttpEntityHeaderOnlyNoAuthHeader();
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getCategory(categoryId), HttpMethod.GET, request, String.class);
} catch (Exception e) {
log.warn("Data service not available to retrieve Category: {}", categoryId);
return new DataCategory();
}
return extractCategoryInfo(response.getBody().toString());
}
protected DataLicense invokeAndExtractLicenseInfo(Integer licenseId) {
HttpEntity<String> request = createHttpEntityHeaderOnlyNoAuthHeader();
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getLicense(licenseId), HttpMethod.GET, request, String.class);
} catch (Exception e) {
log.warn("Data service not available to retrieve License: {}", licenseId);
return new DataLicense();
}
return extractLicenseInfo(response.getBody().toString());
}
protected User2 invokeAndExtractUserInfo(String userId) {
HttpEntity<String> request = createHttpEntityHeaderOnlyNoAuthHeader();
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getUser(userId), HttpMethod.GET, request, String.class);
} catch (Exception e) {
log.warn("User service not available to retrieve User: {}", userId);
return new User2();
}
return extractUserInfo(response.getBody().toString());
}
private Team2 invokeAndExtractTeamInfo(String teamId) {
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity responseEntity = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, request, String.class);
return extractTeamInfo(responseEntity.getBody().toString());
}
private Experiment2 extractExperiment(String experimentJson) {
Experiment2 experiment2 = new Experiment2();
JSONObject object = new JSONObject(experimentJson);
experiment2.setId(object.getLong("id"));
experiment2.setUserId(object.getString("userId"));
experiment2.setTeamId(object.getString(TEAM_ID));
experiment2.setTeamName(object.getString(TEAM_NAME));
experiment2.setName(object.getString("name"));
experiment2.setDescription(object.getString("description"));
experiment2.setNsFile(object.getString("nsFile"));
experiment2.setNsFileContent(object.getString("nsFileContent"));
experiment2.setIdleSwap(object.getInt("idleSwap"));
experiment2.setMaxDuration(object.getInt("maxDuration"));
return experiment2;
}
private Realization invokeAndExtractRealization(String teamName, Long id) {
HttpEntity<String> request = createHttpEntityHeaderOnly();
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = null;
try {
log.info("retrieving the latest exp status: {}", properties.getRealizationByTeam(teamName, id.toString()));
response = restTemplate.exchange(properties.getRealizationByTeam(teamName, id.toString()), HttpMethod.GET, request, String.class);
} catch (Exception e) {
return getCleanRealization();
}
String responseBody;
if (response.getBody() == null) {
return getCleanRealization();
} else {
responseBody = response.getBody().toString();
}
try {
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
log.warn("error in retrieving realization for team: {}, realization: {}", teamName, id);
return getCleanRealization();
} else {
// will throw JSONException if the format return by sio is not a valid JSOn format
// will occur if the realization details are still in the old format
return extractRealization(responseBody);
}
} catch (IOException | JSONException e) {
return getCleanRealization();
}
}
private Realization extractRealization(String json) {
log.info("extracting realization: {}", json);
Realization realization = new Realization();
JSONObject object = new JSONObject(json);
realization.setExperimentId(object.getLong("experimentId"));
realization.setExperimentName(object.getString("experimentName"));
realization.setUserId(object.getString("userId"));
realization.setTeamId(object.getString(TEAM_ID));
realization.setState(object.getString("state"));
String exp_report = "";
Object expDetailsObject = object.get("details");
log.info("exp detail object: {}", expDetailsObject);
if (expDetailsObject == JSONObject.NULL || expDetailsObject.toString().isEmpty()) {
log.info("set details empty");
realization.setDetails("");
realization.setNumberOfNodes(0);
} else {
log.info("exp report to string: {}", expDetailsObject.toString());
exp_report = expDetailsObject.toString();
realization.setDetails(exp_report);
JSONObject nodesInfoObject = new JSONObject(expDetailsObject.toString());
for (Object key : nodesInfoObject.keySet()) {
Map<String, String> nodeDetails = new HashMap<>();
String nodeName = (String) key;
JSONObject nodeDetailsJson = new JSONObject(nodesInfoObject.get(nodeName).toString());
nodeDetails.put("os", getValueFromJSONKey(nodeDetailsJson, "os"));
nodeDetails.put("qualifiedName", getValueFromJSONKey(nodeDetailsJson, "qualifiedName"));
nodeDetails.put(NODE_ID, getValueFromJSONKey(nodeDetailsJson, NODE_ID));
realization.addNodeDetails(nodeName, nodeDetails);
}
log.info("nodes info object: {}", nodesInfoObject);
realization.setNumberOfNodes(nodesInfoObject.keySet().size());
}
return realization;
}
// gets the value that corresponds to a particular key
// checks if a particular key in the JSONObject exists
// returns the value if the key exists, otherwise, returns N.A.
private String getValueFromJSONKey(JSONObject json, String key) {
if (json.has(key)) {
return json.get(key).toString();
}
return NOT_APPLICABLE;
}
/**
* @param zonedDateTimeJSON JSON string
* @return a date in the format MMM-d-yyyy
*/
protected String formatZonedDateTime(String zonedDateTimeJSON) throws Exception {
ZonedDateTime zonedDateTime = getZonedDateTime(zonedDateTimeJSON);
DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM-d-yyyy");
return zonedDateTime.format(format);
}
protected ZonedDateTime getZonedDateTime(String zonedDateTimeJSON) throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
return mapper.readValue(zonedDateTimeJSON, ZonedDateTime.class);
}
/**
* Creates a HttpEntity with a request body and header but no authorization header
* To solve the expired jwt token
*
* @param jsonString The JSON request converted to string
* @return A HttpEntity request
* @see HttpEntity createHttpEntityHeaderOnly() for request with only header
*/
protected HttpEntity<String> createHttpEntityWithBodyNoAuthHeader(String jsonString) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
return new HttpEntity<>(jsonString, headers);
}
/**
* Creates a HttpEntity that contains only a header and empty body but no authorization header
* To solve the expired jwt token
*
* @return A HttpEntity request
* @see HttpEntity createHttpEntityWithBody() for request with both body and header
*/
protected HttpEntity<String> createHttpEntityHeaderOnlyNoAuthHeader() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
return new HttpEntity<>(headers);
}
/**
* Creates a HttpEntity with a request body and header
*
* @param jsonString The JSON request converted to string
* @return A HttpEntity request
* @implNote Authorization header must be set to the JwTToken in the format [Bearer: TOKEN_ID]
* @see HttpEntity createHttpEntityHeaderOnly() for request with only header
*/
protected HttpEntity<String> createHttpEntityWithBody(String jsonString) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization", httpScopedSession.getAttribute(webProperties.getSessionJwtToken()).toString());
return new HttpEntity<>(jsonString, headers);
}
/**
* Creates a HttpEntity that contains only a header and empty body
*
* @return A HttpEntity request
* @implNote Authorization header must be set to the JwTToken in the format [Bearer: TOKEN_ID]
* @see HttpEntity createHttpEntityWithBody() for request with both body and header
*/
protected HttpEntity<String> createHttpEntityHeaderOnly() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization", httpScopedSession.getAttribute(webProperties.getSessionJwtToken()).toString());
return new HttpEntity<>(headers);
}
private void setSessionVariables(HttpSession session, String loginEmail, String id, String firstName, String userRoles, String token) {
User2 user = invokeAndExtractUserInfo(id);
session.setAttribute(webProperties.getSessionEmail(), loginEmail);
session.setAttribute(webProperties.getSessionUserId(), id);
session.setAttribute(webProperties.getSessionUserFirstName(), firstName);
session.setAttribute(webProperties.getSessionRoles(), userRoles);
session.setAttribute(webProperties.getSessionJwtToken(), "Bearer " + token);
log.info("Session variables - sessionLoggedEmail: {}, id: {}, name: {}, roles: {}, token: {}", loginEmail, id, user.getFirstName(), userRoles, token);
}
private void removeSessionVariables(HttpSession session) {
log.info("removing session variables: email: {}, userid: {}, user first name: {}", session.getAttribute(webProperties.getSessionEmail()), session.getAttribute(webProperties.getSessionUserId()), session.getAttribute(webProperties.getSessionUserFirstName()));
session.removeAttribute(webProperties.getSessionEmail());
session.removeAttribute(webProperties.getSessionUserId());
session.removeAttribute(webProperties.getSessionUserFirstName());
session.removeAttribute(webProperties.getSessionRoles());
session.removeAttribute(webProperties.getSessionJwtToken());
session.invalidate();
}
protected boolean validateIfAdmin(HttpSession session) {
//log.info("User: {} is logged on as: {}", session.getAttribute(webProperties.getSessionEmail()), session.getAttribute(webProperties.getSessionRoles()));
return session.getAttribute(webProperties.getSessionRoles()).equals(UserType.ADMIN.toString());
}
/**
* Ensure that only users of the team can realize or un-realize experiment
* A pre-condition is that the users must be approved.
* Teams must also be approved.
*
* @return the main experiment page
*/
private boolean checkPermissionRealizeExperiment(Realization realization, HttpSession session) {
// get list of teamids
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity userRespEntity = restTemplate.exchange(properties.getUser(session.getAttribute("id").toString()), HttpMethod.GET, request, String.class);
JSONObject object = new JSONObject(userRespEntity.getBody().toString());
JSONArray teamIdsJsonArray = object.getJSONArray("teams");
for (int i = 0; i < teamIdsJsonArray.length(); i++) {
String teamId = teamIdsJsonArray.get(i).toString();
if (teamId.equals(realization.getTeamId())) {
return true;
}
}
return false;
}
private String getTeamStatus(String teamId) {
Team2 team = invokeAndExtractTeamInfo(teamId);
return team.getStatus();
}
private Realization getCleanRealization() {
Realization realization = new Realization();
realization.setExperimentId(0L);
realization.setExperimentName("");
realization.setUserId("");
realization.setTeamId("");
realization.setState(RealizationState.ERROR.toString());
realization.setDetails("");
realization.setNumberOfNodes(0);
return realization;
}
/**
* Computes the number of teams that the user is in and the number of running experiments to populate data for the user dashboard
*
* @return a map in the form teams: numberOfTeams, experiments: numberOfExperiments
*/
private Map<String, Integer> getUserDashboardStats(String userId) {
int numberOfRunningExperiments = 0;
Map<String, Integer> userDashboardStats = new HashMap<>();
// get list of teamids
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity userRespEntity = restTemplate.exchange(properties.getUser(userId), HttpMethod.GET, request, String.class);
JSONObject object = new JSONObject(userRespEntity.getBody().toString());
JSONArray teamIdsJsonArray = object.getJSONArray("teams");
int numberOfApprovedTeam = 0;
for (int i = 0; i < teamIdsJsonArray.length(); i++) {
String teamId = teamIdsJsonArray.get(i).toString();
HttpEntity<String> teamRequest = createHttpEntityHeaderOnly();
ResponseEntity teamResponse = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, teamRequest, String.class);
String teamResponseBody = teamResponse.getBody().toString();
if (!isMemberJoinRequestPending(userId, teamResponseBody)) {
// get experiments lists of the teams
HttpEntity<String> expRequest = createHttpEntityHeaderOnly();
ResponseEntity expRespEntity = restTemplate.exchange(properties.getExpListByTeamId(teamId), HttpMethod.GET, expRequest, String.class);
JSONArray experimentsArray = new JSONArray(expRespEntity.getBody().toString());
numberOfRunningExperiments = getNumberOfRunningExperiments(numberOfRunningExperiments, experimentsArray);
numberOfApprovedTeam ++;
}
}
userDashboardStats.put(USER_DASHBOARD_APPROVED_TEAMS, numberOfApprovedTeam);
userDashboardStats.put(USER_DASHBOARD_RUNNING_EXPERIMENTS, numberOfRunningExperiments);
// userDashboardStats.put(USER_DASHBOARD_FREE_NODES, getNodes(NodeType.FREE));
return userDashboardStats;
}
private int getNumberOfRunningExperiments(int numberOfRunningExperiments, JSONArray experimentsArray) {
for (int k = 0; k < experimentsArray.length(); k++) {
Experiment2 experiment2 = extractExperiment(experimentsArray.getJSONObject(k).toString());
Realization realization = invokeAndExtractRealization(experiment2.getTeamName(), experiment2.getId());
if (realization.getState().equals(RealizationState.RUNNING.toString())) {
numberOfRunningExperiments++;
}
}
return numberOfRunningExperiments;
}
private SortedMap<String, Map<String, String>> getGlobalImages() throws IOException {
SortedMap<String, Map<String, String>> globalImagesMap = new TreeMap<>();
log.info("Retrieving list of global images from: {}", properties.getGlobalImages());
try {
HttpEntity<String> request = createHttpEntityHeaderOnlyNoAuthHeader();
ResponseEntity response = restTemplate.exchange(properties.getGlobalImages(), HttpMethod.GET, request, String.class);
ObjectMapper mapper = new ObjectMapper();
String json = new JSONObject(response.getBody().toString()).getString("images");
globalImagesMap = mapper.readValue(json, new TypeReference<SortedMap<String, Map<String, String>>>() {
});
} catch (RestClientException e) {
log.warn("Error connecting to service-image: {}", e);
}
return globalImagesMap;
}
private int getNodes(NodeType nodeType) {
String nodesCount;
log.info("Retrieving number of " + nodeType + " nodes from: {}", properties.getNodes(nodeType));
try {
HttpEntity<String> request = createHttpEntityHeaderOnlyNoAuthHeader();
ResponseEntity response = restTemplate.exchange(properties.getNodes(nodeType), HttpMethod.GET, request, String.class);
JSONObject object = new JSONObject(response.getBody().toString());
nodesCount = object.getString(nodeType.name());
} catch (RestClientException e) {
log.warn(ERROR_CONNECTING_TO_SERVICE_TELEMETRY, e);
nodesCount = "0";
}
return Integer.parseInt(nodesCount);
}
private List<TeamUsageInfo> getTeamsUsageStatisticsForUser(String userId) {
List<TeamUsageInfo> usageInfoList = new ArrayList<>();
// get list of teamids
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity userRespEntity = restTemplate.exchange(properties.getUser(userId), HttpMethod.GET, request, String.class);
JSONObject object = new JSONObject(userRespEntity.getBody().toString());
JSONArray teamIdsJsonArray = object.getJSONArray("teams");
// get team info by team id
for (int i = 0; i < teamIdsJsonArray.length(); i++) {
String teamId = teamIdsJsonArray.get(i).toString();
HttpEntity<String> teamRequest = createHttpEntityHeaderOnly();
ResponseEntity teamResponse = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, teamRequest, String.class);
String teamResponseBody = teamResponse.getBody().toString();
if (!isMemberJoinRequestPending(userId, teamResponseBody)) {
TeamUsageInfo usageInfo = new TeamUsageInfo();
usageInfo.setId(teamId);
usageInfo.setName(new JSONObject(teamResponseBody).getString("name"));
usageInfo.setUsage(getUsageStatisticsByTeamId(teamId));
usageInfoList.add(usageInfo);
}
}
return usageInfoList;
}
private String getUsageStatisticsByTeamId(String id) {
log.info("Getting usage statistics for team {}", id);
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getUsageStat(id), HttpMethod.GET, request, String.class);
} catch (RestClientException e) {
log.warn("Error connecting to sio get usage statistics {}", e);
return "?";
}
return response.getBody().toString();
}
private TeamQuota extractTeamQuotaInfo(String responseBody) {
JSONObject object = new JSONObject(responseBody);
TeamQuota teamQuota = new TeamQuota();
Double charges = Double.parseDouble(accountingProperties.getCharges());
// amountUsed from SIO will never be null => not checking for null value
String usage = object.getString("usage"); // getting usage in String
BigDecimal amountUsed = new BigDecimal(usage); // using BigDecimal to handle currency
amountUsed = amountUsed.multiply(new BigDecimal(charges)); // usage X charges
//quota passed from SIO can be null , so we have to check for null value
if (object.has("quota")) {
Object budgetObject = object.optString("quota", null);
if (budgetObject == null) {
teamQuota.setBudget(""); // there is placeholder here
teamQuota.setResourcesLeft("Unlimited"); // not placeholder so can pass string over
} else {
Double budgetInDouble = object.getDouble("quota"); // retrieve budget from SIO in Double
BigDecimal budgetInBD = BigDecimal.valueOf(budgetInDouble); // handling currency using BigDecimal
// calculate resoucesLeft
BigDecimal resourceLeftInBD = budgetInBD.subtract(amountUsed);
resourceLeftInBD = resourceLeftInBD.divide(new BigDecimal(charges), 0, BigDecimal.ROUND_DOWN);
budgetInBD = budgetInBD.setScale(2, BigDecimal.ROUND_HALF_UP);
// set budget
teamQuota.setBudget(budgetInBD.toString());
//set resroucesLeft
if (resourceLeftInBD.compareTo(BigDecimal.valueOf(0)) < 0)
teamQuota.setResourcesLeft("0");
else
teamQuota.setResourcesLeft(resourceLeftInBD.toString());
}
}
//set teamId and amountUsed
teamQuota.setTeamId(object.getString(TEAM_ID));
amountUsed = amountUsed.setScale(2, BigDecimal.ROUND_HALF_UP);
teamQuota.setAmountUsed(amountUsed.toString());
return teamQuota;
}
/**
* Invokes the get nodes status in the telemetry service
* @return a map containing a list of nodes status by their type
*/
private Map<String, List<Map<String, String>>> getNodesStatus() throws IOException {
log.info("Getting all nodes' status from: {}", properties.getNodesStatus());
Map<String, List<Map<String, String>>> output = new HashMap<>();
try {
HttpEntity<String> request = createHttpEntityHeaderOnlyNoAuthHeader();
ResponseEntity response = restTemplate.exchange(properties.getNodesStatus(), HttpMethod.GET, request, String.class);
JSONObject object = new JSONObject(response.getBody().toString());
if (object == JSONObject.NULL || object.length() == 0) {
return output;
} else {
// loop through the object as there may be more than one machine type
for (int i = 0; i < object.names().length(); i++) {
// for each machine type, get all the current nodes status
String currentMachineType = object.names().getString(i);
// converts the JSON Array of the form [ { id : A, status : B, type : C } ] into a proper list of map
List<Map<String, String>> nodesList = objectMapper.readValue(object.getJSONArray(currentMachineType).toString(), new TypeReference<List<Map>>(){});
output.put(currentMachineType, nodesList);
}
}
} catch (RestClientException e) {
log.warn(ERROR_CONNECTING_TO_SERVICE_TELEMETRY, e);
return new HashMap<>();
}
log.info("Finish getting all nodes: {}", output);
return output;
}
private Map<String,String> getTestbedStats() {
Map<String, String> statsMap = new HashMap<>();
log.info("Retrieving number of logged in users and running experiments from: {}", properties.getTestbedStats());
try {
HttpEntity<String> request = createHttpEntityHeaderOnlyNoAuthHeader();
ResponseEntity response = restTemplate.exchange(properties.getTestbedStats(), HttpMethod.GET, request, String.class);
JSONObject object = new JSONObject(response.getBody().toString());
statsMap.put(USER_DASHBOARD_LOGGED_IN_USERS_COUNT, object.getString("users"));
statsMap.put(USER_DASHBOARD_RUNNING_EXPERIMENTS_COUNT, object.getString("experiments"));
} catch (RestClientException e) {
log.warn(ERROR_CONNECTING_TO_SERVICE_TELEMETRY, e);
statsMap.put(USER_DASHBOARD_LOGGED_IN_USERS_COUNT, "0");
statsMap.put(USER_DASHBOARD_RUNNING_EXPERIMENTS_COUNT, "0");
}
return statsMap;
}
}
|
src/main/java/sg/ncl/MainController.java
|
package sg.ncl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.tomcat.util.codec.binary.Base64;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.support.RequestContextUtils;
import sg.ncl.domain.*;
import sg.ncl.exceptions.*;
import sg.ncl.testbed_interface.*;
import sg.ncl.testbed_interface.Image;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.text.DecimalFormat;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.List;
import java.util.regex.Pattern;
import static java.time.temporal.TemporalAdjusters.firstDayOfMonth;
import static java.time.temporal.TemporalAdjusters.lastDayOfMonth;
import static sg.ncl.domain.ExceptionState.*;
/**
*
* Spring Controller
* Direct the views to appropriate locations and invoke the respective REST API
*
* @author Cassie, Desmond, Te Ye, Vu
*/
@Controller
@Slf4j
public class MainController {
public static final String CONTENT_DISPOSITION = "Content-Disposition";
public static final String APPLICATION_FORCE_DOWNLOAD = "application/force-download";
private static final String SESSION_LOGGED_IN_USER_ID = "loggedInUserId";
private TeamManager teamManager = TeamManager.getInstance();
// private UserManager userManager = UserManager.getInstance();
// private ExperimentManager experimentManager = ExperimentManager.getInstance();
// private DomainManager domainManager = DomainManager.getInstance();
// private DatasetManager datasetManager = DatasetManager.getInstance();
// private NodeManager nodeManager = NodeManager.getInstance();
private static final String CONTACT_EMAIL = "support@ncl.sg";
private static final String UNKNOWN = "?";
private static final String MESSAGE = "message";
private static final String MESSAGE_SUCCESS = "messageSuccess";
private static final String EXPERIMENT_MESSAGE = "exp_message";
private static final String ERROR_PREFIX = "Error: ";
// error messages
private static final String ERROR_CONNECTING_TO_SERVICE_TELEMETRY = "Error connecting to service-telemetry: {}";
private static final String ERR_SERVER_OVERLOAD = "There is a problem with your request. Please contact " + CONTACT_EMAIL;
private static final String CONNECTION_ERROR = "Connection Error";
private final String permissionDeniedMessage = "Permission denied. If the error persists, please contact " + CONTACT_EMAIL;
private static final String ERR_START_DATE_AFTER_END_DATE = "End date must be after start date";
// for user dashboard hashmap key values
private static final String USER_DASHBOARD_APPROVED_TEAMS = "numberOfApprovedTeam";
private static final String USER_DASHBOARD_RUNNING_EXPERIMENTS = "numberOfRunningExperiments";
private static final String USER_DASHBOARD_FREE_NODES = "freeNodes";
private static final String USER_DASHBOARD_TOTAL_NODES = "totalNodes";
private static final String USER_DASHBOARD_GLOBAL_IMAGES = "globalImagesMap";
private static final String USER_DASHBOARD_LOGGED_IN_USERS_COUNT = "loggedInUsersCount";
private static final String USER_DASHBOARD_RUNNING_EXPERIMENTS_COUNT = "runningExperimentsCount";
private static final String DETER_UID = "deterUid";
private static final Pattern VALID_EMAIL_ADDRESS_REGEX =
Pattern.compile("(?:(?:\\r\\n)?[ \\t])*(?:(?:(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*\\<(?:(?:\\r\\n)?[ \\t])*(?:@(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*(?:,@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*)*:(?:(?:\\r\\n)?[ \\t])*)?(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\>(?:(?:\\r\\n)?[ \\t])*)|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*:(?:(?:\\r\\n)?[ \\t])*(?:(?:(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*\\<(?:(?:\\r\\n)?[ \\t])*(?:@(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*(?:,@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*)*:(?:(?:\\r\\n)?[ \\t])*)?(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\>(?:(?:\\r\\n)?[ \\t])*)(?:,\\s*(?:(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*\\<(?:(?:\\r\\n)?[ \\t])*(?:@(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*(?:,@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*)*:(?:(?:\\r\\n)?[ \\t])*)?(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\>(?:(?:\\r\\n)?[ \\t])*))*)?;\\s*)");
private static final String FORGET_PSWD_PAGE = "password_reset_email";
private static final String FORGET_PSWD_NEW_PSWD_PAGE = "password_reset_new_password";
private static final String NO_PERMISSION_PAGE = "nopermission";
private static final String EXPERIMENTS = "experiments";
private static final String APPLICATION_DATE = "applicationDate";
private static final String TEAM_NAME = "teamName";
private static final String TEAM_ID = "teamId";
private static final String NODE_ID = "nodeId";
private static final String PERMISSION_DENIED = "Permission denied";
private static final String TEAM_NOT_FOUND = "Team not found";
private static final String NOT_FOUND = " not found.";
private static final String EDIT_BUDGET = "editBudget";
private static final String ORIGINAL_BUDGET = "originalBudget";
private static final String REDIRECT_TEAM_PROFILE_TEAM_ID = "redirect:/team_profile/{teamId}";
private static final String REDIRECT_TEAM_PROFILE = "redirect:/team_profile/";
private static final String REDIRECT_INDEX_PAGE = "redirect:/";
private static final String REDIRECT_ENERGY_USAGE = "redirect:/energy_usage";
// remove members from team profile; to display the list of experiments created by user
private static final String REMOVE_MEMBER_UID = "removeMemberUid";
private static final String REMOVE_MEMBER_NAME = "removeMemberName";
private static final String MEMBER_TYPE = "memberType";
// admin update data resource to track what fields have been updated
private static final String ORIGINAL_DATARESOURCE = "original_dataresource";
private static final String NOT_APPLICABLE = "N.A.";
@Autowired
protected RestTemplate restTemplate;
@Inject
protected ObjectMapper objectMapper;
@Inject
protected ConnectionProperties properties;
@Inject
protected WebProperties webProperties;
@Inject
protected AccountingProperties accountingProperties;
@Inject
protected HttpSession httpScopedSession;
@RequestMapping("/")
public String index() {
return "index";
}
@RequestMapping("/overview")
public String overview() {
return "overview";
}
@RequestMapping("/community")
public String community() {
return "community";
}
@RequestMapping("/about")
public String about() {
return "about";
}
@RequestMapping("/event")
public String event() {
return "event";
}
@RequestMapping("/plan")
public String plan() {
return "plan";
}
@RequestMapping("/career")
public String career() {
return "career";
}
@RequestMapping("/pricing")
public String pricing() {
return "pricing";
}
@RequestMapping("/resources")
public String resources() {
return "resources";
}
@RequestMapping("/research")
public String research() {
return "research";
}
@RequestMapping("/calendar")
public String calendar() {
return "calendar";
}
@RequestMapping("/tutorials/createaccount")
public String createAccount() {
return "createaccount";
}
@RequestMapping("/tutorials/createexperiment")
public String createExperimentTutorial() {
return "createexperiment";
}
@RequestMapping("/tutorials/loadimage")
public String loadimage() {
return "loadimage";
}
@RequestMapping("/tutorials/saveimage")
public String saveimage() {
return "saveimage";
}
@RequestMapping("/tutorials/applyteam")
public String applyteam() {
return "applyteam";
}
@RequestMapping("/tutorials/jointeam")
public String jointeam() {
return "jointeam";
}
@RequestMapping("/tutorials/usenode")
public String usenode() {
return "usenode";
}
@RequestMapping("/tutorials/usessh")
public String usessh() {
return "usessh";
}
@RequestMapping("/tutorials/usescp")
public String usescp() {
return "usescp";
}
@RequestMapping("/tutorials/usegui")
public String usegui() {
return "usegui";
}
@RequestMapping("/tutorials/manageresource")
public String manageresource() {
return "manageresource";
}
@RequestMapping("/tutorials/testbedinfo")
public String testbedinfo() {
return "testbedinfo";
}
@RequestMapping("/tutorials/createcustom")
public String createcustom() {
return "createcustom";
}
@RequestMapping("/error_openstack")
public String error_openstack() {
return "error_openstack";
}
@RequestMapping("/accessexperiment")
public String accessexperiment() {
return "accessexperiment";
}
@RequestMapping("/resource2")
public String resource2() {
return "resource2";
}
@RequestMapping("/tutorials")
public String tutorials() {
return "tutorials";
}
@RequestMapping("/maintainance")
public String maintainance() {
return "maintainance";
}
@RequestMapping("/testbedInformation")
public String testbedInformation(Model model) throws IOException {
model.addAttribute(USER_DASHBOARD_GLOBAL_IMAGES, getGlobalImages());
return "testbed_information";
}
// get all the nodes' status
// there are three types of status
// "free" : node is free
// "in_use" : node is in use
// "reload" : node is in process of freeing or unknown status
// "reserved" : node is pre-reserved for a project
@RequestMapping("/testbedNodesStatus")
public String testbedNodesStatus(Model model) throws IOException {
// get number of active users and running experiments
Map<String, String> testbedStatsMap = getTestbedStats();
testbedStatsMap.put(USER_DASHBOARD_FREE_NODES, "0");
testbedStatsMap.put(USER_DASHBOARD_TOTAL_NODES, "0");
Map<String, List<Map<String, String>>> nodesStatus = getNodesStatus();
Map<String, Map<String, Long>> nodesStatusCount = new HashMap<>();
// loop through each of the machine type
// tabulate the different nodes type
// count the number of different nodes status, e.g. SYSTEMX = { FREE = 10, IN_USE = 11, ... }
nodesStatus.entrySet().forEach(machineTypeListEntry -> {
Map<String, Long> nodesCountMap = new HashMap<>();
long free = machineTypeListEntry.getValue().stream().filter(stringStringMap -> "free".equalsIgnoreCase(stringStringMap.get("status"))).count();
long inUse = machineTypeListEntry.getValue().stream().filter(stringStringMap -> "in_use".equalsIgnoreCase(stringStringMap.get("status"))).count();
long reserved = machineTypeListEntry.getValue().stream().filter(stringStringMap -> "reserved".equalsIgnoreCase(stringStringMap.get("status"))).count();
long reload = machineTypeListEntry.getValue().stream().filter(stringStringMap -> "reload".equalsIgnoreCase(stringStringMap.get("status"))).count();
long total = free + inUse + reserved + reload;
long currentTotal = Long.parseLong(testbedStatsMap.get(USER_DASHBOARD_TOTAL_NODES)) + total;
long currentFree = Long.parseLong(testbedStatsMap.get(USER_DASHBOARD_FREE_NODES)) + free;
nodesCountMap.put(NodeType.FREE.name(), free);
nodesCountMap.put(NodeType.IN_USE.name(), inUse);
nodesCountMap.put(NodeType.RESERVED.name(), reserved);
nodesCountMap.put(NodeType.RELOADING.name(), reload);
nodesStatusCount.put(machineTypeListEntry.getKey(), nodesCountMap);
testbedStatsMap.put(USER_DASHBOARD_FREE_NODES, Long.toString(currentFree));
testbedStatsMap.put(USER_DASHBOARD_TOTAL_NODES, Long.toString(currentTotal));
});
model.addAttribute("nodesStatus", nodesStatus);
model.addAttribute("nodesStatusCount", nodesStatusCount);
model.addAttribute(USER_DASHBOARD_LOGGED_IN_USERS_COUNT, testbedStatsMap.get(USER_DASHBOARD_LOGGED_IN_USERS_COUNT));
model.addAttribute(USER_DASHBOARD_RUNNING_EXPERIMENTS_COUNT, testbedStatsMap.get(USER_DASHBOARD_RUNNING_EXPERIMENTS_COUNT));
model.addAttribute(USER_DASHBOARD_FREE_NODES, testbedStatsMap.get(USER_DASHBOARD_FREE_NODES));
model.addAttribute(USER_DASHBOARD_TOTAL_NODES, testbedStatsMap.get(USER_DASHBOARD_TOTAL_NODES));
return "testbed_nodes_status";
}
@RequestMapping(value = "/orderform/download", method = RequestMethod.GET)
public void OrderForm_v1Download(HttpServletResponse response) throws OrderFormDownloadException, IOException {
InputStream stream = null;
response.setContentType(MediaType.APPLICATION_PDF_VALUE);
try {
stream = getClass().getClassLoader().getResourceAsStream("downloads/order_form.pdf");
response.setContentType(APPLICATION_FORCE_DOWNLOAD);
response.setHeader(CONTENT_DISPOSITION, "attachment; filename=order_form.pdf");
IOUtils.copy(stream, response.getOutputStream());
response.flushBuffer();
} catch (IOException ex) {
log.info("Error for download orderform.");
throw new OrderFormDownloadException("Error for download orderform.");
} finally {
if (stream != null) {
stream.close();
}
}
}
@RequestMapping("/contactus")
public String contactus() {
return "contactus";
}
@RequestMapping("/notfound")
public String redirectNotFound(HttpSession session) {
if (session.getAttribute("id") != null && !session.getAttribute("id").toString().isEmpty()) {
// user is already logged on and has encountered an error
// redirect to dashboard
return "redirect:/dashboard";
} else {
// user have not logged on before
// redirect to home page
return REDIRECT_INDEX_PAGE;
}
}
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(Model model) {
model.addAttribute("loginForm", new LoginForm());
return "login";
}
@RequestMapping(value = "/emailVerification", params = {"id", "email", "key"})
public String verifyEmail(
@NotNull @RequestParam("id") final String id,
@NotNull @RequestParam("email") final String emailBase64,
@NotNull @RequestParam("key") final String key
) throws UnsupportedEncodingException {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
ObjectNode keyObject = objectMapper.createObjectNode();
keyObject.put("key", key);
HttpEntity<String> request = new HttpEntity<>(keyObject.toString(), headers);
restTemplate.setErrorHandler(new MyResponseErrorHandler());
final String link = properties.getSioRegUrl() + "/users/" + id + "/emails/" + emailBase64;
log.info("Activation link: {}, verification key {}", link, key);
ResponseEntity response = restTemplate.exchange(link, HttpMethod.PUT, request, String.class);
if (RestUtil.isError(response.getStatusCode())) {
log.error("Activation of user {} failed.", id);
return "email_validation_failed";
} else {
log.info("Activation of user {} completed.", id);
return "email_validation_ok";
}
}
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String loginSubmit(
@Valid
@ModelAttribute("loginForm") LoginForm loginForm,
BindingResult bindingResult,
Model model,
HttpSession session, final RedirectAttributes redirectAttributes) throws WebServiceRuntimeException {
if (bindingResult.hasErrors()) {
loginForm.setErrorMsg("Login failed: Invalid email/password.");
return "login";
}
String inputEmail = loginForm.getLoginEmail();
String inputPwd = loginForm.getLoginPassword();
if (inputEmail.trim().isEmpty() || inputPwd.trim().isEmpty()) {
loginForm.setErrorMsg("Email or Password cannot be empty!");
return "login";
}
String plainCreds = inputEmail + ":" + inputPwd;
byte[] plainCredsBytes = plainCreds.getBytes();
byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
String base64Creds = new String(base64CredsBytes);
ResponseEntity response;
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Basic " + base64Creds);
HttpEntity<String> request = new HttpEntity<>(headers);
restTemplate.setErrorHandler(new MyResponseErrorHandler());
try {
response = restTemplate.exchange(properties.getSioAuthUrl(), HttpMethod.POST, request, String.class);
} catch (RestClientException e) {
log.warn("Error connecting to sio authentication service: {}", e);
loginForm.setErrorMsg(ERR_SERVER_OVERLOAD);
return "login";
}
String jwtTokenString = response.getBody().toString();
log.info("token string {}", jwtTokenString);
if (jwtTokenString == null || jwtTokenString.isEmpty()) {
log.warn("login failed for {}: unknown response code", loginForm.getLoginEmail());
loginForm.setErrorMsg("Login failed: Invalid email/password.");
return "login";
}
if (RestUtil.isError(response.getStatusCode())) {
try {
MyErrorResource error = objectMapper.readValue(jwtTokenString, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
if (exceptionState == ExceptionState.CREDENTIALS_NOT_FOUND_EXCEPTION) {
log.warn("login failed for {}: credentials not found", loginForm.getLoginEmail());
loginForm.setErrorMsg("Login failed: Account does not exist. Please register.");
return "login";
}
log.warn("login failed for {}: {}", loginForm.getLoginEmail(), error.getError());
loginForm.setErrorMsg("Login failed: Invalid email/password.");
return "login";
} catch (IOException ioe) {
log.warn("IOException {}", ioe);
throw new WebServiceRuntimeException(ioe.getMessage());
}
}
JSONObject tokenObject = new JSONObject(jwtTokenString);
String token = tokenObject.getString("token");
String id = tokenObject.getString("id");
String role = "";
if (tokenObject.getJSONArray("roles") != null) {
role = tokenObject.getJSONArray("roles").get(0).toString();
}
if (token.trim().isEmpty() || id.trim().isEmpty() || role.trim().isEmpty()) {
log.warn("login failed for {}: empty id {} or token {} or role {}", loginForm.getLoginEmail(), id, token, role);
loginForm.setErrorMsg("Login failed: Invalid email/password.");
return "login";
}
// now check user status to decide what to show to the user
User2 user = invokeAndExtractUserInfo(id);
try {
String userStatus = user.getStatus();
boolean emailVerified = user.getEmailVerified();
if (UserStatus.FROZEN.toString().equals(userStatus)) {
log.warn("User {} login failed: account has been frozen", id);
loginForm.setErrorMsg("Login Failed: Account Frozen. Please contact " + CONTACT_EMAIL);
return "login";
} else if (!emailVerified || (UserStatus.CREATED.toString()).equals(userStatus)) {
redirectAttributes.addAttribute("statuschecklist", userStatus);
log.info("User {} not validated, redirected to email verification page", id);
return "redirect:/email_checklist";
} else if ((UserStatus.PENDING.toString()).equals(userStatus)) {
redirectAttributes.addAttribute("statuschecklist", userStatus);
log.info("User {} not approved, redirected to application pending page", id);
return "redirect:/email_checklist";
} else if ((UserStatus.APPROVED.toString()).equals(userStatus)) {
// set session variables
setSessionVariables(session, loginForm.getLoginEmail(), id, user.getFirstName(), role, token);
log.info("login success for {}, id: {}", loginForm.getLoginEmail(), id);
return "redirect:/dashboard";
} else {
log.warn("login failed for user {}: account is rejected or closed", id);
loginForm.setErrorMsg("Login Failed: Account Rejected/Closed.");
return "login";
}
} catch (Exception e) {
log.warn("Error parsing json object for user: {}", e.getMessage());
loginForm.setErrorMsg(ERR_SERVER_OVERLOAD);
return "login";
}
}
// triggered when user clicks "Forget Password?"
@RequestMapping("/password_reset_email")
public String passwordResetEmail(Model model) {
model.addAttribute("passwordResetRequestForm", new PasswordResetRequestForm());
return FORGET_PSWD_PAGE;
}
// triggered when user clicks "Send Reset Email" button
@PostMapping("/password_reset_request")
public String sendPasswordResetRequest(
@ModelAttribute("passwordResetRequestForm") PasswordResetRequestForm passwordResetRequestForm
) throws WebServiceRuntimeException {
String email = passwordResetRequestForm.getEmail();
if (!VALID_EMAIL_ADDRESS_REGEX.matcher(email).matches()) {
passwordResetRequestForm.setErrMsg("Please provide a valid email address");
return FORGET_PSWD_PAGE;
}
JSONObject obj = new JSONObject();
obj.put("username", email);
log.info("Connecting to sio for password reset email: {}", email);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(obj.toString(), headers);
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = null;
try {
response = restTemplate.exchange(properties.getPasswordResetRequestURI(), HttpMethod.POST, request, String.class);
} catch (RestClientException e) {
log.warn("Cannot connect to sio for password reset email: {}", e);
passwordResetRequestForm.setErrMsg("Cannot connect. Server may be down!");
return FORGET_PSWD_PAGE;
}
if (RestUtil.isError(response.getStatusCode())) {
log.warn("Server responded error for password reset email: {}", response.getStatusCode());
passwordResetRequestForm.setErrMsg("Email not registered. Please use a different email address.");
return FORGET_PSWD_PAGE;
}
log.info("Password reset email sent for {}", email);
return "password_reset_email_sent";
}
// triggered when user clicks password reset link in the email
@RequestMapping(path = "/passwordReset", params = {"key"})
public String passwordResetNewPassword(@NotNull @RequestParam("key") final String key, Model model) {
PasswordResetForm form = new PasswordResetForm();
form.setKey(key);
model.addAttribute("passwordResetForm", form);
// redirect to the page for user to enter new password
return FORGET_PSWD_NEW_PSWD_PAGE;
}
// actual call to sio to reset password
@RequestMapping(path = "/password_reset")
public String resetPassword(@ModelAttribute("passwordResetForm") PasswordResetForm passwordResetForm) throws IOException {
if (!passwordResetForm.isPasswordOk()) {
return FORGET_PSWD_NEW_PSWD_PAGE;
}
JSONObject obj = new JSONObject();
obj.put("key", passwordResetForm.getKey());
obj.put("new", passwordResetForm.getPassword1());
log.info("Connecting to sio for password reset, key = {}", passwordResetForm.getKey());
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(obj.toString(), headers);
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = null;
try {
response = restTemplate.exchange(properties.getPasswordResetURI(), HttpMethod.PUT, request, String.class);
} catch (RestClientException e) {
log.warn("Error connecting to sio for password reset! {}", e);
passwordResetForm.setErrMsg("Cannot connect to server! Please try again later.");
return FORGET_PSWD_NEW_PSWD_PAGE;
}
if (RestUtil.isError(response.getStatusCode())) {
EnumMap<ExceptionState, String> exceptionMessageMap = new EnumMap<>(ExceptionState.class);
exceptionMessageMap.put(PASSWORD_RESET_REQUEST_TIMEOUT_EXCEPTION, "Password reset request timed out. Please request a new reset email.");
exceptionMessageMap.put(PASSWORD_RESET_REQUEST_NOT_FOUND_EXCEPTION, "Invalid password reset request. Please request a new reset email.");
exceptionMessageMap.put(ADAPTER_CONNECTION_EXCEPTION, "Server-side error. Please contact " + CONTACT_EMAIL);
MyErrorResource error = objectMapper.readValue(response.getBody().toString(), MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
final String errMsg = exceptionMessageMap.get(exceptionState) == null ? ERR_SERVER_OVERLOAD : exceptionMessageMap.get(exceptionState);
passwordResetForm.setErrMsg(errMsg);
log.warn("Server responded error for password reset: {}", exceptionState.toString());
return FORGET_PSWD_NEW_PSWD_PAGE;
}
log.info("Password was reset, key = {}", passwordResetForm.getKey());
return "password_reset_success";
}
@RequestMapping("/dashboard")
public String dashboard(Model model, HttpSession session) throws WebServiceRuntimeException {
HttpEntity<String> request = createHttpEntityHeaderOnly();
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = restTemplate.exchange(properties.getDeterUid(session.getAttribute(webProperties.getSessionUserId()).toString()), HttpMethod.GET, request, String.class);
String responseBody = response.getBody().toString();
try {
if (RestUtil.isError(response.getStatusCode())) {
log.error("No user exists : {}", session.getAttribute(webProperties.getSessionUserId()));
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
model.addAttribute(DETER_UID, CONNECTION_ERROR);
} else {
log.info("Show the deter user id: {}", responseBody);
model.addAttribute(DETER_UID, responseBody);
}
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
// retrieve user dashboard stats
Map<String, Integer> userDashboardMap = getUserDashboardStats(session.getAttribute(webProperties.getSessionUserId()).toString());
List<TeamUsageInfo> usageInfoList = getTeamsUsageStatisticsForUser(session.getAttribute(webProperties.getSessionUserId()).toString());
model.addAttribute("userDashboardMap", userDashboardMap);
model.addAttribute("usageInfoList", usageInfoList);
return "dashboard";
}
@RequestMapping(value = "/logout", method = RequestMethod.GET)
public String logout(HttpSession session) {
removeSessionVariables(session);
return REDIRECT_INDEX_PAGE;
}
//--------------------------Sign Up Page--------------------------
@RequestMapping(value = "/signup2", method = RequestMethod.GET)
public String signup2(Model model, HttpServletRequest request) {
Map<String, ?> inputFlashMap = RequestContextUtils.getInputFlashMap(request);
if (inputFlashMap != null) {
log.debug((String) inputFlashMap.get(MESSAGE));
model.addAttribute("signUpMergedForm", (SignUpMergedForm) inputFlashMap.get("signUpMergedForm"));
} else {
log.debug("InputFlashMap is null");
model.addAttribute("signUpMergedForm", new SignUpMergedForm());
}
return "signup2";
}
@RequestMapping(value = "/signup2", method = RequestMethod.POST)
public String validateDetails(
@Valid
@ModelAttribute("signUpMergedForm") SignUpMergedForm signUpMergedForm,
BindingResult bindingResult,
final RedirectAttributes redirectAttributes) throws WebServiceRuntimeException {
if (bindingResult.hasErrors() || signUpMergedForm.getIsValid() == false) {
log.warn("Register form has errors {}", signUpMergedForm.toString());
return "signup2";
}
if (!signUpMergedForm.getHasAcceptTeamOwnerPolicy()) {
signUpMergedForm.setErrorTeamOwnerPolicy("Please accept the team owner policy");
log.warn("Policy not accepted");
return "signup2";
}
// get form fields
// craft the registration json
JSONObject mainObject = new JSONObject();
JSONObject credentialsFields = new JSONObject();
credentialsFields.put("username", signUpMergedForm.getEmail().trim());
credentialsFields.put("password", signUpMergedForm.getPassword());
// create the user JSON
JSONObject userFields = new JSONObject();
JSONObject userDetails = new JSONObject();
JSONObject addressDetails = new JSONObject();
userDetails.put("firstName", signUpMergedForm.getFirstName().trim());
userDetails.put("lastName", signUpMergedForm.getLastName().trim());
userDetails.put("jobTitle", signUpMergedForm.getJobTitle().trim());
userDetails.put("email", signUpMergedForm.getEmail().trim());
userDetails.put("phone", signUpMergedForm.getPhone().trim());
userDetails.put("institution", signUpMergedForm.getInstitution().trim());
userDetails.put("institutionAbbreviation", signUpMergedForm.getInstitutionAbbreviation().trim());
userDetails.put("institutionWeb", signUpMergedForm.getWebsite().trim());
userDetails.put("address", addressDetails);
addressDetails.put("address1", signUpMergedForm.getAddress1().trim());
addressDetails.put("address2", signUpMergedForm.getAddress2().trim());
addressDetails.put("country", signUpMergedForm.getCountry().trim());
addressDetails.put("region", signUpMergedForm.getProvince().trim());
addressDetails.put("city", signUpMergedForm.getCity().trim());
addressDetails.put("zipCode", signUpMergedForm.getPostalCode().trim());
userFields.put("userDetails", userDetails);
userFields.put(APPLICATION_DATE, ZonedDateTime.now());
JSONObject teamFields = new JSONObject();
// add all to main json
mainObject.put("credentials", credentialsFields);
mainObject.put("user", userFields);
mainObject.put("team", teamFields);
// check if user chose create new team or join existing team by checking team name
String createNewTeamName = signUpMergedForm.getTeamName().trim();
String joinNewTeamName = signUpMergedForm.getJoinTeamName().trim();
if (createNewTeamName != null && !createNewTeamName.isEmpty()) {
log.info("Signup new team name {}", createNewTeamName);
boolean errorsFound = false;
if (createNewTeamName.length() < 2 || createNewTeamName.length() > 12) {
errorsFound = true;
signUpMergedForm.setErrorTeamName("Team name must be 2 to 12 alphabetic/numeric characters");
}
if (signUpMergedForm.getTeamDescription() == null || signUpMergedForm.getTeamDescription().isEmpty()) {
errorsFound = true;
signUpMergedForm.setErrorTeamDescription("Team description cannot be empty");
}
if (signUpMergedForm.getTeamWebsite() == null || signUpMergedForm.getTeamWebsite().isEmpty()) {
errorsFound = true;
signUpMergedForm.setErrorTeamWebsite("Team website cannot be empty");
}
if (errorsFound) {
log.warn("Signup new team error {}", signUpMergedForm.toString());
// clear join team name first before submitting the form
signUpMergedForm.setJoinTeamName(null);
return "signup2";
} else {
teamFields.put("name", signUpMergedForm.getTeamName().trim());
teamFields.put("description", signUpMergedForm.getTeamDescription().trim());
teamFields.put("website", signUpMergedForm.getTeamWebsite().trim());
teamFields.put("organisationType", signUpMergedForm.getTeamOrganizationType());
teamFields.put("visibility", signUpMergedForm.getIsPublic());
mainObject.put("isJoinTeam", false);
try {
registerUserToDeter(mainObject);
} catch (
TeamNotFoundException |
TeamNameAlreadyExistsException |
UsernameAlreadyExistsException |
EmailAlreadyExistsException |
InvalidTeamNameException |
InvalidPasswordException |
DeterLabOperationFailedException e) {
redirectAttributes.addFlashAttribute(MESSAGE, e.getMessage());
redirectAttributes.addFlashAttribute("signUpMergedForm", signUpMergedForm);
return "redirect:/signup2";
} catch (Exception e) {
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
redirectAttributes.addFlashAttribute("signUpMergedForm", signUpMergedForm);
return "redirect:/signup2";
}
log.info("Signup new team success");
return "redirect:/team_application_submitted";
}
} else if (joinNewTeamName != null && !joinNewTeamName.isEmpty()) {
log.info("Signup join team name {}", joinNewTeamName);
// get the team JSON from team name
Team2 joinTeamInfo;
try {
joinTeamInfo = getTeamIdByName(signUpMergedForm.getJoinTeamName().trim());
} catch (TeamNotFoundException | AdapterConnectionException e) {
redirectAttributes.addFlashAttribute(MESSAGE, e.getMessage());
redirectAttributes.addFlashAttribute("signUpMergedForm", signUpMergedForm);
return "redirect:/signup2";
}
teamFields.put("id", joinTeamInfo.getId());
// set the flag to indicate to controller that it is joining an existing team
mainObject.put("isJoinTeam", true);
try {
registerUserToDeter(mainObject);
} catch (
TeamNotFoundException |
AdapterConnectionException |
TeamNameAlreadyExistsException |
UsernameAlreadyExistsException |
EmailAlreadyExistsException |
InvalidTeamNameException |
InvalidPasswordException |
DeterLabOperationFailedException e) {
redirectAttributes.addFlashAttribute(MESSAGE, e.getMessage());
redirectAttributes.addFlashAttribute("signUpMergedForm", signUpMergedForm);
return "redirect:/signup2";
} catch (Exception e) {
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
redirectAttributes.addFlashAttribute("signUpMergedForm", signUpMergedForm);
return "redirect:/signup2";
}
log.info("Signup join team success");
log.info("jointeam info: {}", joinTeamInfo);
redirectAttributes.addFlashAttribute("team", joinTeamInfo);
return "redirect:/join_application_submitted";
} else {
log.warn("Signup unreachable statement");
// logic error not suppose to reach here
// possible if user fill up create new team but without the team name
redirectAttributes.addFlashAttribute("signupError", "There is a problem when submitting your form. Please re-enter and submit the details again.");
redirectAttributes.addFlashAttribute("signUpMergedForm", signUpMergedForm);
return "redirect:/signup2";
}
}
/**
* Use when registering new accounts
*
* @param mainObject A JSONObject that contains user's credentials, personal details and team application details
*/
private void registerUserToDeter(JSONObject mainObject) throws
WebServiceRuntimeException,
TeamNotFoundException,
AdapterConnectionException,
TeamNameAlreadyExistsException,
UsernameAlreadyExistsException,
EmailAlreadyExistsException,
InvalidTeamNameException,
InvalidPasswordException,
DeterLabOperationFailedException {
HttpEntity<String> request = createHttpEntityWithBodyNoAuthHeader(mainObject.toString());
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = restTemplate.exchange(properties.getSioRegUrl(), HttpMethod.POST, request, String.class);
String responseBody = response.getBody().toString();
log.info("Register user to deter response: {}", responseBody);
try {
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
log.warn("Register user exception error: {}", error.getError());
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case DETERLAB_OPERATION_FAILED_EXCEPTION:
log.warn("Register new user failed on DeterLab: {}", error.getMessage());
throw new DeterLabOperationFailedException(ERROR_PREFIX + (error.getMessage().contains("unknown error") ? ERR_SERVER_OVERLOAD : error.getMessage()));
case TEAM_NAME_ALREADY_EXISTS_EXCEPTION:
log.warn("Register new users new team request : team name already exists");
throw new TeamNameAlreadyExistsException("Team name already exists");
case INVALID_TEAM_NAME_EXCEPTION:
log.warn("Register new users new team request : team name invalid");
throw new InvalidTeamNameException("Invalid team name: must be 6-12 alphanumeric characters only");
case INVALID_PASSWORD_EXCEPTION:
log.warn("Register new users new team request : invalid password");
throw new InvalidPasswordException("Password is too simple");
case USERNAME_ALREADY_EXISTS_EXCEPTION:
// throw from user service
{
String email = mainObject.getJSONObject("user").getJSONObject("userDetails").getString("email");
log.warn("Register new users : email already exists: {}", email);
throw new UsernameAlreadyExistsException(ERROR_PREFIX + email + " already in use.");
}
case EMAIL_ALREADY_EXISTS_EXCEPTION:
// throw from adapter deterlab
{
String email = mainObject.getJSONObject("user").getJSONObject("userDetails").getString("email");
log.warn("Register new users : email already exists: {}", email);
throw new EmailAlreadyExistsException(ERROR_PREFIX + email + " already in use.");
}
default:
log.warn("Registration or adapter connection fail");
// possible sio or adapter connection fail
throw new AdapterConnectionException(ERR_SERVER_OVERLOAD);
}
} else {
// do nothing
log.info("Not an error for status code: {}", response.getStatusCode());
}
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
}
/**
* Use when users register a new account for joining existing team
*
* @param teamName The team name to join
* @return the team id from sio
*/
private Team2 getTeamIdByName(String teamName) throws WebServiceRuntimeException, TeamNotFoundException, AdapterConnectionException {
// FIXME check if team name exists
// FIXME check for general exception?
HttpEntity<String> request = createHttpEntityHeaderOnlyNoAuthHeader();
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = restTemplate.exchange(properties.getTeamByName(teamName), HttpMethod.GET, request, String.class);
String responseBody = response.getBody().toString();
try {
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
if (exceptionState == ExceptionState.TEAM_NOT_FOUND_EXCEPTION) {
log.warn("Get team by name : team name error");
throw new TeamNotFoundException("Team name " + teamName + " does not exists");
} else {
log.warn("Team service or adapter connection fail");
// possible sio or adapter connection fail
throw new AdapterConnectionException(ERR_SERVER_OVERLOAD);
}
} else {
return extractTeamInfo(responseBody);
}
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
}
//--------------------------Account Settings Page--------------------------
@RequestMapping(value = "/account_settings", method = RequestMethod.GET)
public String accountDetails(Model model, HttpSession session) throws WebServiceRuntimeException {
String userId_uri = properties.getSioUsersUrl() + session.getAttribute("id");
HttpEntity<String> request = createHttpEntityHeaderOnly();
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = restTemplate.exchange(userId_uri, HttpMethod.GET, request, String.class);
String responseBody = response.getBody().toString();
try {
if (RestUtil.isError(response.getStatusCode())) {
log.error("No user to edit : {}", session.getAttribute("id"));
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
throw new RestClientException("[" + error.getError() + "] ");
} else {
User2 user2 = extractUserInfo(responseBody);
// need to do this so that we can compare after submitting the form
session.setAttribute(webProperties.getSessionUserAccount(), user2);
model.addAttribute("editUser", user2);
return "account_settings";
}
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
}
@RequestMapping(value = "/account_settings", method = RequestMethod.POST)
public String editAccountDetails(
@ModelAttribute("editUser") User2 editUser,
final RedirectAttributes redirectAttributes,
HttpSession session) throws WebServiceRuntimeException {
boolean errorsFound = false;
String editPhrase = "editPhrase";
// check fields first
if (errorsFound == false && editUser.getFirstName().isEmpty()) {
redirectAttributes.addFlashAttribute("editFirstName", "fail");
errorsFound = true;
}
if (errorsFound == false && editUser.getLastName().isEmpty()) {
redirectAttributes.addFlashAttribute("editLastName", "fail");
errorsFound = true;
}
if (errorsFound == false && editUser.getPhone().isEmpty()) {
redirectAttributes.addFlashAttribute("editPhone", "fail");
errorsFound = true;
}
if (errorsFound == false && (editUser.getPhone().matches("(.*)[a-zA-Z](.*)") || editUser.getPhone().length() < 6)) {
// previously already check if phone is empty
// now check phone must contain only digits
redirectAttributes.addFlashAttribute("editPhone", "fail");
errorsFound = true;
}
if (errorsFound == false && !editUser.getConfirmPassword().isEmpty() && !editUser.isPasswordValid()) {
redirectAttributes.addFlashAttribute(editPhrase, "invalid");
errorsFound = true;
}
if (errorsFound == false && editUser.getJobTitle().isEmpty()) {
redirectAttributes.addFlashAttribute("editJobTitle", "fail");
errorsFound = true;
}
if (errorsFound == false && editUser.getInstitution().isEmpty()) {
redirectAttributes.addFlashAttribute("editInstitution", "fail");
errorsFound = true;
}
if (errorsFound == false && editUser.getCountry().isEmpty()) {
redirectAttributes.addFlashAttribute("editCountry", "fail");
errorsFound = true;
}
if (errorsFound) {
session.removeAttribute(webProperties.getSessionUserAccount());
return "redirect:/account_settings";
} else {
// used to compare original and edited User2 objects
User2 originalUser = (User2) session.getAttribute(webProperties.getSessionUserAccount());
JSONObject userObject = new JSONObject();
JSONObject userDetails = new JSONObject();
JSONObject address = new JSONObject();
userDetails.put("firstName", editUser.getFirstName());
userDetails.put("lastName", editUser.getLastName());
userDetails.put("email", editUser.getEmail());
userDetails.put("phone", editUser.getPhone());
userDetails.put("jobTitle", editUser.getJobTitle());
userDetails.put("address", address);
userDetails.put("institution", editUser.getInstitution());
userDetails.put("institutionAbbreviation", originalUser.getInstitutionAbbreviation());
userDetails.put("institutionWeb", originalUser.getInstitutionWeb());
address.put("address1", originalUser.getAddress1());
address.put("address2", originalUser.getAddress2());
address.put("country", editUser.getCountry());
address.put("city", originalUser.getCity());
address.put("region", originalUser.getRegion());
address.put("zipCode", originalUser.getPostalCode());
userObject.put("userDetails", userDetails);
String userId_uri = properties.getSioUsersUrl() + session.getAttribute(webProperties.getSessionUserId());
HttpEntity<String> request = createHttpEntityWithBody(userObject.toString());
restTemplate.exchange(userId_uri, HttpMethod.PUT, request, String.class);
if (!originalUser.getFirstName().equals(editUser.getFirstName())) {
redirectAttributes.addFlashAttribute("editFirstName", "success");
}
if (!originalUser.getLastName().equals(editUser.getLastName())) {
redirectAttributes.addFlashAttribute("editLastName", "success");
}
if (!originalUser.getPhone().equals(editUser.getPhone())) {
redirectAttributes.addFlashAttribute("editPhone", "success");
}
if (!originalUser.getJobTitle().equals(editUser.getJobTitle())) {
redirectAttributes.addFlashAttribute("editJobTitle", "success");
}
if (!originalUser.getInstitution().equals(editUser.getInstitution())) {
redirectAttributes.addFlashAttribute("editInstitution", "success");
}
if (!originalUser.getCountry().equals(editUser.getCountry())) {
redirectAttributes.addFlashAttribute("editCountry", "success");
}
// credential service change password
if (editUser.isPasswordMatch()) {
JSONObject credObject = new JSONObject();
credObject.put("password", editUser.getPassword());
HttpEntity<String> credRequest = createHttpEntityWithBody(credObject.toString());
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = restTemplate.exchange(properties.getUpdateCredentials(session.getAttribute("id").toString()), HttpMethod.PUT, credRequest, String.class);
String responseBody = response.getBody().toString();
try {
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
redirectAttributes.addFlashAttribute(editPhrase, "fail");
} else {
redirectAttributes.addFlashAttribute(editPhrase, "success");
}
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
} finally {
session.removeAttribute(webProperties.getSessionUserAccount());
}
}
}
return "redirect:/account_settings";
}
//--------------------User Side Approve Members Page------------
@RequestMapping("/approve_new_user")
public String approveNewUser(Model model, HttpSession session) throws Exception {
// HashMap<Integer, Team> rv = new HashMap<Integer, Team>();
// rv = teamManager.getTeamMapByTeamOwner(getSessionIdOfLoggedInUser(session));
// boolean userHasAnyJoinRequest = hasAnyJoinRequest(rv);
// model.addAttribute("teamMapOwnedByUser", rv);
// model.addAttribute("userHasAnyJoinRequest", userHasAnyJoinRequest);
List<JoinRequestApproval> rv = new ArrayList<>();
List<JoinRequestApproval> temp;
// get list of teamids
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response = restTemplate.exchange(properties.getUser(session.getAttribute("id").toString()), HttpMethod.GET, request, String.class);
String responseBody = response.getBody().toString();
JSONObject object = new JSONObject(responseBody);
JSONArray teamIdsJsonArray = object.getJSONArray("teams");
for (int i = 0; i < teamIdsJsonArray.length(); i++) {
String teamId = teamIdsJsonArray.get(i).toString();
HttpEntity<String> teamRequest = createHttpEntityHeaderOnly();
ResponseEntity teamResponse = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, teamRequest, String.class);
String teamResponseBody = teamResponse.getBody().toString();
Team2 team2 = new Team2();
JSONObject teamObject = new JSONObject(teamResponseBody);
JSONArray membersArray = teamObject.getJSONArray("members");
team2.setId(teamObject.getString("id"));
team2.setName(teamObject.getString("name"));
boolean isTeamLeader = false;
temp = new ArrayList<>();
for (int j = 0; j < membersArray.length(); j++) {
JSONObject memberObject = membersArray.getJSONObject(j);
String userId = memberObject.getString("userId");
String teamMemberType = memberObject.getString(MEMBER_TYPE);
String teamMemberStatus = memberObject.getString("memberStatus");
String teamJoinedDate = formatZonedDateTime(memberObject.get("joinedDate").toString());
JoinRequestApproval joinRequestApproval = new JoinRequestApproval();
if (userId.equals(session.getAttribute("id").toString()) && teamMemberType.equals(MemberType.OWNER.toString())) {
isTeamLeader = true;
}
if (teamMemberStatus.equals(MemberStatus.PENDING.toString()) && teamMemberType.equals(MemberType.MEMBER.toString())) {
User2 myUser = invokeAndExtractUserInfo(userId);
joinRequestApproval.setUserId(myUser.getId());
joinRequestApproval.setUserEmail(myUser.getEmail());
joinRequestApproval.setUserName(myUser.getFirstName() + " " + myUser.getLastName());
joinRequestApproval.setApplicationDate(teamJoinedDate);
joinRequestApproval.setTeamId(team2.getId());
joinRequestApproval.setTeamName(team2.getName());
joinRequestApproval.setVerified(myUser.getEmailVerified());
temp.add(joinRequestApproval);
log.info("Join request: UserId: {}, UserEmail: {}", myUser.getId(), myUser.getEmail());
}
}
if (isTeamLeader) {
if (!temp.isEmpty()) {
rv.addAll(temp);
}
}
}
model.addAttribute("joinApprovalList", rv);
return "approve_new_user";
}
@RequestMapping("/approve_new_user/accept/{teamId}/{userId}")
public String userSideAcceptJoinRequest(
@PathVariable String teamId,
@PathVariable String userId,
HttpSession session,
RedirectAttributes redirectAttributes) throws WebServiceRuntimeException {
log.info("Approve join request: User {}, Team {}, Approver {}",
userId, teamId, session.getAttribute("id").toString());
JSONObject mainObject = new JSONObject();
JSONObject userFields = new JSONObject();
userFields.put("id", session.getAttribute("id").toString());
mainObject.put("user", userFields);
HttpEntity<String> request = createHttpEntityWithBody(mainObject.toString());
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getApproveJoinRequest(teamId, userId), HttpMethod.POST, request, String.class);
} catch (RestClientException e) {
log.warn("Error connecting to sio team service: {}", e);
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
return "redirect:/approve_new_user";
}
String responseBody = response.getBody().toString();
if (RestUtil.isError(response.getStatusCode())) {
try {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case EMAIL_NOT_VERIFIED_EXCEPTION:
log.warn("Approve join request: User {} email not verified", userId);
redirectAttributes.addFlashAttribute(MESSAGE, "User email has not been verified");
break;
case DETERLAB_OPERATION_FAILED_EXCEPTION:
log.warn("Approve join request: User {}, Team {} fail", userId, teamId);
redirectAttributes.addFlashAttribute(MESSAGE, "Approve join request fail");
break;
default:
log.warn("Server side error: {}", error.getError());
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
break;
}
return "redirect:/approve_new_user";
} catch (IOException ioe) {
log.warn("IOException {}", ioe);
throw new WebServiceRuntimeException(ioe.getMessage());
}
}
// everything looks OK?
log.info("Join request has been APPROVED, User {}, Team {}", userId, teamId);
redirectAttributes.addFlashAttribute(MESSAGE_SUCCESS, "Join request has been APPROVED.");
return "redirect:/approve_new_user";
}
@RequestMapping("/approve_new_user/reject/{teamId}/{userId}")
public String userSideRejectJoinRequest(
@PathVariable String teamId,
@PathVariable String userId,
HttpSession session,
RedirectAttributes redirectAttributes) throws WebServiceRuntimeException {
log.info("Reject join request: User {}, Team {}, Approver {}",
userId, teamId, session.getAttribute("id").toString());
JSONObject mainObject = new JSONObject();
JSONObject userFields = new JSONObject();
userFields.put("id", session.getAttribute("id").toString());
mainObject.put("user", userFields);
HttpEntity<String> request = createHttpEntityWithBody(mainObject.toString());
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getRejectJoinRequest(teamId, userId), HttpMethod.DELETE, request, String.class);
} catch (RestClientException e) {
log.warn("Error connecting to sio team service: {}", e);
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
return "redirect:/approve_new_user";
}
String responseBody = response.getBody().toString();
if (RestUtil.isError(response.getStatusCode())) {
try {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case DETERLAB_OPERATION_FAILED_EXCEPTION:
log.warn("Reject join request: User {}, Team {} fail", userId, teamId);
redirectAttributes.addFlashAttribute(MESSAGE, "Reject join request fail");
break;
default:
log.warn("Server side error: {}", error.getError());
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
break;
}
return "redirect:/approve_new_user";
} catch (IOException ioe) {
log.warn("IOException {}", ioe);
throw new WebServiceRuntimeException(ioe.getMessage());
}
}
// everything looks OK?
log.info("Join request has been REJECTED, User {}, Team {}", userId, teamId);
redirectAttributes.addFlashAttribute(MESSAGE, "Join request has been REJECTED.");
return "redirect:/approve_new_user";
}
//--------------------------Teams Page--------------------------
@RequestMapping("/public_teams")
public String publicTeamsBeforeLogin(Model model) {
TeamManager2 teamManager2 = new TeamManager2();
// get public teams
HttpEntity<String> teamRequest = createHttpEntityHeaderOnlyNoAuthHeader();
ResponseEntity teamResponse = restTemplate.exchange(properties.getTeamsByVisibility(TeamVisibility.PUBLIC.toString()), HttpMethod.GET, teamRequest, String.class);
String teamResponseBody = teamResponse.getBody().toString();
JSONArray teamPublicJsonArray = new JSONArray(teamResponseBody);
for (int i = 0; i < teamPublicJsonArray.length(); i++) {
JSONObject teamInfoObject = teamPublicJsonArray.getJSONObject(i);
Team2 team2 = extractTeamInfo(teamInfoObject.toString());
teamManager2.addTeamToPublicTeamMap(team2);
}
model.addAttribute("publicTeamMap2", teamManager2.getPublicTeamMap());
return "public_teams";
}
@RequestMapping("/teams")
public String teams(Model model, HttpSession session) {
// int currentLoggedInUserId = getSessionIdOfLoggedInUser(session);
// model.addAttribute("infoMsg", teamManager.getInfoMsg());
// model.addAttribute("currentLoggedInUserId", currentLoggedInUserId);
// model.addAttribute("teamMap", teamManager.getTeamMap(currentLoggedInUserId));
// model.addAttribute("publicTeamMap", teamManager.getPublicTeamMap());
// model.addAttribute("invitedToParticipateMap2", teamManager.getInvitedToParticipateMap2(currentLoggedInUserId));
// model.addAttribute("joinRequestMap2", teamManager.getJoinRequestTeamMap2(currentLoggedInUserId));
TeamManager2 teamManager2 = new TeamManager2();
// stores the list of images created or in progress of creation by teams
// e.g. teamNameA : "created" : [imageA, imageB], "inProgress" : [imageC, imageD]
Map<String, Map<String, List<Image>>> imageMap = new HashMap<>();
// get list of teamids
String userId = session.getAttribute("id").toString();
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response = restTemplate.exchange(properties.getUser(userId), HttpMethod.GET, request, String.class);
String responseBody = response.getBody().toString();
JSONObject object = new JSONObject(responseBody);
JSONArray teamIdsJsonArray = object.getJSONArray("teams");
String userEmail = object.getJSONObject("userDetails").getString("email");
for (int i = 0; i < teamIdsJsonArray.length(); i++) {
String teamId = teamIdsJsonArray.get(i).toString();
HttpEntity<String> teamRequest = createHttpEntityHeaderOnly();
ResponseEntity teamResponse = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, teamRequest, String.class);
String teamResponseBody = teamResponse.getBody().toString();
//Tran: check if team is approved for userId
Team2 joinRequestTeam = extractTeamInfoUserJoinRequest(userId, teamResponseBody);
if (joinRequestTeam != null) {
teamManager2.addTeamToUserJoinRequestTeamMap(joinRequestTeam);
} else {
Team2 team2 = extractTeamInfo(teamResponseBody);
teamManager2.addTeamToTeamMap(team2);
imageMap.put(team2.getName(), invokeAndGetImageList(teamId)); //Tran : only retrieve images of approved teams
}
}
// check if inner image map is empty, have to do it via this manner
// returns true if the team contains an image list
boolean isInnerImageMapPresent = imageMap.values().stream().filter(perTeamImageMap -> !perTeamImageMap.isEmpty()).findFirst().isPresent();
model.addAttribute("userEmail", userEmail);
model.addAttribute("teamMap2", teamManager2.getTeamMap());
model.addAttribute("userJoinRequestMap", teamManager2.getUserJoinRequestMap());
model.addAttribute("isInnerImageMapPresent", isInnerImageMapPresent);
model.addAttribute("imageMap", imageMap);
return "teams";
}
/**
* Exectues the service-image and returns a Map containing the list of images in two partitions.
* One partition contains the list of already created images.
* The other partition contains the list of currently saving in progress images.
*
* @param teamId The ncl team id to retrieve the list of images from.
* @return Returns a Map containing the list of images in two partitions.
*/
private Map<String, List<Image>> invokeAndGetImageList(String teamId) {
log.info("Getting list of saved images for team {}", teamId);
Map<String, List<Image>> resultMap = new HashMap<>();
List<Image> createdImageList = new ArrayList<>();
List<Image> inProgressImageList = new ArrayList<>();
HttpEntity<String> imageRequest = createHttpEntityHeaderOnly();
ResponseEntity imageResponse;
try {
imageResponse = restTemplate.exchange(properties.getTeamSavedImages(teamId), HttpMethod.GET, imageRequest, String.class);
} catch (ResourceAccessException e) {
log.warn("Error connecting to image service: {}", e);
return new HashMap<>();
}
String imageResponseBody = imageResponse.getBody().toString();
String osImageList = new JSONObject(imageResponseBody).getString(teamId);
JSONObject osImageObject = new JSONObject(osImageList);
log.debug("osImageList: {}", osImageList);
log.debug("osImageObject: {}", osImageObject);
if (osImageObject == JSONObject.NULL || osImageObject.length() == 0) {
log.info("List of saved images for team {} is empty.", teamId);
return resultMap;
}
for (int k = 0; k < osImageObject.names().length(); k++) {
String imageName = osImageObject.names().getString(k);
String imageStatus = osImageObject.getString(imageName);
log.info("Image list for team {}: image name {}, status {}", teamId, imageName, imageStatus);
Image image = new Image();
image.setImageName(imageName);
image.setDescription("-");
image.setTeamId(teamId);
if ("created".equals(imageStatus)) {
createdImageList.add(image);
} else if ("notfound".equals(imageStatus)) {
inProgressImageList.add(image);
}
}
resultMap.put("created", createdImageList);
resultMap.put("inProgress", inProgressImageList);
return resultMap;
}
// @RequestMapping("/accept_participation/{teamId}")
// public String acceptParticipationRequest(@PathVariable Integer teamId, Model model, HttpSession session) {
// int currentLoggedInUserId = getSessionIdOfLoggedInUser(session);
// // get user's participation request list
// // add this user id to the requested list
// teamManager.acceptParticipationRequest(currentLoggedInUserId, teamId);
// // remove participation request since accepted
// teamManager.removeParticipationRequest(currentLoggedInUserId, teamId);
//
// // must get team name
// String teamName = teamManager.getTeamNameByTeamId(teamId);
// teamManager.setInfoMsg("You have just joined Team " + teamName + " !");
//
// return "redirect:/teams";
// }
// @RequestMapping("/ignore_participation/{teamId}")
// public String ignoreParticipationRequest(@PathVariable Integer teamId, Model model, HttpSession session) {
// // get user's participation request list
// // remove this user id from the requested list
// String teamName = teamManager.getTeamNameByTeamId(teamId);
// teamManager.ignoreParticipationRequest2(getSessionIdOfLoggedInUser(session), teamId);
// teamManager.setInfoMsg("You have just ignored a team request from Team " + teamName + " !");
//
// return "redirect:/teams";
// }
// @RequestMapping("/withdraw/{teamId}")
public String withdrawnJoinRequest(@PathVariable Integer teamId, HttpSession session) {
// get user team request
// remove this user id from the user's request list
String teamName = teamManager.getTeamNameByTeamId(teamId);
teamManager.removeUserJoinRequest2(getSessionIdOfLoggedInUser(session), teamId);
teamManager.setInfoMsg("You have withdrawn your join request for Team " + teamName);
return "redirect:/teams";
}
// @RequestMapping(value="/teams/invite_members/{teamId}", method=RequestMethod.GET)
// public String inviteMember(@PathVariable Integer teamId, Model model) {
// model.addAttribute("teamIdVar", teamId);
// model.addAttribute("teamPageInviteMemberForm", new TeamPageInviteMemberForm());
// return "team_page_invite_members";
// }
// @RequestMapping(value="/teams/invite_members/{teamId}", method=RequestMethod.POST)
// public String sendInvitation(@PathVariable Integer teamId, @ModelAttribute TeamPageInviteMemberForm teamPageInviteMemberForm,Model model) {
// int userId = userManager.getUserIdByEmail(teamPageInviteMemberForm.getInviteUserEmail());
// teamManager.addInvitedToParticipateMap(userId, teamId);
// return "redirect:/teams";
// }
@RequestMapping(value = "/teams/members_approval/{teamId}", method = RequestMethod.GET)
public String membersApproval(@PathVariable Integer teamId, Model model) {
model.addAttribute("team", teamManager.getTeamByTeamId(teamId));
return "team_page_approve_members";
}
@RequestMapping("/teams/members_approval/accept/{teamId}/{userId}")
public String acceptJoinRequest(@PathVariable Integer teamId, @PathVariable Integer userId) {
teamManager.acceptJoinRequest(userId, teamId);
return "redirect:/teams/members_approval/{teamId}";
}
@RequestMapping("/teams/members_approval/reject/{teamId}/{userId}")
public String rejectJoinRequest(@PathVariable Integer teamId, @PathVariable Integer userId) {
teamManager.rejectJoinRequest(userId, teamId);
return "redirect:/teams/members_approval/{teamId}";
}
//--------------------------Team Profile Page--------------------------
@RequestMapping(value = "/team_profile/{teamId}", method = RequestMethod.GET)
public String teamProfile(@PathVariable String teamId, Model model, final RedirectAttributes redirectAttributes, HttpSession session) throws IOException {
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, request, String.class);
String responseBody = response.getBody().toString();
Team2 team = extractTeamInfo(responseBody);
model.addAttribute("team", team);
model.addAttribute("owner", team.getOwner());
model.addAttribute("membersList", team.getMembersStatusMap().get(MemberStatus.APPROVED));
session.setAttribute("originalTeam", team);
request = createHttpEntityHeaderOnly();
response = restTemplate.exchange(properties.getExpListByTeamId(teamId), HttpMethod.GET, request, String.class);
JSONArray experimentsArray = new JSONArray(response.getBody().toString());
List<Experiment2> experimentList = new ArrayList<>();
Map<Long, Realization> realizationMap = new HashMap<>();
for (int k = 0; k < experimentsArray.length(); k++) {
Experiment2 experiment2 = extractExperiment(experimentsArray.getJSONObject(k).toString());
Realization realization = invokeAndExtractRealization(experiment2.getTeamName(), experiment2.getId());
realizationMap.put(experiment2.getId(), realization);
experimentList.add(experiment2);
}
model.addAttribute("teamExperimentList", experimentList);
model.addAttribute("teamRealizationMap", realizationMap);
//Starting to get quota
try {
response = restTemplate.exchange(properties.getQuotaByTeamId(teamId), HttpMethod.GET, request, String.class);
} catch (RestClientException e) {
log.warn("Error connecting to sio team service for display team quota: {}", e);
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
return REDIRECT_TEAM_PROFILE_TEAM_ID;
}
responseBody = response.getBody().toString();
// handling exceptions from SIO
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case TEAM_NOT_FOUND_EXCEPTION:
log.warn("Get team quota: Team {} not found", teamId);
return REDIRECT_INDEX_PAGE;
default:
log.warn("Get team quota : sio or deterlab adapter connection error");
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
break;
}
} else {
log.info("Get team quota info : {}", responseBody);
}
TeamQuota teamQuota = extractTeamQuotaInfo(responseBody);
model.addAttribute("teamQuota", teamQuota);
session.setAttribute(ORIGINAL_BUDGET, teamQuota.getBudget()); // this is to check if budget changed later
return "team_profile";
}
@RequestMapping(value = "/team_profile/{teamId}", method = RequestMethod.POST)
public String editTeamProfile(
@PathVariable String teamId,
@ModelAttribute("team") Team2 editTeam,
final RedirectAttributes redirectAttributes,
HttpSession session) {
boolean errorsFound = false;
if (editTeam.getDescription().isEmpty()) {
errorsFound = true;
redirectAttributes.addFlashAttribute("editDesc", "fail");
}
if (errorsFound) {
// safer to remove
session.removeAttribute("originalTeam");
return REDIRECT_TEAM_PROFILE + editTeam.getId();
}
// can edit team description and team website for now
JSONObject teamfields = new JSONObject();
teamfields.put("id", teamId);
teamfields.put("name", editTeam.getName());
teamfields.put("description", editTeam.getDescription());
teamfields.put("website", "http://default.com");
teamfields.put("organisationType", editTeam.getOrganisationType());
teamfields.put("privacy", "OPEN");
teamfields.put("status", editTeam.getStatus());
teamfields.put("members", editTeam.getMembersList());
HttpEntity<String> request = createHttpEntityWithBody(teamfields.toString());
ResponseEntity response = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.PUT, request, String.class);
Team2 originalTeam = (Team2) session.getAttribute("originalTeam");
if (!originalTeam.getDescription().equals(editTeam.getDescription())) {
redirectAttributes.addFlashAttribute("editDesc", "success");
}
// safer to remove
session.removeAttribute("originalTeam");
return REDIRECT_TEAM_PROFILE + teamId;
}
@RequestMapping(value = "/team_quota/{teamId}", method = RequestMethod.POST)
public String editTeamQuota(
@PathVariable String teamId,
@ModelAttribute("teamQuota") TeamQuota editTeamQuota,
final RedirectAttributes redirectAttributes,
HttpSession session) throws IOException {
final String QUOTA = "#quota";
JSONObject teamQuotaJSONObject = new JSONObject();
teamQuotaJSONObject.put(TEAM_ID, teamId);
// check if budget is negative or exceeding limit
if (!editTeamQuota.getBudget().equals("")) {
if (Double.parseDouble(editTeamQuota.getBudget()) < 0) {
redirectAttributes.addFlashAttribute(EDIT_BUDGET, "negativeError");
return REDIRECT_TEAM_PROFILE + teamId + QUOTA;
} else if(Double.parseDouble(editTeamQuota.getBudget()) > 99999999.99) {
redirectAttributes.addFlashAttribute(EDIT_BUDGET, "exceedingLimit");
return REDIRECT_TEAM_PROFILE + teamId + QUOTA;
}
}
teamQuotaJSONObject.put("quota", editTeamQuota.getBudget());
HttpEntity<String> request = createHttpEntityWithBody(teamQuotaJSONObject.toString());
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getQuotaByTeamId(teamId), HttpMethod.PUT, request, String.class);
} catch (RestClientException e) {
log.warn("Error connecting to sio team service for display team quota: {}", e);
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
return REDIRECT_TEAM_PROFILE_TEAM_ID;
}
String responseBody = response.getBody().toString();
// handling exceptions from SIO
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case TEAM_NOT_FOUND_EXCEPTION:
log.warn("Get team quota: Team {} not found", teamId);
return REDIRECT_INDEX_PAGE;
case TEAM_QUOTA_OUT_OF_RANGE_EXCEPTION:
log.warn("Get team quota: Budget is out of range");
return REDIRECT_TEAM_PROFILE + teamId + QUOTA;
case FORBIDDEN_EXCEPTION:
log.warn("Get team quota: Budget can only be updated by team owner.");
redirectAttributes.addFlashAttribute(EDIT_BUDGET, "editDeny");
return REDIRECT_TEAM_PROFILE + teamId + QUOTA;
default:
log.warn("Get team quota : sio or deterlab adapter connection error");
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
return REDIRECT_TEAM_PROFILE + teamId + QUOTA;
}
} else {
log.info("Edit team quota info : {}", responseBody);
}
//check if new budget is different in order to display successful message to user
String originalBudget = (String) session.getAttribute(ORIGINAL_BUDGET);
if (!originalBudget.equals(editTeamQuota.getBudget())) {
redirectAttributes.addFlashAttribute(EDIT_BUDGET, "success");
}
// safer to remove
session.removeAttribute(ORIGINAL_BUDGET);
return REDIRECT_TEAM_PROFILE + teamId + QUOTA;
}
@RequestMapping("/remove_member/{teamId}/{userId}")
public String removeMember(@PathVariable String teamId, @PathVariable String userId, final RedirectAttributes redirectAttributes) throws IOException {
JSONObject teamMemberFields = new JSONObject();
teamMemberFields.put("userId", userId);
teamMemberFields.put(MEMBER_TYPE, MemberType.MEMBER.name());
teamMemberFields.put("memberStatus", MemberStatus.APPROVED.name());
HttpEntity<String> request = createHttpEntityWithBody(teamMemberFields.toString());
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response;
try {
response = restTemplate.exchange(properties.removeUserFromTeam(teamId), HttpMethod.DELETE, request, String.class);
} catch (RestClientException e) {
log.warn("Error connecting to sio team service for remove user: {}", e);
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
return REDIRECT_TEAM_PROFILE_TEAM_ID;
}
String responseBody = response.getBody().toString();
User2 user = invokeAndExtractUserInfo(userId);
String name = user.getFirstName() + " " + user.getLastName();
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case DETERLAB_OPERATION_FAILED_EXCEPTION:
// two subcases when fail to remove users from team
log.warn("Remove member from team: User {}, Team {} fail - {}", userId, teamId, error.getMessage());
if ("user has experiments".equals(error.getMessage())) {
// case 1 - user has experiments
// display the list of experiments that have to be terminated first
// since the team profile page has experiments already, we don't have to retrieve them again
// use the userid to filter out the experiment list at the web pages
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + " Member " + name + " has experiments.");
redirectAttributes.addFlashAttribute(REMOVE_MEMBER_UID, userId);
redirectAttributes.addFlashAttribute(REMOVE_MEMBER_NAME, name);
break;
} else {
// case 2 - deterlab operation failure
log.warn("Remove member from team: deterlab operation failed");
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + " Member " + name + " cannot be removed.");
break;
}
default:
log.warn("Server side error for remove members: {}", error.getError());
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
break;
}
} else {
log.info("Remove member: {}", response.getBody().toString());
// add success message
redirectAttributes.addFlashAttribute(MESSAGE_SUCCESS, "Member " + name + " has been removed.");
}
return REDIRECT_TEAM_PROFILE_TEAM_ID;
}
// @RequestMapping("/team_profile/{teamId}/start_experiment/{expId}")
// public String startExperimentFromTeamProfile(@PathVariable Integer teamId, @PathVariable Integer expId, Model model, HttpSession session) {
// // start experiment
// // ensure experiment is stopped first before starting
// experimentManager.startExperiment(getSessionIdOfLoggedInUser(session), expId);
// return "redirect:/team_profile/{teamId}";
// }
// @RequestMapping("/team_profile/{teamId}/stop_experiment/{expId}")
// public String stopExperimentFromTeamProfile(@PathVariable Integer teamId, @PathVariable Integer expId, Model model, HttpSession session) {
// // stop experiment
// // ensure experiment is in ready mode before stopping
// experimentManager.stopExperiment(getSessionIdOfLoggedInUser(session), expId);
// return "redirect:/team_profile/{teamId}";
// }
// @RequestMapping("/team_profile/{teamId}/remove_experiment/{expId}")
// public String removeExperimentFromTeamProfile(@PathVariable Integer teamId, @PathVariable Integer expId, Model model, HttpSession session) {
// // remove experiment
// // TODO check userid is indeed the experiment owner or team owner
// // ensure experiment is stopped first
// if (experimentManager.removeExperiment(getSessionIdOfLoggedInUser(session), expId) == true) {
// // decrease exp count to be display on Teams page
// teamManager.decrementExperimentCount(teamId);
// }
// model.addAttribute("experimentList", experimentManager.getExperimentListByExperimentOwner(getSessionIdOfLoggedInUser(session)));
// return "redirect:/team_profile/{teamId}";
// }
// @RequestMapping(value="/team_profile/invite_user/{teamId}", method=RequestMethod.GET)
// public String inviteUserFromTeamProfile(@PathVariable Integer teamId, Model model) {
// model.addAttribute("teamIdVar", teamId);
// model.addAttribute("teamPageInviteMemberForm", new TeamPageInviteMemberForm());
// return "team_profile_invite_members";
// }
// @RequestMapping(value="/team_profile/invite_user/{teamId}", method=RequestMethod.POST)
// public String sendInvitationFromTeamProfile(@PathVariable Integer teamId, @ModelAttribute TeamPageInviteMemberForm teamPageInviteMemberForm, Model model) {
// int userId = userManager.getUserIdByEmail(teamPageInviteMemberForm.getInviteUserEmail());
// teamManager.addInvitedToParticipateMap(userId, teamId);
// return "redirect:/team_profile/{teamId}";
// }
//--------------------------Apply for New Team Page--------------------------
@RequestMapping(value = "/teams/apply_team", method = RequestMethod.GET)
public String teamPageApplyTeam(Model model) {
model.addAttribute("teamPageApplyTeamForm", new TeamPageApplyTeamForm());
return "team_page_apply_team";
}
@RequestMapping(value = "/teams/apply_team", method = RequestMethod.POST)
public String checkApplyTeamInfo(
@Valid TeamPageApplyTeamForm teamPageApplyTeamForm,
BindingResult bindingResult,
HttpSession session,
final RedirectAttributes redirectAttributes) throws WebServiceRuntimeException {
final String LOG_PREFIX = "Existing user apply for new team: {}";
if (bindingResult.hasErrors()) {
log.warn(LOG_PREFIX, "Application form error " + teamPageApplyTeamForm.toString());
return "team_page_apply_team";
}
// log data to ensure data has been parsed
log.debug(LOG_PREFIX, properties.getRegisterRequestToApplyTeam(session.getAttribute("id").toString()));
log.info(LOG_PREFIX, teamPageApplyTeamForm.toString());
JSONObject mainObject = new JSONObject();
JSONObject teamFields = new JSONObject();
mainObject.put("team", teamFields);
teamFields.put("name", teamPageApplyTeamForm.getTeamName());
teamFields.put("description", teamPageApplyTeamForm.getTeamDescription());
teamFields.put("website", teamPageApplyTeamForm.getTeamWebsite());
teamFields.put("organisationType", teamPageApplyTeamForm.getTeamOrganizationType());
teamFields.put("visibility", teamPageApplyTeamForm.getIsPublic());
String nclUserId = session.getAttribute("id").toString();
HttpEntity<String> request = createHttpEntityWithBody(mainObject.toString());
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getRegisterRequestToApplyTeam(nclUserId), HttpMethod.POST, request, String.class);
String responseBody = response.getBody().toString();
if (RestUtil.isError(response.getStatusCode())) {
// prepare the exception mapping
EnumMap<ExceptionState, String> exceptionMessageMap = new EnumMap<>(ExceptionState.class);
exceptionMessageMap.put(USER_ID_NULL_OR_EMPTY_EXCEPTION, "User id is null or empty ");
exceptionMessageMap.put(TEAM_NAME_NULL_OR_EMPTY_EXCEPTION, "Team name is null or empty ");
exceptionMessageMap.put(USER_NOT_FOUND_EXCEPTION, "User not found");
exceptionMessageMap.put(TEAM_NAME_ALREADY_EXISTS_EXCEPTION, "Team name already exists");
exceptionMessageMap.put(INVALID_TEAM_NAME_EXCEPTION, "Team name contains invalid characters");
exceptionMessageMap.put(TEAM_MEMBER_ALREADY_EXISTS_EXCEPTION, "Team member already exists");
exceptionMessageMap.put(ADAPTER_CONNECTION_EXCEPTION, "Connection to adapter failed");
exceptionMessageMap.put(ADAPTER_INTERNAL_ERROR_EXCEPTION, "Internal server error on adapter");
exceptionMessageMap.put(DETERLAB_OPERATION_FAILED_EXCEPTION, "Operation failed on DeterLab");
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
final String errorMessage = exceptionMessageMap.containsKey(exceptionState) ? error.getMessage() : ERR_SERVER_OVERLOAD;
log.warn(LOG_PREFIX, responseBody);
redirectAttributes.addFlashAttribute("message", errorMessage);
return "redirect:/teams/apply_team";
} else {
// no errors, everything ok
log.info(LOG_PREFIX, "Application for team " + teamPageApplyTeamForm.getTeamName() + " submitted");
return "redirect:/teams/team_application_submitted";
}
} catch (ResourceAccessException | IOException e) {
log.error(LOG_PREFIX, e);
throw new WebServiceRuntimeException(e.getMessage());
}
}
@RequestMapping(value = "/acceptable_usage_policy", method = RequestMethod.GET)
public String teamOwnerPolicy() {
return "acceptable_usage_policy";
}
@RequestMapping(value = "/terms_and_conditions", method = RequestMethod.GET)
public String termsAndConditions() {
return "terms_and_conditions";
}
//--------------------------Join Team Page--------------------------
@RequestMapping(value = "/teams/join_team", method = RequestMethod.GET)
public String teamPageJoinTeam(Model model) {
model.addAttribute("teamPageJoinTeamForm", new TeamPageJoinTeamForm());
return "team_page_join_team";
}
@RequestMapping(value = "/teams/join_team", method = RequestMethod.POST)
public String checkJoinTeamInfo(
@Valid TeamPageJoinTeamForm teamPageJoinForm,
BindingResult bindingResult,
Model model,
HttpSession session,
final RedirectAttributes redirectAttributes) throws WebServiceRuntimeException {
final String LOG_PREFIX = "Existing user join team: {}";
if (bindingResult.hasErrors()) {
log.warn(LOG_PREFIX, "Application form error " + teamPageJoinForm.toString());
return "team_page_join_team";
}
JSONObject mainObject = new JSONObject();
JSONObject teamFields = new JSONObject();
JSONObject userFields = new JSONObject();
mainObject.put("team", teamFields);
mainObject.put("user", userFields);
userFields.put("id", session.getAttribute("id")); // ncl-id
teamFields.put("name", teamPageJoinForm.getTeamName());
log.info(LOG_PREFIX, "User " + session.getAttribute("id") + ", team " + teamPageJoinForm.getTeamName());
HttpEntity<String> request = createHttpEntityWithBody(mainObject.toString());
ResponseEntity response;
try {
restTemplate.setErrorHandler(new MyResponseErrorHandler());
response = restTemplate.exchange(properties.getJoinRequestExistingUser(), HttpMethod.POST, request, String.class);
String responseBody = response.getBody().toString();
if (RestUtil.isError(response.getStatusCode())) {
// prepare the exception mapping
EnumMap<ExceptionState, String> exceptionMessageMap = new EnumMap<>(ExceptionState.class);
exceptionMessageMap.put(USER_NOT_FOUND_EXCEPTION, "User not found");
exceptionMessageMap.put(USER_ID_NULL_OR_EMPTY_EXCEPTION, "User id is null or empty");
exceptionMessageMap.put(TEAM_NOT_FOUND_EXCEPTION, "Team name not found");
exceptionMessageMap.put(TEAM_NAME_NULL_OR_EMPTY_EXCEPTION, "Team name is null or empty");
exceptionMessageMap.put(USER_ALREADY_IN_TEAM_EXCEPTION, "User already in team");
exceptionMessageMap.put(TEAM_MEMBER_ALREADY_EXISTS_EXCEPTION, "Team member already exists");
exceptionMessageMap.put(ADAPTER_CONNECTION_EXCEPTION, "Connection to adapter failed");
exceptionMessageMap.put(ADAPTER_INTERNAL_ERROR_EXCEPTION, "Internal server error on adapter");
exceptionMessageMap.put(DETERLAB_OPERATION_FAILED_EXCEPTION, "Operation failed on DeterLab");
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
final String errorMessage = exceptionMessageMap.containsKey(exceptionState) ? error.getMessage() : ERR_SERVER_OVERLOAD;
log.warn(LOG_PREFIX, responseBody);
redirectAttributes.addFlashAttribute("message", errorMessage);
return "redirect:/teams/join_team";
} else {
log.info(LOG_PREFIX, "Application for join team " + teamPageJoinForm.getTeamName() + " submitted");
return "redirect:/teams/join_application_submitted/" + teamPageJoinForm.getTeamName();
}
} catch (ResourceAccessException | IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
}
//--------------------------Experiment Page--------------------------
@RequestMapping(value = "/experiments", method = RequestMethod.GET)
public String experiments(Model model, HttpSession session) throws WebServiceRuntimeException {
// long start = System.currentTimeMillis();
List<Experiment2> experimentList = new ArrayList<>();
Map<Long, Realization> realizationMap = new HashMap<>();
HttpEntity<String> request = createHttpEntityHeaderOnly();
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = restTemplate.exchange(properties.getDeterUid(session.getAttribute("id").toString()), HttpMethod.GET, request, String.class);
String responseBody = response.getBody().toString();
try {
if (RestUtil.isError(response.getStatusCode())) {
log.error("No user to get experiment: {}", session.getAttribute("id"));
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
log.info("experiment error: {} - {} - {} - user token:{}", error.getError(), error.getMessage(), error.getLocalizedMessage(), httpScopedSession.getAttribute(webProperties.getSessionJwtToken()));
model.addAttribute(DETER_UID, CONNECTION_ERROR);
} else {
log.info("Show the deter user id: {}", responseBody);
model.addAttribute(DETER_UID, responseBody);
}
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
// get list of teamids
ResponseEntity userRespEntity = restTemplate.exchange(properties.getUser(session.getAttribute("id").toString()), HttpMethod.GET, request, String.class);
JSONObject object = new JSONObject(userRespEntity.getBody().toString());
JSONArray teamIdsJsonArray = object.getJSONArray("teams");
for (int i = 0; i < teamIdsJsonArray.length(); i++) {
String teamId = teamIdsJsonArray.get(i).toString();
HttpEntity<String> teamRequest = createHttpEntityHeaderOnly();
ResponseEntity teamResponse = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, teamRequest, String.class);
String teamResponseBody = teamResponse.getBody().toString();
if (!isMemberJoinRequestPending(session.getAttribute("id").toString(), teamResponseBody)) {
// get experiments lists of the teams
HttpEntity<String> expRequest = createHttpEntityHeaderOnly();
ResponseEntity expRespEntity = restTemplate.exchange(properties.getExpListByTeamId(teamId), HttpMethod.GET, expRequest, String.class);
JSONArray experimentsArray = new JSONArray(expRespEntity.getBody().toString());
for (int k = 0; k < experimentsArray.length(); k++) {
Experiment2 experiment2 = extractExperiment(experimentsArray.getJSONObject(k).toString());
Realization realization = invokeAndExtractRealization(experiment2.getTeamName(), experiment2.getId());
realizationMap.put(experiment2.getId(), realization);
experimentList.add(experiment2);
}
}
}
model.addAttribute("experimentList", experimentList);
model.addAttribute("realizationMap", realizationMap);
// System.out.println("Elapsed time to get experiment page:" + (System.currentTimeMillis() - start));
return EXPERIMENTS;
}
@RequestMapping(value = "/experiments/create", method = RequestMethod.GET)
public String createExperiment(Model model, HttpSession session) throws WebServiceRuntimeException {
log.info("Loading create experiment page");
// a list of teams that the logged in user is in
List<String> scenarioFileNameList = getScenarioFileNameList();
List<Team2> userTeamsList = new ArrayList<>();
// get list of teamids
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response = restTemplate.exchange(properties.getUser(session.getAttribute("id").toString()), HttpMethod.GET, request, String.class);
String responseBody = response.getBody().toString();
JSONObject object = new JSONObject(responseBody);
JSONArray teamIdsJsonArray = object.getJSONArray("teams");
for (int i = 0; i < teamIdsJsonArray.length(); i++) {
String teamId = teamIdsJsonArray.get(i).toString();
HttpEntity<String> teamRequest = createHttpEntityHeaderOnly();
ResponseEntity teamResponse = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, teamRequest, String.class);
String teamResponseBody = teamResponse.getBody().toString();
Team2 team2 = extractTeamInfo(teamResponseBody);
userTeamsList.add(team2);
}
model.addAttribute("scenarioFileNameList", scenarioFileNameList);
model.addAttribute("experimentForm", new ExperimentForm());
model.addAttribute("userTeamsList", userTeamsList);
return "experiment_page_create_experiment";
}
@RequestMapping(value = "/experiments/create", method = RequestMethod.POST)
public String validateExperiment(
@ModelAttribute("experimentForm") ExperimentForm experimentForm,
HttpSession session,
BindingResult bindingResult,
final RedirectAttributes redirectAttributes) throws WebServiceRuntimeException {
if (bindingResult.hasErrors()) {
log.info("Create experiment - form has errors");
return "redirect:/experiments/create";
}
if (experimentForm.getName() == null || experimentForm.getName().isEmpty()) {
redirectAttributes.addFlashAttribute(MESSAGE, "Experiment Name cannot be empty");
return "redirect:/experiments/create";
}
if (experimentForm.getDescription() == null || experimentForm.getDescription().isEmpty()) {
redirectAttributes.addFlashAttribute(MESSAGE, "Description cannot be empty");
return "redirect:/experiments/create";
}
experimentForm.setScenarioContents(getScenarioContentsFromFile(experimentForm.getScenarioFileName()));
JSONObject experimentObject = new JSONObject();
experimentObject.put("userId", session.getAttribute("id").toString());
experimentObject.put(TEAM_ID, experimentForm.getTeamId());
experimentObject.put(TEAM_NAME, experimentForm.getTeamName());
experimentObject.put("name", experimentForm.getName().replaceAll("\\s+", "")); // truncate whitespaces and non-visible characters like \n
experimentObject.put("description", experimentForm.getDescription());
experimentObject.put("nsFile", "file");
experimentObject.put("nsFileContent", experimentForm.getNsFileContent());
experimentObject.put("idleSwap", "240");
experimentObject.put("maxDuration", "960");
log.info("Calling service to create experiment");
HttpEntity<String> request = createHttpEntityWithBody(experimentObject.toString());
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = restTemplate.exchange(properties.getSioExpUrl(), HttpMethod.POST, request, String.class);
String responseBody = response.getBody().toString();
try {
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case NS_FILE_PARSE_EXCEPTION:
log.warn("Ns file error");
redirectAttributes.addFlashAttribute(MESSAGE, "There is an error when parsing the NS File.");
break;
case EXPERIMENT_NAME_ALREADY_EXISTS_EXCEPTION:
log.warn("Exp name already exists");
redirectAttributes.addFlashAttribute(MESSAGE, "Experiment name already exists.");
break;
default:
log.warn("Exp service or adapter fail");
// possible sio or adapter connection fail
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
break;
}
log.info("Experiment {} created", experimentForm);
return "redirect:/experiments/create";
}
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
//
// TODO Uploaded function for network configuration and optional dataset
// if (!networkFile.isEmpty()) {
// try {
// String networkFileName = getSessionIdOfLoggedInUser(session) + "-networkconfig-" + networkFile.getOriginalFilename();
// BufferedOutputStream stream = new BufferedOutputStream(
// new FileOutputStream(new File(App.EXP_CONFIG_DIR + "/" + networkFileName)));
// FileCopyUtils.copy(networkFile.getInputStream(), stream);
// stream.close();
// redirectAttributes.addFlashAttribute(MESSAGE,
// "You successfully uploaded " + networkFile.getOriginalFilename() + "!");
// // remember network file name here
// }
// catch (Exception e) {
// redirectAttributes.addFlashAttribute(MESSAGE,
// "You failed to upload " + networkFile.getOriginalFilename() + " => " + e.getMessage());
// return "redirect:/experiments/create";
// }
// }
//
// if (!dataFile.isEmpty()) {
// try {
// String dataFileName = getSessionIdOfLoggedInUser(session) + "-data-" + dataFile.getOriginalFilename();
// BufferedOutputStream stream = new BufferedOutputStream(
// new FileOutputStream(new File(App.EXP_CONFIG_DIR + "/" + dataFileName)));
// FileCopyUtils.copy(dataFile.getInputStream(), stream);
// stream.close();
// redirectAttributes.addFlashAttribute("message2",
// "You successfully uploaded " + dataFile.getOriginalFilename() + "!");
// // remember data file name here
// }
// catch (Exception e) {
// redirectAttributes.addFlashAttribute("message2",
// "You failed to upload " + dataFile.getOriginalFilename() + " => " + e.getMessage());
// }
// }
//
// // add current experiment to experiment manager
// experimentManager.addExperiment(getSessionIdOfLoggedInUser(session), experiment);
// // increase exp count to be display on Teams page
// teamManager.incrementExperimentCount(experiment.getTeamId());
return "redirect:/experiments";
}
@RequestMapping(value = "/experiments/save_image/{teamId}/{expId}/{nodeId}", method = RequestMethod.GET)
public String saveExperimentImage(@PathVariable String teamId, @PathVariable String expId, @PathVariable String nodeId, Model model) {
Map<String, Map<String, String>> singleNodeInfoMap = new HashMap<>();
Image saveImageForm = new Image();
String teamName = invokeAndExtractTeamInfo(teamId).getName();
Realization realization = invokeAndExtractRealization(teamName, Long.parseLong(expId));
// experiment may have many nodes
// extract just the particular node details to display
for (Map.Entry<String, Map<String, String>> nodesInfo : realization.getNodesInfoMap().entrySet()) {
String nodeName = nodesInfo.getKey();
Map<String, String> singleNodeDetailsMap = nodesInfo.getValue();
if (singleNodeDetailsMap.get(NODE_ID).equals(nodeId)) {
singleNodeInfoMap.put(nodeName, singleNodeDetailsMap);
// store the current os of the node into the form also
// have to pass the the services
saveImageForm.setCurrentOS(singleNodeDetailsMap.get("os"));
}
}
saveImageForm.setTeamId(teamId);
saveImageForm.setNodeId(nodeId);
model.addAttribute("teamName", teamName);
model.addAttribute("singleNodeInfoMap", singleNodeInfoMap);
model.addAttribute("pathTeamId", teamId);
model.addAttribute("pathExperimentId", expId);
model.addAttribute("pathNodeId", nodeId);
model.addAttribute("experimentName", realization.getExperimentName());
model.addAttribute("saveImageForm", saveImageForm);
return "save_experiment_image";
}
// bindingResult is required in the method signature to perform the JSR303 validation for Image object
@RequestMapping(value = "/experiments/save_image/{teamId}/{expId}/{nodeId}", method = RequestMethod.POST)
public String saveExperimentImage(
@Valid @ModelAttribute("saveImageForm") Image saveImageForm,
BindingResult bindingResult,
RedirectAttributes redirectAttributes,
@PathVariable String teamId,
@PathVariable String expId,
@PathVariable String nodeId) throws IOException {
if (saveImageForm.getImageName().length() < 2) {
log.warn("Save image form has errors {}", saveImageForm);
redirectAttributes.addFlashAttribute("message", "Image name too short, minimum 2 characters");
return "redirect:/experiments/save_image/" + teamId + "/" + expId + "/" + nodeId;
}
log.info("Saving image: team {}, experiment {}, node {}", teamId, expId, nodeId);
ObjectMapper mapper = new ObjectMapper();
HttpEntity<String> request = createHttpEntityWithBody(mapper.writeValueAsString(saveImageForm));
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = restTemplate.exchange(properties.saveImage(), HttpMethod.POST, request, String.class);
String responseBody = response.getBody().toString();
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
log.warn("Save image: error with exception {}", exceptionState);
switch (exceptionState) {
case DETERLAB_OPERATION_FAILED_EXCEPTION:
log.warn("Save image: error, operation failed on DeterLab");
redirectAttributes.addFlashAttribute("message", error.getMessage());
break;
case ADAPTER_CONNECTION_EXCEPTION:
log.warn("Save image: error, cannot connect to adapter");
redirectAttributes.addFlashAttribute("message", "connection to adapter failed");
break;
case ADAPTER_INTERNAL_ERROR_EXCEPTION:
log.warn("Save image: error, adapter internal server error");
redirectAttributes.addFlashAttribute("message", "internal error was found on the adapter");
break;
default:
log.warn("Save image: other error");
redirectAttributes.addFlashAttribute("message", ERR_SERVER_OVERLOAD);
}
return "redirect:/experiments/save_image/" + teamId + "/" + expId + "/" + nodeId;
}
// everything looks ok
log.info("Save image in progress: team {}, experiment {}, node {}, image {}", teamId, expId, nodeId, saveImageForm.getImageName());
return "redirect:/experiments";
}
/*
private String processSaveImageRequest(@Valid @ModelAttribute("saveImageForm") Image saveImageForm, RedirectAttributes redirectAttributes, @PathVariable String teamId, @PathVariable String expId, @PathVariable String nodeId, ResponseEntity response, String responseBody) throws IOException {
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
log.warn("Save image exception: {}", exceptionState);
switch (exceptionState) {
case DETERLAB_OPERATION_FAILED_EXCEPTION:
log.warn("adapter deterlab operation failed exception");
redirectAttributes.addFlashAttribute("message", error.getMessage());
break;
default:
log.warn("Image service or adapter fail");
// possible sio or adapter connection fail
redirectAttributes.addFlashAttribute("message", ERR_SERVER_OVERLOAD);
break;
}
return "redirect:/experiments/save_image/" + teamId + "/" + expId + "/" + nodeId;
} else {
// everything ok
log.info("Image service in progress for Team: {}, Exp: {}, Node: {}, Image: {}", teamId, expId, nodeId, saveImageForm.getImageName());
return "redirect:/experiments";
}
}
*/
// @RequestMapping("/experiments/configuration/{expId}")
// public String viewExperimentConfiguration(@PathVariable Integer expId, Model model) {
// // get experiment from expid
// // retrieve the scenario contents to be displayed
// Experiment currExp = experimentManager.getExperimentByExpId(expId);
// model.addAttribute("scenarioContents", currExp.getScenarioContents());
// return "experiment_scenario_contents";
// }
@RequestMapping("/remove_experiment/{teamName}/{teamId}/{expId}")
public String removeExperiment(@PathVariable String teamName, @PathVariable String teamId, @PathVariable String expId, final RedirectAttributes redirectAttributes, HttpSession session) throws WebServiceRuntimeException {
// ensure experiment is stopped first
Realization realization = invokeAndExtractRealization(teamName, Long.parseLong(expId));
Team2 team = invokeAndExtractTeamInfo(teamId);
// check valid authentication to remove experiments
// either admin, experiment creator or experiment owner
if (!validateIfAdmin(session) && !realization.getUserId().equals(session.getAttribute("id").toString()) && !team.getOwner().getId().equals(session.getAttribute(webProperties.getSessionUserId()))) {
log.warn("Permission denied when remove Team:{}, Experiment: {} with User: {}, Role:{}", teamId, expId, session.getAttribute("id"), session.getAttribute(webProperties.getSessionRoles()));
redirectAttributes.addFlashAttribute(MESSAGE, "An error occurred while trying to remove experiment;" + permissionDeniedMessage);
return "redirect:/experiments";
}
if (!realization.getState().equals(RealizationState.NOT_RUNNING.toString())) {
log.warn("Trying to remove Team: {}, Experiment: {} with State: {} that is still in progress?", teamId, expId, realization.getState());
redirectAttributes.addFlashAttribute(MESSAGE, "An error occurred while trying to remove Exp: " + realization.getExperimentName() + ". Please refresh the page again. If the error persists, please contact " + CONTACT_EMAIL);
return "redirect:/experiments";
}
log.info("Removing experiment: at " + properties.getDeleteExperiment(teamId, expId));
HttpEntity<String> request = createHttpEntityHeaderOnly();
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getDeleteExperiment(teamId, expId), HttpMethod.DELETE, request, String.class);
} catch (Exception e) {
log.warn("Error connecting to experiment service to remove experiment", e.getMessage());
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
return "redirect:/experiments";
}
String responseBody = response.getBody().toString();
try {
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case EXPERIMENT_DELETE_EXCEPTION:
case FORBIDDEN_EXCEPTION:
log.warn("remove experiment failed for Team: {}, Exp: {}", teamId, expId);
redirectAttributes.addFlashAttribute(MESSAGE, error.getMessage());
break;
case OBJECT_OPTIMISTIC_LOCKING_FAILURE_EXCEPTION:
// do nothing
log.info("remove experiment database locking failure");
break;
default:
// do nothing
break;
}
return "redirect:/experiments";
} else {
// everything ok
log.info("remove experiment success for Team: {}, Exp: {}", teamId, expId);
redirectAttributes.addFlashAttribute("exp_remove_message", "Team: " + teamName + " has removed Exp: " + realization.getExperimentName());
return "redirect:/experiments";
}
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
}
@RequestMapping("/start_experiment/{teamName}/{expId}")
public String startExperiment(
@PathVariable String teamName,
@PathVariable String expId,
final RedirectAttributes redirectAttributes, Model model, HttpSession session) throws WebServiceRuntimeException {
// ensure experiment is stopped first before starting
Realization realization = invokeAndExtractRealization(teamName, Long.parseLong(expId));
if (!checkPermissionRealizeExperiment(realization, session)) {
log.warn("Permission denied to start experiment: {} for team: {}", realization.getExperimentName(), teamName);
redirectAttributes.addFlashAttribute(MESSAGE, permissionDeniedMessage);
return "redirect:/experiments";
}
String teamId = realization.getTeamId();
String teamStatus = getTeamStatus(teamId);
if (!teamStatus.equals(TeamStatus.APPROVED.name())) {
log.warn("Error: trying to realize an experiment {} on team {} with status {}", realization.getExperimentName(), teamId, teamStatus);
redirectAttributes.addFlashAttribute(MESSAGE, teamName + " is in " + teamStatus + " status and does not have permission to start experiment. Please contact " + CONTACT_EMAIL);
return "redirect:/experiments";
}
if (!realization.getState().equals(RealizationState.NOT_RUNNING.toString())) {
log.warn("Trying to start Team: {}, Experiment: {} with State: {} that is not running?", teamName, expId, realization.getState());
redirectAttributes.addFlashAttribute(MESSAGE, "An error occurred while trying to start Exp: " + realization.getExperimentName() + ". Please refresh the page again. If the error persists, please contact " + CONTACT_EMAIL);
return "redirect:/experiments";
}
//start experiment
log.info("Starting experiment: at " + properties.getStartExperiment(teamName, expId));
HttpEntity<String> request = createHttpEntityHeaderOnly();
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getStartExperiment(teamName, expId), HttpMethod.POST, request, String.class);
} catch (Exception e) {
log.warn("Error connecting to experiment service to start experiment", e.getMessage());
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
return "redirect:/experiments";
}
String responseBody = response.getBody().toString();
try {
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case EXPERIMENT_START_EXCEPTION:
case FORBIDDEN_EXCEPTION:
log.warn("start experiment failed for Team: {}, Exp: {}", teamName, expId);
redirectAttributes.addFlashAttribute(MESSAGE, error.getMessage());
return "redirect:/experiments";
case TEAM_NOT_FOUND_EXCEPTION:
log.warn("Check team quota to start experiment: Team {} not found", teamName);
return REDIRECT_INDEX_PAGE;
case INSUFFICIENT_QUOTA_EXCEPTION:
log.warn("Check team quota to start experiment: Team {} do not have sufficient quota", teamName);
redirectAttributes.addFlashAttribute(MESSAGE, "There is insufficient quota for you to start this experiment. Please contact your team leader for more details.");
return "redirect:/experiments";
case OBJECT_OPTIMISTIC_LOCKING_FAILURE_EXCEPTION:
// do nothing
log.info("start experiment database locking failure");
break;
default:
// do nothing
break;
}
log.warn("start experiment some other error occurred exception: {}", exceptionState);
// possible for it to be error but experiment has started up finish
// if user clicks on start but reloads the page
// model.addAttribute(EXPERIMENT_MESSAGE, "Team: " + teamName + " has started Exp: " + realization.getExperimentName());
return EXPERIMENTS;
} else {
// everything ok
log.info("start experiment success for Team: {}, Exp: {}", teamName, expId);
redirectAttributes.addFlashAttribute(EXPERIMENT_MESSAGE, "Experiment " + realization.getExperimentName() + " in team " + teamName + " is starting. This may take up to 10 minutes depending on the scale of your experiment. Please refresh this page later.");
return "redirect:/experiments";
}
} catch (IOException e) {
log.warn("start experiment error: {]", e.getMessage());
throw new WebServiceRuntimeException(e.getMessage());
}
}
@RequestMapping("/stop_experiment/{teamName}/{expId}")
public String stopExperiment(@PathVariable String teamName, @PathVariable String expId, Model model, final RedirectAttributes redirectAttributes, HttpSession session) throws WebServiceRuntimeException {
// ensure experiment is active first before stopping
Realization realization = invokeAndExtractRealization(teamName, Long.parseLong(expId));
if (isNotAdminAndNotInTeam(session, realization)) {
log.warn("Permission denied to stop experiment: {} for team: {}", realization.getExperimentName(), teamName);
redirectAttributes.addFlashAttribute(MESSAGE, permissionDeniedMessage);
return "redirect:/experiments";
}
if (!realization.getState().equals(RealizationState.RUNNING.toString())) {
log.warn("Trying to stop Team: {}, Experiment: {} with State: {} that is still in progress?", teamName, expId, realization.getState());
redirectAttributes.addFlashAttribute(MESSAGE, "An error occurred while trying to stop Exp: " + realization.getExperimentName() + ". Please refresh the page again. If the error persists, please contact " + CONTACT_EMAIL);
return "redirect:/experiments";
}
log.info("Stopping experiment: at " + properties.getStopExperiment(teamName, expId));
HttpEntity<String> request = createHttpEntityHeaderOnly();
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response;
return abc(teamName, expId, redirectAttributes, realization, request);
}
@RequestMapping("/get_topology/{teamName}/{expId}")
@ResponseBody
public String getTopology(@PathVariable String teamName, @PathVariable String expId) {
try {
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response = restTemplate.exchange(properties.getTopology(teamName, expId), HttpMethod.GET, request, String.class);
log.info("Retrieve experiment topo success");
return "data:image/png;base64," + response.getBody();
} catch (Exception e) {
log.error("Error getting topology thumbnail", e.getMessage());
return "";
}
}
private String abc(@PathVariable String teamName, @PathVariable String expId, RedirectAttributes redirectAttributes, Realization realization, HttpEntity<String> request) throws WebServiceRuntimeException {
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getStopExperiment(teamName, expId), HttpMethod.POST, request, String.class);
} catch (Exception e) {
log.warn("Error connecting to experiment service to stop experiment", e.getMessage());
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
return "redirect:/experiments";
}
String responseBody = response.getBody().toString();
try {
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
if (exceptionState == ExceptionState.FORBIDDEN_EXCEPTION) {
log.warn("Permission denied to stop experiment: {} for team: {}", realization.getExperimentName(), teamName);
redirectAttributes.addFlashAttribute(MESSAGE, permissionDeniedMessage);
}
if (exceptionState == ExceptionState.OBJECT_OPTIMISTIC_LOCKING_FAILURE_EXCEPTION) {
log.info("stop experiment database locking failure");
}
} else {
// everything ok
log.info("stop experiment success for Team: {}, Exp: {}", teamName, expId);
redirectAttributes.addFlashAttribute(EXPERIMENT_MESSAGE, "Experiment " + realization.getExperimentName() + " in team " + teamName + " is stopping. Please refresh this page in a few minutes.");
}
return "redirect:/experiments";
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
}
private boolean isNotAdminAndNotInTeam(HttpSession session, Realization realization) {
return !validateIfAdmin(session) && !checkPermissionRealizeExperiment(realization, session);
}
//-----------------------------------------------------------------------
//--------------------------Admin Revamp---------------------------------
//-----------------------------------------------------------------------
//---------------------------------Admin---------------------------------
@RequestMapping("/admin")
public String admin(Model model, HttpSession session) {
if (!validateIfAdmin(session)) {
return NO_PERMISSION_PAGE;
}
List<Team2> pendingApprovalTeamsList = new ArrayList<>();
//------------------------------------
// get list of teams pending for approval
//------------------------------------
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity responseEntity = restTemplate.exchange(properties.getSioTeamsUrl(), HttpMethod.GET, request, String.class);
JSONArray jsonArray = new JSONArray(responseEntity.getBody().toString());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Team2 one = extractTeamInfo(jsonObject.toString());
if (one.getStatus().equals(TeamStatus.PENDING.name())) {
pendingApprovalTeamsList.add(one);
}
}
model.addAttribute("pendingApprovalTeamsList", pendingApprovalTeamsList);
return "admin3";
}
@RequestMapping("/admin/data")
public String adminDataManagement(Model model, HttpSession session) {
if (!validateIfAdmin(session)) {
return NO_PERMISSION_PAGE;
}
//------------------------------------
// get list of datasets
//------------------------------------
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response = restTemplate.exchange(properties.getData(), HttpMethod.GET, request, String.class);
String responseBody = response.getBody().toString();
List<Dataset> datasetsList = new ArrayList<>();
JSONArray dataJsonArray = new JSONArray(responseBody);
for (int i = 0; i < dataJsonArray.length(); i++) {
JSONObject dataInfoObject = dataJsonArray.getJSONObject(i);
Dataset dataset = extractDataInfo(dataInfoObject.toString());
datasetsList.add(dataset);
}
ResponseEntity response4 = restTemplate.exchange(properties.getDownloadStat(), HttpMethod.GET, request, String.class);
String responseBody4 = response4.getBody().toString();
Map<Integer, Long> dataDownloadStats = new HashMap<>();
JSONArray statJsonArray = new JSONArray(responseBody4);
for (int i = 0; i < statJsonArray.length(); i++) {
JSONObject statInfoObject = statJsonArray.getJSONObject(i);
dataDownloadStats.put(statInfoObject.getInt("dataId"), statInfoObject.getLong("count"));
}
model.addAttribute("dataList", datasetsList);
model.addAttribute("downloadStats", dataDownloadStats);
return "data_dashboard";
}
@RequestMapping("/admin/data/{datasetId}/resources")
public String adminViewDataResources(@PathVariable String datasetId, Model model, HttpSession session) {
if (!validateIfAdmin(session)) {
return NO_PERMISSION_PAGE;
}
//----------------------------------------
// get list of data resources in a dataset
//----------------------------------------
Dataset dataset = invokeAndExtractDataInfo(Long.parseLong(datasetId));
model.addAttribute("dataset", dataset);
return "admin_data_resources";
}
@RequestMapping(value = "/admin/data/{datasetId}/resources/{resourceId}/update", method = RequestMethod.GET)
public String adminUpdateResource(@PathVariable String datasetId, @PathVariable String resourceId, Model model, HttpSession session) {
if (!validateIfAdmin(session)) {
return NO_PERMISSION_PAGE;
}
Dataset dataset = invokeAndExtractDataInfo(Long.parseLong(datasetId));
DataResource currentDataResource = new DataResource();
for (DataResource dataResource : dataset.getDataResources()) {
if (dataResource.getId() == Long.parseLong(resourceId)) {
currentDataResource = dataResource;
break;
}
}
model.addAttribute("did", dataset.getId());
model.addAttribute("dataresource", currentDataResource);
session.setAttribute(ORIGINAL_DATARESOURCE, currentDataResource);
return "admin_data_resources_update";
}
// updates the malicious status of a data resource
@RequestMapping(value = "/admin/data/{datasetId}/resources/{resourceId}/update", method = RequestMethod.POST)
public String adminUpdateResourceFormSubmit(@PathVariable String datasetId, @PathVariable String resourceId, @ModelAttribute DataResource dataResource, Model model, HttpSession session, RedirectAttributes redirectAttributes) throws IOException {
if (!validateIfAdmin(session)) {
return NO_PERMISSION_PAGE;
}
DataResource original = (DataResource) session.getAttribute(ORIGINAL_DATARESOURCE);
Dataset dataset = invokeAndExtractDataInfo(Long.parseLong(datasetId));
updateDataset(dataset, dataResource);
// add redirect attributes variable to notify what has been modified
if (!original.getMaliciousFlag().equalsIgnoreCase(dataResource.getMaliciousFlag())) {
redirectAttributes.addFlashAttribute("editMaliciousFlag", "success");
}
log.info("Data updated... {}", dataset.getName());
model.addAttribute("did", dataset.getId());
model.addAttribute("dataresource", dataResource);
session.removeAttribute(ORIGINAL_DATARESOURCE);
return "redirect:/admin/data/" + datasetId + "/resources/" + resourceId + "/update";
}
private Dataset updateDataset(Dataset dataset, DataResource dataResource) throws IOException {
log.info("Data resource updating... {}", dataResource);
HttpEntity<String> request = createHttpEntityWithBody(objectMapper.writeValueAsString(dataResource));
ResponseEntity response = restTemplate.exchange(properties.getResource(dataset.getId().toString(), dataResource.getId().toString()), HttpMethod.PUT, request, String.class);
Dataset updatedDataset = extractDataInfo(response.getBody().toString());
log.info("Data resource updated... {}", dataResource.getUri());
return updatedDataset;
}
@RequestMapping("/admin/experiments")
public String adminExperimentsManagement(Model model, HttpSession session) {
if (!validateIfAdmin(session)) {
return NO_PERMISSION_PAGE;
}
//------------------------------------
// get list of experiments
//------------------------------------
HttpEntity<String> expRequest = createHttpEntityHeaderOnly();
ResponseEntity expResponseEntity = restTemplate.exchange(properties.getSioExpUrl(), HttpMethod.GET, expRequest, String.class);
//------------------------------------
// get list of realizations
//------------------------------------
HttpEntity<String> realizationRequest = createHttpEntityHeaderOnly();
ResponseEntity realizationResponseEntity = restTemplate.exchange(properties.getAllRealizations(), HttpMethod.GET, realizationRequest, String.class);
JSONArray jsonExpArray = new JSONArray(expResponseEntity.getBody().toString());
JSONArray jsonRealizationArray = new JSONArray(realizationResponseEntity.getBody().toString());
Map<Experiment2, Realization> experiment2Map = new HashMap<>(); // exp id, experiment
Map<Long, Realization> realizationMap = new HashMap<>(); // exp id, realization
for (int k = 0; k < jsonRealizationArray.length(); k++) {
Realization realization;
try {
realization = extractRealization(jsonRealizationArray.getJSONObject(k).toString());
} catch (JSONException e) {
log.debug("Admin extract realization {}", e);
realization = getCleanRealization();
}
if (realization.getState().equals(RealizationState.RUNNING.name())) {
realizationMap.put(realization.getExperimentId(), realization);
}
}
for (int i = 0; i < jsonExpArray.length(); i++) {
Experiment2 experiment2 = extractExperiment(jsonExpArray.getJSONObject(i).toString());
if (realizationMap.containsKey(experiment2.getId())) {
experiment2Map.put(experiment2, realizationMap.get(experiment2.getId()));
}
}
model.addAttribute("runningExpMap", experiment2Map);
return "experiment_dashboard";
}
@RequestMapping("/admin/teams")
public String adminTeamsManagement(Model model, HttpSession session) {
if (!validateIfAdmin(session)) {
return NO_PERMISSION_PAGE;
}
//------------------------------------
// get list of teams
//------------------------------------
TeamManager2 teamManager2 = new TeamManager2();
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity responseEntity = restTemplate.exchange(properties.getSioTeamsUrl(), HttpMethod.GET, request, String.class);
JSONArray jsonArray = new JSONArray(responseEntity.getBody().toString());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Team2 one = extractTeamInfo(jsonObject.toString());
teamManager2.addTeamToTeamMap(one);
}
model.addAttribute("teamsMap", teamManager2.getTeamMap());
return "team_dashboard";
}
@RequestMapping("/admin/users")
public String adminUsersManagement(Model model, HttpSession session) {
if (!validateIfAdmin(session)) {
return NO_PERMISSION_PAGE;
}
//------------------------------------
// get list of users
//------------------------------------
Map<String, List<String>> userToTeamMap = new HashMap<>(); // userId : list of team names
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response2 = restTemplate.exchange(properties.getSioUsersUrl(), HttpMethod.GET, request, String.class);
String responseBody2 = response2.getBody().toString();
JSONArray jsonUserArray = new JSONArray(responseBody2);
List<User2> usersList = new ArrayList<>();
for (int i = 0; i < jsonUserArray.length(); i++) {
JSONObject userObject = jsonUserArray.getJSONObject(i);
User2 user = extractUserInfo(userObject.toString());
usersList.add(user);
// get list of teams' names for each user
List<String> perUserTeamList = new ArrayList<>();
if (userObject.get("teams") != null) {
JSONArray teamJsonArray = userObject.getJSONArray("teams");
for (int k = 0; k < teamJsonArray.length(); k++) {
Team2 team = invokeAndExtractTeamInfo(teamJsonArray.get(k).toString());
perUserTeamList.add(team.getName());
}
userToTeamMap.put(user.getId(), perUserTeamList);
}
}
model.addAttribute("usersList", usersList);
model.addAttribute("userToTeamMap", userToTeamMap);
return "user_dashboard";
}
@RequestMapping("/admin/usage")
public String adminTeamUsage(Model model,
@RequestParam(value = "team", required = false) String team,
@RequestParam(value = "start", required = false) String start,
@RequestParam(value = "end", required = false) String end,
HttpSession session) {
if (!validateIfAdmin(session)) {
return NO_PERMISSION_PAGE;
}
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
ZonedDateTime now = ZonedDateTime.now();
if (start == null) {
ZonedDateTime startDate = now.with(firstDayOfMonth());
start = startDate.format(formatter);
}
if (end == null) {
ZonedDateTime endDate = now.with(lastDayOfMonth());
end = endDate.format(formatter);
}
// get list of teamids
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity responseEntity = restTemplate.exchange(properties.getSioTeamsUrl(), HttpMethod.GET, request, String.class);
JSONArray jsonArray = new JSONArray(responseEntity.getBody().toString());
TeamManager2 teamManager2 = new TeamManager2();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Team2 one = extractTeamInfo(jsonObject.toString());
teamManager2.addTeamToTeamMap(one);
}
if (team != null) {
responseEntity = restTemplate.exchange(properties.getUsageStat(team, "startDate=" + start, "endDate=" + end), HttpMethod.GET, request, String.class);
String usage = responseEntity.getBody().toString();
model.addAttribute("usage", usage);
}
model.addAttribute("teamsMap", teamManager2.getTeamMap());
model.addAttribute("start", start);
model.addAttribute("end", end);
model.addAttribute("team", team);
return "usage_statistics";
}
@RequestMapping(value = "/admin/energy", method = RequestMethod.GET)
public String adminEnergy(Model model,
@RequestParam(value = "start", required = false) String start,
@RequestParam(value = "end", required = false) String end,
final RedirectAttributes redirectAttributes,
HttpSession session) throws IOException {
if (!validateIfAdmin(session)) {
return NO_PERMISSION_PAGE;
}
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
ZonedDateTime now = ZonedDateTime.now();
if (start == null) {
ZonedDateTime startDate = now.with(firstDayOfMonth());
start = startDate.format(formatter);
}
if (end == null) {
ZonedDateTime endDate = now.with(lastDayOfMonth());
end = endDate.format(formatter);
}
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity responseEntity;
try {
responseEntity = restTemplate.exchange(properties.getEnergyStatistics("startDate=" + start, "endDate=" + end), HttpMethod.GET, request, String.class);
} catch (RestClientException e) {
log.warn("Error connecting to sio analytics service for energy usage: {}", e);
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
return REDIRECT_ENERGY_USAGE;
}
String responseBody = responseEntity.getBody().toString();
JSONArray jsonArray = new JSONArray(responseBody);
// handling exceptions from SIO
if (RestUtil.isError(responseEntity.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case START_DATE_AFTER_END_DATE_EXCEPTION:
log.warn("Get energy usage : Start date after end date error");
redirectAttributes.addFlashAttribute(MESSAGE, ERR_START_DATE_AFTER_END_DATE);
return REDIRECT_ENERGY_USAGE;
default:
log.warn("Get energy usage : sio or deterlab adapter connection error");
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
return REDIRECT_ENERGY_USAGE;
}
} else {
log.info("Get energy usage info : {}", responseBody);
}
DecimalFormat df2 = new DecimalFormat(".##");
double sumEnergy = 0.00;
List<String> listOfDate = new ArrayList<>();
List<Double> listOfEnergy = new ArrayList<>();
ZonedDateTime currentZonedDateTime = convertToZonedDateTime(start);
String currentDate = null;
for (int i = 0; i < jsonArray.length(); i++) {
sumEnergy += jsonArray.getDouble(i);
// add into listOfDate to display graph
currentDate = currentZonedDateTime.format(formatter);
listOfDate.add(currentDate);
// add into listOfEnergy to display graph
double energy = Double.valueOf(df2.format(jsonArray.getDouble(i)));
listOfEnergy.add(energy);
currentZonedDateTime = convertToZonedDateTime(currentDate).plusDays(1);
}
sumEnergy = Double.valueOf(df2.format(sumEnergy));
model.addAttribute("listOfDate", listOfDate);
model.addAttribute("listOfEnergy", listOfEnergy);
model.addAttribute("start", start);
model.addAttribute("end", end);
model.addAttribute("energy", sumEnergy);
return "energy_usage";
}
@RequestMapping("/admin/nodesStatus")
public String adminNodesStatus(Model model, HttpSession session) throws IOException {
if (!validateIfAdmin(session)) {
return NO_PERMISSION_PAGE;
}
// get number of active users and running experiments
Map<String, String> testbedStatsMap = getTestbedStats();
testbedStatsMap.put(USER_DASHBOARD_FREE_NODES, "0");
testbedStatsMap.put(USER_DASHBOARD_TOTAL_NODES, "0");
Map<String, List<Map<String, String>>> nodesStatus = getNodesStatus();
Map<String, Map<String, Long>> nodesStatusCount = new HashMap<>();
// loop through each of the machine type
// tabulate the different nodes type
// count the number of different nodes status, e.g. SYSTEMX = { FREE = 10, IN_USE = 11, ... }
nodesStatus.entrySet().forEach(machineTypeListEntry -> {
Map<String, Long> nodesCountMap = new HashMap<>();
long free = machineTypeListEntry.getValue().stream().filter(stringStringMap -> "free".equalsIgnoreCase(stringStringMap.get("status"))).count();
long inUse = machineTypeListEntry.getValue().stream().filter(stringStringMap -> "in_use".equalsIgnoreCase(stringStringMap.get("status"))).count();
long reserved = machineTypeListEntry.getValue().stream().filter(stringStringMap -> "reserved".equalsIgnoreCase(stringStringMap.get("status"))).count();
long reload = machineTypeListEntry.getValue().stream().filter(stringStringMap -> "reload".equalsIgnoreCase(stringStringMap.get("status"))).count();
long total = free + inUse + reserved + reload;
long currentTotal = Long.parseLong(testbedStatsMap.get(USER_DASHBOARD_TOTAL_NODES)) + total;
long currentFree = Long.parseLong(testbedStatsMap.get(USER_DASHBOARD_FREE_NODES)) + free;
nodesCountMap.put(NodeType.FREE.name(), free);
nodesCountMap.put(NodeType.IN_USE.name(), inUse);
nodesCountMap.put(NodeType.RESERVED.name(), reserved);
nodesCountMap.put(NodeType.RELOADING.name(), reload);
nodesStatusCount.put(machineTypeListEntry.getKey(), nodesCountMap);
testbedStatsMap.put(USER_DASHBOARD_FREE_NODES, Long.toString(currentFree));
testbedStatsMap.put(USER_DASHBOARD_TOTAL_NODES, Long.toString(currentTotal));
});
model.addAttribute("nodesStatus", nodesStatus);
model.addAttribute("nodesStatusCount", nodesStatusCount);
model.addAttribute(USER_DASHBOARD_LOGGED_IN_USERS_COUNT, testbedStatsMap.get(USER_DASHBOARD_LOGGED_IN_USERS_COUNT));
model.addAttribute(USER_DASHBOARD_RUNNING_EXPERIMENTS_COUNT, testbedStatsMap.get(USER_DASHBOARD_RUNNING_EXPERIMENTS_COUNT));
model.addAttribute(USER_DASHBOARD_FREE_NODES, testbedStatsMap.get(USER_DASHBOARD_FREE_NODES));
model.addAttribute(USER_DASHBOARD_TOTAL_NODES, testbedStatsMap.get(USER_DASHBOARD_TOTAL_NODES));
return "node_status";
}
/**
* Get simple ZonedDateTime from date string in the format 'YYYY-MM-DD'.
* @param date date string to convert
* @return ZonedDateTime of
*/
private ZonedDateTime convertToZonedDateTime(String date) {
String[] result = date.split("-");
return ZonedDateTime.of(
Integer.parseInt(result[0]),
Integer.parseInt(result[1]),
Integer.parseInt(result[2]),
0, 0, 0, 0, ZoneId.of("Asia/Singapore"));
}
// @RequestMapping(value="/admin/domains/add", method=RequestMethod.POST)
// public String addDomain(@Valid Domain domain, BindingResult bindingResult) {
// if (bindingResult.hasErrors()) {
// return "redirect:/admin";
// } else {
// domainManager.addDomains(domain.getDomainName());
// }
// return "redirect:/admin";
// }
// @RequestMapping("/admin/domains/remove/{domainKey}")
// public String removeDomain(@PathVariable String domainKey) {
// domainManager.removeDomains(domainKey);
// return "redirect:/admin";
// }
@RequestMapping("/admin/teams/accept/{teamId}/{teamOwnerId}")
public String approveTeam(
@PathVariable String teamId,
@PathVariable String teamOwnerId,
final RedirectAttributes redirectAttributes,
HttpSession session
) throws WebServiceRuntimeException {
if (!validateIfAdmin(session)) {
return NO_PERMISSION_PAGE;
}
//FIXME require approver info
log.info("Approving new team {}, team owner {}", teamId, teamOwnerId);
HttpEntity<String> request = createHttpEntityHeaderOnly();
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = restTemplate.exchange(
properties.getApproveTeam(teamId, teamOwnerId, TeamStatus.APPROVED), HttpMethod.POST, request, String.class);
String responseBody = response.getBody().toString();
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error;
try {
error = objectMapper.readValue(responseBody, MyErrorResource.class);
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case TEAM_ID_NULL_OR_EMPTY_EXCEPTION:
log.warn("Approve team: TeamId cannot be null or empty: {}",
teamId);
redirectAttributes.addFlashAttribute(MESSAGE, "TeamId cannot be null or empty");
break;
case USER_ID_NULL_OR_EMPTY_EXCEPTION:
log.warn("Approve team: UserId cannot be null or empty: {}",
teamOwnerId);
redirectAttributes.addFlashAttribute(MESSAGE, "UserId cannot be null or empty");
break;
case EMAIL_NOT_VERIFIED_EXCEPTION:
log.warn("Approve team: User {} email not verified", teamOwnerId);
redirectAttributes.addFlashAttribute(MESSAGE, "User email has not been verified");
break;
case INVALID_TEAM_STATUS_EXCEPTION:
log.warn("Approve team: TeamStatus is invalid");
redirectAttributes.addFlashAttribute(MESSAGE, "Team status is invalid");
break;
case TEAM_NOT_FOUND_EXCEPTION:
log.warn("Approve team: Team {} not found", teamId);
redirectAttributes.addFlashAttribute(MESSAGE, "Team does not exist");
break;
case DETERLAB_OPERATION_FAILED_EXCEPTION:
log.warn("Approve team: Team {} fail", teamId);
redirectAttributes.addFlashAttribute(MESSAGE, "Approve team request fail on Deterlab");
break;
default:
log.warn("Approve team : sio or deterlab adapter connection error");
// possible sio or adapter connection fail
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
break;
}
return "redirect:/admin";
}
// http status code is OK, then need to check the response message
String msg = new JSONObject(responseBody).getString("msg");
if ("approve project OK".equals(msg)) {
log.info("Approve team {} OK", teamId);
} else {
log.warn("Approve team {} FAIL", teamId);
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
}
return "redirect:/admin";
}
@RequestMapping("/admin/teams/reject/{teamId}/{teamOwnerId}")
public String rejectTeam(
@PathVariable String teamId,
@PathVariable String teamOwnerId,
@RequestParam("reason") String reason,
final RedirectAttributes redirectAttributes,
HttpSession session
) throws WebServiceRuntimeException {
if (!validateIfAdmin(session)) {
return NO_PERMISSION_PAGE;
}
//FIXME require approver info
log.info("Rejecting new team {}, team owner {}, reason {}", teamId, teamOwnerId, reason);
HttpEntity<String> request = createHttpEntityWithBody(reason);
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = restTemplate.exchange(
properties.getApproveTeam(teamId, teamOwnerId, TeamStatus.REJECTED), HttpMethod.POST, request, String.class);
String responseBody = response.getBody().toString();
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error;
try {
error = objectMapper.readValue(responseBody, MyErrorResource.class);
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case TEAM_ID_NULL_OR_EMPTY_EXCEPTION:
log.warn("Reject team: TeamId cannot be null or empty: {}",
teamId);
redirectAttributes.addFlashAttribute(MESSAGE, "TeamId cannot be null or empty");
break;
case USER_ID_NULL_OR_EMPTY_EXCEPTION:
log.warn("Reject team: UserId cannot be null or empty: {}",
teamOwnerId);
redirectAttributes.addFlashAttribute(MESSAGE, "UserId cannot be null or empty");
break;
case INVALID_TEAM_STATUS_EXCEPTION:
log.warn("Reject team: TeamStatus is invalid");
redirectAttributes.addFlashAttribute(MESSAGE, "Team status is invalid");
break;
case TEAM_NOT_FOUND_EXCEPTION:
log.warn("Reject team: Team {} not found", teamId);
redirectAttributes.addFlashAttribute(MESSAGE, "Team does not exist");
break;
case DETERLAB_OPERATION_FAILED_EXCEPTION:
log.warn("Reject team: Team {} fail", teamId);
redirectAttributes.addFlashAttribute(MESSAGE, "Reject team request fail on Deterlab");
break;
default:
log.warn("Reject team : sio or deterlab adapter connection error");
// possible sio or adapter connection fail
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
break;
}
return "redirect:/admin";
}
// http status code is OK, then need to check the response message
String msg = new JSONObject(responseBody).getString("msg");
if ("reject project OK".equals(msg)) {
log.info("Reject team {} OK", teamId);
} else {
log.warn("Reject team {} FAIL", teamId);
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
}
return "redirect:/admin";
}
@RequestMapping("/admin/teams/{teamId}")
public String setupTeamRestriction(
@PathVariable final String teamId,
@RequestParam(value = "action", required = true) final String action,
final RedirectAttributes redirectAttributes,
HttpSession session) throws IOException {
final String LOG_MESSAGE = "Updating restriction settings for team {}: {}";
// check if admin
if (!validateIfAdmin(session)) {
log.warn(LOG_MESSAGE, teamId, PERMISSION_DENIED);
return NO_PERMISSION_PAGE;
}
Team2 team = invokeAndExtractTeamInfo(teamId);
// check if team is approved before restricted
if ("restrict".equals(action) && team.getStatus().equals(TeamStatus.APPROVED.name())) {
return restrictTeam(team, redirectAttributes);
}
// check if team is restricted before freeing it back to approved
else if ("free".equals(action) && team.getStatus().equals(TeamStatus.RESTRICTED.name())) {
return freeTeam(team, redirectAttributes);
} else {
log.warn(LOG_MESSAGE, teamId, "Cannot " + action + " team with status " + team.getStatus());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + "Cannot " + action + " team " + team.getName() + " with status " + team.getStatus());
return "redirect:/admin/teams";
}
}
private String restrictTeam(final Team2 team, RedirectAttributes redirectAttributes) throws IOException {
log.info("Restricting team {}", team.getId());
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response = restTemplate.exchange(
properties.getSioTeamsStatusUrl(team.getId(), TeamStatus.RESTRICTED),
HttpMethod.PUT, request, String.class);
String responseBody = response.getBody().toString();
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
String logMessage = "Failed to restrict team {}: {}";
switch (exceptionState) {
case TEAM_NOT_FOUND_EXCEPTION:
log.warn(logMessage, team.getId(), TEAM_NOT_FOUND);
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + TEAM_NOT_FOUND);
break;
case INVALID_STATUS_TRANSITION_EXCEPTION:
log.warn(logMessage, team.getId(), error.getMessage());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage());
break;
case INVALID_TEAM_STATUS_EXCEPTION:
log.warn(logMessage, team.getId(), error.getMessage());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage());
break;
case FORBIDDEN_EXCEPTION:
log.warn(logMessage, team.getId(), PERMISSION_DENIED);
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + PERMISSION_DENIED);
break;
default:
log.warn(logMessage, team.getId(), exceptionState.getExceptionName());
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
}
return "redirect:/admin";
} else {
// good
log.info("Team {} has been restricted", team.getId());
redirectAttributes.addFlashAttribute(MESSAGE_SUCCESS, "Team " + team.getName() + " status has been changed to " + TeamStatus.RESTRICTED.name());
return "redirect:/admin";
}
}
private String freeTeam(final Team2 team, RedirectAttributes redirectAttributes) throws IOException {
log.info("Freeing team {}", team.getId());
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response = restTemplate.exchange(
properties.getSioTeamsStatusUrl(team.getId(), TeamStatus.APPROVED),
HttpMethod.PUT, request, String.class);
String responseBody = response.getBody().toString();
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
String logMessage = "Failed to free team {}: {}";
switch (exceptionState) {
case TEAM_NOT_FOUND_EXCEPTION:
log.warn(logMessage, team.getId(), TEAM_NOT_FOUND);
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + TEAM_NOT_FOUND);
break;
case INVALID_STATUS_TRANSITION_EXCEPTION:
log.warn(logMessage, team.getId(), error.getMessage());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage());
break;
case INVALID_TEAM_STATUS_EXCEPTION:
log.warn(logMessage, team.getId(), error.getMessage());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage());
break;
case FORBIDDEN_EXCEPTION:
log.warn(logMessage, team.getId(), PERMISSION_DENIED);
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + PERMISSION_DENIED);
break;
default:
log.warn(logMessage, team.getId(), exceptionState.getExceptionName());
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
}
return "redirect:/admin";
} else {
// good
log.info("Team {} has been freed", team.getId());
redirectAttributes.addFlashAttribute(MESSAGE_SUCCESS, "Team " + team.getName() + " status has been changed to " + TeamStatus.APPROVED.name());
return "redirect:/admin";
}
}
@RequestMapping("/admin/users/{userId}")
public String freezeUnfreezeUsers(
@PathVariable final String userId,
@RequestParam(value = "action", required = true) final String action,
final RedirectAttributes redirectAttributes,
HttpSession session) throws IOException {
User2 user = invokeAndExtractUserInfo(userId);
// check if admin
if (!validateIfAdmin(session)) {
log.warn("Access denied when trying to freeze/unfreeze user {}: must be admin!", userId);
return NO_PERMISSION_PAGE;
}
// check if user status is approved before freeze
if ("freeze".equals(action) && user.getStatus().equals(UserStatus.APPROVED.toString())) {
return freezeUser(user, redirectAttributes);
}
// check if user status is frozen before unfreeze
else if ("unfreeze".equals(action) && user.getStatus().equals(UserStatus.FROZEN.toString())) {
return unfreezeUser(user, redirectAttributes);
} else {
log.warn("Error in freeze/unfreeze user {}: failed to {} user with status {}", userId, action, user.getStatus());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + "failed to " + action + " user " + user.getEmail() + " with status " + user.getStatus());
return "redirect:/admin/users";
}
}
private String freezeUser(final User2 user, RedirectAttributes redirectAttributes) throws IOException {
log.info("Freezing user {}, email {}", user.getId(), user.getEmail());
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response = restTemplate.exchange(
properties.getSioUsersStatusUrl(user.getId(), UserStatus.FROZEN.toString()),
HttpMethod.PUT, request, String.class);
String responseBody = response.getBody().toString();
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case USER_NOT_FOUND_EXCEPTION:
log.warn("Failed to freeze user {}: user not found", user.getId());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + " user " + user.getEmail() + NOT_FOUND);
break;
case INVALID_STATUS_TRANSITION_EXCEPTION:
log.warn("Failed to freeze user {}: invalid status transition {}", user.getId(), error.getMessage());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage() + " is not allowed.");
break;
case INVALID_USER_STATUS_EXCEPTION:
log.warn("Failed to freeze user {}: invalid user status {}", user.getId(), error.getMessage());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage() + " is not a valid status.");
break;
case FORBIDDEN_EXCEPTION:
log.warn("Failed to freeze user {}: must be an Admin", user.getId());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + " permission denied.");
break;
default:
log.warn("Failed to freeze user {}: {}", user.getId(), exceptionState.getExceptionName());
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
break;
}
return "redirect:/admin";
} else {
// good
log.info("User {} has been frozen", user.getId());
redirectAttributes.addFlashAttribute(MESSAGE_SUCCESS, "User " + user.getEmail() + " has been banned.");
return "redirect:/admin";
}
}
private String unfreezeUser(final User2 user, RedirectAttributes redirectAttributes) throws IOException {
log.info("Unfreezing user {}, email {}", user.getId(), user.getEmail());
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response = restTemplate.exchange(
properties.getSioUsersStatusUrl(user.getId(), UserStatus.APPROVED.toString()),
HttpMethod.PUT, request, String.class);
String responseBody = response.getBody().toString();
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case USER_NOT_FOUND_EXCEPTION:
log.warn("Failed to unfreeze user {}: user not found", user.getId());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + " user " + user.getEmail() + NOT_FOUND);
break;
case INVALID_STATUS_TRANSITION_EXCEPTION:
log.warn("Failed to unfreeze user {}: invalid status transition {}", user.getId(), error.getMessage());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage() + " is not allowed.");
break;
case INVALID_USER_STATUS_EXCEPTION:
log.warn("Failed to unfreeze user {}: invalid user status {}", user.getId(), error.getMessage());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage() + " is not a valid status.");
break;
case FORBIDDEN_EXCEPTION:
log.warn("Failed to unfreeze user {}: must be an Admin", user.getId());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + " permission denied.");
break;
default:
log.warn("Failed to unfreeze user {}: {}", user.getId(), exceptionState.getExceptionName());
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
break;
}
return "redirect:/admin";
} else {
// good
log.info("User {} has been unfrozen", user.getId());
redirectAttributes.addFlashAttribute(MESSAGE_SUCCESS, "User " + user.getEmail() + " has been unbanned.");
return "redirect:/admin";
}
}
@RequestMapping("/admin/users/{userId}/remove")
public String removeUser(@PathVariable final String userId, final RedirectAttributes redirectAttributes, HttpSession session) throws IOException {
// check if admin
if (!validateIfAdmin(session)) {
log.warn("Access denied when trying to remove user {}: must be admin!", userId);
return NO_PERMISSION_PAGE;
}
User2 user = invokeAndExtractUserInfo(userId);
HttpEntity<String> request = createHttpEntityHeaderOnly();
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = restTemplate.exchange(properties.getUser(user.getId()), HttpMethod.DELETE, request, String.class);
String responseBody = response.getBody().toString();
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case USER_NOT_FOUND_EXCEPTION:
log.warn("Failed to remove user {}: user not found", user.getId());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + " user " + user.getEmail() + NOT_FOUND);
break;
case USER_IS_NOT_DELETABLE_EXCEPTION:
log.warn("Failed to remove user {}: user is not deletable", user.getId());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + " user " + user.getEmail() + " is not deletable.");
break;
case CREDENTIALS_NOT_FOUND_EXCEPTION:
log.warn("Failed to remove user {}: unable to find credentials", user.getId());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + " user " + user.getEmail() + " is not found.");
break;
default:
log.warn("Failed to remove user {}: {}", user.getId(), exceptionState.getExceptionName());
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
break;
}
} else {
log.info("User {} has been removed", userId);
redirectAttributes.addFlashAttribute(MESSAGE_SUCCESS, "User " + user.getEmail() + " has been removed.");
}
return "redirect:/admin/users";
}
// @RequestMapping("/admin/experiments/remove/{expId}")
// public String adminRemoveExp(@PathVariable Integer expId) {
// int teamId = experimentManager.getExperimentByExpId(expId).getTeamId();
// experimentManager.adminRemoveExperiment(expId);
//
// // decrease exp count to be display on Teams page
// teamManager.decrementExperimentCount(teamId);
// return "redirect:/admin";
// }
// @RequestMapping(value="/admin/data/contribute", method=RequestMethod.GET)
// public String adminContributeDataset(Model model) {
// model.addAttribute("dataset", new Dataset());
//
// File rootFolder = new File(App.ROOT);
// List<String> fileNames = Arrays.stream(rootFolder.listFiles())
// .map(f -> f.getError())
// .collect(Collectors.toList());
//
// model.addAttribute("files",
// Arrays.stream(rootFolder.listFiles())
// .sorted(Comparator.comparingLong(f -> -1 * f.lastModified()))
// .map(f -> f.getError())
// .collect(Collectors.toList())
// );
//
// return "admin_contribute_data";
// }
// @RequestMapping(value="/admin/data/contribute", method=RequestMethod.POST)
// public String validateAdminContributeDataset(@ModelAttribute("dataset") Dataset dataset, HttpSession session, @RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) throws IOException {
// BufferedOutputStream stream = null;
// FileOutputStream fileOutputStream = null;
// // TODO
// // validation
// // get file from user upload to server
// if (!file.isEmpty()) {
// try {
// String fileName = getSessionIdOfLoggedInUser(session) + "-" + file.getOriginalFilename();
// fileOutputStream = new FileOutputStream(new File(App.ROOT + "/" + fileName));
// stream = new BufferedOutputStream(fileOutputStream);
// FileCopyUtils.copy(file.getInputStream(), stream);
// redirectAttributes.addFlashAttribute(MESSAGE,
// "You successfully uploaded " + file.getOriginalFilename() + "!");
// datasetManager.addDataset(getSessionIdOfLoggedInUser(session), dataset, file.getOriginalFilename());
// }
// catch (Exception e) {
// redirectAttributes.addFlashAttribute(MESSAGE,
// "You failed to upload " + file.getOriginalFilename() + " => " + e.getMessage());
// } finally {
// if (stream != null) {
// stream.close();
// }
// if (fileOutputStream != null) {
// fileOutputStream.close();
// }
// }
// }
// else {
// redirectAttributes.addFlashAttribute(MESSAGE,
// "You failed to upload " + file.getOriginalFilename() + " because the file was empty");
// }
// return "redirect:/admin";
// }
// @RequestMapping("/admin/data/remove/{datasetId}")
// public String adminRemoveDataset(@PathVariable Integer datasetId) {
// datasetManager.removeDataset(datasetId);
// return "redirect:/admin";
// }
// @RequestMapping(value="/admin/node/add", method=RequestMethod.GET)
// public String adminAddNode(Model model) {
// model.addAttribute("node", new Node());
// return "admin_add_node";
// }
// @RequestMapping(value="/admin/node/add", method=RequestMethod.POST)
// public String adminAddNode(@ModelAttribute("node") Node node) {
// // TODO
// // validate fields, eg should be integer
// nodeManager.addNode(node);
// return "redirect:/admin";
// }
//--------------------------Static pages for teams--------------------------
@RequestMapping("/teams/team_application_submitted")
public String teamAppSubmitFromTeamsPage() {
return "team_page_application_submitted";
}
@RequestMapping("/teams/join_application_submitted/{teamName}")
public String teamAppJoinFromTeamsPage(@PathVariable String teamName, Model model) throws WebServiceRuntimeException {
log.info("Redirecting to join application submitted page");
HttpEntity<String> request = createHttpEntityHeaderOnly();
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = restTemplate.exchange(properties.getTeamByName(teamName), HttpMethod.GET, request, String.class);
String responseBody = response.getBody().toString();
try {
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case TEAM_NOT_FOUND_EXCEPTION:
log.warn("submitted join team request : team name error");
break;
default:
log.warn("submitted join team request : some other failure");
// possible sio or adapter connection fail
break;
}
return "redirect:/teams/join_team";
}
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
Team2 one = extractTeamInfo(responseBody);
model.addAttribute("team", one);
return "team_page_join_application_submitted";
}
//--------------------------Static pages for sign up--------------------------
@RequestMapping("/team_application_submitted")
public String teamAppSubmit() {
return "team_application_submitted";
}
/**
* A page to show new users has successfully registered to apply to join an existing team
* The page contains the team owner information which the users requested to join
*
* @param model The model which is passed from signup
* @return A success page otherwise an error page if the user tries to access this page directly
*/
@RequestMapping("/join_application_submitted")
public String joinTeamAppSubmit(Model model) {
// model attribute should be passed from /signup2
// team is required to display the team owner details
if (model.containsAttribute("team")) {
return "join_team_application_submitted";
}
return "error";
}
@RequestMapping("/email_not_validated")
public String emailNotValidated() {
return "email_not_validated";
}
@RequestMapping("/team_application_under_review")
public String teamAppUnderReview() {
return "team_application_under_review";
}
// model attribute name come from /login
@RequestMapping("/email_checklist")
public String emailChecklist(@ModelAttribute("statuschecklist") String status) {
return "email_checklist";
}
@RequestMapping("/join_application_awaiting_approval")
public String joinTeamAppAwaitingApproval(Model model) {
model.addAttribute("loginForm", new LoginForm());
model.addAttribute("signUpMergedForm", new SignUpMergedForm());
return "join_team_application_awaiting_approval";
}
//--------------------------Get List of scenarios filenames--------------------------
private List<String> getScenarioFileNameList() throws WebServiceRuntimeException {
log.info("Retrieving scenario file names");
// List<String> scenarioFileNameList = null;
// try {
// scenarioFileNameList = IOUtils.readLines(getClass().getClassLoader().getResourceAsStream("scenarios"), StandardCharsets.UTF_8);
// } catch (IOException e) {
// throw new WebServiceRuntimeException(e.getMessage());
// }
// File folder = null;
// try {
// folder = new ClassPathResource("scenarios").getFile();
// } catch (IOException e) {
// throw new WebServiceRuntimeException(e.getMessage());
// }
// List<String> scenarioFileNameList = new ArrayList<>();
// File[] files = folder.listFiles();
// for (File file : files) {
// if (file.isFile()) {
// scenarioFileNameList.add(file.getError());
// }
// }
// FIXME: hardcode list of filenames for now
List<String> scenarioFileNameList = new ArrayList<>();
scenarioFileNameList.add("Scenario 1 - Experiment with a single node");
scenarioFileNameList.add("Scenario 2 - Experiment with 2 nodes and 10Gb link");
scenarioFileNameList.add("Scenario 3 - Experiment with 3 nodes in a LAN");
scenarioFileNameList.add("Scenario 4 - Experiment with 2 nodes and customized link property");
scenarioFileNameList.add("Scenario 5 - Single SDN switch connected to two nodes");
scenarioFileNameList.add("Scenario 6 - Tree Topology with configurable SDN switches");
// scenarioFileNameList.add("Scenario 4 - Two nodes linked with a 10Gbps SDN switch");
// scenarioFileNameList.add("Scenario 5 - Three nodes with Blockchain capabilities");
log.info("Scenario file list: {}", scenarioFileNameList);
return scenarioFileNameList;
}
private String getScenarioContentsFromFile(String scenarioFileName) throws WebServiceRuntimeException {
// FIXME: switch to better way of referencing scenario descriptions to actual filenames
String actualScenarioFileName;
if (scenarioFileName.contains("Scenario 1")) {
actualScenarioFileName = "basic1.ns";
} else if (scenarioFileName.contains("Scenario 2")) {
actualScenarioFileName = "basic2.ns";
} else if (scenarioFileName.contains("Scenario 3")) {
actualScenarioFileName = "basic3.ns";
} else if (scenarioFileName.contains("Scenario 4")) {
actualScenarioFileName = "basic4.ns";
} else if (scenarioFileName.contains("Scenario 5")) {
actualScenarioFileName = "basic5.ns";
} else if (scenarioFileName.contains("Scenario 6")) {
actualScenarioFileName = "basic6.ns";
} else {
// defaults to basic single node
actualScenarioFileName = "basic1.ns";
}
try {
log.info("Retrieving scenario files {}", getClass().getClassLoader().getResourceAsStream("scenarios/" + actualScenarioFileName));
List<String> lines = IOUtils.readLines(getClass().getClassLoader().getResourceAsStream("scenarios/" + actualScenarioFileName), StandardCharsets.UTF_8);
StringBuilder sb = new StringBuilder();
for (String line : lines) {
sb.append(line);
sb.append(System.getProperty("line.separator"));
}
log.info("Experiment ns file contents: {}", sb);
return sb.toString();
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
}
//---Check if user is a team owner and has any join request waiting for approval----
private boolean hasAnyJoinRequest(HashMap<Integer, Team> teamMapOwnedByUser) {
for (Map.Entry<Integer, Team> entry : teamMapOwnedByUser.entrySet()) {
Team currTeam = entry.getValue();
if (currTeam.isUserJoinRequestEmpty() == false) {
// at least one team has join user request
return true;
}
}
// loop through all teams but never return a single true
// therefore, user's controlled teams has no join request
return false;
}
//--------------------------MISC--------------------------
private int getSessionIdOfLoggedInUser(HttpSession session) {
return Integer.parseInt(session.getAttribute(SESSION_LOGGED_IN_USER_ID).toString());
}
private User2 extractUserInfo(String userJson) {
User2 user2 = new User2();
if (userJson == null) {
// return empty user
return user2;
}
JSONObject object = new JSONObject(userJson);
JSONObject userDetails = object.getJSONObject("userDetails");
JSONObject address = userDetails.getJSONObject("address");
user2.setId(object.getString("id"));
user2.setFirstName(getJSONStr(userDetails.getString("firstName")));
user2.setLastName(getJSONStr(userDetails.getString("lastName")));
user2.setJobTitle(userDetails.getString("jobTitle"));
user2.setEmail(userDetails.getString("email"));
user2.setPhone(userDetails.getString("phone"));
user2.setAddress1(address.getString("address1"));
user2.setAddress2(address.getString("address2"));
user2.setCountry(address.getString("country"));
user2.setRegion(address.getString("region"));
user2.setPostalCode(address.getString("zipCode"));
user2.setCity(address.getString("city"));
user2.setInstitution(userDetails.getString("institution"));
user2.setInstitutionAbbreviation(userDetails.getString("institutionAbbreviation"));
user2.setInstitutionWeb(userDetails.getString("institutionWeb"));
user2.setStatus(object.getString("status"));
user2.setEmailVerified(object.getBoolean("emailVerified"));
// applicationDate is ZonedDateTime
try {
user2.setApplicationDate(object.get(APPLICATION_DATE).toString());
} catch (Exception e) {
// since applicationDate date is a ZonedDateTime and not String
// set to '?' at the html page
log.warn("Error getting user application date {}", e);
}
return user2;
}
private Team2 extractTeamInfo(String json) {
Team2 team2 = new Team2();
JSONObject object = new JSONObject(json);
JSONArray membersArray = object.getJSONArray("members");
// createdDate is ZonedDateTime
// processedDate is ZonedDateTime
try {
team2.setApplicationDate(object.get(APPLICATION_DATE).toString());
team2.setProcessedDate(object.get("processedDate").toString());
} catch (Exception e) {
log.warn("Error getting team application date and/or processedDate {}", e);
// created date is a ZonedDateTime
// since created date and proccessed date is a ZonedDateTime and not String
// both is set to '?' at the html page if exception
}
team2.setId(object.getString("id"));
team2.setName(object.getString("name"));
team2.setDescription(object.getString("description"));
team2.setWebsite(object.getString("website"));
team2.setOrganisationType(object.getString("organisationType"));
team2.setStatus(object.getString("status"));
team2.setVisibility(object.getString("visibility"));
for (int i = 0; i < membersArray.length(); i++) {
JSONObject memberObject = membersArray.getJSONObject(i);
String userId = memberObject.getString("userId");
String teamMemberType = memberObject.getString(MEMBER_TYPE);
String teamMemberStatus = memberObject.getString("memberStatus");
User2 myUser = invokeAndExtractUserInfo(userId);
if (teamMemberType.equals(MemberType.MEMBER.name())) {
// add to pending members list for Members Awaiting Approval function
if (teamMemberStatus.equals(MemberStatus.PENDING.name())) {
team2.addPendingMembers(myUser);
}
} else if (teamMemberType.equals(MemberType.OWNER.name())) {
// explicit safer check
team2.setOwner(myUser);
}
team2.addMembersToStatusMap(MemberStatus.valueOf(teamMemberStatus), myUser);
}
team2.setMembersCount(team2.getMembersStatusMap().get(MemberStatus.APPROVED).size());
return team2;
}
// use to extract JSON Strings from services
// in the case where the JSON Strings are null, return "Connection Error"
private String getJSONStr(String jsonString) {
if (jsonString == null || jsonString.isEmpty()) {
return CONNECTION_ERROR;
}
return jsonString;
}
/**
* Checks if user is pending for join request approval from team leader
* Use for fixing bug for view experiment page where users previously can view the experiments just by issuing a join request
*
* @param json the response body after calling team service
* @param loginUserId the current logged in user id
* @return True if the user is anything but APPROVED, false otherwise
*/
private boolean isMemberJoinRequestPending(String loginUserId, String json) {
if (json == null) {
return true;
}
JSONObject object = new JSONObject(json);
JSONArray membersArray = object.getJSONArray("members");
for (int i = 0; i < membersArray.length(); i++) {
JSONObject memberObject = membersArray.getJSONObject(i);
String userId = memberObject.getString("userId");
String teamMemberStatus = memberObject.getString("memberStatus");
if (userId.equals(loginUserId) && !teamMemberStatus.equals(MemberStatus.APPROVED.toString())) {
return true;
}
}
log.info("User: {} is viewing experiment page", loginUserId);
return false;
}
private Team2 extractTeamInfoUserJoinRequest(String userId, String json) {
Team2 team2 = new Team2();
JSONObject object = new JSONObject(json);
JSONArray membersArray = object.getJSONArray("members");
for (int i = 0; i < membersArray.length(); i++) {
JSONObject memberObject = membersArray.getJSONObject(i);
String uid = memberObject.getString("userId");
String teamMemberStatus = memberObject.getString("memberStatus");
if (uid.equals(userId) && teamMemberStatus.equals(MemberStatus.PENDING.toString())) {
team2.setId(object.getString("id"));
team2.setName(object.getString("name"));
team2.setDescription(object.getString("description"));
team2.setWebsite(object.getString("website"));
team2.setOrganisationType(object.getString("organisationType"));
team2.setStatus(object.getString("status"));
team2.setVisibility(object.getString("visibility"));
team2.setMembersCount(membersArray.length());
return team2;
}
}
// no such member in the team found
return null;
}
protected Dataset invokeAndExtractDataInfo(Long dataId) {
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response = restTemplate.exchange(properties.getDataset(dataId.toString()), HttpMethod.GET, request, String.class);
return extractDataInfo(response.getBody().toString());
}
protected Dataset extractDataInfo(String json) {
log.debug(json);
JSONObject object = new JSONObject(json);
Dataset dataset = new Dataset();
dataset.setId(object.getInt("id"));
dataset.setName(object.getString("name"));
dataset.setDescription(object.getString("description"));
dataset.setContributorId(object.getString("contributorId"));
dataset.addVisibility(object.getString("visibility"));
dataset.addAccessibility(object.getString("accessibility"));
try {
dataset.setReleasedDate(getZonedDateTime(object.get("releasedDate").toString()));
} catch (IOException e) {
log.warn("Error getting released date {}", e);
dataset.setReleasedDate(null);
}
dataset.setCategoryId(object.getInt("categoryId"));
dataset.setLicenseId(object.getInt("licenseId"));
dataset.setContributor(invokeAndExtractUserInfo(dataset.getContributorId()));
dataset.setCategory(invokeAndExtractCategoryInfo(dataset.getCategoryId()));
dataset.setLicense(invokeAndExtractLicenseInfo(dataset.getLicenseId()));
JSONArray resources = object.getJSONArray("resources");
for (int i = 0; i < resources.length(); i++) {
JSONObject resource = resources.getJSONObject(i);
DataResource dataResource = new DataResource();
dataResource.setId(resource.getLong("id"));
dataResource.setUri(resource.getString("uri"));
dataResource.setMalicious(resource.getBoolean("malicious"));
dataResource.setScanned(resource.getBoolean("scanned"));
dataset.addResource(dataResource);
}
JSONArray approvedUsers = object.getJSONArray("approvedUsers");
for (int i = 0; i < approvedUsers.length(); i++) {
dataset.addApprovedUser(approvedUsers.getString(i));
}
JSONArray keywords = object.getJSONArray("keywords");
List<String> keywordList = new ArrayList<>();
for (int i = 0; i < keywords.length(); i++) {
keywordList.add(keywords.getString(i));
}
dataset.setKeywordList(keywordList);
return dataset;
}
protected DataCategory extractCategoryInfo(String json) {
log.debug(json);
DataCategory dataCategory = new DataCategory();
JSONObject object = new JSONObject(json);
dataCategory.setId(object.getLong("id"));
dataCategory.setName(object.getString("name"));
dataCategory.setDescription(object.getString("description"));
return dataCategory;
}
protected DataLicense extractLicenseInfo(String json) {
log.debug(json);
DataLicense dataLicense = new DataLicense();
JSONObject object = new JSONObject(json);
dataLicense.setId(object.getLong("id"));
dataLicense.setName(object.getString("name"));
dataLicense.setAcronym(object.getString("acronym"));
dataLicense.setDescription(object.getString("description"));
dataLicense.setLink(object.getString("link"));
return dataLicense;
}
protected DataCategory invokeAndExtractCategoryInfo(Integer categoryId) {
HttpEntity<String> request = createHttpEntityHeaderOnlyNoAuthHeader();
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getCategory(categoryId), HttpMethod.GET, request, String.class);
} catch (Exception e) {
log.warn("Data service not available to retrieve Category: {}", categoryId);
return new DataCategory();
}
return extractCategoryInfo(response.getBody().toString());
}
protected DataLicense invokeAndExtractLicenseInfo(Integer licenseId) {
HttpEntity<String> request = createHttpEntityHeaderOnlyNoAuthHeader();
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getLicense(licenseId), HttpMethod.GET, request, String.class);
} catch (Exception e) {
log.warn("Data service not available to retrieve License: {}", licenseId);
return new DataLicense();
}
return extractLicenseInfo(response.getBody().toString());
}
protected User2 invokeAndExtractUserInfo(String userId) {
HttpEntity<String> request = createHttpEntityHeaderOnlyNoAuthHeader();
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getUser(userId), HttpMethod.GET, request, String.class);
} catch (Exception e) {
log.warn("User service not available to retrieve User: {}", userId);
return new User2();
}
return extractUserInfo(response.getBody().toString());
}
private Team2 invokeAndExtractTeamInfo(String teamId) {
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity responseEntity = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, request, String.class);
return extractTeamInfo(responseEntity.getBody().toString());
}
private Experiment2 extractExperiment(String experimentJson) {
Experiment2 experiment2 = new Experiment2();
JSONObject object = new JSONObject(experimentJson);
experiment2.setId(object.getLong("id"));
experiment2.setUserId(object.getString("userId"));
experiment2.setTeamId(object.getString(TEAM_ID));
experiment2.setTeamName(object.getString(TEAM_NAME));
experiment2.setName(object.getString("name"));
experiment2.setDescription(object.getString("description"));
experiment2.setNsFile(object.getString("nsFile"));
experiment2.setNsFileContent(object.getString("nsFileContent"));
experiment2.setIdleSwap(object.getInt("idleSwap"));
experiment2.setMaxDuration(object.getInt("maxDuration"));
return experiment2;
}
private Realization invokeAndExtractRealization(String teamName, Long id) {
HttpEntity<String> request = createHttpEntityHeaderOnly();
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = null;
try {
log.info("retrieving the latest exp status: {}", properties.getRealizationByTeam(teamName, id.toString()));
response = restTemplate.exchange(properties.getRealizationByTeam(teamName, id.toString()), HttpMethod.GET, request, String.class);
} catch (Exception e) {
return getCleanRealization();
}
String responseBody;
if (response.getBody() == null) {
return getCleanRealization();
} else {
responseBody = response.getBody().toString();
}
try {
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
log.warn("error in retrieving realization for team: {}, realization: {}", teamName, id);
return getCleanRealization();
} else {
// will throw JSONException if the format return by sio is not a valid JSOn format
// will occur if the realization details are still in the old format
return extractRealization(responseBody);
}
} catch (IOException | JSONException e) {
return getCleanRealization();
}
}
private Realization extractRealization(String json) {
log.info("extracting realization: {}", json);
Realization realization = new Realization();
JSONObject object = new JSONObject(json);
realization.setExperimentId(object.getLong("experimentId"));
realization.setExperimentName(object.getString("experimentName"));
realization.setUserId(object.getString("userId"));
realization.setTeamId(object.getString(TEAM_ID));
realization.setState(object.getString("state"));
String exp_report = "";
Object expDetailsObject = object.get("details");
log.info("exp detail object: {}", expDetailsObject);
if (expDetailsObject == JSONObject.NULL || expDetailsObject.toString().isEmpty()) {
log.info("set details empty");
realization.setDetails("");
realization.setNumberOfNodes(0);
} else {
log.info("exp report to string: {}", expDetailsObject.toString());
exp_report = expDetailsObject.toString();
realization.setDetails(exp_report);
JSONObject nodesInfoObject = new JSONObject(expDetailsObject.toString());
for (Object key : nodesInfoObject.keySet()) {
Map<String, String> nodeDetails = new HashMap<>();
String nodeName = (String) key;
JSONObject nodeDetailsJson = new JSONObject(nodesInfoObject.get(nodeName).toString());
nodeDetails.put("os", getValueFromJSONKey(nodeDetailsJson, "os"));
nodeDetails.put("qualifiedName", getValueFromJSONKey(nodeDetailsJson, "qualifiedName"));
nodeDetails.put(NODE_ID, getValueFromJSONKey(nodeDetailsJson, NODE_ID));
realization.addNodeDetails(nodeName, nodeDetails);
}
log.info("nodes info object: {}", nodesInfoObject);
realization.setNumberOfNodes(nodesInfoObject.keySet().size());
}
return realization;
}
// gets the value that corresponds to a particular key
// checks if a particular key in the JSONObject exists
// returns the value if the key exists, otherwise, returns N.A.
private String getValueFromJSONKey(JSONObject json, String key) {
if (json.has(key)) {
return json.get(key).toString();
}
return NOT_APPLICABLE;
}
/**
* @param zonedDateTimeJSON JSON string
* @return a date in the format MMM-d-yyyy
*/
protected String formatZonedDateTime(String zonedDateTimeJSON) throws Exception {
ZonedDateTime zonedDateTime = getZonedDateTime(zonedDateTimeJSON);
DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM-d-yyyy");
return zonedDateTime.format(format);
}
protected ZonedDateTime getZonedDateTime(String zonedDateTimeJSON) throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
return mapper.readValue(zonedDateTimeJSON, ZonedDateTime.class);
}
/**
* Creates a HttpEntity with a request body and header but no authorization header
* To solve the expired jwt token
*
* @param jsonString The JSON request converted to string
* @return A HttpEntity request
* @see HttpEntity createHttpEntityHeaderOnly() for request with only header
*/
protected HttpEntity<String> createHttpEntityWithBodyNoAuthHeader(String jsonString) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
return new HttpEntity<>(jsonString, headers);
}
/**
* Creates a HttpEntity that contains only a header and empty body but no authorization header
* To solve the expired jwt token
*
* @return A HttpEntity request
* @see HttpEntity createHttpEntityWithBody() for request with both body and header
*/
protected HttpEntity<String> createHttpEntityHeaderOnlyNoAuthHeader() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
return new HttpEntity<>(headers);
}
/**
* Creates a HttpEntity with a request body and header
*
* @param jsonString The JSON request converted to string
* @return A HttpEntity request
* @implNote Authorization header must be set to the JwTToken in the format [Bearer: TOKEN_ID]
* @see HttpEntity createHttpEntityHeaderOnly() for request with only header
*/
protected HttpEntity<String> createHttpEntityWithBody(String jsonString) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization", httpScopedSession.getAttribute(webProperties.getSessionJwtToken()).toString());
return new HttpEntity<>(jsonString, headers);
}
/**
* Creates a HttpEntity that contains only a header and empty body
*
* @return A HttpEntity request
* @implNote Authorization header must be set to the JwTToken in the format [Bearer: TOKEN_ID]
* @see HttpEntity createHttpEntityWithBody() for request with both body and header
*/
protected HttpEntity<String> createHttpEntityHeaderOnly() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization", httpScopedSession.getAttribute(webProperties.getSessionJwtToken()).toString());
return new HttpEntity<>(headers);
}
private void setSessionVariables(HttpSession session, String loginEmail, String id, String firstName, String userRoles, String token) {
User2 user = invokeAndExtractUserInfo(id);
session.setAttribute(webProperties.getSessionEmail(), loginEmail);
session.setAttribute(webProperties.getSessionUserId(), id);
session.setAttribute(webProperties.getSessionUserFirstName(), firstName);
session.setAttribute(webProperties.getSessionRoles(), userRoles);
session.setAttribute(webProperties.getSessionJwtToken(), "Bearer " + token);
log.info("Session variables - sessionLoggedEmail: {}, id: {}, name: {}, roles: {}, token: {}", loginEmail, id, user.getFirstName(), userRoles, token);
}
private void removeSessionVariables(HttpSession session) {
log.info("removing session variables: email: {}, userid: {}, user first name: {}", session.getAttribute(webProperties.getSessionEmail()), session.getAttribute(webProperties.getSessionUserId()), session.getAttribute(webProperties.getSessionUserFirstName()));
session.removeAttribute(webProperties.getSessionEmail());
session.removeAttribute(webProperties.getSessionUserId());
session.removeAttribute(webProperties.getSessionUserFirstName());
session.removeAttribute(webProperties.getSessionRoles());
session.removeAttribute(webProperties.getSessionJwtToken());
session.invalidate();
}
protected boolean validateIfAdmin(HttpSession session) {
//log.info("User: {} is logged on as: {}", session.getAttribute(webProperties.getSessionEmail()), session.getAttribute(webProperties.getSessionRoles()));
return session.getAttribute(webProperties.getSessionRoles()).equals(UserType.ADMIN.toString());
}
/**
* Ensure that only users of the team can realize or un-realize experiment
* A pre-condition is that the users must be approved.
* Teams must also be approved.
*
* @return the main experiment page
*/
private boolean checkPermissionRealizeExperiment(Realization realization, HttpSession session) {
// get list of teamids
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity userRespEntity = restTemplate.exchange(properties.getUser(session.getAttribute("id").toString()), HttpMethod.GET, request, String.class);
JSONObject object = new JSONObject(userRespEntity.getBody().toString());
JSONArray teamIdsJsonArray = object.getJSONArray("teams");
for (int i = 0; i < teamIdsJsonArray.length(); i++) {
String teamId = teamIdsJsonArray.get(i).toString();
if (teamId.equals(realization.getTeamId())) {
return true;
}
}
return false;
}
private String getTeamStatus(String teamId) {
Team2 team = invokeAndExtractTeamInfo(teamId);
return team.getStatus();
}
private Realization getCleanRealization() {
Realization realization = new Realization();
realization.setExperimentId(0L);
realization.setExperimentName("");
realization.setUserId("");
realization.setTeamId("");
realization.setState(RealizationState.ERROR.toString());
realization.setDetails("");
realization.setNumberOfNodes(0);
return realization;
}
/**
* Computes the number of teams that the user is in and the number of running experiments to populate data for the user dashboard
*
* @return a map in the form teams: numberOfTeams, experiments: numberOfExperiments
*/
private Map<String, Integer> getUserDashboardStats(String userId) {
int numberOfRunningExperiments = 0;
Map<String, Integer> userDashboardStats = new HashMap<>();
// get list of teamids
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity userRespEntity = restTemplate.exchange(properties.getUser(userId), HttpMethod.GET, request, String.class);
JSONObject object = new JSONObject(userRespEntity.getBody().toString());
JSONArray teamIdsJsonArray = object.getJSONArray("teams");
int numberOfApprovedTeam = 0;
for (int i = 0; i < teamIdsJsonArray.length(); i++) {
String teamId = teamIdsJsonArray.get(i).toString();
HttpEntity<String> teamRequest = createHttpEntityHeaderOnly();
ResponseEntity teamResponse = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, teamRequest, String.class);
String teamResponseBody = teamResponse.getBody().toString();
if (!isMemberJoinRequestPending(userId, teamResponseBody)) {
// get experiments lists of the teams
HttpEntity<String> expRequest = createHttpEntityHeaderOnly();
ResponseEntity expRespEntity = restTemplate.exchange(properties.getExpListByTeamId(teamId), HttpMethod.GET, expRequest, String.class);
JSONArray experimentsArray = new JSONArray(expRespEntity.getBody().toString());
numberOfRunningExperiments = getNumberOfRunningExperiments(numberOfRunningExperiments, experimentsArray);
numberOfApprovedTeam ++;
}
}
userDashboardStats.put(USER_DASHBOARD_APPROVED_TEAMS, numberOfApprovedTeam);
userDashboardStats.put(USER_DASHBOARD_RUNNING_EXPERIMENTS, numberOfRunningExperiments);
// userDashboardStats.put(USER_DASHBOARD_FREE_NODES, getNodes(NodeType.FREE));
return userDashboardStats;
}
private int getNumberOfRunningExperiments(int numberOfRunningExperiments, JSONArray experimentsArray) {
for (int k = 0; k < experimentsArray.length(); k++) {
Experiment2 experiment2 = extractExperiment(experimentsArray.getJSONObject(k).toString());
Realization realization = invokeAndExtractRealization(experiment2.getTeamName(), experiment2.getId());
if (realization.getState().equals(RealizationState.RUNNING.toString())) {
numberOfRunningExperiments++;
}
}
return numberOfRunningExperiments;
}
private SortedMap<String, Map<String, String>> getGlobalImages() throws IOException {
SortedMap<String, Map<String, String>> globalImagesMap = new TreeMap<>();
log.info("Retrieving list of global images from: {}", properties.getGlobalImages());
try {
HttpEntity<String> request = createHttpEntityHeaderOnlyNoAuthHeader();
ResponseEntity response = restTemplate.exchange(properties.getGlobalImages(), HttpMethod.GET, request, String.class);
ObjectMapper mapper = new ObjectMapper();
String json = new JSONObject(response.getBody().toString()).getString("images");
globalImagesMap = mapper.readValue(json, new TypeReference<SortedMap<String, Map<String, String>>>() {
});
} catch (RestClientException e) {
log.warn("Error connecting to service-image: {}", e);
}
return globalImagesMap;
}
private int getNodes(NodeType nodeType) {
String nodesCount;
log.info("Retrieving number of " + nodeType + " nodes from: {}", properties.getNodes(nodeType));
try {
HttpEntity<String> request = createHttpEntityHeaderOnlyNoAuthHeader();
ResponseEntity response = restTemplate.exchange(properties.getNodes(nodeType), HttpMethod.GET, request, String.class);
JSONObject object = new JSONObject(response.getBody().toString());
nodesCount = object.getString(nodeType.name());
} catch (RestClientException e) {
log.warn(ERROR_CONNECTING_TO_SERVICE_TELEMETRY, e);
nodesCount = "0";
}
return Integer.parseInt(nodesCount);
}
private List<TeamUsageInfo> getTeamsUsageStatisticsForUser(String userId) {
List<TeamUsageInfo> usageInfoList = new ArrayList<>();
// get list of teamids
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity userRespEntity = restTemplate.exchange(properties.getUser(userId), HttpMethod.GET, request, String.class);
JSONObject object = new JSONObject(userRespEntity.getBody().toString());
JSONArray teamIdsJsonArray = object.getJSONArray("teams");
// get team info by team id
for (int i = 0; i < teamIdsJsonArray.length(); i++) {
String teamId = teamIdsJsonArray.get(i).toString();
HttpEntity<String> teamRequest = createHttpEntityHeaderOnly();
ResponseEntity teamResponse = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, teamRequest, String.class);
String teamResponseBody = teamResponse.getBody().toString();
if (!isMemberJoinRequestPending(userId, teamResponseBody)) {
TeamUsageInfo usageInfo = new TeamUsageInfo();
usageInfo.setId(teamId);
usageInfo.setName(new JSONObject(teamResponseBody).getString("name"));
usageInfo.setUsage(getUsageStatisticsByTeamId(teamId));
usageInfoList.add(usageInfo);
}
}
return usageInfoList;
}
private String getUsageStatisticsByTeamId(String id) {
log.info("Getting usage statistics for team {}", id);
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getUsageStat(id), HttpMethod.GET, request, String.class);
} catch (RestClientException e) {
log.warn("Error connecting to sio get usage statistics {}", e);
return "?";
}
return response.getBody().toString();
}
private TeamQuota extractTeamQuotaInfo(String responseBody) {
JSONObject object = new JSONObject(responseBody);
TeamQuota teamQuota = new TeamQuota();
Double charges = Double.parseDouble(accountingProperties.getCharges());
// amountUsed from SIO will never be null => not checking for null value
String usage = object.getString("usage"); // getting usage in String
BigDecimal amountUsed = new BigDecimal(usage); // using BigDecimal to handle currency
amountUsed = amountUsed.multiply(new BigDecimal(charges)); // usage X charges
//quota passed from SIO can be null , so we have to check for null value
if (object.has("quota")) {
Object budgetObject = object.optString("quota", null);
if (budgetObject == null) {
teamQuota.setBudget(""); // there is placeholder here
teamQuota.setResourcesLeft("Unlimited"); // not placeholder so can pass string over
} else {
Double budgetInDouble = object.getDouble("quota"); // retrieve budget from SIO in Double
BigDecimal budgetInBD = BigDecimal.valueOf(budgetInDouble); // handling currency using BigDecimal
// calculate resoucesLeft
BigDecimal resourceLeftInBD = budgetInBD.subtract(amountUsed);
resourceLeftInBD = resourceLeftInBD.divide(new BigDecimal(charges), 0, BigDecimal.ROUND_DOWN);
budgetInBD = budgetInBD.setScale(2, BigDecimal.ROUND_HALF_UP);
// set budget
teamQuota.setBudget(budgetInBD.toString());
//set resroucesLeft
if (resourceLeftInBD.compareTo(BigDecimal.valueOf(0)) < 0)
teamQuota.setResourcesLeft("0");
else
teamQuota.setResourcesLeft(resourceLeftInBD.toString());
}
}
//set teamId and amountUsed
teamQuota.setTeamId(object.getString(TEAM_ID));
amountUsed = amountUsed.setScale(2, BigDecimal.ROUND_HALF_UP);
teamQuota.setAmountUsed(amountUsed.toString());
return teamQuota;
}
/**
* Invokes the get nodes status in the telemetry service
* @return a map containing a list of nodes status by their type
*/
private Map<String, List<Map<String, String>>> getNodesStatus() throws IOException {
log.info("Getting all nodes' status from: {}", properties.getNodesStatus());
Map<String, List<Map<String, String>>> output = new HashMap<>();
try {
HttpEntity<String> request = createHttpEntityHeaderOnlyNoAuthHeader();
ResponseEntity response = restTemplate.exchange(properties.getNodesStatus(), HttpMethod.GET, request, String.class);
JSONObject object = new JSONObject(response.getBody().toString());
if (object == JSONObject.NULL || object.length() == 0) {
return output;
} else {
// loop through the object as there may be more than one machine type
for (int i = 0; i < object.names().length(); i++) {
// for each machine type, get all the current nodes status
String currentMachineType = object.names().getString(i);
// converts the JSON Array of the form [ { id : A, status : B, type : C } ] into a proper list of map
List<Map<String, String>> nodesList = objectMapper.readValue(object.getJSONArray(currentMachineType).toString(), new TypeReference<List<Map>>(){});
output.put(currentMachineType, nodesList);
}
}
} catch (RestClientException e) {
log.warn(ERROR_CONNECTING_TO_SERVICE_TELEMETRY, e);
return new HashMap<>();
}
log.info("Finish getting all nodes: {}", output);
return output;
}
private Map<String,String> getTestbedStats() {
Map<String, String> statsMap = new HashMap<>();
log.info("Retrieving number of logged in users and running experiments from: {}", properties.getTestbedStats());
try {
HttpEntity<String> request = createHttpEntityHeaderOnlyNoAuthHeader();
ResponseEntity response = restTemplate.exchange(properties.getTestbedStats(), HttpMethod.GET, request, String.class);
JSONObject object = new JSONObject(response.getBody().toString());
statsMap.put(USER_DASHBOARD_LOGGED_IN_USERS_COUNT, object.getString("users"));
statsMap.put(USER_DASHBOARD_RUNNING_EXPERIMENTS_COUNT, object.getString("experiments"));
} catch (RestClientException e) {
log.warn(ERROR_CONNECTING_TO_SERVICE_TELEMETRY, e);
statsMap.put(USER_DASHBOARD_LOGGED_IN_USERS_COUNT, "0");
statsMap.put(USER_DASHBOARD_RUNNING_EXPERIMENTS_COUNT, "0");
}
return statsMap;
}
}
|
add data table for exp
Signed-off-by: Tran Ly Vu <0555cc0f3d5a46ac8c0e84ddf31443494c66bd55@gmail.com>
|
src/main/java/sg/ncl/MainController.java
|
add data table for exp
|
|
Java
|
apache-2.0
|
925eff9398e13a2076eccd9ac7e83555055cbf9e
| 0
|
nus-ncl/service-web,nus-ncl/service-web,nus-ncl/service-web,nus-ncl/service-web
|
package sg.ncl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.tomcat.util.codec.binary.Base64;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.support.RequestContextUtils;
import sg.ncl.domain.*;
import sg.ncl.exceptions.*;
import sg.ncl.testbed_interface.*;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Pattern;
import static java.time.temporal.TemporalAdjusters.firstDayOfMonth;
import static java.time.temporal.TemporalAdjusters.lastDayOfMonth;
import static sg.ncl.domain.ExceptionState.*;
/**
*
* Spring Controller
* Direct the views to appropriate locations and invoke the respective REST API
*
* @author Cassie, Desmond, Te Ye, Vu
*/
@Controller
@Slf4j
public class MainController {
public static final String CONTENT_DISPOSITION = "Content-Disposition";
public static final String APPLICATION_FORCE_DOWNLOAD = "application/force-download";
private static final String SESSION_LOGGED_IN_USER_ID = "loggedInUserId";
private TeamManager teamManager = TeamManager.getInstance();
// private UserManager userManager = UserManager.getInstance();
// private ExperimentManager experimentManager = ExperimentManager.getInstance();
// private DomainManager domainManager = DomainManager.getInstance();
// private DatasetManager datasetManager = DatasetManager.getInstance();
// private NodeManager nodeManager = NodeManager.getInstance();
private static final String CONTACT_EMAIL = "support@ncl.sg";
private static final String UNKNOWN = "?";
private static final String MESSAGE = "message";
private static final String MESSAGE_SUCCESS = "messageSuccess";
private static final String EXPERIMENT_MESSAGE = "exp_message";
private static final String ERROR_PREFIX = "Error: ";
// error messages
private static final String ERR_SERVER_OVERLOAD = "There is a problem with your request. Please contact " + CONTACT_EMAIL;
private static final String CONNECTION_ERROR = "Connection Error";
private final String permissionDeniedMessage = "Permission denied. If the error persists, please contact " + CONTACT_EMAIL;
// for user dashboard hashmap key values
private static final String USER_DASHBOARD_TEAMS = "teams";
private static final String USER_DASHBOARD_RUNNING_EXPERIMENTS = "runningExperiments";
private static final String USER_DASHBOARD_FREE_NODES = "freeNodes";
private static final String USER_DASHBOARD_TOTAL_NODES = "totalNodes";
private static final String USER_DASHBOARD_GLOBAL_IMAGES = "globalImagesMap";
private static final String DETER_UID = "deterUid";
private static final Pattern VALID_EMAIL_ADDRESS_REGEX =
Pattern.compile("(?:(?:\\r\\n)?[ \\t])*(?:(?:(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*\\<(?:(?:\\r\\n)?[ \\t])*(?:@(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*(?:,@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*)*:(?:(?:\\r\\n)?[ \\t])*)?(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\>(?:(?:\\r\\n)?[ \\t])*)|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*:(?:(?:\\r\\n)?[ \\t])*(?:(?:(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*\\<(?:(?:\\r\\n)?[ \\t])*(?:@(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*(?:,@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*)*:(?:(?:\\r\\n)?[ \\t])*)?(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\>(?:(?:\\r\\n)?[ \\t])*)(?:,\\s*(?:(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*\\<(?:(?:\\r\\n)?[ \\t])*(?:@(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*(?:,@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*)*:(?:(?:\\r\\n)?[ \\t])*)?(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\>(?:(?:\\r\\n)?[ \\t])*))*)?;\\s*)");
private static final String FORGET_PSWD_PAGE = "password_reset_email";
private static final String FORGET_PSWD_NEW_PSWD_PAGE = "password_reset_new_password";
private static final String NO_PERMISSION_PAGE = "nopermission";
private static final String TEAM_NAME = "teamName";
private static final String TEAM_ID = "teamId";
private static final String NODE_ID = "nodeId";
private static final String PERMISSION_DENIED = "Permission denied";
private static final String TEAM_NOT_FOUND = "Team not found";
private static final String EDIT_BUDGET = "editBudget";
private static final String ORIGINAL_BUDGET = "originalBudget";
private static final String REDIRECT_TEAM_PROFILE_TEAM_ID = "redirect:/team_profile/{teamId}";
private static final String REDIRECT_TEAM_PROFILE = "redirect:/team_profile/";
// remove members from team profile; to display the list of experiments created by user
private static final String REMOVE_MEMBER_UID = "removeMemberUid";
private static final String REMOVE_MEMBER_NAME = "removeMemberName";
private static final String MEMBER_TYPE = "memberType";
@Autowired
protected RestTemplate restTemplate;
@Inject
protected ObjectMapper objectMapper;
@Inject
protected ConnectionProperties properties;
@Inject
protected WebProperties webProperties;
@Inject
protected AccountingProperties accountingProperties;
@Inject
protected HttpSession httpScopedSession;
@RequestMapping("/")
public String index() {
return "index";
}
@RequestMapping("/overview")
public String overview() {
return "overview";
}
@RequestMapping("/community")
public String community() {
return "community";
}
@RequestMapping("/about")
public String about() {
return "about";
}
@RequestMapping("/event")
public String event() {
return "event";
}
@RequestMapping("/plan")
public String plan() {
return "plan";
}
// @RequestMapping("/futureplan")
// public String futureplan() {
// return "futureplan";
// }
@RequestMapping("/pricing")
public String pricing() {
return "pricing";
}
@RequestMapping("/resources")
public String resources() {
return "resources";
}
@RequestMapping("/research")
public String research() {
return "research";
}
@RequestMapping("/calendar")
public String calendar() {
return "calendar";
}
@RequestMapping("/tools")
public String tools() {
return "tools";
}
@RequestMapping("/tutorials/createaccount")
public String createAccount() {
return "createaccount";
}
@RequestMapping("/tutorials/createexperiment")
public String createExperimentTutorial() {
return "createexperiment";
}
@RequestMapping("/tutorials/loadimage")
public String loadimage() {
return "loadimage";
}
@RequestMapping("/tutorials/saveimage")
public String saveimage() {
return "saveimage";
}
@RequestMapping("/tutorials/applyteam")
public String applyteam() {
return "applyteam";
}
@RequestMapping("/tutorials/jointeam")
public String jointeam() {
return "jointeam";
}
@RequestMapping("/error_openstack")
public String error_openstack() {
return "error_openstack";
}
@RequestMapping("/accessexperiment")
public String accessexperiment() {
return "accessexperiment";
}
@RequestMapping("/resource2")
public String resource2() {
return "resource2";
}
// @RequestMapping("/admin2")
// public String admin2() {
// return "admin2";
// }
@RequestMapping("/tutorials")
public String tutorials() {
return "tutorials";
}
@RequestMapping("/maintainance")
public String maintainance() {
return "maintainance";
}
@RequestMapping("/testbedInformation")
public String testbedInformation(Model model) throws IOException {
model.addAttribute(USER_DASHBOARD_GLOBAL_IMAGES, getGlobalImages());
model.addAttribute(USER_DASHBOARD_TOTAL_NODES, getNodes(NodeType.TOTAL));
return "testbedInformation";
}
// @RequestMapping(value="/futureplan/download", method=RequestMethod.GET)
// public void futureplanDownload(HttpServletResponse response) throws FuturePlanDownloadException, IOException {
// InputStream stream = null;
// response.setContentType("application/pdf");
// try {
// stream = getClass().getClassLoader().getResourceAsStream("downloads/future_plan.pdf");
// response.setContentType("application/force-download");
// response.setHeader("Content-Disposition", "attachment; filename=future_plan.pdf");
// IOUtils.copy(stream, response.getOutputStream());
// response.flushBuffer();
// } catch (Exception ex) {
// logger.info("Error writing file to output stream.");
// throw new FuturePlanDownloadException("IOError writing file to output stream");
// } finally {
// if (stream != null) {
// stream.close();
// }
// }
// }
@RequestMapping(value = "/orderform/download", method = RequestMethod.GET)
public void OrderForm_v1Download(HttpServletResponse response) throws OrderFormDownloadException, IOException {
InputStream stream = null;
response.setContentType(MediaType.APPLICATION_PDF_VALUE);
try {
stream = getClass().getClassLoader().getResourceAsStream("downloads/order_form.pdf");
response.setContentType(APPLICATION_FORCE_DOWNLOAD);
response.setHeader(CONTENT_DISPOSITION, "attachment; filename=order_form.pdf");
IOUtils.copy(stream, response.getOutputStream());
response.flushBuffer();
} catch (IOException ex) {
log.info("Error for download orderform.");
throw new OrderFormDownloadException("Error for download orderform.");
} finally {
if (stream != null) {
stream.close();
}
}
}
@RequestMapping("/contactus")
public String contactus() {
return "contactus";
}
@RequestMapping("/notfound")
public String redirectNotFound(HttpSession session) {
if (session.getAttribute("id") != null && !session.getAttribute("id").toString().isEmpty()) {
// user is already logged on and has encountered an error
// redirect to dashboard
return "redirect:/dashboard";
} else {
// user have not logged on before
// redirect to home page
return "redirect:/";
}
}
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(Model model) {
model.addAttribute("loginForm", new LoginForm());
return "login";
}
@RequestMapping(value = "/emailVerification", params = {"id", "email", "key"})
public String verifyEmail(
@NotNull @RequestParam("id") final String id,
@NotNull @RequestParam("email") final String emailBase64,
@NotNull @RequestParam("key") final String key
) throws UnsupportedEncodingException {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
ObjectNode keyObject = objectMapper.createObjectNode();
keyObject.put("key", key);
HttpEntity<String> request = new HttpEntity<>(keyObject.toString(), headers);
restTemplate.setErrorHandler(new MyResponseErrorHandler());
final String link = properties.getSioUsersUrl() + id + "/emails/" + emailBase64;
log.info("Activation link: {}, verification key {}", link, key);
ResponseEntity response = restTemplate.exchange(link, HttpMethod.PUT, request, String.class);
if (RestUtil.isError(response.getStatusCode())) {
log.error("Activation of user {} failed.", id);
return "email_validation_failed";
} else {
log.info("Activation of user {} completed.", id);
return "email_validation_ok";
}
}
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String loginSubmit(
@Valid
@ModelAttribute("loginForm") LoginForm loginForm,
BindingResult bindingResult,
Model model,
HttpSession session, final RedirectAttributes redirectAttributes) throws WebServiceRuntimeException {
if (bindingResult.hasErrors()) {
loginForm.setErrorMsg("Login failed: Invalid email/password.");
return "login";
}
String inputEmail = loginForm.getLoginEmail();
String inputPwd = loginForm.getLoginPassword();
if (inputEmail.trim().isEmpty() || inputPwd.trim().isEmpty()) {
loginForm.setErrorMsg("Email or Password cannot be empty!");
return "login";
}
String plainCreds = inputEmail + ":" + inputPwd;
byte[] plainCredsBytes = plainCreds.getBytes();
byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
String base64Creds = new String(base64CredsBytes);
ResponseEntity response;
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Basic " + base64Creds);
HttpEntity<String> request = new HttpEntity<>(headers);
restTemplate.setErrorHandler(new MyResponseErrorHandler());
try {
response = restTemplate.exchange(properties.getSioAuthUrl(), HttpMethod.POST, request, String.class);
} catch (RestClientException e) {
log.warn("Error connecting to sio authentication service: {}", e);
loginForm.setErrorMsg(ERR_SERVER_OVERLOAD);
return "login";
}
String jwtTokenString = response.getBody().toString();
log.info("token string {}", jwtTokenString);
if (jwtTokenString == null || jwtTokenString.isEmpty()) {
log.warn("login failed for {}: unknown response code", loginForm.getLoginEmail());
loginForm.setErrorMsg("Login failed: Invalid email/password.");
return "login";
}
if (RestUtil.isError(response.getStatusCode())) {
try {
MyErrorResource error = objectMapper.readValue(jwtTokenString, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
if (exceptionState == ExceptionState.CREDENTIALS_NOT_FOUND_EXCEPTION) {
log.warn("login failed for {}: credentials not found", loginForm.getLoginEmail());
loginForm.setErrorMsg("Login failed: Account does not exist. Please register.");
return "login";
}
log.warn("login failed for {}: {}", loginForm.getLoginEmail(), error.getError());
loginForm.setErrorMsg("Login failed: Invalid email/password.");
return "login";
} catch (IOException ioe) {
log.warn("IOException {}", ioe);
throw new WebServiceRuntimeException(ioe.getMessage());
}
}
JSONObject tokenObject = new JSONObject(jwtTokenString);
String token = tokenObject.getString("token");
String id = tokenObject.getString("id");
String role = "";
if (tokenObject.getJSONArray("roles") != null) {
role = tokenObject.getJSONArray("roles").get(0).toString();
}
if (token.trim().isEmpty() || id.trim().isEmpty() || role.trim().isEmpty()) {
log.warn("login failed for {}: empty id {} or token {} or role {}", loginForm.getLoginEmail(), id, token, role);
loginForm.setErrorMsg("Login failed: Invalid email/password.");
return "login";
}
// now check user status to decide what to show to the user
User2 user = invokeAndExtractUserInfo(id);
try {
String userStatus = user.getStatus();
boolean emailVerified = user.getEmailVerified();
if (UserStatus.FROZEN.toString().equals(userStatus)) {
log.warn("User {} login failed: account has been frozen", id);
loginForm.setErrorMsg("Login Failed: Account Frozen. Please contact " + CONTACT_EMAIL);
return "login";
} else if (!emailVerified || (UserStatus.CREATED.toString()).equals(userStatus)) {
redirectAttributes.addAttribute("statuschecklist", userStatus);
log.info("User {} not validated, redirected to email verification page", id);
return "redirect:/email_checklist";
} else if ((UserStatus.PENDING.toString()).equals(userStatus)) {
redirectAttributes.addAttribute("statuschecklist", userStatus);
log.info("User {} not approved, redirected to application pending page", id);
return "redirect:/email_checklist";
} else if ((UserStatus.APPROVED.toString()).equals(userStatus)) {
// set session variables
setSessionVariables(session, loginForm.getLoginEmail(), id, user.getFirstName(), role, token);
log.info("login success for {}, id: {}", loginForm.getLoginEmail(), id);
return "redirect:/dashboard";
} else {
log.warn("login failed for user {}: account is rejected or closed", id);
loginForm.setErrorMsg("Login Failed: Account Rejected/Closed.");
return "login";
}
} catch (Exception e) {
log.warn("Error parsing json object for user: {}", e.getMessage());
loginForm.setErrorMsg(ERR_SERVER_OVERLOAD);
return "login";
}
}
// triggered when user clicks "Forget Password?"
@RequestMapping("/password_reset_email")
public String passwordResetEmail(Model model) {
model.addAttribute("passwordResetRequestForm", new PasswordResetRequestForm());
return FORGET_PSWD_PAGE;
}
// triggered when user clicks "Send Reset Email" button
@PostMapping("/password_reset_request")
public String sendPasswordResetRequest(
@ModelAttribute("passwordResetRequestForm") PasswordResetRequestForm passwordResetRequestForm
) throws WebServiceRuntimeException {
String email = passwordResetRequestForm.getEmail();
if (!VALID_EMAIL_ADDRESS_REGEX.matcher(email).matches()) {
passwordResetRequestForm.setErrMsg("Please provide a valid email address");
return FORGET_PSWD_PAGE;
}
JSONObject obj = new JSONObject();
obj.put("username", email);
log.info("Connecting to sio for password reset email: {}", email);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(obj.toString(), headers);
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = null;
try {
response = restTemplate.exchange(properties.getPasswordResetRequestURI(), HttpMethod.POST, request, String.class);
} catch (RestClientException e) {
log.warn("Cannot connect to sio for password reset email: {}", e);
passwordResetRequestForm.setErrMsg("Cannot connect. Server may be down!");
return FORGET_PSWD_PAGE;
}
if (RestUtil.isError(response.getStatusCode())) {
log.warn("Server responded error for password reset email: {}", response.getStatusCode());
passwordResetRequestForm.setErrMsg("Email not registered. Please use a different email address.");
return FORGET_PSWD_PAGE;
}
log.info("Password reset email sent for {}", email);
return "password_reset_email_sent";
}
// triggered when user clicks password reset link in the email
@RequestMapping(path = "/passwordReset", params = {"key"})
public String passwordResetNewPassword(@NotNull @RequestParam("key") final String key, Model model) {
PasswordResetForm form = new PasswordResetForm();
form.setKey(key);
model.addAttribute("passwordResetForm", form);
// redirect to the page for user to enter new password
return FORGET_PSWD_NEW_PSWD_PAGE;
}
// actual call to sio to reset password
@RequestMapping(path = "/password_reset")
public String resetPassword(@ModelAttribute("passwordResetForm") PasswordResetForm passwordResetForm) throws IOException {
if (!passwordResetForm.isPasswordOk()) {
return FORGET_PSWD_NEW_PSWD_PAGE;
}
JSONObject obj = new JSONObject();
obj.put("key", passwordResetForm.getKey());
obj.put("new", passwordResetForm.getPassword1());
log.info("Connecting to sio for password reset, key = {}", passwordResetForm.getKey());
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(obj.toString(), headers);
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = null;
try {
response = restTemplate.exchange(properties.getPasswordResetURI(), HttpMethod.PUT, request, String.class);
} catch (RestClientException e) {
log.warn("Error connecting to sio for password reset! {}", e);
passwordResetForm.setErrMsg("Cannot connect to server! Please try again later.");
return FORGET_PSWD_NEW_PSWD_PAGE;
}
if (RestUtil.isError(response.getStatusCode())) {
EnumMap<ExceptionState, String> exceptionMessageMap = new EnumMap<>(ExceptionState.class);
exceptionMessageMap.put(PASSWORD_RESET_REQUEST_TIMEOUT_EXCEPTION, "Password reset request timed out. Please request a new reset email.");
exceptionMessageMap.put(PASSWORD_RESET_REQUEST_NOT_FOUND_EXCEPTION, "Invalid password reset request. Please request a new reset email.");
exceptionMessageMap.put(ADAPTER_CONNECTION_EXCEPTION, "Server-side error. Please contact " + CONTACT_EMAIL);
MyErrorResource error = objectMapper.readValue(response.getBody().toString(), MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
final String errMsg = exceptionMessageMap.get(exceptionState) == null ? ERR_SERVER_OVERLOAD : exceptionMessageMap.get(exceptionState);
passwordResetForm.setErrMsg(errMsg);
log.warn("Server responded error for password reset: {}", exceptionState.toString());
return FORGET_PSWD_NEW_PSWD_PAGE;
}
log.info("Password was reset, key = {}", passwordResetForm.getKey());
return "password_reset_success";
}
@RequestMapping("/dashboard")
public String dashboard(Model model, HttpSession session) throws WebServiceRuntimeException {
HttpEntity<String> request = createHttpEntityHeaderOnly();
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = restTemplate.exchange(properties.getDeterUid(session.getAttribute(webProperties.getSessionUserId()).toString()), HttpMethod.GET, request, String.class);
String responseBody = response.getBody().toString();
try {
if (RestUtil.isError(response.getStatusCode())) {
log.error("No user exists : {}", session.getAttribute(webProperties.getSessionUserId()));
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
model.addAttribute(DETER_UID, CONNECTION_ERROR);
} else {
log.info("Show the deter user id: {}", responseBody);
model.addAttribute(DETER_UID, responseBody);
}
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
// retrieve user dashboard stats
Map<String, Integer> userDashboardMap = getUserDashboardStats(session.getAttribute(webProperties.getSessionUserId()).toString());
List<TeamUsageInfo> usageInfoList = getTeamsUsageStatisticsForUser(session.getAttribute(webProperties.getSessionUserId()).toString());
model.addAttribute("userDashboardMap", userDashboardMap);
model.addAttribute("usageInfoList", usageInfoList);
return "dashboard";
}
@RequestMapping(value = "/logout", method = RequestMethod.GET)
public String logout(HttpSession session) {
removeSessionVariables(session);
return "redirect:/";
}
//--------------------------Sign Up Page--------------------------
@RequestMapping(value = "/signup2", method = RequestMethod.GET)
public String signup2(Model model, HttpServletRequest request) {
Map<String, ?> inputFlashMap = RequestContextUtils.getInputFlashMap(request);
if (inputFlashMap != null) {
log.debug((String) inputFlashMap.get(MESSAGE));
model.addAttribute("signUpMergedForm", (SignUpMergedForm) inputFlashMap.get("signUpMergedForm"));
} else {
log.debug("InputFlashMap is null");
model.addAttribute("signUpMergedForm", new SignUpMergedForm());
}
return "signup2";
}
@RequestMapping(value = "/signup2", method = RequestMethod.POST)
public String validateDetails(
@Valid
@ModelAttribute("signUpMergedForm") SignUpMergedForm signUpMergedForm,
BindingResult bindingResult,
final RedirectAttributes redirectAttributes) throws WebServiceRuntimeException {
if (bindingResult.hasErrors() || signUpMergedForm.getIsValid() == false) {
log.warn("Register form has errors {}", signUpMergedForm.toString());
return "signup2";
}
if (!signUpMergedForm.getHasAcceptTeamOwnerPolicy()) {
signUpMergedForm.setErrorTeamOwnerPolicy("Please accept the team owner policy");
log.warn("Policy not accepted");
return "signup2";
}
// get form fields
// craft the registration json
JSONObject mainObject = new JSONObject();
JSONObject credentialsFields = new JSONObject();
credentialsFields.put("username", signUpMergedForm.getEmail().trim());
credentialsFields.put("password", signUpMergedForm.getPassword());
// create the user JSON
JSONObject userFields = new JSONObject();
JSONObject userDetails = new JSONObject();
JSONObject addressDetails = new JSONObject();
userDetails.put("firstName", signUpMergedForm.getFirstName().trim());
userDetails.put("lastName", signUpMergedForm.getLastName().trim());
userDetails.put("jobTitle", signUpMergedForm.getJobTitle().trim());
userDetails.put("email", signUpMergedForm.getEmail().trim());
userDetails.put("phone", signUpMergedForm.getPhone().trim());
userDetails.put("institution", signUpMergedForm.getInstitution().trim());
userDetails.put("institutionAbbreviation", signUpMergedForm.getInstitutionAbbreviation().trim());
userDetails.put("institutionWeb", signUpMergedForm.getWebsite().trim());
userDetails.put("address", addressDetails);
addressDetails.put("address1", signUpMergedForm.getAddress1().trim());
addressDetails.put("address2", signUpMergedForm.getAddress2().trim());
addressDetails.put("country", signUpMergedForm.getCountry().trim());
addressDetails.put("region", signUpMergedForm.getProvince().trim());
addressDetails.put("city", signUpMergedForm.getCity().trim());
addressDetails.put("zipCode", signUpMergedForm.getPostalCode().trim());
userFields.put("userDetails", userDetails);
userFields.put("applicationDate", ZonedDateTime.now());
JSONObject teamFields = new JSONObject();
// add all to main json
mainObject.put("credentials", credentialsFields);
mainObject.put("user", userFields);
mainObject.put("team", teamFields);
// check if user chose create new team or join existing team by checking team name
String createNewTeamName = signUpMergedForm.getTeamName().trim();
String joinNewTeamName = signUpMergedForm.getJoinTeamName().trim();
if (createNewTeamName != null && !createNewTeamName.isEmpty()) {
log.info("Signup new team name {}", createNewTeamName);
boolean errorsFound = false;
if (createNewTeamName.length() < 2 || createNewTeamName.length() > 12) {
errorsFound = true;
signUpMergedForm.setErrorTeamName("Team name must be 2 to 12 alphabetic/numeric characters");
}
if (signUpMergedForm.getTeamDescription() == null || signUpMergedForm.getTeamDescription().isEmpty()) {
errorsFound = true;
signUpMergedForm.setErrorTeamDescription("Team description cannot be empty");
}
if (signUpMergedForm.getTeamWebsite() == null || signUpMergedForm.getTeamWebsite().isEmpty()) {
errorsFound = true;
signUpMergedForm.setErrorTeamWebsite("Team website cannot be empty");
}
if (errorsFound) {
log.warn("Signup new team error {}", signUpMergedForm.toString());
// clear join team name first before submitting the form
signUpMergedForm.setJoinTeamName(null);
return "signup2";
} else {
teamFields.put("name", signUpMergedForm.getTeamName().trim());
teamFields.put("description", signUpMergedForm.getTeamDescription().trim());
teamFields.put("website", signUpMergedForm.getTeamWebsite().trim());
teamFields.put("organisationType", signUpMergedForm.getTeamOrganizationType());
teamFields.put("visibility", signUpMergedForm.getIsPublic());
mainObject.put("isJoinTeam", false);
try {
registerUserToDeter(mainObject);
} catch (
TeamNotFoundException |
TeamNameAlreadyExistsException |
UsernameAlreadyExistsException |
EmailAlreadyExistsException |
InvalidTeamNameException |
InvalidPasswordException |
DeterLabOperationFailedException e) {
redirectAttributes.addFlashAttribute(MESSAGE, e.getMessage());
redirectAttributes.addFlashAttribute("signUpMergedForm", signUpMergedForm);
return "redirect:/signup2";
} catch (Exception e) {
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
redirectAttributes.addFlashAttribute("signUpMergedForm", signUpMergedForm);
return "redirect:/signup2";
}
log.info("Signup new team success");
return "redirect:/team_application_submitted";
}
} else if (joinNewTeamName != null && !joinNewTeamName.isEmpty()) {
log.info("Signup join team name {}", joinNewTeamName);
// get the team JSON from team name
Team2 joinTeamInfo;
try {
joinTeamInfo = getTeamIdByName(signUpMergedForm.getJoinTeamName().trim());
} catch (TeamNotFoundException | AdapterConnectionException e) {
redirectAttributes.addFlashAttribute(MESSAGE, e.getMessage());
redirectAttributes.addFlashAttribute("signUpMergedForm", signUpMergedForm);
return "redirect:/signup2";
}
teamFields.put("id", joinTeamInfo.getId());
// set the flag to indicate to controller that it is joining an existing team
mainObject.put("isJoinTeam", true);
try {
registerUserToDeter(mainObject);
} catch (
TeamNotFoundException |
AdapterConnectionException |
TeamNameAlreadyExistsException |
UsernameAlreadyExistsException |
EmailAlreadyExistsException |
InvalidTeamNameException |
InvalidPasswordException |
DeterLabOperationFailedException e) {
redirectAttributes.addFlashAttribute(MESSAGE, e.getMessage());
redirectAttributes.addFlashAttribute("signUpMergedForm", signUpMergedForm);
return "redirect:/signup2";
} catch (Exception e) {
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
redirectAttributes.addFlashAttribute("signUpMergedForm", signUpMergedForm);
return "redirect:/signup2";
}
log.info("Signup join team success");
log.info("jointeam info: {}", joinTeamInfo);
redirectAttributes.addFlashAttribute("team", joinTeamInfo);
return "redirect:/join_application_submitted";
} else {
log.warn("Signup unreachable statement");
// logic error not suppose to reach here
// possible if user fill up create new team but without the team name
redirectAttributes.addFlashAttribute("signupError", "There is a problem when submitting your form. Please re-enter and submit the details again.");
redirectAttributes.addFlashAttribute("signUpMergedForm", signUpMergedForm);
return "redirect:/signup2";
}
}
/**
* Use when registering new accounts
*
* @param mainObject A JSONObject that contains user's credentials, personal details and team application details
*/
private void registerUserToDeter(JSONObject mainObject) throws
WebServiceRuntimeException,
TeamNotFoundException,
AdapterConnectionException,
TeamNameAlreadyExistsException,
UsernameAlreadyExistsException,
EmailAlreadyExistsException,
InvalidTeamNameException,
InvalidPasswordException,
DeterLabOperationFailedException {
HttpEntity<String> request = createHttpEntityWithBodyNoAuthHeader(mainObject.toString());
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = restTemplate.exchange(properties.getSioRegUrl(), HttpMethod.POST, request, String.class);
String responseBody = response.getBody().toString();
log.info("Register user to deter response: {}", responseBody);
try {
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
log.warn("Register user exception error: {}", error.getError());
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
final String errorPrefix = "Error: ";
switch (exceptionState) {
case DETERLAB_OPERATION_FAILED_EXCEPTION:
log.warn("Register new user failed on DeterLab: {}", error.getMessage());
throw new DeterLabOperationFailedException(errorPrefix + (error.getMessage().contains("unknown error") ? ERR_SERVER_OVERLOAD : error.getMessage()));
case TEAM_NAME_ALREADY_EXISTS_EXCEPTION:
log.warn("Register new users new team request : team name already exists");
throw new TeamNameAlreadyExistsException("Team name already exists");
case INVALID_TEAM_NAME_EXCEPTION:
log.warn("Register new users new team request : team name invalid");
throw new InvalidTeamNameException("Invalid team name: must be 6-12 alphanumeric characters only");
case INVALID_PASSWORD_EXCEPTION:
log.warn("Register new users new team request : invalid password");
throw new InvalidPasswordException("Password is too simple");
case USERNAME_ALREADY_EXISTS_EXCEPTION:
// throw from user service
{
String email = mainObject.getJSONObject("user").getJSONObject("userDetails").getString("email");
log.warn("Register new users : email already exists: {}", email);
throw new UsernameAlreadyExistsException(errorPrefix + email + " already in use.");
}
case EMAIL_ALREADY_EXISTS_EXCEPTION:
// throw from adapter deterlab
{
String email = mainObject.getJSONObject("user").getJSONObject("userDetails").getString("email");
log.warn("Register new users : email already exists: {}", email);
throw new EmailAlreadyExistsException(errorPrefix + email + " already in use.");
}
default:
log.warn("Registration or adapter connection fail");
// possible sio or adapter connection fail
throw new AdapterConnectionException(ERR_SERVER_OVERLOAD);
}
} else {
// do nothing
log.info("Not an error for status code: {}", response.getStatusCode());
}
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
}
/**
* Use when users register a new account for joining existing team
*
* @param teamName The team name to join
* @return the team id from sio
*/
private Team2 getTeamIdByName(String teamName) throws WebServiceRuntimeException, TeamNotFoundException, AdapterConnectionException {
// FIXME check if team name exists
// FIXME check for general exception?
HttpEntity<String> request = createHttpEntityHeaderOnlyNoAuthHeader();
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = restTemplate.exchange(properties.getTeamByName(teamName), HttpMethod.GET, request, String.class);
String responseBody = response.getBody().toString();
try {
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
if (exceptionState == ExceptionState.TEAM_NOT_FOUND_EXCEPTION) {
log.warn("Get team by name : team name error");
throw new TeamNotFoundException("Team name " + teamName + " does not exists");
} else {
log.warn("Team service or adapter connection fail");
// possible sio or adapter connection fail
throw new AdapterConnectionException(ERR_SERVER_OVERLOAD);
}
} else {
return extractTeamInfo(responseBody);
}
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
}
//--------------------------Account Settings Page--------------------------
@RequestMapping(value = "/account_settings", method = RequestMethod.GET)
public String accountDetails(Model model, HttpSession session) throws WebServiceRuntimeException {
String userId_uri = properties.getSioUsersUrl() + session.getAttribute("id");
HttpEntity<String> request = createHttpEntityHeaderOnly();
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = restTemplate.exchange(userId_uri, HttpMethod.GET, request, String.class);
String responseBody = response.getBody().toString();
try {
if (RestUtil.isError(response.getStatusCode())) {
log.error("No user to edit : {}", session.getAttribute("id"));
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
throw new RestClientException("[" + error.getError() + "] ");
} else {
User2 user2 = extractUserInfo(responseBody);
// need to do this so that we can compare after submitting the form
session.setAttribute(webProperties.getSessionUserAccount(), user2);
model.addAttribute("editUser", user2);
return "account_settings";
}
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
}
@RequestMapping(value = "/account_settings", method = RequestMethod.POST)
public String editAccountDetails(
@ModelAttribute("editUser") User2 editUser,
final RedirectAttributes redirectAttributes,
HttpSession session) throws WebServiceRuntimeException {
boolean errorsFound = false;
String editPhrase = "editPhrase";
// check fields first
if (errorsFound == false && editUser.getFirstName().isEmpty()) {
redirectAttributes.addFlashAttribute("editFirstName", "fail");
errorsFound = true;
}
if (errorsFound == false && editUser.getLastName().isEmpty()) {
redirectAttributes.addFlashAttribute("editLastName", "fail");
errorsFound = true;
}
if (errorsFound == false && editUser.getPhone().isEmpty()) {
redirectAttributes.addFlashAttribute("editPhone", "fail");
errorsFound = true;
}
if (errorsFound == false && (editUser.getPhone().matches("(.*)[a-zA-Z](.*)") || editUser.getPhone().length() < 6)) {
// previously already check if phone is empty
// now check phone must contain only digits
redirectAttributes.addFlashAttribute("editPhone", "fail");
errorsFound = true;
}
if (errorsFound == false && !editUser.getConfirmPassword().isEmpty() && !editUser.isPasswordValid()) {
redirectAttributes.addFlashAttribute(editPhrase, "invalid");
errorsFound = true;
}
if (errorsFound == false && editUser.getJobTitle().isEmpty()) {
redirectAttributes.addFlashAttribute("editJobTitle", "fail");
errorsFound = true;
}
if (errorsFound == false && editUser.getInstitution().isEmpty()) {
redirectAttributes.addFlashAttribute("editInstitution", "fail");
errorsFound = true;
}
if (errorsFound == false && editUser.getCountry().isEmpty()) {
redirectAttributes.addFlashAttribute("editCountry", "fail");
errorsFound = true;
}
if (errorsFound) {
session.removeAttribute(webProperties.getSessionUserAccount());
return "redirect:/account_settings";
} else {
// used to compare original and edited User2 objects
User2 originalUser = (User2) session.getAttribute(webProperties.getSessionUserAccount());
JSONObject userObject = new JSONObject();
JSONObject userDetails = new JSONObject();
JSONObject address = new JSONObject();
userDetails.put("firstName", editUser.getFirstName());
userDetails.put("lastName", editUser.getLastName());
userDetails.put("email", editUser.getEmail());
userDetails.put("phone", editUser.getPhone());
userDetails.put("jobTitle", editUser.getJobTitle());
userDetails.put("address", address);
userDetails.put("institution", editUser.getInstitution());
userDetails.put("institutionAbbreviation", originalUser.getInstitutionAbbreviation());
userDetails.put("institutionWeb", originalUser.getInstitutionWeb());
address.put("address1", originalUser.getAddress1());
address.put("address2", originalUser.getAddress2());
address.put("country", editUser.getCountry());
address.put("city", originalUser.getCity());
address.put("region", originalUser.getRegion());
address.put("zipCode", originalUser.getPostalCode());
userObject.put("userDetails", userDetails);
String userId_uri = properties.getSioUsersUrl() + session.getAttribute(webProperties.getSessionUserId());
HttpEntity<String> request = createHttpEntityWithBody(userObject.toString());
restTemplate.exchange(userId_uri, HttpMethod.PUT, request, String.class);
if (!originalUser.getFirstName().equals(editUser.getFirstName())) {
redirectAttributes.addFlashAttribute("editFirstName", "success");
}
if (!originalUser.getLastName().equals(editUser.getLastName())) {
redirectAttributes.addFlashAttribute("editLastName", "success");
}
if (!originalUser.getPhone().equals(editUser.getPhone())) {
redirectAttributes.addFlashAttribute("editPhone", "success");
}
if (!originalUser.getJobTitle().equals(editUser.getJobTitle())) {
redirectAttributes.addFlashAttribute("editJobTitle", "success");
}
if (!originalUser.getInstitution().equals(editUser.getInstitution())) {
redirectAttributes.addFlashAttribute("editInstitution", "success");
}
if (!originalUser.getCountry().equals(editUser.getCountry())) {
redirectAttributes.addFlashAttribute("editCountry", "success");
}
// credential service change password
if (editUser.isPasswordMatch()) {
JSONObject credObject = new JSONObject();
credObject.put("password", editUser.getPassword());
HttpEntity<String> credRequest = createHttpEntityWithBody(credObject.toString());
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = restTemplate.exchange(properties.getUpdateCredentials(session.getAttribute("id").toString()), HttpMethod.PUT, credRequest, String.class);
String responseBody = response.getBody().toString();
try {
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
redirectAttributes.addFlashAttribute(editPhrase, "fail");
} else {
redirectAttributes.addFlashAttribute(editPhrase, "success");
}
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
} finally {
session.removeAttribute(webProperties.getSessionUserAccount());
}
}
}
return "redirect:/account_settings";
}
//--------------------User Side Approve Members Page------------
@RequestMapping("/approve_new_user")
public String approveNewUser(Model model, HttpSession session) throws Exception {
// HashMap<Integer, Team> rv = new HashMap<Integer, Team>();
// rv = teamManager.getTeamMapByTeamOwner(getSessionIdOfLoggedInUser(session));
// boolean userHasAnyJoinRequest = hasAnyJoinRequest(rv);
// model.addAttribute("teamMapOwnedByUser", rv);
// model.addAttribute("userHasAnyJoinRequest", userHasAnyJoinRequest);
List<JoinRequestApproval> rv = new ArrayList<>();
List<JoinRequestApproval> temp;
// get list of teamids
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response = restTemplate.exchange(properties.getUser(session.getAttribute("id").toString()), HttpMethod.GET, request, String.class);
String responseBody = response.getBody().toString();
JSONObject object = new JSONObject(responseBody);
JSONArray teamIdsJsonArray = object.getJSONArray("teams");
for (int i = 0; i < teamIdsJsonArray.length(); i++) {
String teamId = teamIdsJsonArray.get(i).toString();
HttpEntity<String> teamRequest = createHttpEntityHeaderOnly();
ResponseEntity teamResponse = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, teamRequest, String.class);
String teamResponseBody = teamResponse.getBody().toString();
Team2 team2 = new Team2();
JSONObject teamObject = new JSONObject(teamResponseBody);
JSONArray membersArray = teamObject.getJSONArray("members");
team2.setId(teamObject.getString("id"));
team2.setName(teamObject.getString("name"));
boolean isTeamLeader = false;
temp = new ArrayList<>();
for (int j = 0; j < membersArray.length(); j++) {
JSONObject memberObject = membersArray.getJSONObject(j);
String userId = memberObject.getString("userId");
String teamMemberType = memberObject.getString(MEMBER_TYPE);
String teamMemberStatus = memberObject.getString("memberStatus");
String teamJoinedDate = formatZonedDateTime(memberObject.get("joinedDate").toString());
JoinRequestApproval joinRequestApproval = new JoinRequestApproval();
if (userId.equals(session.getAttribute("id").toString()) && teamMemberType.equals(MemberType.OWNER.toString())) {
isTeamLeader = true;
}
if (teamMemberStatus.equals(MemberStatus.PENDING.toString()) && teamMemberType.equals(MemberType.MEMBER.toString())) {
User2 myUser = invokeAndExtractUserInfo(userId);
joinRequestApproval.setUserId(myUser.getId());
joinRequestApproval.setUserEmail(myUser.getEmail());
joinRequestApproval.setUserName(myUser.getFirstName() + " " + myUser.getLastName());
joinRequestApproval.setApplicationDate(teamJoinedDate);
joinRequestApproval.setTeamId(team2.getId());
joinRequestApproval.setTeamName(team2.getName());
temp.add(joinRequestApproval);
log.info("Join request: UserId: {}, UserEmail: {}", myUser.getId(), myUser.getEmail());
}
}
if (isTeamLeader) {
if (!temp.isEmpty()) {
rv.addAll(temp);
}
}
}
model.addAttribute("joinApprovalList", rv);
return "approve_new_user";
}
@RequestMapping("/approve_new_user/accept/{teamId}/{userId}")
public String userSideAcceptJoinRequest(
@PathVariable String teamId,
@PathVariable String userId,
HttpSession session,
RedirectAttributes redirectAttributes) throws WebServiceRuntimeException {
log.info("Approve join request: User {}, Team {}, Approver {}",
userId, teamId, session.getAttribute("id").toString());
JSONObject mainObject = new JSONObject();
JSONObject userFields = new JSONObject();
userFields.put("id", session.getAttribute("id").toString());
mainObject.put("user", userFields);
HttpEntity<String> request = createHttpEntityWithBody(mainObject.toString());
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getApproveJoinRequest(teamId, userId), HttpMethod.POST, request, String.class);
} catch (RestClientException e) {
log.warn("Error connecting to sio team service: {}", e);
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
return "redirect:/approve_new_user";
}
String responseBody = response.getBody().toString();
if (RestUtil.isError(response.getStatusCode())) {
try {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case DETERLAB_OPERATION_FAILED_EXCEPTION:
log.warn("Approve join request: User {}, Team {} fail", userId, teamId);
redirectAttributes.addFlashAttribute(MESSAGE, "Approve join request fail");
break;
default:
log.warn("Server side error: {}", error.getError());
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
break;
}
return "redirect:/approve_new_user";
} catch (IOException ioe) {
log.warn("IOException {}", ioe);
throw new WebServiceRuntimeException(ioe.getMessage());
}
}
// everything looks OK?
log.info("Join request has been APPROVED, User {}, Team {}", userId, teamId);
redirectAttributes.addFlashAttribute(MESSAGE_SUCCESS, "Join request has been APPROVED.");
return "redirect:/approve_new_user";
}
@RequestMapping("/approve_new_user/reject/{teamId}/{userId}")
public String userSideRejectJoinRequest(
@PathVariable String teamId,
@PathVariable String userId,
HttpSession session,
RedirectAttributes redirectAttributes) throws WebServiceRuntimeException {
log.info("Reject join request: User {}, Team {}, Approver {}",
userId, teamId, session.getAttribute("id").toString());
JSONObject mainObject = new JSONObject();
JSONObject userFields = new JSONObject();
userFields.put("id", session.getAttribute("id").toString());
mainObject.put("user", userFields);
HttpEntity<String> request = createHttpEntityWithBody(mainObject.toString());
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getRejectJoinRequest(teamId, userId), HttpMethod.DELETE, request, String.class);
} catch (RestClientException e) {
log.warn("Error connecting to sio team service: {}", e);
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
return "redirect:/approve_new_user";
}
String responseBody = response.getBody().toString();
if (RestUtil.isError(response.getStatusCode())) {
try {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case DETERLAB_OPERATION_FAILED_EXCEPTION:
log.warn("Reject join request: User {}, Team {} fail", userId, teamId);
redirectAttributes.addFlashAttribute(MESSAGE, "Reject join request fail");
break;
default:
log.warn("Server side error: {}", error.getError());
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
break;
}
return "redirect:/approve_new_user";
} catch (IOException ioe) {
log.warn("IOException {}", ioe);
throw new WebServiceRuntimeException(ioe.getMessage());
}
}
// everything looks OK?
log.info("Join request has been REJECTED, User {}, Team {}", userId, teamId);
redirectAttributes.addFlashAttribute(MESSAGE, "Join request has been REJECTED.");
return "redirect:/approve_new_user";
}
//--------------------------Teams Page--------------------------
@RequestMapping("/public_teams")
public String publicTeamsBeforeLogin(Model model) {
TeamManager2 teamManager2 = new TeamManager2();
// get public teams
HttpEntity<String> teamRequest = createHttpEntityHeaderOnlyNoAuthHeader();
ResponseEntity teamResponse = restTemplate.exchange(properties.getTeamsByVisibility(TeamVisibility.PUBLIC.toString()), HttpMethod.GET, teamRequest, String.class);
String teamResponseBody = teamResponse.getBody().toString();
JSONArray teamPublicJsonArray = new JSONArray(teamResponseBody);
for (int i = 0; i < teamPublicJsonArray.length(); i++) {
JSONObject teamInfoObject = teamPublicJsonArray.getJSONObject(i);
Team2 team2 = extractTeamInfo(teamInfoObject.toString());
teamManager2.addTeamToPublicTeamMap(team2);
}
model.addAttribute("publicTeamMap2", teamManager2.getPublicTeamMap());
return "public_teams";
}
@RequestMapping("/teams")
public String teams(Model model, HttpSession session) {
// int currentLoggedInUserId = getSessionIdOfLoggedInUser(session);
// model.addAttribute("infoMsg", teamManager.getInfoMsg());
// model.addAttribute("currentLoggedInUserId", currentLoggedInUserId);
// model.addAttribute("teamMap", teamManager.getTeamMap(currentLoggedInUserId));
// model.addAttribute("publicTeamMap", teamManager.getPublicTeamMap());
// model.addAttribute("invitedToParticipateMap2", teamManager.getInvitedToParticipateMap2(currentLoggedInUserId));
// model.addAttribute("joinRequestMap2", teamManager.getJoinRequestTeamMap2(currentLoggedInUserId));
TeamManager2 teamManager2 = new TeamManager2();
// stores the list of images created or in progress of creation by teams
// e.g. teamNameA : "created" : [imageA, imageB], "inProgress" : [imageC, imageD]
Map<String, Map<String, List<Image>>> imageMap = new HashMap<>();
// get list of teamids
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response = restTemplate.exchange(properties.getUser(session.getAttribute("id").toString()), HttpMethod.GET, request, String.class);
String responseBody = response.getBody().toString();
JSONObject object = new JSONObject(responseBody);
JSONArray teamIdsJsonArray = object.getJSONArray("teams");
String userEmail = object.getJSONObject("userDetails").getString("email");
for (int i = 0; i < teamIdsJsonArray.length(); i++) {
String teamId = teamIdsJsonArray.get(i).toString();
HttpEntity<String> teamRequest = createHttpEntityHeaderOnly();
ResponseEntity teamResponse = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, teamRequest, String.class);
String teamResponseBody = teamResponse.getBody().toString();
Team2 team2 = extractTeamInfo(teamResponseBody);
teamManager2.addTeamToTeamMap(team2);
Team2 joinRequestTeam = extractTeamInfoUserJoinRequest(session.getAttribute("id").toString(), teamResponseBody);
if (joinRequestTeam != null) {
teamManager2.addTeamToUserJoinRequestTeamMap(joinRequestTeam);
}
imageMap.put(team2.getName(), invokeAndGetImageList(teamId));
}
// check if inner image map is empty, have to do it via this manner
// returns true if the team contains an image list
boolean isInnerImageMapPresent = imageMap.values().stream().filter(perTeamImageMap -> !perTeamImageMap.isEmpty()).findFirst().isPresent();
model.addAttribute("userEmail", userEmail);
model.addAttribute("teamMap2", teamManager2.getTeamMap());
model.addAttribute("userJoinRequestMap", teamManager2.getUserJoinRequestMap());
model.addAttribute("isInnerImageMapPresent", isInnerImageMapPresent);
model.addAttribute("imageMap", imageMap);
return "teams";
}
/**
* Exectues the service-image and returns a Map containing the list of images in two partitions.
* One partition contains the list of already created images.
* The other partition contains the list of currently saving in progress images.
*
* @param teamId The ncl team id to retrieve the list of images from.
* @return Returns a Map containing the list of images in two partitions.
*/
private Map<String, List<Image>> invokeAndGetImageList(String teamId) {
log.info("Getting list of saved images for team {}", teamId);
Map<String, List<Image>> resultMap = new HashMap<>();
List<Image> createdImageList = new ArrayList<>();
List<Image> inProgressImageList = new ArrayList<>();
HttpEntity<String> imageRequest = createHttpEntityHeaderOnly();
ResponseEntity imageResponse;
try {
imageResponse = restTemplate.exchange(properties.getTeamSavedImages(teamId), HttpMethod.GET, imageRequest, String.class);
} catch (ResourceAccessException e) {
log.warn("Error connecting to image service: {}", e);
return new HashMap<>();
}
String imageResponseBody = imageResponse.getBody().toString();
String osImageList = new JSONObject(imageResponseBody).getString(teamId);
JSONObject osImageObject = new JSONObject(osImageList);
log.debug("osImageList: {}", osImageList);
log.debug("osImageObject: {}", osImageObject);
if (osImageObject == JSONObject.NULL || osImageObject.length() == 0) {
log.info("List of saved images for team {} is empty.", teamId);
return resultMap;
}
for (int k = 0; k < osImageObject.names().length(); k++) {
String imageName = osImageObject.names().getString(k);
String imageStatus = osImageObject.getString(imageName);
log.info("Image list for team {}: image name {}, status {}", teamId, imageName, imageStatus);
Image image = new Image();
image.setImageName(imageName);
image.setDescription("-");
image.setTeamId(teamId);
if ("created".equals(imageStatus)) {
createdImageList.add(image);
} else if ("notfound".equals(imageStatus)) {
inProgressImageList.add(image);
}
}
resultMap.put("created", createdImageList);
resultMap.put("inProgress", inProgressImageList);
return resultMap;
}
// @RequestMapping("/accept_participation/{teamId}")
// public String acceptParticipationRequest(@PathVariable Integer teamId, Model model, HttpSession session) {
// int currentLoggedInUserId = getSessionIdOfLoggedInUser(session);
// // get user's participation request list
// // add this user id to the requested list
// teamManager.acceptParticipationRequest(currentLoggedInUserId, teamId);
// // remove participation request since accepted
// teamManager.removeParticipationRequest(currentLoggedInUserId, teamId);
//
// // must get team name
// String teamName = teamManager.getTeamNameByTeamId(teamId);
// teamManager.setInfoMsg("You have just joined Team " + teamName + " !");
//
// return "redirect:/teams";
// }
// @RequestMapping("/ignore_participation/{teamId}")
// public String ignoreParticipationRequest(@PathVariable Integer teamId, Model model, HttpSession session) {
// // get user's participation request list
// // remove this user id from the requested list
// String teamName = teamManager.getTeamNameByTeamId(teamId);
// teamManager.ignoreParticipationRequest2(getSessionIdOfLoggedInUser(session), teamId);
// teamManager.setInfoMsg("You have just ignored a team request from Team " + teamName + " !");
//
// return "redirect:/teams";
// }
// @RequestMapping("/withdraw/{teamId}")
public String withdrawnJoinRequest(@PathVariable Integer teamId, HttpSession session) {
// get user team request
// remove this user id from the user's request list
String teamName = teamManager.getTeamNameByTeamId(teamId);
teamManager.removeUserJoinRequest2(getSessionIdOfLoggedInUser(session), teamId);
teamManager.setInfoMsg("You have withdrawn your join request for Team " + teamName);
return "redirect:/teams";
}
// @RequestMapping(value="/teams/invite_members/{teamId}", method=RequestMethod.GET)
// public String inviteMember(@PathVariable Integer teamId, Model model) {
// model.addAttribute("teamIdVar", teamId);
// model.addAttribute("teamPageInviteMemberForm", new TeamPageInviteMemberForm());
// return "team_page_invite_members";
// }
// @RequestMapping(value="/teams/invite_members/{teamId}", method=RequestMethod.POST)
// public String sendInvitation(@PathVariable Integer teamId, @ModelAttribute TeamPageInviteMemberForm teamPageInviteMemberForm,Model model) {
// int userId = userManager.getUserIdByEmail(teamPageInviteMemberForm.getInviteUserEmail());
// teamManager.addInvitedToParticipateMap(userId, teamId);
// return "redirect:/teams";
// }
@RequestMapping(value = "/teams/members_approval/{teamId}", method = RequestMethod.GET)
public String membersApproval(@PathVariable Integer teamId, Model model) {
model.addAttribute("team", teamManager.getTeamByTeamId(teamId));
return "team_page_approve_members";
}
@RequestMapping("/teams/members_approval/accept/{teamId}/{userId}")
public String acceptJoinRequest(@PathVariable Integer teamId, @PathVariable Integer userId) {
teamManager.acceptJoinRequest(userId, teamId);
return "redirect:/teams/members_approval/{teamId}";
}
@RequestMapping("/teams/members_approval/reject/{teamId}/{userId}")
public String rejectJoinRequest(@PathVariable Integer teamId, @PathVariable Integer userId) {
teamManager.rejectJoinRequest(userId, teamId);
return "redirect:/teams/members_approval/{teamId}";
}
//--------------------------Team Profile Page--------------------------
@RequestMapping(value = "/team_profile/{teamId}", method = RequestMethod.GET)
public String teamProfile(@PathVariable String teamId, Model model, final RedirectAttributes redirectAttributes, HttpSession session) throws IOException {
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, request, String.class);
String responseBody = response.getBody().toString();
Team2 team = extractTeamInfo(responseBody);
model.addAttribute("team", team);
model.addAttribute("owner", team.getOwner());
model.addAttribute("membersList", team.getMembersStatusMap().get(MemberStatus.APPROVED));
session.setAttribute("originalTeam", team);
request = createHttpEntityHeaderOnly();
response = restTemplate.exchange(properties.getExpListByTeamId(teamId), HttpMethod.GET, request, String.class);
JSONArray experimentsArray = new JSONArray(response.getBody().toString());
List<Experiment2> experimentList = new ArrayList<>();
Map<Long, Realization> realizationMap = new HashMap<>();
for (int k = 0; k < experimentsArray.length(); k++) {
Experiment2 experiment2 = extractExperiment(experimentsArray.getJSONObject(k).toString());
Realization realization = invokeAndExtractRealization(experiment2.getTeamName(), experiment2.getId());
realizationMap.put(experiment2.getId(), realization);
experimentList.add(experiment2);
}
model.addAttribute("teamExperimentList", experimentList);
model.addAttribute("teamRealizationMap", realizationMap);
//Starting to get quota
try {
response = restTemplate.exchange(properties.getQuotaByTeamId(teamId), HttpMethod.GET, request, String.class);
} catch (RestClientException e) {
log.warn("Error connecting to sio team service for display team quota: {}", e);
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
return REDIRECT_TEAM_PROFILE_TEAM_ID;
}
responseBody = response.getBody().toString();
// handling exceptions from SIO
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case TEAM_NOT_FOUND_EXCEPTION:
log.warn("Get team quota: Team {} not found", teamId);
break;
default:
log.warn("Get team quota : sio or deterlab adapter connection error");
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
break;
}
} else {
log.info("Get team quota info : {}", responseBody);
}
TeamQuota teamQuota = extractTeamQuotaInfo(responseBody);
model.addAttribute("teamQuota", teamQuota);
session.setAttribute(ORIGINAL_BUDGET, teamQuota.getBudget()); // this is to check if budget changed later
return "team_profile";
}
@RequestMapping(value = "/team_profile/{teamId}", method = RequestMethod.POST)
public String editTeamProfile(
@PathVariable String teamId,
@ModelAttribute("team") Team2 editTeam,
final RedirectAttributes redirectAttributes,
HttpSession session) {
boolean errorsFound = false;
if (editTeam.getDescription().isEmpty()) {
errorsFound = true;
redirectAttributes.addFlashAttribute("editDesc", "fail");
}
if (errorsFound) {
// safer to remove
session.removeAttribute("originalTeam");
return REDIRECT_TEAM_PROFILE + editTeam.getId();
}
// can edit team description and team website for now
JSONObject teamfields = new JSONObject();
teamfields.put("id", teamId);
teamfields.put("name", editTeam.getName());
teamfields.put("description", editTeam.getDescription());
teamfields.put("website", "http://default.com");
teamfields.put("organisationType", editTeam.getOrganisationType());
teamfields.put("privacy", "OPEN");
teamfields.put("status", editTeam.getStatus());
teamfields.put("members", editTeam.getMembersList());
HttpEntity<String> request = createHttpEntityWithBody(teamfields.toString());
ResponseEntity response = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.PUT, request, String.class);
Team2 originalTeam = (Team2) session.getAttribute("originalTeam");
if (!originalTeam.getDescription().equals(editTeam.getDescription())) {
redirectAttributes.addFlashAttribute("editDesc", "success");
}
// safer to remove
session.removeAttribute("originalTeam");
return REDIRECT_TEAM_PROFILE + teamId;
}
@RequestMapping(value = "/team_quota/{teamId}", method = RequestMethod.POST)
public String editTeamQuota(
@PathVariable String teamId,
@ModelAttribute("teamQuota") TeamQuota editTeamQuota,
final RedirectAttributes redirectAttributes,
HttpSession session) throws IOException {
final String QUOTA = "#quota";
JSONObject teamQuotaJSONObject = new JSONObject();
teamQuotaJSONObject.put(TEAM_ID, teamId);
//check if budget input is positive
if (Double.parseDouble(editTeamQuota.getBudget()) < 0) {
redirectAttributes.addFlashAttribute(EDIT_BUDGET, "negativeError");
return REDIRECT_TEAM_PROFILE + teamId + QUOTA;
}
//check if budget input exceed database limit of 99999999.99
if (Double.parseDouble(editTeamQuota.getBudget()) > 99999999.99) {
redirectAttributes.addFlashAttribute(EDIT_BUDGET, "exceedingLimit");
return REDIRECT_TEAM_PROFILE + teamId + QUOTA;
}
teamQuotaJSONObject.put("quota", editTeamQuota.getBudget());
HttpEntity<String> request = createHttpEntityWithBody(teamQuotaJSONObject.toString());
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getQuotaByTeamId(teamId), HttpMethod.PUT, request, String.class);
} catch (RestClientException e) {
log.warn("Error connecting to sio team service for display team quota: {}", e);
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
return REDIRECT_TEAM_PROFILE_TEAM_ID;
}
String responseBody = response.getBody().toString();
// handling exceptions from SIO
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case TEAM_NOT_FOUND_EXCEPTION:
log.warn("Get team quota: Team {} not found", teamId);
break;
case TEAM_QUOTA_OUT_OF_RANGE_EXCEPTION:
log.warn("Get team quota: Budget is out of range");
return REDIRECT_TEAM_PROFILE + teamId + QUOTA;
default:
log.warn("Get team quota : sio or deterlab adapter connection error");
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
break;
}
} else {
log.info("Edit team quota info : {}", responseBody);
}
//check if new budget is different in order to display successful message to user
String originalBudget = (String) session.getAttribute(ORIGINAL_BUDGET);
if (!originalBudget.equals(editTeamQuota.getBudget())) {
redirectAttributes.addFlashAttribute(EDIT_BUDGET, "success");
}
// safer to remove
session.removeAttribute(ORIGINAL_BUDGET);
return REDIRECT_TEAM_PROFILE + teamId + QUOTA;
}
@RequestMapping("/remove_member/{teamId}/{userId}")
public String removeMember(@PathVariable String teamId, @PathVariable String userId, final RedirectAttributes redirectAttributes) throws IOException {
JSONObject teamMemberFields = new JSONObject();
teamMemberFields.put("userId", userId);
teamMemberFields.put(MEMBER_TYPE, MemberType.MEMBER.name());
teamMemberFields.put("memberStatus", MemberStatus.APPROVED.name());
HttpEntity<String> request = createHttpEntityWithBody(teamMemberFields.toString());
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response;
try {
response = restTemplate.exchange(properties.removeUserFromTeam(teamId), HttpMethod.DELETE, request, String.class);
} catch (RestClientException e) {
log.warn("Error connecting to sio team service for remove user: {}", e);
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
return REDIRECT_TEAM_PROFILE_TEAM_ID;
}
String responseBody = response.getBody().toString();
User2 user = invokeAndExtractUserInfo(userId);
String name = user.getFirstName() + " " + user.getLastName();
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case DETERLAB_OPERATION_FAILED_EXCEPTION:
// two subcases when fail to remove users from team
log.warn("Remove member from team: User {}, Team {} fail - {}", userId, teamId, error.getMessage());
if ("user has experiments".equals(error.getMessage())) {
// case 1 - user has experiments
// display the list of experiments that have to be terminated first
// since the team profile page has experiments already, we don't have to retrieve them again
// use the userid to filter out the experiment list at the web pages
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + " Member " + name + " has experiments.");
redirectAttributes.addFlashAttribute(REMOVE_MEMBER_UID, userId);
redirectAttributes.addFlashAttribute(REMOVE_MEMBER_NAME, name);
break;
} else {
// case 2 - deterlab operation failure
log.warn("Remove member from team: deterlab operation failed");
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + " Member " + name + " cannot be removed.");
break;
}
default:
log.warn("Server side error for remove members: {}", error.getError());
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
break;
}
} else {
log.info("Remove member: {}", response.getBody().toString());
// add success message
redirectAttributes.addFlashAttribute(MESSAGE_SUCCESS, "Member " + name + " has been removed.");
}
return REDIRECT_TEAM_PROFILE_TEAM_ID;
}
// @RequestMapping("/team_profile/{teamId}/start_experiment/{expId}")
// public String startExperimentFromTeamProfile(@PathVariable Integer teamId, @PathVariable Integer expId, Model model, HttpSession session) {
// // start experiment
// // ensure experiment is stopped first before starting
// experimentManager.startExperiment(getSessionIdOfLoggedInUser(session), expId);
// return "redirect:/team_profile/{teamId}";
// }
// @RequestMapping("/team_profile/{teamId}/stop_experiment/{expId}")
// public String stopExperimentFromTeamProfile(@PathVariable Integer teamId, @PathVariable Integer expId, Model model, HttpSession session) {
// // stop experiment
// // ensure experiment is in ready mode before stopping
// experimentManager.stopExperiment(getSessionIdOfLoggedInUser(session), expId);
// return "redirect:/team_profile/{teamId}";
// }
// @RequestMapping("/team_profile/{teamId}/remove_experiment/{expId}")
// public String removeExperimentFromTeamProfile(@PathVariable Integer teamId, @PathVariable Integer expId, Model model, HttpSession session) {
// // remove experiment
// // TODO check userid is indeed the experiment owner or team owner
// // ensure experiment is stopped first
// if (experimentManager.removeExperiment(getSessionIdOfLoggedInUser(session), expId) == true) {
// // decrease exp count to be display on Teams page
// teamManager.decrementExperimentCount(teamId);
// }
// model.addAttribute("experimentList", experimentManager.getExperimentListByExperimentOwner(getSessionIdOfLoggedInUser(session)));
// return "redirect:/team_profile/{teamId}";
// }
// @RequestMapping(value="/team_profile/invite_user/{teamId}", method=RequestMethod.GET)
// public String inviteUserFromTeamProfile(@PathVariable Integer teamId, Model model) {
// model.addAttribute("teamIdVar", teamId);
// model.addAttribute("teamPageInviteMemberForm", new TeamPageInviteMemberForm());
// return "team_profile_invite_members";
// }
// @RequestMapping(value="/team_profile/invite_user/{teamId}", method=RequestMethod.POST)
// public String sendInvitationFromTeamProfile(@PathVariable Integer teamId, @ModelAttribute TeamPageInviteMemberForm teamPageInviteMemberForm, Model model) {
// int userId = userManager.getUserIdByEmail(teamPageInviteMemberForm.getInviteUserEmail());
// teamManager.addInvitedToParticipateMap(userId, teamId);
// return "redirect:/team_profile/{teamId}";
// }
//--------------------------Apply for New Team Page--------------------------
@RequestMapping(value = "/teams/apply_team", method = RequestMethod.GET)
public String teamPageApplyTeam(Model model) {
model.addAttribute("teamPageApplyTeamForm", new TeamPageApplyTeamForm());
return "team_page_apply_team";
}
@RequestMapping(value = "/teams/apply_team", method = RequestMethod.POST)
public String checkApplyTeamInfo(
@Valid TeamPageApplyTeamForm teamPageApplyTeamForm,
BindingResult bindingResult,
HttpSession session,
final RedirectAttributes redirectAttributes) throws WebServiceRuntimeException {
final String logPrefix = "Existing user apply for new team: {}";
if (bindingResult.hasErrors()) {
log.warn(logPrefix, "Application form error " + teamPageApplyTeamForm.toString());
return "team_page_apply_team";
}
// log data to ensure data has been parsed
log.debug(logPrefix, properties.getRegisterRequestToApplyTeam(session.getAttribute("id").toString()));
log.info(logPrefix, teamPageApplyTeamForm.toString());
JSONObject mainObject = new JSONObject();
JSONObject teamFields = new JSONObject();
mainObject.put("team", teamFields);
teamFields.put("name", teamPageApplyTeamForm.getTeamName());
teamFields.put("description", teamPageApplyTeamForm.getTeamDescription());
teamFields.put("website", teamPageApplyTeamForm.getTeamWebsite());
teamFields.put("organisationType", teamPageApplyTeamForm.getTeamOrganizationType());
teamFields.put("visibility", teamPageApplyTeamForm.getIsPublic());
String nclUserId = session.getAttribute("id").toString();
HttpEntity<String> request = createHttpEntityWithBody(mainObject.toString());
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getRegisterRequestToApplyTeam(nclUserId), HttpMethod.POST, request, String.class);
String responseBody = response.getBody().toString();
if (RestUtil.isError(response.getStatusCode())) {
// prepare the exception mapping
EnumMap<ExceptionState, String> exceptionMessageMap = new EnumMap<>(ExceptionState.class);
exceptionMessageMap.put(USER_ID_NULL_OR_EMPTY_EXCEPTION, "User id is null or empty ");
exceptionMessageMap.put(TEAM_NAME_NULL_OR_EMPTY_EXCEPTION, "Team name is null or empty ");
exceptionMessageMap.put(USER_NOT_FOUND_EXCEPTION, "User not found");
exceptionMessageMap.put(TEAM_NAME_ALREADY_EXISTS_EXCEPTION, "Team name already exists");
exceptionMessageMap.put(INVALID_TEAM_NAME_EXCEPTION, "Team name contains invalid characters");
exceptionMessageMap.put(TEAM_MEMBER_ALREADY_EXISTS_EXCEPTION, "Team member already exists");
exceptionMessageMap.put(ADAPTER_CONNECTION_EXCEPTION, "Connection to adapter failed");
exceptionMessageMap.put(ADAPTER_INTERNAL_ERROR_EXCEPTION, "Internal server error on adapter");
exceptionMessageMap.put(DETERLAB_OPERATION_FAILED_EXCEPTION, "Operation failed on DeterLab");
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
final String errorMessage = exceptionMessageMap.containsKey(exceptionState) ? error.getMessage() : ERR_SERVER_OVERLOAD;
log.warn(logPrefix, responseBody);
redirectAttributes.addFlashAttribute("message", errorMessage);
return "redirect:/teams/apply_team";
} else {
// no errors, everything ok
log.info(logPrefix, "Application for team " + teamPageApplyTeamForm.getTeamName() + " submitted");
return "redirect:/teams/team_application_submitted";
}
} catch (ResourceAccessException | IOException e) {
log.error(logPrefix, e);
throw new WebServiceRuntimeException(e.getMessage());
}
}
@RequestMapping(value = "/acceptable_usage_policy", method = RequestMethod.GET)
public String teamOwnerPolicy() {
return "acceptable_usage_policy";
}
@RequestMapping(value = "/terms_and_conditions", method = RequestMethod.GET)
public String termsAndConditions() {
return "terms_and_conditions";
}
//--------------------------Join Team Page--------------------------
@RequestMapping(value = "/teams/join_team", method = RequestMethod.GET)
public String teamPageJoinTeam(Model model) {
model.addAttribute("teamPageJoinTeamForm", new TeamPageJoinTeamForm());
return "team_page_join_team";
}
@RequestMapping(value = "/teams/join_team", method = RequestMethod.POST)
public String checkJoinTeamInfo(
@Valid TeamPageJoinTeamForm teamPageJoinForm,
BindingResult bindingResult,
Model model,
HttpSession session,
final RedirectAttributes redirectAttributes) throws WebServiceRuntimeException {
final String logPrefix = "Existing user join team: {}";
if (bindingResult.hasErrors()) {
log.warn(logPrefix, "Application form error " + teamPageJoinForm.toString());
return "team_page_join_team";
}
JSONObject mainObject = new JSONObject();
JSONObject teamFields = new JSONObject();
JSONObject userFields = new JSONObject();
mainObject.put("team", teamFields);
mainObject.put("user", userFields);
userFields.put("id", session.getAttribute("id")); // ncl-id
teamFields.put("name", teamPageJoinForm.getTeamName());
log.info(logPrefix, "User " + session.getAttribute("id") + ", team " + teamPageJoinForm.getTeamName());
HttpEntity<String> request = createHttpEntityWithBody(mainObject.toString());
ResponseEntity response;
try {
restTemplate.setErrorHandler(new MyResponseErrorHandler());
response = restTemplate.exchange(properties.getJoinRequestExistingUser(), HttpMethod.POST, request, String.class);
String responseBody = response.getBody().toString();
if (RestUtil.isError(response.getStatusCode())) {
// prepare the exception mapping
EnumMap<ExceptionState, String> exceptionMessageMap = new EnumMap<>(ExceptionState.class);
exceptionMessageMap.put(USER_NOT_FOUND_EXCEPTION, "User not found");
exceptionMessageMap.put(USER_ID_NULL_OR_EMPTY_EXCEPTION, "User id is null or empty");
exceptionMessageMap.put(TEAM_NOT_FOUND_EXCEPTION, "Team name not found");
exceptionMessageMap.put(TEAM_NAME_NULL_OR_EMPTY_EXCEPTION, "Team name is null or empty");
exceptionMessageMap.put(USER_ALREADY_IN_TEAM_EXCEPTION, "User already in team");
exceptionMessageMap.put(TEAM_MEMBER_ALREADY_EXISTS_EXCEPTION, "Team member already exists");
exceptionMessageMap.put(ADAPTER_CONNECTION_EXCEPTION, "Connection to adapter failed");
exceptionMessageMap.put(ADAPTER_INTERNAL_ERROR_EXCEPTION, "Internal server error on adapter");
exceptionMessageMap.put(DETERLAB_OPERATION_FAILED_EXCEPTION, "Operation failed on DeterLab");
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
final String errorMessage = exceptionMessageMap.containsKey(exceptionState) ? error.getMessage() : ERR_SERVER_OVERLOAD;
log.warn(logPrefix, responseBody);
redirectAttributes.addFlashAttribute("message", errorMessage);
return "redirect:/teams/join_team";
} else {
log.info(logPrefix, "Application for join team " + teamPageJoinForm.getTeamName() + " submitted");
return "redirect:/teams/join_application_submitted/" + teamPageJoinForm.getTeamName();
}
} catch (ResourceAccessException | IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
}
//--------------------------Experiment Page--------------------------
@RequestMapping(value = "/experiments", method = RequestMethod.GET)
public String experiments(Model model, HttpSession session) throws WebServiceRuntimeException {
// long start = System.currentTimeMillis();
List<Experiment2> experimentList = new ArrayList<>();
Map<Long, Realization> realizationMap = new HashMap<>();
HttpEntity<String> request = createHttpEntityHeaderOnly();
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = restTemplate.exchange(properties.getDeterUid(session.getAttribute("id").toString()), HttpMethod.GET, request, String.class);
String responseBody = response.getBody().toString();
try {
if (RestUtil.isError(response.getStatusCode())) {
log.error("No user to get experiment: {}", session.getAttribute("id"));
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
log.info("experiment error: {} - {} - {} - user token:{}", error.getError(), error.getMessage(), error.getLocalizedMessage(), httpScopedSession.getAttribute(webProperties.getSessionJwtToken()));
model.addAttribute(DETER_UID, CONNECTION_ERROR);
} else {
log.info("Show the deter user id: {}", responseBody);
model.addAttribute(DETER_UID, responseBody);
}
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
// get list of teamids
ResponseEntity userRespEntity = restTemplate.exchange(properties.getUser(session.getAttribute("id").toString()), HttpMethod.GET, request, String.class);
JSONObject object = new JSONObject(userRespEntity.getBody().toString());
JSONArray teamIdsJsonArray = object.getJSONArray("teams");
for (int i = 0; i < teamIdsJsonArray.length(); i++) {
String teamId = teamIdsJsonArray.get(i).toString();
HttpEntity<String> teamRequest = createHttpEntityHeaderOnly();
ResponseEntity teamResponse = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, teamRequest, String.class);
String teamResponseBody = teamResponse.getBody().toString();
if (!isMemberJoinRequestPending(session.getAttribute("id").toString(), teamResponseBody)) {
// get experiments lists of the teams
HttpEntity<String> expRequest = createHttpEntityHeaderOnly();
ResponseEntity expRespEntity = restTemplate.exchange(properties.getExpListByTeamId(teamId), HttpMethod.GET, expRequest, String.class);
JSONArray experimentsArray = new JSONArray(expRespEntity.getBody().toString());
for (int k = 0; k < experimentsArray.length(); k++) {
Experiment2 experiment2 = extractExperiment(experimentsArray.getJSONObject(k).toString());
Realization realization = invokeAndExtractRealization(experiment2.getTeamName(), experiment2.getId());
realizationMap.put(experiment2.getId(), realization);
experimentList.add(experiment2);
}
}
}
model.addAttribute("experimentList", experimentList);
model.addAttribute("realizationMap", realizationMap);
// System.out.println("Elapsed time to get experiment page:" + (System.currentTimeMillis() - start));
return "experiments";
}
@RequestMapping(value = "/experiments/create", method = RequestMethod.GET)
public String createExperiment(Model model, HttpSession session) throws WebServiceRuntimeException {
log.info("Loading create experiment page");
// a list of teams that the logged in user is in
List<String> scenarioFileNameList = getScenarioFileNameList();
List<Team2> userTeamsList = new ArrayList<>();
// get list of teamids
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response = restTemplate.exchange(properties.getUser(session.getAttribute("id").toString()), HttpMethod.GET, request, String.class);
String responseBody = response.getBody().toString();
JSONObject object = new JSONObject(responseBody);
JSONArray teamIdsJsonArray = object.getJSONArray("teams");
for (int i = 0; i < teamIdsJsonArray.length(); i++) {
String teamId = teamIdsJsonArray.get(i).toString();
HttpEntity<String> teamRequest = createHttpEntityHeaderOnly();
ResponseEntity teamResponse = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, teamRequest, String.class);
String teamResponseBody = teamResponse.getBody().toString();
Team2 team2 = extractTeamInfo(teamResponseBody);
userTeamsList.add(team2);
}
model.addAttribute("scenarioFileNameList", scenarioFileNameList);
model.addAttribute("experimentForm", new ExperimentForm());
model.addAttribute("userTeamsList", userTeamsList);
return "experiment_page_create_experiment";
}
@RequestMapping(value = "/experiments/create", method = RequestMethod.POST)
public String validateExperiment(
@ModelAttribute("experimentForm") ExperimentForm experimentForm,
HttpSession session,
BindingResult bindingResult,
final RedirectAttributes redirectAttributes) throws WebServiceRuntimeException {
if (bindingResult.hasErrors()) {
log.info("Create experiment - form has errors");
return "redirect:/experiments/create";
}
if (experimentForm.getName() == null || experimentForm.getName().isEmpty()) {
redirectAttributes.addFlashAttribute(MESSAGE, "Experiment Name cannot be empty");
return "redirect:/experiments/create";
}
if (experimentForm.getDescription() == null || experimentForm.getDescription().isEmpty()) {
redirectAttributes.addFlashAttribute(MESSAGE, "Description cannot be empty");
return "redirect:/experiments/create";
}
experimentForm.setScenarioContents(getScenarioContentsFromFile(experimentForm.getScenarioFileName()));
JSONObject experimentObject = new JSONObject();
experimentObject.put("userId", session.getAttribute("id").toString());
experimentObject.put(TEAM_ID, experimentForm.getTeamId());
experimentObject.put(TEAM_NAME, experimentForm.getTeamName());
experimentObject.put("name", experimentForm.getName().replaceAll("\\s+", "")); // truncate whitespaces and non-visible characters like \n
experimentObject.put("description", experimentForm.getDescription());
experimentObject.put("nsFile", "file");
experimentObject.put("nsFileContent", experimentForm.getNsFileContent());
experimentObject.put("idleSwap", "240");
experimentObject.put("maxDuration", "960");
log.info("Calling service to create experiment");
HttpEntity<String> request = createHttpEntityWithBody(experimentObject.toString());
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = restTemplate.exchange(properties.getSioExpUrl(), HttpMethod.POST, request, String.class);
String responseBody = response.getBody().toString();
try {
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case NS_FILE_PARSE_EXCEPTION:
log.warn("Ns file error");
redirectAttributes.addFlashAttribute(MESSAGE, "There is an error when parsing the NS File.");
break;
case EXPERIMENT_NAME_ALREADY_EXISTS_EXCEPTION:
log.warn("Exp name already exists");
redirectAttributes.addFlashAttribute(MESSAGE, "Experiment name already exists.");
break;
default:
log.warn("Exp service or adapter fail");
// possible sio or adapter connection fail
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
break;
}
log.info("Experiment {} created", experimentForm);
return "redirect:/experiments/create";
}
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
//
// TODO Uploaded function for network configuration and optional dataset
// if (!networkFile.isEmpty()) {
// try {
// String networkFileName = getSessionIdOfLoggedInUser(session) + "-networkconfig-" + networkFile.getOriginalFilename();
// BufferedOutputStream stream = new BufferedOutputStream(
// new FileOutputStream(new File(App.EXP_CONFIG_DIR + "/" + networkFileName)));
// FileCopyUtils.copy(networkFile.getInputStream(), stream);
// stream.close();
// redirectAttributes.addFlashAttribute(MESSAGE,
// "You successfully uploaded " + networkFile.getOriginalFilename() + "!");
// // remember network file name here
// }
// catch (Exception e) {
// redirectAttributes.addFlashAttribute(MESSAGE,
// "You failed to upload " + networkFile.getOriginalFilename() + " => " + e.getMessage());
// return "redirect:/experiments/create";
// }
// }
//
// if (!dataFile.isEmpty()) {
// try {
// String dataFileName = getSessionIdOfLoggedInUser(session) + "-data-" + dataFile.getOriginalFilename();
// BufferedOutputStream stream = new BufferedOutputStream(
// new FileOutputStream(new File(App.EXP_CONFIG_DIR + "/" + dataFileName)));
// FileCopyUtils.copy(dataFile.getInputStream(), stream);
// stream.close();
// redirectAttributes.addFlashAttribute("message2",
// "You successfully uploaded " + dataFile.getOriginalFilename() + "!");
// // remember data file name here
// }
// catch (Exception e) {
// redirectAttributes.addFlashAttribute("message2",
// "You failed to upload " + dataFile.getOriginalFilename() + " => " + e.getMessage());
// }
// }
//
// // add current experiment to experiment manager
// experimentManager.addExperiment(getSessionIdOfLoggedInUser(session), experiment);
// // increase exp count to be display on Teams page
// teamManager.incrementExperimentCount(experiment.getTeamId());
return "redirect:/experiments";
}
@RequestMapping(value = "/experiments/save_image/{teamId}/{expId}/{nodeId}", method = RequestMethod.GET)
public String saveExperimentImage(@PathVariable String teamId, @PathVariable String expId, @PathVariable String nodeId, Model model) {
Map<String, Map<String, String>> singleNodeInfoMap = new HashMap<>();
Image saveImageForm = new Image();
String teamName = invokeAndExtractTeamInfo(teamId).getName();
Realization realization = invokeAndExtractRealization(teamName, Long.parseLong(expId));
// experiment may have many nodes
// extract just the particular node details to display
for (Map.Entry<String, Map<String, String>> nodesInfo : realization.getNodesInfoMap().entrySet()) {
String nodeName = nodesInfo.getKey();
Map<String, String> singleNodeDetailsMap = nodesInfo.getValue();
if (singleNodeDetailsMap.get(NODE_ID).equals(nodeId)) {
singleNodeInfoMap.put(nodeName, singleNodeDetailsMap);
// store the current os of the node into the form also
// have to pass the the services
saveImageForm.setCurrentOS(singleNodeDetailsMap.get("os"));
}
}
saveImageForm.setTeamId(teamId);
saveImageForm.setNodeId(nodeId);
model.addAttribute("teamName", teamName);
model.addAttribute("singleNodeInfoMap", singleNodeInfoMap);
model.addAttribute("pathTeamId", teamId);
model.addAttribute("pathExperimentId", expId);
model.addAttribute("pathNodeId", nodeId);
model.addAttribute("experimentName", realization.getExperimentName());
model.addAttribute("saveImageForm", saveImageForm);
return "save_experiment_image";
}
// bindingResult is required in the method signature to perform the JSR303 validation for Image object
@RequestMapping(value = "/experiments/save_image/{teamId}/{expId}/{nodeId}", method = RequestMethod.POST)
public String saveExperimentImage(
@Valid @ModelAttribute("saveImageForm") Image saveImageForm,
BindingResult bindingResult,
RedirectAttributes redirectAttributes,
@PathVariable String teamId,
@PathVariable String expId,
@PathVariable String nodeId) throws IOException {
if (saveImageForm.getImageName().length() < 2) {
log.warn("Save image form has errors {}", saveImageForm);
redirectAttributes.addFlashAttribute("message", "Image name too short, minimum 2 characters");
return "redirect:/experiments/save_image/" + teamId + "/" + expId + "/" + nodeId;
}
log.info("Saving image: team {}, experiment {}, node {}", teamId, expId, nodeId);
ObjectMapper mapper = new ObjectMapper();
HttpEntity<String> request = createHttpEntityWithBody(mapper.writeValueAsString(saveImageForm));
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = restTemplate.exchange(properties.saveImage(), HttpMethod.POST, request, String.class);
String responseBody = response.getBody().toString();
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
log.warn("Save image: error with exception {}", exceptionState);
switch (exceptionState) {
case DETERLAB_OPERATION_FAILED_EXCEPTION:
log.warn("Save image: error, operation failed on DeterLab");
redirectAttributes.addFlashAttribute("message", error.getMessage());
break;
case ADAPTER_CONNECTION_EXCEPTION:
log.warn("Save image: error, cannot connect to adapter");
redirectAttributes.addFlashAttribute("message", "connection to adapter failed");
break;
case ADAPTER_INTERNAL_ERROR_EXCEPTION:
log.warn("Save image: error, adapter internal server error");
redirectAttributes.addFlashAttribute("message", "internal error was found on the adapter");
break;
default:
log.warn("Save image: other error");
redirectAttributes.addFlashAttribute("message", ERR_SERVER_OVERLOAD);
}
return "redirect:/experiments/save_image/" + teamId + "/" + expId + "/" + nodeId;
}
// everything looks ok
log.info("Save image in progress: team {}, experiment {}, node {}, image {}", teamId, expId, nodeId, saveImageForm.getImageName());
return "redirect:/experiments";
}
/*
private String processSaveImageRequest(@Valid @ModelAttribute("saveImageForm") Image saveImageForm, RedirectAttributes redirectAttributes, @PathVariable String teamId, @PathVariable String expId, @PathVariable String nodeId, ResponseEntity response, String responseBody) throws IOException {
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
log.warn("Save image exception: {}", exceptionState);
switch (exceptionState) {
case DETERLAB_OPERATION_FAILED_EXCEPTION:
log.warn("adapter deterlab operation failed exception");
redirectAttributes.addFlashAttribute("message", error.getMessage());
break;
default:
log.warn("Image service or adapter fail");
// possible sio or adapter connection fail
redirectAttributes.addFlashAttribute("message", ERR_SERVER_OVERLOAD);
break;
}
return "redirect:/experiments/save_image/" + teamId + "/" + expId + "/" + nodeId;
} else {
// everything ok
log.info("Image service in progress for Team: {}, Exp: {}, Node: {}, Image: {}", teamId, expId, nodeId, saveImageForm.getImageName());
return "redirect:/experiments";
}
}
*/
// @RequestMapping("/experiments/configuration/{expId}")
// public String viewExperimentConfiguration(@PathVariable Integer expId, Model model) {
// // get experiment from expid
// // retrieve the scenario contents to be displayed
// Experiment currExp = experimentManager.getExperimentByExpId(expId);
// model.addAttribute("scenarioContents", currExp.getScenarioContents());
// return "experiment_scenario_contents";
// }
@RequestMapping("/remove_experiment/{teamName}/{teamId}/{expId}")
public String removeExperiment(@PathVariable String teamName, @PathVariable String teamId, @PathVariable String expId, final RedirectAttributes redirectAttributes, HttpSession session) throws WebServiceRuntimeException {
// ensure experiment is stopped first
Realization realization = invokeAndExtractRealization(teamName, Long.parseLong(expId));
Team2 team = invokeAndExtractTeamInfo(teamId);
// check valid authentication to remove experiments
// either admin, experiment creator or experiment owner
if (!validateIfAdmin(session) && !realization.getUserId().equals(session.getAttribute("id").toString()) && !team.getOwner().getId().equals(session.getAttribute(webProperties.getSessionUserId()))) {
log.warn("Permission denied when remove Team:{}, Experiment: {} with User: {}, Role:{}", teamId, expId, session.getAttribute("id"), session.getAttribute(webProperties.getSessionRoles()));
redirectAttributes.addFlashAttribute(MESSAGE, "An error occurred while trying to remove experiment;" + permissionDeniedMessage);
return "redirect:/experiments";
}
if (!realization.getState().equals(RealizationState.NOT_RUNNING.toString())) {
log.warn("Trying to remove Team: {}, Experiment: {} with State: {} that is still in progress?", teamId, expId, realization.getState());
redirectAttributes.addFlashAttribute(MESSAGE, "An error occurred while trying to remove Exp: " + realization.getExperimentName() + ". Please refresh the page again. If the error persists, please contact " + CONTACT_EMAIL);
return "redirect:/experiments";
}
log.info("Removing experiment: at " + properties.getDeleteExperiment(teamId, expId));
HttpEntity<String> request = createHttpEntityHeaderOnly();
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getDeleteExperiment(teamId, expId), HttpMethod.DELETE, request, String.class);
} catch (Exception e) {
log.warn("Error connecting to experiment service to remove experiment", e.getMessage());
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
return "redirect:/experiments";
}
String responseBody = response.getBody().toString();
try {
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case EXPERIMENT_DELETE_EXCEPTION:
case FORBIDDEN_EXCEPTION:
log.warn("remove experiment failed for Team: {}, Exp: {}", teamId, expId);
redirectAttributes.addFlashAttribute(MESSAGE, error.getMessage());
break;
case OBJECT_OPTIMISTIC_LOCKING_FAILURE_EXCEPTION:
// do nothing
log.info("remove experiment database locking failure");
break;
default:
// do nothing
break;
}
return "redirect:/experiments";
} else {
// everything ok
log.info("remove experiment success for Team: {}, Exp: {}", teamId, expId);
redirectAttributes.addFlashAttribute("exp_remove_message", "Team: " + teamName + " has removed Exp: " + realization.getExperimentName());
return "redirect:/experiments";
}
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
}
@RequestMapping("/start_experiment/{teamName}/{expId}")
public String startExperiment(
@PathVariable String teamName,
@PathVariable String expId,
final RedirectAttributes redirectAttributes, Model model, HttpSession session) throws WebServiceRuntimeException {
// ensure experiment is stopped first before starting
Realization realization = invokeAndExtractRealization(teamName, Long.parseLong(expId));
if (!checkPermissionRealizeExperiment(realization, session)) {
log.warn("Permission denied to start experiment: {} for team: {}", realization.getExperimentName(), teamName);
redirectAttributes.addFlashAttribute(MESSAGE, permissionDeniedMessage);
return "redirect:/experiments";
}
String teamStatus = getTeamStatus(realization.getTeamId());
if (!teamStatus.equals(TeamStatus.APPROVED.name())) {
log.warn("Error: trying to realize an experiment {} on team {} with status {}", realization.getExperimentName(), realization.getTeamId(), teamStatus);
redirectAttributes.addFlashAttribute(MESSAGE, teamName + " is in " + teamStatus + " status and does not have permission to start experiment. Please contact " + CONTACT_EMAIL);
return "redirect:/experiments";
}
if (!realization.getState().equals(RealizationState.NOT_RUNNING.toString())) {
log.warn("Trying to start Team: {}, Experiment: {} with State: {} that is not running?", teamName, expId, realization.getState());
redirectAttributes.addFlashAttribute(MESSAGE, "An error occurred while trying to start Exp: " + realization.getExperimentName() + ". Please refresh the page again. If the error persists, please contact " + CONTACT_EMAIL);
return "redirect:/experiments";
}
log.info("Starting experiment: at " + properties.getStartExperiment(teamName, expId));
HttpEntity<String> request = createHttpEntityHeaderOnly();
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getStartExperiment(teamName, expId), HttpMethod.POST, request, String.class);
} catch (Exception e) {
log.warn("Error connecting to experiment service to start experiment", e.getMessage());
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
return "redirect:/experiments";
}
String responseBody = response.getBody().toString();
try {
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case EXPERIMENT_START_EXCEPTION:
case FORBIDDEN_EXCEPTION:
log.warn("start experiment failed for Team: {}, Exp: {}", teamName, expId);
redirectAttributes.addFlashAttribute(MESSAGE, error.getMessage());
return "redirect:/experiments";
case OBJECT_OPTIMISTIC_LOCKING_FAILURE_EXCEPTION:
// do nothing
log.info("start experiment database locking failure");
break;
default:
// do nothing
break;
}
log.warn("start experiment some other error occurred exception: {}", exceptionState);
// possible for it to be error but experiment has started up finish
// if user clicks on start but reloads the page
// model.addAttribute(EXPERIMENT_MESSAGE, "Team: " + teamName + " has started Exp: " + realization.getExperimentName());
return "experiments";
} else {
// everything ok
log.info("start experiment success for Team: {}, Exp: {}", teamName, expId);
redirectAttributes.addFlashAttribute(EXPERIMENT_MESSAGE, "Experiment " + realization.getExperimentName() + " in team " + teamName + " is starting. This may take up to 10 minutes depending on the scale of your experiment. Please refresh this page later.");
return "redirect:/experiments";
}
} catch (IOException e) {
log.warn("start experiment error: {]", e.getMessage());
throw new WebServiceRuntimeException(e.getMessage());
}
}
@RequestMapping("/stop_experiment/{teamName}/{expId}")
public String stopExperiment(@PathVariable String teamName, @PathVariable String expId, Model model, final RedirectAttributes redirectAttributes, HttpSession session) throws WebServiceRuntimeException {
// ensure experiment is active first before stopping
Realization realization = invokeAndExtractRealization(teamName, Long.parseLong(expId));
if (isNotAdminAndNotInTeam(session, realization)) {
log.warn("Permission denied to stop experiment: {} for team: {}", realization.getExperimentName(), teamName);
redirectAttributes.addFlashAttribute(MESSAGE, permissionDeniedMessage);
return "redirect:/experiments";
}
if (!realization.getState().equals(RealizationState.RUNNING.toString())) {
log.warn("Trying to stop Team: {}, Experiment: {} with State: {} that is still in progress?", teamName, expId, realization.getState());
redirectAttributes.addFlashAttribute(MESSAGE, "An error occurred while trying to stop Exp: " + realization.getExperimentName() + ". Please refresh the page again. If the error persists, please contact " + CONTACT_EMAIL);
return "redirect:/experiments";
}
log.info("Stopping experiment: at " + properties.getStopExperiment(teamName, expId));
HttpEntity<String> request = createHttpEntityHeaderOnly();
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response;
return abc(teamName, expId, redirectAttributes, realization, request);
}
@RequestMapping("/get_topology/{teamName}/{expId}")
@ResponseBody
public String getTopology(@PathVariable String teamName, @PathVariable String expId) {
try {
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response = restTemplate.exchange(properties.getTopology(teamName, expId), HttpMethod.GET, request, String.class);
log.info("Retrieve experiment topo success");
return "data:image/png;base64," + response.getBody();
} catch (Exception e) {
log.error("Error getting topology thumbnail", e.getMessage());
return "";
}
}
private String abc(@PathVariable String teamName, @PathVariable String expId, RedirectAttributes redirectAttributes, Realization realization, HttpEntity<String> request) throws WebServiceRuntimeException {
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getStopExperiment(teamName, expId), HttpMethod.POST, request, String.class);
} catch (Exception e) {
log.warn("Error connecting to experiment service to stop experiment", e.getMessage());
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
return "redirect:/experiments";
}
String responseBody = response.getBody().toString();
try {
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
if (exceptionState == ExceptionState.FORBIDDEN_EXCEPTION) {
log.warn("Permission denied to stop experiment: {} for team: {}", realization.getExperimentName(), teamName);
redirectAttributes.addFlashAttribute(MESSAGE, permissionDeniedMessage);
}
if (exceptionState == ExceptionState.OBJECT_OPTIMISTIC_LOCKING_FAILURE_EXCEPTION) {
log.info("stop experiment database locking failure");
}
} else {
// everything ok
log.info("stop experiment success for Team: {}, Exp: {}", teamName, expId);
redirectAttributes.addFlashAttribute(EXPERIMENT_MESSAGE, "Experiment " + realization.getExperimentName() + " in team " + teamName + " is stopping. Please refresh this page in a few minutes.");
}
return "redirect:/experiments";
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
}
private boolean isNotAdminAndNotInTeam(HttpSession session, Realization realization) {
return !validateIfAdmin(session) && !checkPermissionRealizeExperiment(realization, session);
}
//-----------------------------------------------------------------------
//--------------------------Admin Revamp---------------------------------
//-----------------------------------------------------------------------
//---------------------------------Admin---------------------------------
@RequestMapping("/admin")
public String admin(Model model, HttpSession session) {
if (!validateIfAdmin(session)) {
return NO_PERMISSION_PAGE;
}
TeamManager2 teamManager2 = new TeamManager2();
Map<String, List<String>> userToTeamMap = new HashMap<>(); // userId : list of team names
List<Team2> pendingApprovalTeamsList = new ArrayList<>();
//------------------------------------
// get list of teams
// get list of teams pending for approval
//------------------------------------
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity responseEntity = restTemplate.exchange(properties.getSioTeamsUrl(), HttpMethod.GET, request, String.class);
JSONArray jsonArray = new JSONArray(responseEntity.getBody().toString());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Team2 one = extractTeamInfo(jsonObject.toString());
teamManager2.addTeamToTeamMap(one);
if (one.getStatus().equals(TeamStatus.PENDING.name())) {
pendingApprovalTeamsList.add(one);
}
}
//------------------------------------
// get list of users
//------------------------------------
ResponseEntity response2 = restTemplate.exchange(properties.getSioUsersUrl(), HttpMethod.GET, request, String.class);
String responseBody2 = response2.getBody().toString();
JSONArray jsonUserArray = new JSONArray(responseBody2);
List<User2> usersList = new ArrayList<>();
for (int i = 0; i < jsonUserArray.length(); i++) {
JSONObject userObject = jsonUserArray.getJSONObject(i);
User2 user = extractUserInfo(userObject.toString());
usersList.add(user);
// get list of teams' names for each user
List<String> perUserTeamList = new ArrayList<>();
if (userObject.get("teams") != null) {
JSONArray teamJsonArray = userObject.getJSONArray("teams");
for (int k = 0; k < teamJsonArray.length(); k++) {
Team2 team = invokeAndExtractTeamInfo(teamJsonArray.get(k).toString());
perUserTeamList.add(team.getName());
}
userToTeamMap.put(user.getId(), perUserTeamList);
}
}
model.addAttribute("teamsMap", teamManager2.getTeamMap());
model.addAttribute("pendingApprovalTeamsList", pendingApprovalTeamsList);
model.addAttribute("usersList", usersList);
model.addAttribute("userToTeamMap", userToTeamMap);
return "admin2";
}
@RequestMapping("/admin/data")
public String adminDataManagement(Model model, HttpSession session) {
if (!validateIfAdmin(session)) {
return NO_PERMISSION_PAGE;
}
//------------------------------------
// get list of datasets
//------------------------------------
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response = restTemplate.exchange(properties.getData(), HttpMethod.GET, request, String.class);
String responseBody = response.getBody().toString();
List<Dataset> datasetsList = new ArrayList<>();
JSONArray dataJsonArray = new JSONArray(responseBody);
for (int i = 0; i < dataJsonArray.length(); i++) {
JSONObject dataInfoObject = dataJsonArray.getJSONObject(i);
Dataset dataset = extractDataInfo(dataInfoObject.toString());
datasetsList.add(dataset);
}
ResponseEntity response4 = restTemplate.exchange(properties.getDownloadStat(), HttpMethod.GET, request, String.class);
String responseBody4 = response4.getBody().toString();
Map<Integer, Long> dataDownloadStats = new HashMap<>();
JSONArray statJsonArray = new JSONArray(responseBody4);
for (int i = 0; i < statJsonArray.length(); i++) {
JSONObject statInfoObject = statJsonArray.getJSONObject(i);
dataDownloadStats.put(statInfoObject.getInt("dataId"), statInfoObject.getLong("count"));
}
model.addAttribute("dataList", datasetsList);
model.addAttribute("downloadStats", dataDownloadStats);
return "data_dashboard";
}
@RequestMapping("/admin/experiments")
public String adminExperimentsManagement(Model model, HttpSession session) {
if (!validateIfAdmin(session)) {
return NO_PERMISSION_PAGE;
}
//------------------------------------
// get list of experiments
//------------------------------------
HttpEntity<String> expRequest = createHttpEntityHeaderOnly();
ResponseEntity expResponseEntity = restTemplate.exchange(properties.getSioExpUrl(), HttpMethod.GET, expRequest, String.class);
//------------------------------------
// get list of realizations
//------------------------------------
HttpEntity<String> realizationRequest = createHttpEntityHeaderOnly();
ResponseEntity realizationResponseEntity = restTemplate.exchange(properties.getAllRealizations(), HttpMethod.GET, realizationRequest, String.class);
JSONArray jsonExpArray = new JSONArray(expResponseEntity.getBody().toString());
JSONArray jsonRealizationArray = new JSONArray(realizationResponseEntity.getBody().toString());
Map<Experiment2, Realization> experiment2Map = new HashMap<>(); // exp id, experiment
Map<Long, Realization> realizationMap = new HashMap<>(); // exp id, realization
for (int k = 0; k < jsonRealizationArray.length(); k++) {
Realization realization;
try {
realization = extractRealization(jsonRealizationArray.getJSONObject(k).toString());
} catch (JSONException e) {
log.debug("Admin extract realization {}", e);
realization = getCleanRealization();
}
if (realization.getState().equals(RealizationState.RUNNING.name())) {
realizationMap.put(realization.getExperimentId(), realization);
}
}
for (int i = 0; i < jsonExpArray.length(); i++) {
Experiment2 experiment2 = extractExperiment(jsonExpArray.getJSONObject(i).toString());
if (realizationMap.containsKey(experiment2.getId())) {
experiment2Map.put(experiment2, realizationMap.get(experiment2.getId()));
}
}
model.addAttribute("runningExpMap", experiment2Map);
return "experiment_dashboard";
}
@RequestMapping("/admin/usage")
public String adminTeamUsage(Model model,
@RequestParam(value = "team", required = false) String team,
@RequestParam(value = "start", required = false) String start,
@RequestParam(value = "end", required = false) String end,
HttpSession session) {
if (!validateIfAdmin(session)) {
return NO_PERMISSION_PAGE;
}
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
ZonedDateTime now = ZonedDateTime.now();
if (start == null) {
ZonedDateTime startDate = now.with(firstDayOfMonth());
start = startDate.format(formatter);
}
if (end == null) {
ZonedDateTime endDate = now.with(lastDayOfMonth());
end = endDate.format(formatter);
}
// get list of teamids
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity responseEntity = restTemplate.exchange(properties.getSioTeamsUrl(), HttpMethod.GET, request, String.class);
JSONArray jsonArray = new JSONArray(responseEntity.getBody().toString());
TeamManager2 teamManager2 = new TeamManager2();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Team2 one = extractTeamInfo(jsonObject.toString());
teamManager2.addTeamToTeamMap(one);
}
if (team != null) {
responseEntity = restTemplate.exchange(properties.getUsageStat(team, "startDate=" + start, "endDate=" + end), HttpMethod.GET, request, String.class);
String usage = responseEntity.getBody().toString();
model.addAttribute("usage", usage);
}
model.addAttribute("teamsMap", teamManager2.getTeamMap());
model.addAttribute("start", start);
model.addAttribute("end", end);
model.addAttribute("team", team);
return "usage_statistics";
}
// @RequestMapping(value="/admin/domains/add", method=RequestMethod.POST)
// public String addDomain(@Valid Domain domain, BindingResult bindingResult) {
// if (bindingResult.hasErrors()) {
// return "redirect:/admin";
// } else {
// domainManager.addDomains(domain.getDomainName());
// }
// return "redirect:/admin";
// }
// @RequestMapping("/admin/domains/remove/{domainKey}")
// public String removeDomain(@PathVariable String domainKey) {
// domainManager.removeDomains(domainKey);
// return "redirect:/admin";
// }
@RequestMapping("/admin/teams/accept/{teamId}/{teamOwnerId}")
public String approveTeam(
@PathVariable String teamId,
@PathVariable String teamOwnerId,
final RedirectAttributes redirectAttributes,
HttpSession session
) throws WebServiceRuntimeException {
if (!validateIfAdmin(session)) {
return NO_PERMISSION_PAGE;
}
//FIXME require approver info
log.info("Approving new team {}, team owner {}", teamId, teamOwnerId);
HttpEntity<String> request = createHttpEntityHeaderOnly();
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = restTemplate.exchange(
properties.getApproveTeam(teamId, teamOwnerId, TeamStatus.APPROVED), HttpMethod.POST, request, String.class);
String responseBody = response.getBody().toString();
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error;
try {
error = objectMapper.readValue(responseBody, MyErrorResource.class);
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case TEAM_ID_NULL_OR_EMPTY_EXCEPTION:
log.warn("Approve team: TeamId cannot be null or empty: {}",
teamId);
redirectAttributes.addFlashAttribute(MESSAGE, "TeamId cannot be null or empty");
break;
case USER_ID_NULL_OR_EMPTY_EXCEPTION:
log.warn("Approve team: UserId cannot be null or empty: {}",
teamOwnerId);
redirectAttributes.addFlashAttribute(MESSAGE, "UserId cannot be null or empty");
break;
case INVALID_TEAM_STATUS_EXCEPTION:
log.warn("Approve team: TeamStatus is invalid");
redirectAttributes.addFlashAttribute(MESSAGE, "Team status is invalid");
break;
case TEAM_NOT_FOUND_EXCEPTION:
log.warn("Approve team: Team {} not found", teamId);
redirectAttributes.addFlashAttribute(MESSAGE, "Team does not exist");
break;
case DETERLAB_OPERATION_FAILED_EXCEPTION:
log.warn("Approve team: Team {} fail", teamId);
redirectAttributes.addFlashAttribute(MESSAGE, "Approve team request fail on Deterlab");
break;
default:
log.warn("Approve team : sio or deterlab adapter connection error");
// possible sio or adapter connection fail
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
break;
}
return "redirect:/admin";
}
// http status code is OK, then need to check the response message
String msg = new JSONObject(responseBody).getString("msg");
if ("approve project OK".equals(msg)) {
log.info("Approve team {} OK", teamId);
} else {
log.warn("Approve team {} FAIL", teamId);
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
}
return "redirect:/admin";
}
@RequestMapping("/admin/teams/reject/{teamId}/{teamOwnerId}")
public String rejectTeam(
@PathVariable String teamId,
@PathVariable String teamOwnerId,
final RedirectAttributes redirectAttributes,
HttpSession session
) throws WebServiceRuntimeException {
if (!validateIfAdmin(session)) {
return NO_PERMISSION_PAGE;
}
//FIXME require approver info
log.info("Rejecting new team {}, team owner {}", teamId, teamOwnerId);
HttpEntity<String> request = createHttpEntityHeaderOnly();
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = restTemplate.exchange(
properties.getApproveTeam(teamId, teamOwnerId, TeamStatus.REJECTED), HttpMethod.POST, request, String.class);
String responseBody = response.getBody().toString();
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error;
try {
error = objectMapper.readValue(responseBody, MyErrorResource.class);
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case TEAM_ID_NULL_OR_EMPTY_EXCEPTION:
log.warn("Reject team: TeamId cannot be null or empty: {}",
teamId);
redirectAttributes.addFlashAttribute(MESSAGE, "TeamId cannot be null or empty");
break;
case USER_ID_NULL_OR_EMPTY_EXCEPTION:
log.warn("Reject team: UserId cannot be null or empty: {}",
teamOwnerId);
redirectAttributes.addFlashAttribute(MESSAGE, "UserId cannot be null or empty");
break;
case INVALID_TEAM_STATUS_EXCEPTION:
log.warn("Reject team: TeamStatus is invalid");
redirectAttributes.addFlashAttribute(MESSAGE, "Team status is invalid");
break;
case TEAM_NOT_FOUND_EXCEPTION:
log.warn("Reject team: Team {} not found", teamId);
redirectAttributes.addFlashAttribute(MESSAGE, "Team does not exist");
break;
case DETERLAB_OPERATION_FAILED_EXCEPTION:
log.warn("Reject team: Team {} fail", teamId);
redirectAttributes.addFlashAttribute(MESSAGE, "Reject team request fail on Deterlab");
break;
default:
log.warn("Reject team : sio or deterlab adapter connection error");
// possible sio or adapter connection fail
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
break;
}
return "redirect:/admin";
}
// http status code is OK, then need to check the response message
String msg = new JSONObject(responseBody).getString("msg");
if ("reject project OK".equals(msg)) {
log.info("Reject team {} OK", teamId);
} else {
log.warn("Reject team {} FAIL", teamId);
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
}
return "redirect:/admin";
}
@RequestMapping("/admin/teams/{teamId}")
public String setupTeamRestriction(
@PathVariable final String teamId,
@RequestParam(value = "action", required = true) final String action,
final RedirectAttributes redirectAttributes,
HttpSession session) throws IOException {
final String logMessage = "Updating restriction settings for team {}: {}";
// check if admin
if (!validateIfAdmin(session)) {
log.warn(logMessage, teamId, PERMISSION_DENIED);
return NO_PERMISSION_PAGE;
}
Team2 team = invokeAndExtractTeamInfo(teamId);
// check if team is approved before restricted
if ("restrict".equals(action) && team.getStatus().equals(TeamStatus.APPROVED.name())) {
return restrictTeam(team, redirectAttributes);
}
// check if team is restricted before freeing it back to approved
else if ("free".equals(action) && team.getStatus().equals(TeamStatus.RESTRICTED.name())) {
return freeTeam(team, redirectAttributes);
} else {
log.warn(logMessage, teamId, "Cannot " + action + " team with status " + team.getStatus());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + "Cannot " + action + " team " + team.getName() + " with status " + team.getStatus());
return "redirect:/admin";
}
}
private String restrictTeam(final Team2 team, RedirectAttributes redirectAttributes) throws IOException {
log.info("Restricting team {}", team.getId());
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response = restTemplate.exchange(
properties.getSioTeamsStatusUrl(team.getId(), TeamStatus.RESTRICTED),
HttpMethod.PUT, request, String.class);
String responseBody = response.getBody().toString();
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
String logMessage = "Failed to restrict team {}: {}";
switch (exceptionState) {
case TEAM_NOT_FOUND_EXCEPTION:
log.warn(logMessage, team.getId(), TEAM_NOT_FOUND);
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + TEAM_NOT_FOUND);
break;
case INVALID_STATUS_TRANSITION_EXCEPTION:
log.warn(logMessage, team.getId(), error.getMessage());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage());
break;
case INVALID_TEAM_STATUS_EXCEPTION:
log.warn(logMessage, team.getId(), error.getMessage());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage());
break;
case FORBIDDEN_EXCEPTION:
log.warn(logMessage, team.getId(), PERMISSION_DENIED);
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + PERMISSION_DENIED);
break;
default:
log.warn(logMessage, team.getId(), exceptionState.getExceptionName());
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
}
return "redirect:/admin";
} else {
// good
log.info("Team {} has been restricted", team.getId());
redirectAttributes.addFlashAttribute(MESSAGE_SUCCESS, "Team " + team.getName() + " status has been changed to " + TeamStatus.RESTRICTED.name());
return "redirect:/admin";
}
}
private String freeTeam(final Team2 team, RedirectAttributes redirectAttributes) throws IOException {
log.info("Freeing team {}", team.getId());
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response = restTemplate.exchange(
properties.getSioTeamsStatusUrl(team.getId(), TeamStatus.APPROVED),
HttpMethod.PUT, request, String.class);
String responseBody = response.getBody().toString();
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
String logMessage = "Failed to free team {}: {}";
switch (exceptionState) {
case TEAM_NOT_FOUND_EXCEPTION:
log.warn(logMessage, team.getId(), TEAM_NOT_FOUND);
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + TEAM_NOT_FOUND);
break;
case INVALID_STATUS_TRANSITION_EXCEPTION:
log.warn(logMessage, team.getId(), error.getMessage());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage());
break;
case INVALID_TEAM_STATUS_EXCEPTION:
log.warn(logMessage, team.getId(), error.getMessage());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage());
break;
case FORBIDDEN_EXCEPTION:
log.warn(logMessage, team.getId(), PERMISSION_DENIED);
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + PERMISSION_DENIED);
break;
default:
log.warn(logMessage, team.getId(), exceptionState.getExceptionName());
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
}
return "redirect:/admin";
} else {
// good
log.info("Team {} has been freed", team.getId());
redirectAttributes.addFlashAttribute(MESSAGE_SUCCESS, "Team " + team.getName() + " status has been changed to " + TeamStatus.APPROVED.name());
return "redirect:/admin";
}
}
@RequestMapping("/admin/users/{userId}")
public String freezeUnfreezeUsers(
@PathVariable final String userId,
@RequestParam(value = "action", required = true) final String action,
final RedirectAttributes redirectAttributes,
HttpSession session) throws IOException {
User2 user = invokeAndExtractUserInfo(userId);
// check if admin
if (!validateIfAdmin(session)) {
log.warn("Access denied when trying to freeze/unfreeze user {}: must be admin!", userId);
return NO_PERMISSION_PAGE;
}
// check if user status is approved before freeze
if ("freeze".equals(action) && user.getStatus().equals(UserStatus.APPROVED.toString())) {
return freezeUser(user, redirectAttributes);
}
// check if user status is frozen before unfreeze
else if ("unfreeze".equals(action) && user.getStatus().equals(UserStatus.FROZEN.toString())) {
return unfreezeUser(user, redirectAttributes);
} else {
log.warn("Error in freeze/unfreeze user {}: failed to {} user with status {}", userId, action, user.getStatus());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + "failed to " + action + " user " + user.getEmail() + " with status " + user.getStatus());
return "redirect:/admin";
}
}
private String freezeUser(final User2 user, RedirectAttributes redirectAttributes) throws IOException {
log.info("Freezing user {}, email {}", user.getId(), user.getEmail());
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response = restTemplate.exchange(
properties.getSioUsersStatusUrl(user.getId(), UserStatus.FROZEN.toString()),
HttpMethod.PUT, request, String.class);
String responseBody = response.getBody().toString();
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case USER_NOT_FOUND_EXCEPTION:
log.warn("Failed to freeze user {}: user not found", user.getId());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + " user " + user.getEmail() + " not found.");
break;
case INVALID_STATUS_TRANSITION_EXCEPTION:
log.warn("Failed to freeze user {}: invalid status transition {}", user.getId(), error.getMessage());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage() + " is not allowed.");
break;
case INVALID_USER_STATUS_EXCEPTION:
log.warn("Failed to freeze user {}: invalid user status {}", user.getId(), error.getMessage());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage() + " is not a valid status.");
break;
case FORBIDDEN_EXCEPTION:
log.warn("Failed to freeze user {}: must be an Admin", user.getId());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + " permission denied.");
break;
default:
log.warn("Failed to freeze user {}: {}", user.getId(), exceptionState.getExceptionName());
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
break;
}
return "redirect:/admin";
} else {
// good
log.info("User {} has been frozen", user.getId());
redirectAttributes.addFlashAttribute(MESSAGE_SUCCESS, "User " + user.getEmail() + " has been banned.");
return "redirect:/admin";
}
}
private String unfreezeUser(final User2 user, RedirectAttributes redirectAttributes) throws IOException {
log.info("Unfreezing user {}, email {}", user.getId(), user.getEmail());
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response = restTemplate.exchange(
properties.getSioUsersStatusUrl(user.getId(), UserStatus.APPROVED.toString()),
HttpMethod.PUT, request, String.class);
String responseBody = response.getBody().toString();
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case USER_NOT_FOUND_EXCEPTION:
log.warn("Failed to unfreeze user {}: user not found", user.getId());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + " user " + user.getEmail() + " not found.");
break;
case INVALID_STATUS_TRANSITION_EXCEPTION:
log.warn("Failed to unfreeze user {}: invalid status transition {}", user.getId(), error.getMessage());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage() + " is not allowed.");
break;
case INVALID_USER_STATUS_EXCEPTION:
log.warn("Failed to unfreeze user {}: invalid user status {}", user.getId(), error.getMessage());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage() + " is not a valid status.");
break;
case FORBIDDEN_EXCEPTION:
log.warn("Failed to unfreeze user {}: must be an Admin", user.getId());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + " permission denied.");
break;
default:
log.warn("Failed to unfreeze user {}: {}", user.getId(), exceptionState.getExceptionName());
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
break;
}
return "redirect:/admin";
} else {
// good
log.info("User {} has been unfrozen", user.getId());
redirectAttributes.addFlashAttribute(MESSAGE_SUCCESS, "User " + user.getEmail() + " has been unbanned.");
return "redirect:/admin";
}
}
// @RequestMapping("/admin/experiments/remove/{expId}")
// public String adminRemoveExp(@PathVariable Integer expId) {
// int teamId = experimentManager.getExperimentByExpId(expId).getTeamId();
// experimentManager.adminRemoveExperiment(expId);
//
// // decrease exp count to be display on Teams page
// teamManager.decrementExperimentCount(teamId);
// return "redirect:/admin";
// }
// @RequestMapping(value="/admin/data/contribute", method=RequestMethod.GET)
// public String adminContributeDataset(Model model) {
// model.addAttribute("dataset", new Dataset());
//
// File rootFolder = new File(App.ROOT);
// List<String> fileNames = Arrays.stream(rootFolder.listFiles())
// .map(f -> f.getError())
// .collect(Collectors.toList());
//
// model.addAttribute("files",
// Arrays.stream(rootFolder.listFiles())
// .sorted(Comparator.comparingLong(f -> -1 * f.lastModified()))
// .map(f -> f.getError())
// .collect(Collectors.toList())
// );
//
// return "admin_contribute_data";
// }
// @RequestMapping(value="/admin/data/contribute", method=RequestMethod.POST)
// public String validateAdminContributeDataset(@ModelAttribute("dataset") Dataset dataset, HttpSession session, @RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) throws IOException {
// BufferedOutputStream stream = null;
// FileOutputStream fileOutputStream = null;
// // TODO
// // validation
// // get file from user upload to server
// if (!file.isEmpty()) {
// try {
// String fileName = getSessionIdOfLoggedInUser(session) + "-" + file.getOriginalFilename();
// fileOutputStream = new FileOutputStream(new File(App.ROOT + "/" + fileName));
// stream = new BufferedOutputStream(fileOutputStream);
// FileCopyUtils.copy(file.getInputStream(), stream);
// redirectAttributes.addFlashAttribute(MESSAGE,
// "You successfully uploaded " + file.getOriginalFilename() + "!");
// datasetManager.addDataset(getSessionIdOfLoggedInUser(session), dataset, file.getOriginalFilename());
// }
// catch (Exception e) {
// redirectAttributes.addFlashAttribute(MESSAGE,
// "You failed to upload " + file.getOriginalFilename() + " => " + e.getMessage());
// } finally {
// if (stream != null) {
// stream.close();
// }
// if (fileOutputStream != null) {
// fileOutputStream.close();
// }
// }
// }
// else {
// redirectAttributes.addFlashAttribute(MESSAGE,
// "You failed to upload " + file.getOriginalFilename() + " because the file was empty");
// }
// return "redirect:/admin";
// }
// @RequestMapping("/admin/data/remove/{datasetId}")
// public String adminRemoveDataset(@PathVariable Integer datasetId) {
// datasetManager.removeDataset(datasetId);
// return "redirect:/admin";
// }
// @RequestMapping(value="/admin/node/add", method=RequestMethod.GET)
// public String adminAddNode(Model model) {
// model.addAttribute("node", new Node());
// return "admin_add_node";
// }
// @RequestMapping(value="/admin/node/add", method=RequestMethod.POST)
// public String adminAddNode(@ModelAttribute("node") Node node) {
// // TODO
// // validate fields, eg should be integer
// nodeManager.addNode(node);
// return "redirect:/admin";
// }
//--------------------------Static pages for teams--------------------------
@RequestMapping("/teams/team_application_submitted")
public String teamAppSubmitFromTeamsPage() {
return "team_page_application_submitted";
}
@RequestMapping("/teams/join_application_submitted/{teamName}")
public String teamAppJoinFromTeamsPage(@PathVariable String teamName, Model model) throws WebServiceRuntimeException {
log.info("Redirecting to join application submitted page");
HttpEntity<String> request = createHttpEntityHeaderOnly();
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = restTemplate.exchange(properties.getTeamByName(teamName), HttpMethod.GET, request, String.class);
String responseBody = response.getBody().toString();
try {
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case TEAM_NOT_FOUND_EXCEPTION:
log.warn("submitted join team request : team name error");
break;
default:
log.warn("submitted join team request : some other failure");
// possible sio or adapter connection fail
break;
}
return "redirect:/teams/join_team";
}
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
Team2 one = extractTeamInfo(responseBody);
model.addAttribute("team", one);
return "team_page_join_application_submitted";
}
//--------------------------Static pages for sign up--------------------------
@RequestMapping("/team_application_submitted")
public String teamAppSubmit() {
return "team_application_submitted";
}
/**
* A page to show new users has successfully registered to apply to join an existing team
* The page contains the team owner information which the users requested to join
*
* @param model The model which is passed from signup
* @return A success page otherwise an error page if the user tries to access this page directly
*/
@RequestMapping("/join_application_submitted")
public String joinTeamAppSubmit(Model model) {
// model attribute should be passed from /signup2
// team is required to display the team owner details
if (model.containsAttribute("team")) {
return "join_team_application_submitted";
}
return "error";
}
@RequestMapping("/email_not_validated")
public String emailNotValidated() {
return "email_not_validated";
}
@RequestMapping("/team_application_under_review")
public String teamAppUnderReview() {
return "team_application_under_review";
}
// model attribute name come from /login
@RequestMapping("/email_checklist")
public String emailChecklist(@ModelAttribute("statuschecklist") String status) {
return "email_checklist";
}
@RequestMapping("/join_application_awaiting_approval")
public String joinTeamAppAwaitingApproval(Model model) {
model.addAttribute("loginForm", new LoginForm());
model.addAttribute("signUpMergedForm", new SignUpMergedForm());
return "join_team_application_awaiting_approval";
}
//--------------------------Get List of scenarios filenames--------------------------
private List<String> getScenarioFileNameList() throws WebServiceRuntimeException {
log.info("Retrieving scenario file names");
// List<String> scenarioFileNameList = null;
// try {
// scenarioFileNameList = IOUtils.readLines(getClass().getClassLoader().getResourceAsStream("scenarios"), StandardCharsets.UTF_8);
// } catch (IOException e) {
// throw new WebServiceRuntimeException(e.getMessage());
// }
// File folder = null;
// try {
// folder = new ClassPathResource("scenarios").getFile();
// } catch (IOException e) {
// throw new WebServiceRuntimeException(e.getMessage());
// }
// List<String> scenarioFileNameList = new ArrayList<>();
// File[] files = folder.listFiles();
// for (File file : files) {
// if (file.isFile()) {
// scenarioFileNameList.add(file.getError());
// }
// }
// FIXME: hardcode list of filenames for now
List<String> scenarioFileNameList = new ArrayList<>();
scenarioFileNameList.add("Scenario 1 - Experiment with a single node");
scenarioFileNameList.add("Scenario 2 - Experiment with 2 nodes and 10Gb link");
scenarioFileNameList.add("Scenario 3 - Experiment with 3 nodes in a LAN");
scenarioFileNameList.add("Scenario 4 - Experiment with 2 nodes and customized link property");
// scenarioFileNameList.add("Scenario 4 - Two nodes linked with a 10Gbps SDN switch");
// scenarioFileNameList.add("Scenario 5 - Three nodes with Blockchain capabilities");
log.info("Scenario file list: {}", scenarioFileNameList);
return scenarioFileNameList;
}
private String getScenarioContentsFromFile(String scenarioFileName) throws WebServiceRuntimeException {
// FIXME: switch to better way of referencing scenario descriptions to actual filenames
String actualScenarioFileName;
if (scenarioFileName.contains("Scenario 1")) {
actualScenarioFileName = "basic1.ns";
} else if (scenarioFileName.contains("Scenario 2")) {
actualScenarioFileName = "basic2.ns";
} else if (scenarioFileName.contains("Scenario 3")) {
actualScenarioFileName = "basic3.ns";
} else if (scenarioFileName.contains("Scenario 4")) {
actualScenarioFileName = "basic4.ns";
} else {
// defaults to basic single node
actualScenarioFileName = "basic1.ns";
}
try {
log.info("Retrieving scenario files {}", getClass().getClassLoader().getResourceAsStream("scenarios/" + actualScenarioFileName));
List<String> lines = IOUtils.readLines(getClass().getClassLoader().getResourceAsStream("scenarios/" + actualScenarioFileName), StandardCharsets.UTF_8);
StringBuilder sb = new StringBuilder();
for (String line : lines) {
sb.append(line);
sb.append(System.getProperty("line.separator"));
}
log.info("Experiment ns file contents: {}", sb);
return sb.toString();
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
}
//---Check if user is a team owner and has any join request waiting for approval----
private boolean hasAnyJoinRequest(HashMap<Integer, Team> teamMapOwnedByUser) {
for (Map.Entry<Integer, Team> entry : teamMapOwnedByUser.entrySet()) {
Team currTeam = entry.getValue();
if (currTeam.isUserJoinRequestEmpty() == false) {
// at least one team has join user request
return true;
}
}
// loop through all teams but never return a single true
// therefore, user's controlled teams has no join request
return false;
}
//--------------------------MISC--------------------------
private int getSessionIdOfLoggedInUser(HttpSession session) {
return Integer.parseInt(session.getAttribute(SESSION_LOGGED_IN_USER_ID).toString());
}
private User2 extractUserInfo(String userJson) {
User2 user2 = new User2();
if (userJson == null) {
// return empty user
return user2;
}
JSONObject object = new JSONObject(userJson);
JSONObject userDetails = object.getJSONObject("userDetails");
JSONObject address = userDetails.getJSONObject("address");
user2.setId(object.getString("id"));
user2.setFirstName(getJSONStr(userDetails.getString("firstName")));
user2.setLastName(getJSONStr(userDetails.getString("lastName")));
user2.setJobTitle(userDetails.getString("jobTitle"));
user2.setEmail(userDetails.getString("email"));
user2.setPhone(userDetails.getString("phone"));
user2.setAddress1(address.getString("address1"));
user2.setAddress2(address.getString("address2"));
user2.setCountry(address.getString("country"));
user2.setRegion(address.getString("region"));
user2.setPostalCode(address.getString("zipCode"));
user2.setCity(address.getString("city"));
user2.setInstitution(userDetails.getString("institution"));
user2.setInstitutionAbbreviation(userDetails.getString("institutionAbbreviation"));
user2.setInstitutionWeb(userDetails.getString("institutionWeb"));
user2.setStatus(object.getString("status"));
user2.setEmailVerified(object.getBoolean("emailVerified"));
return user2;
}
private Team2 extractTeamInfo(String json) {
Team2 team2 = new Team2();
JSONObject object = new JSONObject(json);
JSONArray membersArray = object.getJSONArray("members");
try {
team2.setCreatedDate(formatZonedDateTime(object.get("applicationDate").toString()));
} catch (Exception e) {
log.warn("Error getting team application date {}", e);
team2.setCreatedDate(UNKNOWN);
}
team2.setId(object.getString("id"));
team2.setName(object.getString("name"));
team2.setDescription(object.getString("description"));
team2.setWebsite(object.getString("website"));
team2.setOrganisationType(object.getString("organisationType"));
team2.setStatus(object.getString("status"));
team2.setVisibility(object.getString("visibility"));
for (int i = 0; i < membersArray.length(); i++) {
JSONObject memberObject = membersArray.getJSONObject(i);
String userId = memberObject.getString("userId");
String teamMemberType = memberObject.getString(MEMBER_TYPE);
String teamMemberStatus = memberObject.getString("memberStatus");
User2 myUser = invokeAndExtractUserInfo(userId);
if (teamMemberType.equals(MemberType.MEMBER.name())) {
// add to pending members list for Members Awaiting Approval function
if (teamMemberStatus.equals(MemberStatus.PENDING.name())) {
team2.addPendingMembers(myUser);
}
} else if (teamMemberType.equals(MemberType.OWNER.name())) {
// explicit safer check
team2.setOwner(myUser);
}
team2.addMembersToStatusMap(MemberStatus.valueOf(teamMemberStatus), myUser);
}
team2.setMembersCount(team2.getMembersStatusMap().get(MemberStatus.APPROVED).size());
return team2;
}
// use to extract JSON Strings from services
// in the case where the JSON Strings are null, return "Connection Error"
private String getJSONStr(String jsonString) {
if (jsonString == null || jsonString.isEmpty()) {
return CONNECTION_ERROR;
}
return jsonString;
}
/**
* Checks if user is pending for join request approval from team leader
* Use for fixing bug for view experiment page where users previously can view the experiments just by issuing a join request
*
* @param json the response body after calling team service
* @param loginUserId the current logged in user id
* @return True if the user is anything but APPROVED, false otherwise
*/
private boolean isMemberJoinRequestPending(String loginUserId, String json) {
if (json == null) {
return true;
}
JSONObject object = new JSONObject(json);
JSONArray membersArray = object.getJSONArray("members");
for (int i = 0; i < membersArray.length(); i++) {
JSONObject memberObject = membersArray.getJSONObject(i);
String userId = memberObject.getString("userId");
String teamMemberStatus = memberObject.getString("memberStatus");
if (userId.equals(loginUserId) && !teamMemberStatus.equals(MemberStatus.APPROVED.toString())) {
return true;
}
}
log.info("User: {} is viewing experiment page", loginUserId);
return false;
}
private Team2 extractTeamInfoUserJoinRequest(String userId, String json) {
Team2 team2 = new Team2();
JSONObject object = new JSONObject(json);
JSONArray membersArray = object.getJSONArray("members");
for (int i = 0; i < membersArray.length(); i++) {
JSONObject memberObject = membersArray.getJSONObject(i);
String uid = memberObject.getString("userId");
String teamMemberStatus = memberObject.getString("memberStatus");
if (uid.equals(userId) && teamMemberStatus.equals(MemberStatus.PENDING.toString())) {
team2.setId(object.getString("id"));
team2.setName(object.getString("name"));
team2.setDescription(object.getString("description"));
team2.setWebsite(object.getString("website"));
team2.setOrganisationType(object.getString("organisationType"));
team2.setStatus(object.getString("status"));
team2.setVisibility(object.getString("visibility"));
team2.setMembersCount(membersArray.length());
return team2;
}
}
// no such member in the team found
return null;
}
protected Dataset extractDataInfo(String json) {
log.debug(json);
JSONObject object = new JSONObject(json);
Dataset dataset = new Dataset();
dataset.setId(object.getInt("id"));
dataset.setName(object.getString("name"));
dataset.setDescription(object.getString("description"));
dataset.setContributorId(object.getString("contributorId"));
dataset.addVisibility(object.getString("visibility"));
dataset.addAccessibility(object.getString("accessibility"));
try {
dataset.setReleasedDate(getZonedDateTime(object.get("releasedDate").toString()));
} catch (IOException e) {
log.warn("Error getting released date {}", e);
dataset.setReleasedDate(null);
}
dataset.setContributor(invokeAndExtractUserInfo(dataset.getContributorId()));
JSONArray resources = object.getJSONArray("resources");
for (int i = 0; i < resources.length(); i++) {
JSONObject resource = resources.getJSONObject(i);
DataResource dataResource = new DataResource();
dataResource.setId(resource.getLong("id"));
dataResource.setUri(resource.getString("uri"));
dataset.addResource(dataResource);
}
JSONArray approvedUsers = object.getJSONArray("approvedUsers");
for (int i = 0; i < approvedUsers.length(); i++) {
dataset.addApprovedUser(approvedUsers.getString(0));
}
return dataset;
}
protected User2 invokeAndExtractUserInfo(String userId) {
HttpEntity<String> request = createHttpEntityHeaderOnlyNoAuthHeader();
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getUser(userId), HttpMethod.GET, request, String.class);
} catch (Exception e) {
log.warn("User service not available to retrieve User: {}", userId);
return new User2();
}
return extractUserInfo(response.getBody().toString());
}
private Team2 invokeAndExtractTeamInfo(String teamId) {
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity responseEntity = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, request, String.class);
return extractTeamInfo(responseEntity.getBody().toString());
}
private Experiment2 extractExperiment(String experimentJson) {
Experiment2 experiment2 = new Experiment2();
JSONObject object = new JSONObject(experimentJson);
experiment2.setId(object.getLong("id"));
experiment2.setUserId(object.getString("userId"));
experiment2.setTeamId(object.getString(TEAM_ID));
experiment2.setTeamName(object.getString(TEAM_NAME));
experiment2.setName(object.getString("name"));
experiment2.setDescription(object.getString("description"));
experiment2.setNsFile(object.getString("nsFile"));
experiment2.setNsFileContent(object.getString("nsFileContent"));
experiment2.setIdleSwap(object.getInt("idleSwap"));
experiment2.setMaxDuration(object.getInt("maxDuration"));
return experiment2;
}
private Realization invokeAndExtractRealization(String teamName, Long id) {
HttpEntity<String> request = createHttpEntityHeaderOnly();
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = null;
try {
log.info("retrieving the latest exp status: {}", properties.getRealizationByTeam(teamName, id.toString()));
response = restTemplate.exchange(properties.getRealizationByTeam(teamName, id.toString()), HttpMethod.GET, request, String.class);
} catch (Exception e) {
return getCleanRealization();
}
String responseBody;
if (response.getBody() == null) {
return getCleanRealization();
} else {
responseBody = response.getBody().toString();
}
try {
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
log.warn("error in retrieving realization for team: {}, realization: {}", teamName, id);
return getCleanRealization();
} else {
// will throw JSONException if the format return by sio is not a valid JSOn format
// will occur if the realization details are still in the old format
return extractRealization(responseBody);
}
} catch (IOException | JSONException e) {
return getCleanRealization();
}
}
private Realization extractRealization(String json) {
log.info("extracting realization: {}", json);
Realization realization = new Realization();
JSONObject object = new JSONObject(json);
realization.setExperimentId(object.getLong("experimentId"));
realization.setExperimentName(object.getString("experimentName"));
realization.setUserId(object.getString("userId"));
realization.setTeamId(object.getString(TEAM_ID));
realization.setState(object.getString("state"));
String exp_report = "";
Object expDetailsObject = object.get("details");
log.info("exp detail object: {}", expDetailsObject);
if (expDetailsObject == JSONObject.NULL || expDetailsObject.toString().isEmpty()) {
log.info("set details empty");
realization.setDetails("");
realization.setNumberOfNodes(0);
} else {
log.info("exp report to string: {}", expDetailsObject.toString());
exp_report = expDetailsObject.toString();
realization.setDetails(exp_report);
JSONObject nodesInfoObject = new JSONObject(expDetailsObject.toString());
for (Object key : nodesInfoObject.keySet()) {
Map<String, String> nodeDetails = new HashMap<>();
String nodeName = (String) key;
JSONObject nodeDetailsJson = new JSONObject(nodesInfoObject.get(nodeName).toString());
nodeDetails.put("os", nodeDetailsJson.getString("os"));
nodeDetails.put("qualifiedName", nodeDetailsJson.getString("qualifiedName"));
nodeDetails.put(NODE_ID, nodeDetailsJson.getString(NODE_ID));
realization.addNodeDetails(nodeName, nodeDetails);
}
log.info("nodes info object: {}", nodesInfoObject);
realization.setNumberOfNodes(nodesInfoObject.keySet().size());
}
return realization;
}
/**
* @param zonedDateTimeJSON JSON string
* @return a date in the format MMM-d-yyyy
*/
protected String formatZonedDateTime(String zonedDateTimeJSON) throws Exception {
ZonedDateTime zonedDateTime = getZonedDateTime(zonedDateTimeJSON);
DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM-d-yyyy");
return zonedDateTime.format(format);
}
protected ZonedDateTime getZonedDateTime(String zonedDateTimeJSON) throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
return mapper.readValue(zonedDateTimeJSON, ZonedDateTime.class);
}
/**
* Creates a HttpEntity with a request body and header but no authorization header
* To solve the expired jwt token
*
* @param jsonString The JSON request converted to string
* @return A HttpEntity request
* @see HttpEntity createHttpEntityHeaderOnly() for request with only header
*/
protected HttpEntity<String> createHttpEntityWithBodyNoAuthHeader(String jsonString) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
return new HttpEntity<>(jsonString, headers);
}
/**
* Creates a HttpEntity that contains only a header and empty body but no authorization header
* To solve the expired jwt token
*
* @return A HttpEntity request
* @see HttpEntity createHttpEntityWithBody() for request with both body and header
*/
protected HttpEntity<String> createHttpEntityHeaderOnlyNoAuthHeader() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
return new HttpEntity<>(headers);
}
/**
* Creates a HttpEntity with a request body and header
*
* @param jsonString The JSON request converted to string
* @return A HttpEntity request
* @implNote Authorization header must be set to the JwTToken in the format [Bearer: TOKEN_ID]
* @see HttpEntity createHttpEntityHeaderOnly() for request with only header
*/
protected HttpEntity<String> createHttpEntityWithBody(String jsonString) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization", httpScopedSession.getAttribute(webProperties.getSessionJwtToken()).toString());
return new HttpEntity<>(jsonString, headers);
}
/**
* Creates a HttpEntity that contains only a header and empty body
*
* @return A HttpEntity request
* @implNote Authorization header must be set to the JwTToken in the format [Bearer: TOKEN_ID]
* @see HttpEntity createHttpEntityWithBody() for request with both body and header
*/
protected HttpEntity<String> createHttpEntityHeaderOnly() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization", httpScopedSession.getAttribute(webProperties.getSessionJwtToken()).toString());
return new HttpEntity<>(headers);
}
private void setSessionVariables(HttpSession session, String loginEmail, String id, String firstName, String userRoles, String token) {
User2 user = invokeAndExtractUserInfo(id);
session.setAttribute(webProperties.getSessionEmail(), loginEmail);
session.setAttribute(webProperties.getSessionUserId(), id);
session.setAttribute(webProperties.getSessionUserFirstName(), firstName);
session.setAttribute(webProperties.getSessionRoles(), userRoles);
session.setAttribute(webProperties.getSessionJwtToken(), "Bearer " + token);
log.info("Session variables - sessionLoggedEmail: {}, id: {}, name: {}, roles: {}, token: {}", loginEmail, id, user.getFirstName(), userRoles, token);
}
private void removeSessionVariables(HttpSession session) {
log.info("removing session variables: email: {}, userid: {}, user first name: {}", session.getAttribute(webProperties.getSessionEmail()), session.getAttribute(webProperties.getSessionUserId()), session.getAttribute(webProperties.getSessionUserFirstName()));
session.removeAttribute(webProperties.getSessionEmail());
session.removeAttribute(webProperties.getSessionUserId());
session.removeAttribute(webProperties.getSessionUserFirstName());
session.removeAttribute(webProperties.getSessionRoles());
session.removeAttribute(webProperties.getSessionJwtToken());
session.invalidate();
}
protected boolean validateIfAdmin(HttpSession session) {
//log.info("User: {} is logged on as: {}", session.getAttribute(webProperties.getSessionEmail()), session.getAttribute(webProperties.getSessionRoles()));
return session.getAttribute(webProperties.getSessionRoles()).equals(UserType.ADMIN.toString());
}
/**
* Ensure that only users of the team can realize or un-realize experiment
* A pre-condition is that the users must be approved.
* Teams must also be approved.
*
* @return the main experiment page
*/
private boolean checkPermissionRealizeExperiment(Realization realization, HttpSession session) {
// get list of teamids
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity userRespEntity = restTemplate.exchange(properties.getUser(session.getAttribute("id").toString()), HttpMethod.GET, request, String.class);
JSONObject object = new JSONObject(userRespEntity.getBody().toString());
JSONArray teamIdsJsonArray = object.getJSONArray("teams");
for (int i = 0; i < teamIdsJsonArray.length(); i++) {
String teamId = teamIdsJsonArray.get(i).toString();
if (teamId.equals(realization.getTeamId())) {
return true;
}
}
return false;
}
private String getTeamStatus(String teamId) {
Team2 team = invokeAndExtractTeamInfo(teamId);
return team.getStatus();
}
private Realization getCleanRealization() {
Realization realization = new Realization();
realization.setExperimentId(0L);
realization.setExperimentName("");
realization.setUserId("");
realization.setTeamId("");
realization.setState(RealizationState.ERROR.toString());
realization.setDetails("");
realization.setNumberOfNodes(0);
return realization;
}
/**
* Computes the number of teams that the user is in and the number of running experiments to populate data for the user dashboard
*
* @return a map in the form teams: numberOfTeams, experiments: numberOfExperiments
*/
private Map<String, Integer> getUserDashboardStats(String userId) {
int numberOfRunningExperiments = 0;
Map<String, Integer> userDashboardStats = new HashMap<>();
// get list of teamids
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity userRespEntity = restTemplate.exchange(properties.getUser(userId), HttpMethod.GET, request, String.class);
JSONObject object = new JSONObject(userRespEntity.getBody().toString());
JSONArray teamIdsJsonArray = object.getJSONArray("teams");
for (int i = 0; i < teamIdsJsonArray.length(); i++) {
String teamId = teamIdsJsonArray.get(i).toString();
HttpEntity<String> teamRequest = createHttpEntityHeaderOnly();
ResponseEntity teamResponse = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, teamRequest, String.class);
String teamResponseBody = teamResponse.getBody().toString();
if (!isMemberJoinRequestPending(userId, teamResponseBody)) {
// get experiments lists of the teams
HttpEntity<String> expRequest = createHttpEntityHeaderOnly();
ResponseEntity expRespEntity = restTemplate.exchange(properties.getExpListByTeamId(teamId), HttpMethod.GET, expRequest, String.class);
JSONArray experimentsArray = new JSONArray(expRespEntity.getBody().toString());
numberOfRunningExperiments = getNumberOfRunningExperiments(numberOfRunningExperiments, experimentsArray);
}
}
userDashboardStats.put(USER_DASHBOARD_TEAMS, teamIdsJsonArray.length());
userDashboardStats.put(USER_DASHBOARD_RUNNING_EXPERIMENTS, numberOfRunningExperiments);
userDashboardStats.put(USER_DASHBOARD_FREE_NODES, getNodes(NodeType.FREE));
return userDashboardStats;
}
private int getNumberOfRunningExperiments(int numberOfRunningExperiments, JSONArray experimentsArray) {
for (int k = 0; k < experimentsArray.length(); k++) {
Experiment2 experiment2 = extractExperiment(experimentsArray.getJSONObject(k).toString());
Realization realization = invokeAndExtractRealization(experiment2.getTeamName(), experiment2.getId());
if (realization.getState().equals(RealizationState.RUNNING.toString())) {
numberOfRunningExperiments++;
}
}
return numberOfRunningExperiments;
}
private SortedMap<String, Map<String, String>> getGlobalImages() throws IOException {
SortedMap<String, Map<String, String>> globalImagesMap = new TreeMap<>();
log.info("Retrieving list of global images from: {}", properties.getGlobalImages());
try {
HttpEntity<String> request = createHttpEntityHeaderOnlyNoAuthHeader();
ResponseEntity response = restTemplate.exchange(properties.getGlobalImages(), HttpMethod.GET, request, String.class);
ObjectMapper mapper = new ObjectMapper();
String json = new JSONObject(response.getBody().toString()).getString("images");
globalImagesMap = mapper.readValue(json, new TypeReference<SortedMap<String, Map<String, String>>>() {
});
} catch (RestClientException e) {
log.warn("Error connecting to service-image: {}", e);
}
return globalImagesMap;
}
private int getNodes(NodeType nodeType) {
String nodesCount;
log.info("Retrieving number of " + nodeType + " nodes from: {}", properties.getNodes(nodeType));
try {
HttpEntity<String> request = createHttpEntityHeaderOnlyNoAuthHeader();
ResponseEntity response = restTemplate.exchange(properties.getNodes(nodeType), HttpMethod.GET, request, String.class);
JSONObject object = new JSONObject(response.getBody().toString());
nodesCount = object.getString(nodeType.name());
} catch (RestClientException e) {
log.warn("Error connecting to service-telemetry: {}", e);
nodesCount = "0";
}
return Integer.parseInt(nodesCount);
}
private List<TeamUsageInfo> getTeamsUsageStatisticsForUser(String userId) {
List<TeamUsageInfo> usageInfoList = new ArrayList<>();
// get list of teamids
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity userRespEntity = restTemplate.exchange(properties.getUser(userId), HttpMethod.GET, request, String.class);
JSONObject object = new JSONObject(userRespEntity.getBody().toString());
JSONArray teamIdsJsonArray = object.getJSONArray("teams");
// get team info by team id
for (int i = 0; i < teamIdsJsonArray.length(); i++) {
String teamId = teamIdsJsonArray.get(i).toString();
HttpEntity<String> teamRequest = createHttpEntityHeaderOnly();
ResponseEntity teamResponse = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, teamRequest, String.class);
String teamResponseBody = teamResponse.getBody().toString();
if (!isMemberJoinRequestPending(userId, teamResponseBody)) {
TeamUsageInfo usageInfo = new TeamUsageInfo();
usageInfo.setId(teamId);
usageInfo.setName(new JSONObject(teamResponseBody).getString("name"));
usageInfo.setUsage(getUsageStatisticsByTeamId(teamId));
usageInfoList.add(usageInfo);
}
}
return usageInfoList;
}
private String getUsageStatisticsByTeamId(String id) {
log.info("Getting usage statistics for team {}", id);
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getUsageStat(id), HttpMethod.GET, request, String.class);
} catch (RestClientException e) {
log.warn("Error connecting to sio get usage statistics {}", e);
return "?";
}
return response.getBody().toString();
}
private TeamQuota extractTeamQuotaInfo(String responseBody) {
JSONObject object = new JSONObject(responseBody);
TeamQuota teamQuota = new TeamQuota();
Double charges = Double.parseDouble(accountingProperties.getCharges());
// amountUsed from SIO will never be null => not checking for null value
String usage = object.getString("usage"); // getting usage in String
BigDecimal amountUsed = new BigDecimal(usage); // using BigDecimal to handle currency
amountUsed = amountUsed.multiply(new BigDecimal(charges)); // usage X charges
//quota passed from SIO can be null , so we have to check for null value
if (object.has("quota")) {
Object budgetObject = object.optString("quota", null);
if (budgetObject == null) {
teamQuota.setBudget(""); // there is placeholder here
teamQuota.setResourcesLeft("Unlimited"); // not placeholder so can pass string over
} else {
Double budgetInDouble = object.getDouble("quota"); // retrieve budget from SIO in Double
BigDecimal budgetInBD = BigDecimal.valueOf(budgetInDouble); // handling currency using BigDecimal
// calculate resoucesLeft
BigDecimal resourceLeftInBD = budgetInBD.subtract(amountUsed);
resourceLeftInBD = resourceLeftInBD.divide(new BigDecimal(charges), 2, BigDecimal.ROUND_HALF_UP);
// set budget and resourceLeft
budgetInBD = budgetInBD.setScale(2, BigDecimal.ROUND_HALF_UP);
teamQuota.setBudget(budgetInBD.toString());
teamQuota.setResourcesLeft(resourceLeftInBD.toString());
}
}
teamQuota.setTeamId(object.getString(TEAM_ID));
amountUsed = amountUsed.setScale(2, BigDecimal.ROUND_HALF_UP);
teamQuota.setAmountUsed(amountUsed.toString());
return teamQuota;
}
}
|
src/main/java/sg/ncl/MainController.java
|
package sg.ncl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.tomcat.util.codec.binary.Base64;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.support.RequestContextUtils;
import sg.ncl.domain.*;
import sg.ncl.exceptions.*;
import sg.ncl.testbed_interface.*;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Pattern;
import static java.time.temporal.TemporalAdjusters.firstDayOfMonth;
import static java.time.temporal.TemporalAdjusters.lastDayOfMonth;
import static sg.ncl.domain.ExceptionState.*;
/**
*
* Spring Controller
* Direct the views to appropriate locations and invoke the respective REST API
*
* @author Cassie, Desmond, Te Ye, Vu
*/
@Controller
@Slf4j
public class MainController {
public static final String CONTENT_DISPOSITION = "Content-Disposition";
public static final String APPLICATION_FORCE_DOWNLOAD = "application/force-download";
private static final String SESSION_LOGGED_IN_USER_ID = "loggedInUserId";
private TeamManager teamManager = TeamManager.getInstance();
// private UserManager userManager = UserManager.getInstance();
// private ExperimentManager experimentManager = ExperimentManager.getInstance();
// private DomainManager domainManager = DomainManager.getInstance();
// private DatasetManager datasetManager = DatasetManager.getInstance();
// private NodeManager nodeManager = NodeManager.getInstance();
private static final String CONTACT_EMAIL = "support@ncl.sg";
private static final String UNKNOWN = "?";
private static final String MESSAGE = "message";
private static final String MESSAGE_SUCCESS = "messageSuccess";
private static final String EXPERIMENT_MESSAGE = "exp_message";
private static final String ERROR_PREFIX = "Error: ";
// error messages
private static final String ERR_SERVER_OVERLOAD = "There is a problem with your request. Please contact " + CONTACT_EMAIL;
private static final String CONNECTION_ERROR = "Connection Error";
private final String permissionDeniedMessage = "Permission denied. If the error persists, please contact " + CONTACT_EMAIL;
// for user dashboard hashmap key values
private static final String USER_DASHBOARD_TEAMS = "teams";
private static final String USER_DASHBOARD_RUNNING_EXPERIMENTS = "runningExperiments";
private static final String USER_DASHBOARD_FREE_NODES = "freeNodes";
private static final String USER_DASHBOARD_TOTAL_NODES = "totalNodes";
private static final String USER_DASHBOARD_GLOBAL_IMAGES = "globalImagesMap";
private static final String DETER_UID = "deterUid";
private static final Pattern VALID_EMAIL_ADDRESS_REGEX =
Pattern.compile("(?:(?:\\r\\n)?[ \\t])*(?:(?:(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*\\<(?:(?:\\r\\n)?[ \\t])*(?:@(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*(?:,@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*)*:(?:(?:\\r\\n)?[ \\t])*)?(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\>(?:(?:\\r\\n)?[ \\t])*)|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*:(?:(?:\\r\\n)?[ \\t])*(?:(?:(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*\\<(?:(?:\\r\\n)?[ \\t])*(?:@(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*(?:,@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*)*:(?:(?:\\r\\n)?[ \\t])*)?(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\>(?:(?:\\r\\n)?[ \\t])*)(?:,\\s*(?:(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*\\<(?:(?:\\r\\n)?[ \\t])*(?:@(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*(?:,@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*)*:(?:(?:\\r\\n)?[ \\t])*)?(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\>(?:(?:\\r\\n)?[ \\t])*))*)?;\\s*)");
private static final String FORGET_PSWD_PAGE = "password_reset_email";
private static final String FORGET_PSWD_NEW_PSWD_PAGE = "password_reset_new_password";
private static final String NO_PERMISSION_PAGE = "nopermission";
private static final String TEAM_NAME = "teamName";
private static final String TEAM_ID = "teamId";
private static final String NODE_ID = "nodeId";
private static final String PERMISSION_DENIED = "Permission denied";
private static final String TEAM_NOT_FOUND = "Team not found";
private static final String EDIT_BUDGET = "editBudget";
private static final String ORIGINAL_BUDGET = "originalBudget";
private static final String REDIRECT_TEAM_PROFILE_TEAM_ID = "redirect:/team_profile/{teamId}";
// remove members from team profile; to display the list of experiments created by user
private static final String REMOVE_MEMBER_UID = "removeMemberUid";
private static final String REMOVE_MEMBER_NAME = "removeMemberName";
private static final String MEMBER_TYPE = "memberType";
@Autowired
protected RestTemplate restTemplate;
@Inject
protected ObjectMapper objectMapper;
@Inject
protected ConnectionProperties properties;
@Inject
protected WebProperties webProperties;
@Inject
protected AccountingProperties accountingProperties;
@Inject
protected HttpSession httpScopedSession;
@RequestMapping("/")
public String index() {
return "index";
}
@RequestMapping("/overview")
public String overview() {
return "overview";
}
@RequestMapping("/community")
public String community() {
return "community";
}
@RequestMapping("/about")
public String about() {
return "about";
}
@RequestMapping("/event")
public String event() {
return "event";
}
@RequestMapping("/plan")
public String plan() {
return "plan";
}
// @RequestMapping("/futureplan")
// public String futureplan() {
// return "futureplan";
// }
@RequestMapping("/pricing")
public String pricing() {
return "pricing";
}
@RequestMapping("/resources")
public String resources() {
return "resources";
}
@RequestMapping("/research")
public String research() {
return "research";
}
@RequestMapping("/calendar")
public String calendar() {
return "calendar";
}
@RequestMapping("/tools")
public String tools() {
return "tools";
}
@RequestMapping("/tutorials/createaccount")
public String createAccount() {
return "createaccount";
}
@RequestMapping("/tutorials/createexperiment")
public String createExperimentTutorial() {
return "createexperiment";
}
@RequestMapping("/tutorials/loadimage")
public String loadimage() {
return "loadimage";
}
@RequestMapping("/tutorials/saveimage")
public String saveimage() {
return "saveimage";
}
@RequestMapping("/tutorials/applyteam")
public String applyteam() {
return "applyteam";
}
@RequestMapping("/tutorials/jointeam")
public String jointeam() {
return "jointeam";
}
@RequestMapping("/error_openstack")
public String error_openstack() {
return "error_openstack";
}
@RequestMapping("/accessexperiment")
public String accessexperiment() {
return "accessexperiment";
}
@RequestMapping("/resource2")
public String resource2() {
return "resource2";
}
// @RequestMapping("/admin2")
// public String admin2() {
// return "admin2";
// }
@RequestMapping("/tutorials")
public String tutorials() {
return "tutorials";
}
@RequestMapping("/maintainance")
public String maintainance() {
return "maintainance";
}
@RequestMapping("/testbedInformation")
public String testbedInformation(Model model) throws IOException {
model.addAttribute(USER_DASHBOARD_GLOBAL_IMAGES, getGlobalImages());
model.addAttribute(USER_DASHBOARD_TOTAL_NODES, getNodes(NodeType.TOTAL));
return "testbedInformation";
}
// @RequestMapping(value="/futureplan/download", method=RequestMethod.GET)
// public void futureplanDownload(HttpServletResponse response) throws FuturePlanDownloadException, IOException {
// InputStream stream = null;
// response.setContentType("application/pdf");
// try {
// stream = getClass().getClassLoader().getResourceAsStream("downloads/future_plan.pdf");
// response.setContentType("application/force-download");
// response.setHeader("Content-Disposition", "attachment; filename=future_plan.pdf");
// IOUtils.copy(stream, response.getOutputStream());
// response.flushBuffer();
// } catch (Exception ex) {
// logger.info("Error writing file to output stream.");
// throw new FuturePlanDownloadException("IOError writing file to output stream");
// } finally {
// if (stream != null) {
// stream.close();
// }
// }
// }
@RequestMapping(value = "/orderform/download", method = RequestMethod.GET)
public void OrderForm_v1Download(HttpServletResponse response) throws OrderFormDownloadException, IOException {
InputStream stream = null;
response.setContentType(MediaType.APPLICATION_PDF_VALUE);
try {
stream = getClass().getClassLoader().getResourceAsStream("downloads/order_form.pdf");
response.setContentType(APPLICATION_FORCE_DOWNLOAD);
response.setHeader(CONTENT_DISPOSITION, "attachment; filename=order_form.pdf");
IOUtils.copy(stream, response.getOutputStream());
response.flushBuffer();
} catch (IOException ex) {
log.info("Error for download orderform.");
throw new OrderFormDownloadException("Error for download orderform.");
} finally {
if (stream != null) {
stream.close();
}
}
}
@RequestMapping("/contactus")
public String contactus() {
return "contactus";
}
@RequestMapping("/notfound")
public String redirectNotFound(HttpSession session) {
if (session.getAttribute("id") != null && !session.getAttribute("id").toString().isEmpty()) {
// user is already logged on and has encountered an error
// redirect to dashboard
return "redirect:/dashboard";
} else {
// user have not logged on before
// redirect to home page
return "redirect:/";
}
}
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(Model model) {
model.addAttribute("loginForm", new LoginForm());
return "login";
}
@RequestMapping(value = "/emailVerification", params = {"id", "email", "key"})
public String verifyEmail(
@NotNull @RequestParam("id") final String id,
@NotNull @RequestParam("email") final String emailBase64,
@NotNull @RequestParam("key") final String key
) throws UnsupportedEncodingException {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
ObjectNode keyObject = objectMapper.createObjectNode();
keyObject.put("key", key);
HttpEntity<String> request = new HttpEntity<>(keyObject.toString(), headers);
restTemplate.setErrorHandler(new MyResponseErrorHandler());
final String link = properties.getSioUsersUrl() + id + "/emails/" + emailBase64;
log.info("Activation link: {}, verification key {}", link, key);
ResponseEntity response = restTemplate.exchange(link, HttpMethod.PUT, request, String.class);
if (RestUtil.isError(response.getStatusCode())) {
log.error("Activation of user {} failed.", id);
return "email_validation_failed";
} else {
log.info("Activation of user {} completed.", id);
return "email_validation_ok";
}
}
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String loginSubmit(
@Valid
@ModelAttribute("loginForm") LoginForm loginForm,
BindingResult bindingResult,
Model model,
HttpSession session, final RedirectAttributes redirectAttributes) throws WebServiceRuntimeException {
if (bindingResult.hasErrors()) {
loginForm.setErrorMsg("Login failed: Invalid email/password.");
return "login";
}
String inputEmail = loginForm.getLoginEmail();
String inputPwd = loginForm.getLoginPassword();
if (inputEmail.trim().isEmpty() || inputPwd.trim().isEmpty()) {
loginForm.setErrorMsg("Email or Password cannot be empty!");
return "login";
}
String plainCreds = inputEmail + ":" + inputPwd;
byte[] plainCredsBytes = plainCreds.getBytes();
byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
String base64Creds = new String(base64CredsBytes);
ResponseEntity response;
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Basic " + base64Creds);
HttpEntity<String> request = new HttpEntity<>(headers);
restTemplate.setErrorHandler(new MyResponseErrorHandler());
try {
response = restTemplate.exchange(properties.getSioAuthUrl(), HttpMethod.POST, request, String.class);
} catch (RestClientException e) {
log.warn("Error connecting to sio authentication service: {}", e);
loginForm.setErrorMsg(ERR_SERVER_OVERLOAD);
return "login";
}
String jwtTokenString = response.getBody().toString();
log.info("token string {}", jwtTokenString);
if (jwtTokenString == null || jwtTokenString.isEmpty()) {
log.warn("login failed for {}: unknown response code", loginForm.getLoginEmail());
loginForm.setErrorMsg("Login failed: Invalid email/password.");
return "login";
}
if (RestUtil.isError(response.getStatusCode())) {
try {
MyErrorResource error = objectMapper.readValue(jwtTokenString, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
if (exceptionState == ExceptionState.CREDENTIALS_NOT_FOUND_EXCEPTION) {
log.warn("login failed for {}: credentials not found", loginForm.getLoginEmail());
loginForm.setErrorMsg("Login failed: Account does not exist. Please register.");
return "login";
}
log.warn("login failed for {}: {}", loginForm.getLoginEmail(), error.getError());
loginForm.setErrorMsg("Login failed: Invalid email/password.");
return "login";
} catch (IOException ioe) {
log.warn("IOException {}", ioe);
throw new WebServiceRuntimeException(ioe.getMessage());
}
}
JSONObject tokenObject = new JSONObject(jwtTokenString);
String token = tokenObject.getString("token");
String id = tokenObject.getString("id");
String role = "";
if (tokenObject.getJSONArray("roles") != null) {
role = tokenObject.getJSONArray("roles").get(0).toString();
}
if (token.trim().isEmpty() || id.trim().isEmpty() || role.trim().isEmpty()) {
log.warn("login failed for {}: empty id {} or token {} or role {}", loginForm.getLoginEmail(), id, token, role);
loginForm.setErrorMsg("Login failed: Invalid email/password.");
return "login";
}
// now check user status to decide what to show to the user
User2 user = invokeAndExtractUserInfo(id);
try {
String userStatus = user.getStatus();
boolean emailVerified = user.getEmailVerified();
if (UserStatus.FROZEN.toString().equals(userStatus)) {
log.warn("User {} login failed: account has been frozen", id);
loginForm.setErrorMsg("Login Failed: Account Frozen. Please contact " + CONTACT_EMAIL);
return "login";
} else if (!emailVerified || (UserStatus.CREATED.toString()).equals(userStatus)) {
redirectAttributes.addAttribute("statuschecklist", userStatus);
log.info("User {} not validated, redirected to email verification page", id);
return "redirect:/email_checklist";
} else if ((UserStatus.PENDING.toString()).equals(userStatus)) {
redirectAttributes.addAttribute("statuschecklist", userStatus);
log.info("User {} not approved, redirected to application pending page", id);
return "redirect:/email_checklist";
} else if ((UserStatus.APPROVED.toString()).equals(userStatus)) {
// set session variables
setSessionVariables(session, loginForm.getLoginEmail(), id, user.getFirstName(), role, token);
log.info("login success for {}, id: {}", loginForm.getLoginEmail(), id);
return "redirect:/dashboard";
} else {
log.warn("login failed for user {}: account is rejected or closed", id);
loginForm.setErrorMsg("Login Failed: Account Rejected/Closed.");
return "login";
}
} catch (Exception e) {
log.warn("Error parsing json object for user: {}", e.getMessage());
loginForm.setErrorMsg(ERR_SERVER_OVERLOAD);
return "login";
}
}
// triggered when user clicks "Forget Password?"
@RequestMapping("/password_reset_email")
public String passwordResetEmail(Model model) {
model.addAttribute("passwordResetRequestForm", new PasswordResetRequestForm());
return FORGET_PSWD_PAGE;
}
// triggered when user clicks "Send Reset Email" button
@PostMapping("/password_reset_request")
public String sendPasswordResetRequest(
@ModelAttribute("passwordResetRequestForm") PasswordResetRequestForm passwordResetRequestForm
) throws WebServiceRuntimeException {
String email = passwordResetRequestForm.getEmail();
if (!VALID_EMAIL_ADDRESS_REGEX.matcher(email).matches()) {
passwordResetRequestForm.setErrMsg("Please provide a valid email address");
return FORGET_PSWD_PAGE;
}
JSONObject obj = new JSONObject();
obj.put("username", email);
log.info("Connecting to sio for password reset email: {}", email);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(obj.toString(), headers);
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = null;
try {
response = restTemplate.exchange(properties.getPasswordResetRequestURI(), HttpMethod.POST, request, String.class);
} catch (RestClientException e) {
log.warn("Cannot connect to sio for password reset email: {}", e);
passwordResetRequestForm.setErrMsg("Cannot connect. Server may be down!");
return FORGET_PSWD_PAGE;
}
if (RestUtil.isError(response.getStatusCode())) {
log.warn("Server responded error for password reset email: {}", response.getStatusCode());
passwordResetRequestForm.setErrMsg("Email not registered. Please use a different email address.");
return FORGET_PSWD_PAGE;
}
log.info("Password reset email sent for {}", email);
return "password_reset_email_sent";
}
// triggered when user clicks password reset link in the email
@RequestMapping(path = "/passwordReset", params = {"key"})
public String passwordResetNewPassword(@NotNull @RequestParam("key") final String key, Model model) {
PasswordResetForm form = new PasswordResetForm();
form.setKey(key);
model.addAttribute("passwordResetForm", form);
// redirect to the page for user to enter new password
return FORGET_PSWD_NEW_PSWD_PAGE;
}
// actual call to sio to reset password
@RequestMapping(path = "/password_reset")
public String resetPassword(@ModelAttribute("passwordResetForm") PasswordResetForm passwordResetForm) throws IOException {
if (!passwordResetForm.isPasswordOk()) {
return FORGET_PSWD_NEW_PSWD_PAGE;
}
JSONObject obj = new JSONObject();
obj.put("key", passwordResetForm.getKey());
obj.put("new", passwordResetForm.getPassword1());
log.info("Connecting to sio for password reset, key = {}", passwordResetForm.getKey());
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(obj.toString(), headers);
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = null;
try {
response = restTemplate.exchange(properties.getPasswordResetURI(), HttpMethod.PUT, request, String.class);
} catch (RestClientException e) {
log.warn("Error connecting to sio for password reset! {}", e);
passwordResetForm.setErrMsg("Cannot connect to server! Please try again later.");
return FORGET_PSWD_NEW_PSWD_PAGE;
}
if (RestUtil.isError(response.getStatusCode())) {
EnumMap<ExceptionState, String> exceptionMessageMap = new EnumMap<>(ExceptionState.class);
exceptionMessageMap.put(PASSWORD_RESET_REQUEST_TIMEOUT_EXCEPTION, "Password reset request timed out. Please request a new reset email.");
exceptionMessageMap.put(PASSWORD_RESET_REQUEST_NOT_FOUND_EXCEPTION, "Invalid password reset request. Please request a new reset email.");
exceptionMessageMap.put(ADAPTER_CONNECTION_EXCEPTION, "Server-side error. Please contact " + CONTACT_EMAIL);
MyErrorResource error = objectMapper.readValue(response.getBody().toString(), MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
final String errMsg = exceptionMessageMap.get(exceptionState) == null ? ERR_SERVER_OVERLOAD : exceptionMessageMap.get(exceptionState);
passwordResetForm.setErrMsg(errMsg);
log.warn("Server responded error for password reset: {}", exceptionState.toString());
return FORGET_PSWD_NEW_PSWD_PAGE;
}
log.info("Password was reset, key = {}", passwordResetForm.getKey());
return "password_reset_success";
}
@RequestMapping("/dashboard")
public String dashboard(Model model, HttpSession session) throws WebServiceRuntimeException {
HttpEntity<String> request = createHttpEntityHeaderOnly();
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = restTemplate.exchange(properties.getDeterUid(session.getAttribute(webProperties.getSessionUserId()).toString()), HttpMethod.GET, request, String.class);
String responseBody = response.getBody().toString();
try {
if (RestUtil.isError(response.getStatusCode())) {
log.error("No user exists : {}", session.getAttribute(webProperties.getSessionUserId()));
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
model.addAttribute(DETER_UID, CONNECTION_ERROR);
} else {
log.info("Show the deter user id: {}", responseBody);
model.addAttribute(DETER_UID, responseBody);
}
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
// retrieve user dashboard stats
Map<String, Integer> userDashboardMap = getUserDashboardStats(session.getAttribute(webProperties.getSessionUserId()).toString());
List<TeamUsageInfo> usageInfoList = getTeamsUsageStatisticsForUser(session.getAttribute(webProperties.getSessionUserId()).toString());
model.addAttribute("userDashboardMap", userDashboardMap);
model.addAttribute("usageInfoList", usageInfoList);
return "dashboard";
}
@RequestMapping(value = "/logout", method = RequestMethod.GET)
public String logout(HttpSession session) {
removeSessionVariables(session);
return "redirect:/";
}
//--------------------------Sign Up Page--------------------------
@RequestMapping(value = "/signup2", method = RequestMethod.GET)
public String signup2(Model model, HttpServletRequest request) {
Map<String, ?> inputFlashMap = RequestContextUtils.getInputFlashMap(request);
if (inputFlashMap != null) {
log.debug((String) inputFlashMap.get(MESSAGE));
model.addAttribute("signUpMergedForm", (SignUpMergedForm) inputFlashMap.get("signUpMergedForm"));
} else {
log.debug("InputFlashMap is null");
model.addAttribute("signUpMergedForm", new SignUpMergedForm());
}
return "signup2";
}
@RequestMapping(value = "/signup2", method = RequestMethod.POST)
public String validateDetails(
@Valid
@ModelAttribute("signUpMergedForm") SignUpMergedForm signUpMergedForm,
BindingResult bindingResult,
final RedirectAttributes redirectAttributes) throws WebServiceRuntimeException {
if (bindingResult.hasErrors() || signUpMergedForm.getIsValid() == false) {
log.warn("Register form has errors {}", signUpMergedForm.toString());
return "signup2";
}
if (!signUpMergedForm.getHasAcceptTeamOwnerPolicy()) {
signUpMergedForm.setErrorTeamOwnerPolicy("Please accept the team owner policy");
log.warn("Policy not accepted");
return "signup2";
}
// get form fields
// craft the registration json
JSONObject mainObject = new JSONObject();
JSONObject credentialsFields = new JSONObject();
credentialsFields.put("username", signUpMergedForm.getEmail().trim());
credentialsFields.put("password", signUpMergedForm.getPassword());
// create the user JSON
JSONObject userFields = new JSONObject();
JSONObject userDetails = new JSONObject();
JSONObject addressDetails = new JSONObject();
userDetails.put("firstName", signUpMergedForm.getFirstName().trim());
userDetails.put("lastName", signUpMergedForm.getLastName().trim());
userDetails.put("jobTitle", signUpMergedForm.getJobTitle().trim());
userDetails.put("email", signUpMergedForm.getEmail().trim());
userDetails.put("phone", signUpMergedForm.getPhone().trim());
userDetails.put("institution", signUpMergedForm.getInstitution().trim());
userDetails.put("institutionAbbreviation", signUpMergedForm.getInstitutionAbbreviation().trim());
userDetails.put("institutionWeb", signUpMergedForm.getWebsite().trim());
userDetails.put("address", addressDetails);
addressDetails.put("address1", signUpMergedForm.getAddress1().trim());
addressDetails.put("address2", signUpMergedForm.getAddress2().trim());
addressDetails.put("country", signUpMergedForm.getCountry().trim());
addressDetails.put("region", signUpMergedForm.getProvince().trim());
addressDetails.put("city", signUpMergedForm.getCity().trim());
addressDetails.put("zipCode", signUpMergedForm.getPostalCode().trim());
userFields.put("userDetails", userDetails);
userFields.put("applicationDate", ZonedDateTime.now());
JSONObject teamFields = new JSONObject();
// add all to main json
mainObject.put("credentials", credentialsFields);
mainObject.put("user", userFields);
mainObject.put("team", teamFields);
// check if user chose create new team or join existing team by checking team name
String createNewTeamName = signUpMergedForm.getTeamName().trim();
String joinNewTeamName = signUpMergedForm.getJoinTeamName().trim();
if (createNewTeamName != null && !createNewTeamName.isEmpty()) {
log.info("Signup new team name {}", createNewTeamName);
boolean errorsFound = false;
if (createNewTeamName.length() < 2 || createNewTeamName.length() > 12) {
errorsFound = true;
signUpMergedForm.setErrorTeamName("Team name must be 2 to 12 alphabetic/numeric characters");
}
if (signUpMergedForm.getTeamDescription() == null || signUpMergedForm.getTeamDescription().isEmpty()) {
errorsFound = true;
signUpMergedForm.setErrorTeamDescription("Team description cannot be empty");
}
if (signUpMergedForm.getTeamWebsite() == null || signUpMergedForm.getTeamWebsite().isEmpty()) {
errorsFound = true;
signUpMergedForm.setErrorTeamWebsite("Team website cannot be empty");
}
if (errorsFound) {
log.warn("Signup new team error {}", signUpMergedForm.toString());
// clear join team name first before submitting the form
signUpMergedForm.setJoinTeamName(null);
return "signup2";
} else {
teamFields.put("name", signUpMergedForm.getTeamName().trim());
teamFields.put("description", signUpMergedForm.getTeamDescription().trim());
teamFields.put("website", signUpMergedForm.getTeamWebsite().trim());
teamFields.put("organisationType", signUpMergedForm.getTeamOrganizationType());
teamFields.put("visibility", signUpMergedForm.getIsPublic());
mainObject.put("isJoinTeam", false);
try {
registerUserToDeter(mainObject);
} catch (
TeamNotFoundException |
TeamNameAlreadyExistsException |
UsernameAlreadyExistsException |
EmailAlreadyExistsException |
InvalidTeamNameException |
InvalidPasswordException |
DeterLabOperationFailedException e) {
redirectAttributes.addFlashAttribute(MESSAGE, e.getMessage());
redirectAttributes.addFlashAttribute("signUpMergedForm", signUpMergedForm);
return "redirect:/signup2";
} catch (Exception e) {
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
redirectAttributes.addFlashAttribute("signUpMergedForm", signUpMergedForm);
return "redirect:/signup2";
}
log.info("Signup new team success");
return "redirect:/team_application_submitted";
}
} else if (joinNewTeamName != null && !joinNewTeamName.isEmpty()) {
log.info("Signup join team name {}", joinNewTeamName);
// get the team JSON from team name
Team2 joinTeamInfo;
try {
joinTeamInfo = getTeamIdByName(signUpMergedForm.getJoinTeamName().trim());
} catch (TeamNotFoundException | AdapterConnectionException e) {
redirectAttributes.addFlashAttribute(MESSAGE, e.getMessage());
redirectAttributes.addFlashAttribute("signUpMergedForm", signUpMergedForm);
return "redirect:/signup2";
}
teamFields.put("id", joinTeamInfo.getId());
// set the flag to indicate to controller that it is joining an existing team
mainObject.put("isJoinTeam", true);
try {
registerUserToDeter(mainObject);
} catch (
TeamNotFoundException |
AdapterConnectionException |
TeamNameAlreadyExistsException |
UsernameAlreadyExistsException |
EmailAlreadyExistsException |
InvalidTeamNameException |
InvalidPasswordException |
DeterLabOperationFailedException e) {
redirectAttributes.addFlashAttribute(MESSAGE, e.getMessage());
redirectAttributes.addFlashAttribute("signUpMergedForm", signUpMergedForm);
return "redirect:/signup2";
} catch (Exception e) {
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
redirectAttributes.addFlashAttribute("signUpMergedForm", signUpMergedForm);
return "redirect:/signup2";
}
log.info("Signup join team success");
log.info("jointeam info: {}", joinTeamInfo);
redirectAttributes.addFlashAttribute("team", joinTeamInfo);
return "redirect:/join_application_submitted";
} else {
log.warn("Signup unreachable statement");
// logic error not suppose to reach here
// possible if user fill up create new team but without the team name
redirectAttributes.addFlashAttribute("signupError", "There is a problem when submitting your form. Please re-enter and submit the details again.");
redirectAttributes.addFlashAttribute("signUpMergedForm", signUpMergedForm);
return "redirect:/signup2";
}
}
/**
* Use when registering new accounts
*
* @param mainObject A JSONObject that contains user's credentials, personal details and team application details
*/
private void registerUserToDeter(JSONObject mainObject) throws
WebServiceRuntimeException,
TeamNotFoundException,
AdapterConnectionException,
TeamNameAlreadyExistsException,
UsernameAlreadyExistsException,
EmailAlreadyExistsException,
InvalidTeamNameException,
InvalidPasswordException,
DeterLabOperationFailedException {
HttpEntity<String> request = createHttpEntityWithBodyNoAuthHeader(mainObject.toString());
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = restTemplate.exchange(properties.getSioRegUrl(), HttpMethod.POST, request, String.class);
String responseBody = response.getBody().toString();
log.info("Register user to deter response: {}", responseBody);
try {
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
log.warn("Register user exception error: {}", error.getError());
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
final String errorPrefix = "Error: ";
switch (exceptionState) {
case DETERLAB_OPERATION_FAILED_EXCEPTION:
log.warn("Register new user failed on DeterLab: {}", error.getMessage());
throw new DeterLabOperationFailedException(errorPrefix + (error.getMessage().contains("unknown error") ? ERR_SERVER_OVERLOAD : error.getMessage()));
case TEAM_NAME_ALREADY_EXISTS_EXCEPTION:
log.warn("Register new users new team request : team name already exists");
throw new TeamNameAlreadyExistsException("Team name already exists");
case INVALID_TEAM_NAME_EXCEPTION:
log.warn("Register new users new team request : team name invalid");
throw new InvalidTeamNameException("Invalid team name: must be 6-12 alphanumeric characters only");
case INVALID_PASSWORD_EXCEPTION:
log.warn("Register new users new team request : invalid password");
throw new InvalidPasswordException("Password is too simple");
case USERNAME_ALREADY_EXISTS_EXCEPTION:
// throw from user service
{
String email = mainObject.getJSONObject("user").getJSONObject("userDetails").getString("email");
log.warn("Register new users : email already exists: {}", email);
throw new UsernameAlreadyExistsException(errorPrefix + email + " already in use.");
}
case EMAIL_ALREADY_EXISTS_EXCEPTION:
// throw from adapter deterlab
{
String email = mainObject.getJSONObject("user").getJSONObject("userDetails").getString("email");
log.warn("Register new users : email already exists: {}", email);
throw new EmailAlreadyExistsException(errorPrefix + email + " already in use.");
}
default:
log.warn("Registration or adapter connection fail");
// possible sio or adapter connection fail
throw new AdapterConnectionException(ERR_SERVER_OVERLOAD);
}
} else {
// do nothing
log.info("Not an error for status code: {}", response.getStatusCode());
}
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
}
/**
* Use when users register a new account for joining existing team
*
* @param teamName The team name to join
* @return the team id from sio
*/
private Team2 getTeamIdByName(String teamName) throws WebServiceRuntimeException, TeamNotFoundException, AdapterConnectionException {
// FIXME check if team name exists
// FIXME check for general exception?
HttpEntity<String> request = createHttpEntityHeaderOnlyNoAuthHeader();
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = restTemplate.exchange(properties.getTeamByName(teamName), HttpMethod.GET, request, String.class);
String responseBody = response.getBody().toString();
try {
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
if (exceptionState == ExceptionState.TEAM_NOT_FOUND_EXCEPTION) {
log.warn("Get team by name : team name error");
throw new TeamNotFoundException("Team name " + teamName + " does not exists");
} else {
log.warn("Team service or adapter connection fail");
// possible sio or adapter connection fail
throw new AdapterConnectionException(ERR_SERVER_OVERLOAD);
}
} else {
return extractTeamInfo(responseBody);
}
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
}
//--------------------------Account Settings Page--------------------------
@RequestMapping(value = "/account_settings", method = RequestMethod.GET)
public String accountDetails(Model model, HttpSession session) throws WebServiceRuntimeException {
String userId_uri = properties.getSioUsersUrl() + session.getAttribute("id");
HttpEntity<String> request = createHttpEntityHeaderOnly();
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = restTemplate.exchange(userId_uri, HttpMethod.GET, request, String.class);
String responseBody = response.getBody().toString();
try {
if (RestUtil.isError(response.getStatusCode())) {
log.error("No user to edit : {}", session.getAttribute("id"));
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
throw new RestClientException("[" + error.getError() + "] ");
} else {
User2 user2 = extractUserInfo(responseBody);
// need to do this so that we can compare after submitting the form
session.setAttribute(webProperties.getSessionUserAccount(), user2);
model.addAttribute("editUser", user2);
return "account_settings";
}
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
}
@RequestMapping(value = "/account_settings", method = RequestMethod.POST)
public String editAccountDetails(
@ModelAttribute("editUser") User2 editUser,
final RedirectAttributes redirectAttributes,
HttpSession session) throws WebServiceRuntimeException {
boolean errorsFound = false;
String editPhrase = "editPhrase";
// check fields first
if (errorsFound == false && editUser.getFirstName().isEmpty()) {
redirectAttributes.addFlashAttribute("editFirstName", "fail");
errorsFound = true;
}
if (errorsFound == false && editUser.getLastName().isEmpty()) {
redirectAttributes.addFlashAttribute("editLastName", "fail");
errorsFound = true;
}
if (errorsFound == false && editUser.getPhone().isEmpty()) {
redirectAttributes.addFlashAttribute("editPhone", "fail");
errorsFound = true;
}
if (errorsFound == false && (editUser.getPhone().matches("(.*)[a-zA-Z](.*)") || editUser.getPhone().length() < 6)) {
// previously already check if phone is empty
// now check phone must contain only digits
redirectAttributes.addFlashAttribute("editPhone", "fail");
errorsFound = true;
}
if (errorsFound == false && !editUser.getConfirmPassword().isEmpty() && !editUser.isPasswordValid()) {
redirectAttributes.addFlashAttribute(editPhrase, "invalid");
errorsFound = true;
}
if (errorsFound == false && editUser.getJobTitle().isEmpty()) {
redirectAttributes.addFlashAttribute("editJobTitle", "fail");
errorsFound = true;
}
if (errorsFound == false && editUser.getInstitution().isEmpty()) {
redirectAttributes.addFlashAttribute("editInstitution", "fail");
errorsFound = true;
}
if (errorsFound == false && editUser.getCountry().isEmpty()) {
redirectAttributes.addFlashAttribute("editCountry", "fail");
errorsFound = true;
}
if (errorsFound) {
session.removeAttribute(webProperties.getSessionUserAccount());
return "redirect:/account_settings";
} else {
// used to compare original and edited User2 objects
User2 originalUser = (User2) session.getAttribute(webProperties.getSessionUserAccount());
JSONObject userObject = new JSONObject();
JSONObject userDetails = new JSONObject();
JSONObject address = new JSONObject();
userDetails.put("firstName", editUser.getFirstName());
userDetails.put("lastName", editUser.getLastName());
userDetails.put("email", editUser.getEmail());
userDetails.put("phone", editUser.getPhone());
userDetails.put("jobTitle", editUser.getJobTitle());
userDetails.put("address", address);
userDetails.put("institution", editUser.getInstitution());
userDetails.put("institutionAbbreviation", originalUser.getInstitutionAbbreviation());
userDetails.put("institutionWeb", originalUser.getInstitutionWeb());
address.put("address1", originalUser.getAddress1());
address.put("address2", originalUser.getAddress2());
address.put("country", editUser.getCountry());
address.put("city", originalUser.getCity());
address.put("region", originalUser.getRegion());
address.put("zipCode", originalUser.getPostalCode());
userObject.put("userDetails", userDetails);
String userId_uri = properties.getSioUsersUrl() + session.getAttribute(webProperties.getSessionUserId());
HttpEntity<String> request = createHttpEntityWithBody(userObject.toString());
restTemplate.exchange(userId_uri, HttpMethod.PUT, request, String.class);
if (!originalUser.getFirstName().equals(editUser.getFirstName())) {
redirectAttributes.addFlashAttribute("editFirstName", "success");
}
if (!originalUser.getLastName().equals(editUser.getLastName())) {
redirectAttributes.addFlashAttribute("editLastName", "success");
}
if (!originalUser.getPhone().equals(editUser.getPhone())) {
redirectAttributes.addFlashAttribute("editPhone", "success");
}
if (!originalUser.getJobTitle().equals(editUser.getJobTitle())) {
redirectAttributes.addFlashAttribute("editJobTitle", "success");
}
if (!originalUser.getInstitution().equals(editUser.getInstitution())) {
redirectAttributes.addFlashAttribute("editInstitution", "success");
}
if (!originalUser.getCountry().equals(editUser.getCountry())) {
redirectAttributes.addFlashAttribute("editCountry", "success");
}
// credential service change password
if (editUser.isPasswordMatch()) {
JSONObject credObject = new JSONObject();
credObject.put("password", editUser.getPassword());
HttpEntity<String> credRequest = createHttpEntityWithBody(credObject.toString());
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = restTemplate.exchange(properties.getUpdateCredentials(session.getAttribute("id").toString()), HttpMethod.PUT, credRequest, String.class);
String responseBody = response.getBody().toString();
try {
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
redirectAttributes.addFlashAttribute(editPhrase, "fail");
} else {
redirectAttributes.addFlashAttribute(editPhrase, "success");
}
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
} finally {
session.removeAttribute(webProperties.getSessionUserAccount());
}
}
}
return "redirect:/account_settings";
}
//--------------------User Side Approve Members Page------------
@RequestMapping("/approve_new_user")
public String approveNewUser(Model model, HttpSession session) throws Exception {
// HashMap<Integer, Team> rv = new HashMap<Integer, Team>();
// rv = teamManager.getTeamMapByTeamOwner(getSessionIdOfLoggedInUser(session));
// boolean userHasAnyJoinRequest = hasAnyJoinRequest(rv);
// model.addAttribute("teamMapOwnedByUser", rv);
// model.addAttribute("userHasAnyJoinRequest", userHasAnyJoinRequest);
List<JoinRequestApproval> rv = new ArrayList<>();
List<JoinRequestApproval> temp;
// get list of teamids
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response = restTemplate.exchange(properties.getUser(session.getAttribute("id").toString()), HttpMethod.GET, request, String.class);
String responseBody = response.getBody().toString();
JSONObject object = new JSONObject(responseBody);
JSONArray teamIdsJsonArray = object.getJSONArray("teams");
for (int i = 0; i < teamIdsJsonArray.length(); i++) {
String teamId = teamIdsJsonArray.get(i).toString();
HttpEntity<String> teamRequest = createHttpEntityHeaderOnly();
ResponseEntity teamResponse = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, teamRequest, String.class);
String teamResponseBody = teamResponse.getBody().toString();
Team2 team2 = new Team2();
JSONObject teamObject = new JSONObject(teamResponseBody);
JSONArray membersArray = teamObject.getJSONArray("members");
team2.setId(teamObject.getString("id"));
team2.setName(teamObject.getString("name"));
boolean isTeamLeader = false;
temp = new ArrayList<>();
for (int j = 0; j < membersArray.length(); j++) {
JSONObject memberObject = membersArray.getJSONObject(j);
String userId = memberObject.getString("userId");
String teamMemberType = memberObject.getString(MEMBER_TYPE);
String teamMemberStatus = memberObject.getString("memberStatus");
String teamJoinedDate = formatZonedDateTime(memberObject.get("joinedDate").toString());
JoinRequestApproval joinRequestApproval = new JoinRequestApproval();
if (userId.equals(session.getAttribute("id").toString()) && teamMemberType.equals(MemberType.OWNER.toString())) {
isTeamLeader = true;
}
if (teamMemberStatus.equals(MemberStatus.PENDING.toString()) && teamMemberType.equals(MemberType.MEMBER.toString())) {
User2 myUser = invokeAndExtractUserInfo(userId);
joinRequestApproval.setUserId(myUser.getId());
joinRequestApproval.setUserEmail(myUser.getEmail());
joinRequestApproval.setUserName(myUser.getFirstName() + " " + myUser.getLastName());
joinRequestApproval.setApplicationDate(teamJoinedDate);
joinRequestApproval.setTeamId(team2.getId());
joinRequestApproval.setTeamName(team2.getName());
temp.add(joinRequestApproval);
log.info("Join request: UserId: {}, UserEmail: {}", myUser.getId(), myUser.getEmail());
}
}
if (isTeamLeader) {
if (!temp.isEmpty()) {
rv.addAll(temp);
}
}
}
model.addAttribute("joinApprovalList", rv);
return "approve_new_user";
}
@RequestMapping("/approve_new_user/accept/{teamId}/{userId}")
public String userSideAcceptJoinRequest(
@PathVariable String teamId,
@PathVariable String userId,
HttpSession session,
RedirectAttributes redirectAttributes) throws WebServiceRuntimeException {
log.info("Approve join request: User {}, Team {}, Approver {}",
userId, teamId, session.getAttribute("id").toString());
JSONObject mainObject = new JSONObject();
JSONObject userFields = new JSONObject();
userFields.put("id", session.getAttribute("id").toString());
mainObject.put("user", userFields);
HttpEntity<String> request = createHttpEntityWithBody(mainObject.toString());
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getApproveJoinRequest(teamId, userId), HttpMethod.POST, request, String.class);
} catch (RestClientException e) {
log.warn("Error connecting to sio team service: {}", e);
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
return "redirect:/approve_new_user";
}
String responseBody = response.getBody().toString();
if (RestUtil.isError(response.getStatusCode())) {
try {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case DETERLAB_OPERATION_FAILED_EXCEPTION:
log.warn("Approve join request: User {}, Team {} fail", userId, teamId);
redirectAttributes.addFlashAttribute(MESSAGE, "Approve join request fail");
break;
default:
log.warn("Server side error: {}", error.getError());
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
break;
}
return "redirect:/approve_new_user";
} catch (IOException ioe) {
log.warn("IOException {}", ioe);
throw new WebServiceRuntimeException(ioe.getMessage());
}
}
// everything looks OK?
log.info("Join request has been APPROVED, User {}, Team {}", userId, teamId);
redirectAttributes.addFlashAttribute(MESSAGE_SUCCESS, "Join request has been APPROVED.");
return "redirect:/approve_new_user";
}
@RequestMapping("/approve_new_user/reject/{teamId}/{userId}")
public String userSideRejectJoinRequest(
@PathVariable String teamId,
@PathVariable String userId,
HttpSession session,
RedirectAttributes redirectAttributes) throws WebServiceRuntimeException {
log.info("Reject join request: User {}, Team {}, Approver {}",
userId, teamId, session.getAttribute("id").toString());
JSONObject mainObject = new JSONObject();
JSONObject userFields = new JSONObject();
userFields.put("id", session.getAttribute("id").toString());
mainObject.put("user", userFields);
HttpEntity<String> request = createHttpEntityWithBody(mainObject.toString());
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getRejectJoinRequest(teamId, userId), HttpMethod.DELETE, request, String.class);
} catch (RestClientException e) {
log.warn("Error connecting to sio team service: {}", e);
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
return "redirect:/approve_new_user";
}
String responseBody = response.getBody().toString();
if (RestUtil.isError(response.getStatusCode())) {
try {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case DETERLAB_OPERATION_FAILED_EXCEPTION:
log.warn("Reject join request: User {}, Team {} fail", userId, teamId);
redirectAttributes.addFlashAttribute(MESSAGE, "Reject join request fail");
break;
default:
log.warn("Server side error: {}", error.getError());
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
break;
}
return "redirect:/approve_new_user";
} catch (IOException ioe) {
log.warn("IOException {}", ioe);
throw new WebServiceRuntimeException(ioe.getMessage());
}
}
// everything looks OK?
log.info("Join request has been REJECTED, User {}, Team {}", userId, teamId);
redirectAttributes.addFlashAttribute(MESSAGE, "Join request has been REJECTED.");
return "redirect:/approve_new_user";
}
//--------------------------Teams Page--------------------------
@RequestMapping("/public_teams")
public String publicTeamsBeforeLogin(Model model) {
TeamManager2 teamManager2 = new TeamManager2();
// get public teams
HttpEntity<String> teamRequest = createHttpEntityHeaderOnlyNoAuthHeader();
ResponseEntity teamResponse = restTemplate.exchange(properties.getTeamsByVisibility(TeamVisibility.PUBLIC.toString()), HttpMethod.GET, teamRequest, String.class);
String teamResponseBody = teamResponse.getBody().toString();
JSONArray teamPublicJsonArray = new JSONArray(teamResponseBody);
for (int i = 0; i < teamPublicJsonArray.length(); i++) {
JSONObject teamInfoObject = teamPublicJsonArray.getJSONObject(i);
Team2 team2 = extractTeamInfo(teamInfoObject.toString());
teamManager2.addTeamToPublicTeamMap(team2);
}
model.addAttribute("publicTeamMap2", teamManager2.getPublicTeamMap());
return "public_teams";
}
@RequestMapping("/teams")
public String teams(Model model, HttpSession session) {
// int currentLoggedInUserId = getSessionIdOfLoggedInUser(session);
// model.addAttribute("infoMsg", teamManager.getInfoMsg());
// model.addAttribute("currentLoggedInUserId", currentLoggedInUserId);
// model.addAttribute("teamMap", teamManager.getTeamMap(currentLoggedInUserId));
// model.addAttribute("publicTeamMap", teamManager.getPublicTeamMap());
// model.addAttribute("invitedToParticipateMap2", teamManager.getInvitedToParticipateMap2(currentLoggedInUserId));
// model.addAttribute("joinRequestMap2", teamManager.getJoinRequestTeamMap2(currentLoggedInUserId));
TeamManager2 teamManager2 = new TeamManager2();
// stores the list of images created or in progress of creation by teams
// e.g. teamNameA : "created" : [imageA, imageB], "inProgress" : [imageC, imageD]
Map<String, Map<String, List<Image>>> imageMap = new HashMap<>();
// get list of teamids
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response = restTemplate.exchange(properties.getUser(session.getAttribute("id").toString()), HttpMethod.GET, request, String.class);
String responseBody = response.getBody().toString();
JSONObject object = new JSONObject(responseBody);
JSONArray teamIdsJsonArray = object.getJSONArray("teams");
String userEmail = object.getJSONObject("userDetails").getString("email");
for (int i = 0; i < teamIdsJsonArray.length(); i++) {
String teamId = teamIdsJsonArray.get(i).toString();
HttpEntity<String> teamRequest = createHttpEntityHeaderOnly();
ResponseEntity teamResponse = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, teamRequest, String.class);
String teamResponseBody = teamResponse.getBody().toString();
Team2 team2 = extractTeamInfo(teamResponseBody);
teamManager2.addTeamToTeamMap(team2);
Team2 joinRequestTeam = extractTeamInfoUserJoinRequest(session.getAttribute("id").toString(), teamResponseBody);
if (joinRequestTeam != null) {
teamManager2.addTeamToUserJoinRequestTeamMap(joinRequestTeam);
}
imageMap.put(team2.getName(), invokeAndGetImageList(teamId));
}
// check if inner image map is empty, have to do it via this manner
// returns true if the team contains an image list
boolean isInnerImageMapPresent = imageMap.values().stream().filter(perTeamImageMap -> !perTeamImageMap.isEmpty()).findFirst().isPresent();
model.addAttribute("userEmail", userEmail);
model.addAttribute("teamMap2", teamManager2.getTeamMap());
model.addAttribute("userJoinRequestMap", teamManager2.getUserJoinRequestMap());
model.addAttribute("isInnerImageMapPresent", isInnerImageMapPresent);
model.addAttribute("imageMap", imageMap);
return "teams";
}
/**
* Exectues the service-image and returns a Map containing the list of images in two partitions.
* One partition contains the list of already created images.
* The other partition contains the list of currently saving in progress images.
*
* @param teamId The ncl team id to retrieve the list of images from.
* @return Returns a Map containing the list of images in two partitions.
*/
private Map<String, List<Image>> invokeAndGetImageList(String teamId) {
log.info("Getting list of saved images for team {}", teamId);
Map<String, List<Image>> resultMap = new HashMap<>();
List<Image> createdImageList = new ArrayList<>();
List<Image> inProgressImageList = new ArrayList<>();
HttpEntity<String> imageRequest = createHttpEntityHeaderOnly();
ResponseEntity imageResponse;
try {
imageResponse = restTemplate.exchange(properties.getTeamSavedImages(teamId), HttpMethod.GET, imageRequest, String.class);
} catch (ResourceAccessException e) {
log.warn("Error connecting to image service: {}", e);
return new HashMap<>();
}
String imageResponseBody = imageResponse.getBody().toString();
String osImageList = new JSONObject(imageResponseBody).getString(teamId);
JSONObject osImageObject = new JSONObject(osImageList);
log.debug("osImageList: {}", osImageList);
log.debug("osImageObject: {}", osImageObject);
if (osImageObject == JSONObject.NULL || osImageObject.length() == 0) {
log.info("List of saved images for team {} is empty.", teamId);
return resultMap;
}
for (int k = 0; k < osImageObject.names().length(); k++) {
String imageName = osImageObject.names().getString(k);
String imageStatus = osImageObject.getString(imageName);
log.info("Image list for team {}: image name {}, status {}", teamId, imageName, imageStatus);
Image image = new Image();
image.setImageName(imageName);
image.setDescription("-");
image.setTeamId(teamId);
if ("created".equals(imageStatus)) {
createdImageList.add(image);
} else if ("notfound".equals(imageStatus)) {
inProgressImageList.add(image);
}
}
resultMap.put("created", createdImageList);
resultMap.put("inProgress", inProgressImageList);
return resultMap;
}
// @RequestMapping("/accept_participation/{teamId}")
// public String acceptParticipationRequest(@PathVariable Integer teamId, Model model, HttpSession session) {
// int currentLoggedInUserId = getSessionIdOfLoggedInUser(session);
// // get user's participation request list
// // add this user id to the requested list
// teamManager.acceptParticipationRequest(currentLoggedInUserId, teamId);
// // remove participation request since accepted
// teamManager.removeParticipationRequest(currentLoggedInUserId, teamId);
//
// // must get team name
// String teamName = teamManager.getTeamNameByTeamId(teamId);
// teamManager.setInfoMsg("You have just joined Team " + teamName + " !");
//
// return "redirect:/teams";
// }
// @RequestMapping("/ignore_participation/{teamId}")
// public String ignoreParticipationRequest(@PathVariable Integer teamId, Model model, HttpSession session) {
// // get user's participation request list
// // remove this user id from the requested list
// String teamName = teamManager.getTeamNameByTeamId(teamId);
// teamManager.ignoreParticipationRequest2(getSessionIdOfLoggedInUser(session), teamId);
// teamManager.setInfoMsg("You have just ignored a team request from Team " + teamName + " !");
//
// return "redirect:/teams";
// }
// @RequestMapping("/withdraw/{teamId}")
public String withdrawnJoinRequest(@PathVariable Integer teamId, HttpSession session) {
// get user team request
// remove this user id from the user's request list
String teamName = teamManager.getTeamNameByTeamId(teamId);
teamManager.removeUserJoinRequest2(getSessionIdOfLoggedInUser(session), teamId);
teamManager.setInfoMsg("You have withdrawn your join request for Team " + teamName);
return "redirect:/teams";
}
// @RequestMapping(value="/teams/invite_members/{teamId}", method=RequestMethod.GET)
// public String inviteMember(@PathVariable Integer teamId, Model model) {
// model.addAttribute("teamIdVar", teamId);
// model.addAttribute("teamPageInviteMemberForm", new TeamPageInviteMemberForm());
// return "team_page_invite_members";
// }
// @RequestMapping(value="/teams/invite_members/{teamId}", method=RequestMethod.POST)
// public String sendInvitation(@PathVariable Integer teamId, @ModelAttribute TeamPageInviteMemberForm teamPageInviteMemberForm,Model model) {
// int userId = userManager.getUserIdByEmail(teamPageInviteMemberForm.getInviteUserEmail());
// teamManager.addInvitedToParticipateMap(userId, teamId);
// return "redirect:/teams";
// }
@RequestMapping(value = "/teams/members_approval/{teamId}", method = RequestMethod.GET)
public String membersApproval(@PathVariable Integer teamId, Model model) {
model.addAttribute("team", teamManager.getTeamByTeamId(teamId));
return "team_page_approve_members";
}
@RequestMapping("/teams/members_approval/accept/{teamId}/{userId}")
public String acceptJoinRequest(@PathVariable Integer teamId, @PathVariable Integer userId) {
teamManager.acceptJoinRequest(userId, teamId);
return "redirect:/teams/members_approval/{teamId}";
}
@RequestMapping("/teams/members_approval/reject/{teamId}/{userId}")
public String rejectJoinRequest(@PathVariable Integer teamId, @PathVariable Integer userId) {
teamManager.rejectJoinRequest(userId, teamId);
return "redirect:/teams/members_approval/{teamId}";
}
//--------------------------Team Profile Page--------------------------
@RequestMapping(value = "/team_profile/{teamId}", method = RequestMethod.GET)
public String teamProfile(@PathVariable String teamId, Model model, final RedirectAttributes redirectAttributes, HttpSession session) throws IOException {
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, request, String.class);
String responseBody = response.getBody().toString();
Team2 team = extractTeamInfo(responseBody);
model.addAttribute("team", team);
model.addAttribute("owner", team.getOwner());
model.addAttribute("membersList", team.getMembersStatusMap().get(MemberStatus.APPROVED));
session.setAttribute("originalTeam", team);
request = createHttpEntityHeaderOnly();
response = restTemplate.exchange(properties.getExpListByTeamId(teamId), HttpMethod.GET, request, String.class);
JSONArray experimentsArray = new JSONArray(response.getBody().toString());
List<Experiment2> experimentList = new ArrayList<>();
Map<Long, Realization> realizationMap = new HashMap<>();
for (int k = 0; k < experimentsArray.length(); k++) {
Experiment2 experiment2 = extractExperiment(experimentsArray.getJSONObject(k).toString());
Realization realization = invokeAndExtractRealization(experiment2.getTeamName(), experiment2.getId());
realizationMap.put(experiment2.getId(), realization);
experimentList.add(experiment2);
}
model.addAttribute("teamExperimentList", experimentList);
model.addAttribute("teamRealizationMap", realizationMap);
//Starting to get quota
try {
response = restTemplate.exchange(properties.getQuotaByTeamId(teamId), HttpMethod.GET, request, String.class);
} catch (RestClientException e) {
log.warn("Error connecting to sio team service for display team quota: {}", e);
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
return REDIRECT_TEAM_PROFILE_TEAM_ID;
}
responseBody = response.getBody().toString();
// handling exceptions from SIO
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case TEAM_NOT_FOUND_EXCEPTION:
log.warn("Get team quota: Team {} not found", teamId);
break;
default:
log.warn("Get team quota : sio or deterlab adapter connection error");
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
break;
}
}
TeamQuota teamQuota = extractTeamQuotaInfo(responseBody);
model.addAttribute("teamQuota", teamQuota);
session.setAttribute(ORIGINAL_BUDGET, teamQuota.getBudget()); // this is to check if budget changed later
return "team_profile";
}
@RequestMapping(value = "/team_profile/{teamId}", method = RequestMethod.POST)
public String editTeamProfile(
@PathVariable String teamId,
@ModelAttribute("team") Team2 editTeam,
final RedirectAttributes redirectAttributes,
HttpSession session) {
boolean errorsFound = false;
if (editTeam.getDescription().isEmpty()) {
errorsFound = true;
redirectAttributes.addFlashAttribute("editDesc", "fail");
}
if (errorsFound) {
// safer to remove
session.removeAttribute("originalTeam");
return "redirect:/team_profile/" + editTeam.getId();
}
// can edit team description and team website for now
JSONObject teamfields = new JSONObject();
teamfields.put("id", teamId);
teamfields.put("name", editTeam.getName());
teamfields.put("description", editTeam.getDescription());
teamfields.put("website", "http://default.com");
teamfields.put("organisationType", editTeam.getOrganisationType());
teamfields.put("privacy", "OPEN");
teamfields.put("status", editTeam.getStatus());
teamfields.put("members", editTeam.getMembersList());
HttpEntity<String> request = createHttpEntityWithBody(teamfields.toString());
ResponseEntity response = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.PUT, request, String.class);
Team2 originalTeam = (Team2) session.getAttribute("originalTeam");
if (!originalTeam.getDescription().equals(editTeam.getDescription())) {
redirectAttributes.addFlashAttribute("editDesc", "success");
}
// safer to remove
session.removeAttribute("originalTeam");
return "redirect:/team_profile/" + teamId;
}
@RequestMapping(value = "/team_quota/{teamId}", method = RequestMethod.POST)
public String editTeamQuota(
@PathVariable String teamId,
@ModelAttribute("teamQuota") TeamQuota editTeamQuota,
final RedirectAttributes redirectAttributes,
HttpSession session) throws IOException {
final String QUOTA = "#quota";
JSONObject teamQuotaJSONObject = new JSONObject();
teamQuotaJSONObject.put(TEAM_ID, teamId);
//check if budget input is positive
if (Double.parseDouble(editTeamQuota.getBudget()) < 0) {
redirectAttributes.addFlashAttribute(EDIT_BUDGET, "negativeError");
return "redirect:/team_profile/" + teamId + QUOTA;
}
//check if budget input exceed database limit of 99999999.99
if (Double.parseDouble(editTeamQuota.getBudget()) > 99999999.99) {
redirectAttributes.addFlashAttribute(EDIT_BUDGET, "exceedingLimit");
return "redirect:/team_profile/" + teamId + QUOTA;
}
teamQuotaJSONObject.put("quota", editTeamQuota.getBudget());
HttpEntity<String> request = createHttpEntityWithBody(teamQuotaJSONObject.toString());
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getQuotaByTeamId(teamId), HttpMethod.PUT, request, String.class);
} catch (RestClientException e) {
log.warn("Error connecting to sio team service for display team quota: {}", e);
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
return REDIRECT_TEAM_PROFILE_TEAM_ID;
}
String responseBody = response.getBody().toString();
// handling exceptions from SIO
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case TEAM_NOT_FOUND_EXCEPTION:
log.warn("Get team quota: Team {} not found", teamId);
break;
case TEAM_QUOTA_OUT_OF_RANGE_EXCEPTION:
log.warn("Get team quota: Budget is out of range");
return "redirect:/team_profile/" + teamId + QUOTA;
default:
log.warn("Get team quota : sio or deterlab adapter connection error");
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
break;
}
}
//check if new budget is different in order to display successful message to user
String originalBudget = (String) session.getAttribute(ORIGINAL_BUDGET);
if (!originalBudget.equals(editTeamQuota.getBudget())) {
redirectAttributes.addFlashAttribute(EDIT_BUDGET, "success");
}
// safer to remove
session.removeAttribute(ORIGINAL_BUDGET);
return "redirect:/team_profile/" + teamId + QUOTA;
}
@RequestMapping("/remove_member/{teamId}/{userId}")
public String removeMember(@PathVariable String teamId, @PathVariable String userId, final RedirectAttributes redirectAttributes) throws IOException {
JSONObject teamMemberFields = new JSONObject();
teamMemberFields.put("userId", userId);
teamMemberFields.put(MEMBER_TYPE, MemberType.MEMBER.name());
teamMemberFields.put("memberStatus", MemberStatus.APPROVED.name());
HttpEntity<String> request = createHttpEntityWithBody(teamMemberFields.toString());
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response;
try {
response = restTemplate.exchange(properties.removeUserFromTeam(teamId), HttpMethod.DELETE, request, String.class);
} catch (RestClientException e) {
log.warn("Error connecting to sio team service for remove user: {}", e);
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
return REDIRECT_TEAM_PROFILE_TEAM_ID;
}
String responseBody = response.getBody().toString();
User2 user = invokeAndExtractUserInfo(userId);
String name = user.getFirstName() + " " + user.getLastName();
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case DETERLAB_OPERATION_FAILED_EXCEPTION:
// two subcases when fail to remove users from team
log.warn("Remove member from team: User {}, Team {} fail - {}", userId, teamId, error.getMessage());
if ("user has experiments".equals(error.getMessage())) {
// case 1 - user has experiments
// display the list of experiments that have to be terminated first
// since the team profile page has experiments already, we don't have to retrieve them again
// use the userid to filter out the experiment list at the web pages
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + " Member " + name + " has experiments.");
redirectAttributes.addFlashAttribute(REMOVE_MEMBER_UID, userId);
redirectAttributes.addFlashAttribute(REMOVE_MEMBER_NAME, name);
break;
} else {
// case 2 - deterlab operation failure
log.warn("Remove member from team: deterlab operation failed");
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + " Member " + name + " cannot be removed.");
break;
}
default:
log.warn("Server side error for remove members: {}", error.getError());
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
break;
}
} else {
log.info("Remove member: {}", response.getBody().toString());
// add success message
redirectAttributes.addFlashAttribute(MESSAGE_SUCCESS, "Member " + name + " has been removed.");
}
return REDIRECT_TEAM_PROFILE_TEAM_ID;
}
// @RequestMapping("/team_profile/{teamId}/start_experiment/{expId}")
// public String startExperimentFromTeamProfile(@PathVariable Integer teamId, @PathVariable Integer expId, Model model, HttpSession session) {
// // start experiment
// // ensure experiment is stopped first before starting
// experimentManager.startExperiment(getSessionIdOfLoggedInUser(session), expId);
// return "redirect:/team_profile/{teamId}";
// }
// @RequestMapping("/team_profile/{teamId}/stop_experiment/{expId}")
// public String stopExperimentFromTeamProfile(@PathVariable Integer teamId, @PathVariable Integer expId, Model model, HttpSession session) {
// // stop experiment
// // ensure experiment is in ready mode before stopping
// experimentManager.stopExperiment(getSessionIdOfLoggedInUser(session), expId);
// return "redirect:/team_profile/{teamId}";
// }
// @RequestMapping("/team_profile/{teamId}/remove_experiment/{expId}")
// public String removeExperimentFromTeamProfile(@PathVariable Integer teamId, @PathVariable Integer expId, Model model, HttpSession session) {
// // remove experiment
// // TODO check userid is indeed the experiment owner or team owner
// // ensure experiment is stopped first
// if (experimentManager.removeExperiment(getSessionIdOfLoggedInUser(session), expId) == true) {
// // decrease exp count to be display on Teams page
// teamManager.decrementExperimentCount(teamId);
// }
// model.addAttribute("experimentList", experimentManager.getExperimentListByExperimentOwner(getSessionIdOfLoggedInUser(session)));
// return "redirect:/team_profile/{teamId}";
// }
// @RequestMapping(value="/team_profile/invite_user/{teamId}", method=RequestMethod.GET)
// public String inviteUserFromTeamProfile(@PathVariable Integer teamId, Model model) {
// model.addAttribute("teamIdVar", teamId);
// model.addAttribute("teamPageInviteMemberForm", new TeamPageInviteMemberForm());
// return "team_profile_invite_members";
// }
// @RequestMapping(value="/team_profile/invite_user/{teamId}", method=RequestMethod.POST)
// public String sendInvitationFromTeamProfile(@PathVariable Integer teamId, @ModelAttribute TeamPageInviteMemberForm teamPageInviteMemberForm, Model model) {
// int userId = userManager.getUserIdByEmail(teamPageInviteMemberForm.getInviteUserEmail());
// teamManager.addInvitedToParticipateMap(userId, teamId);
// return "redirect:/team_profile/{teamId}";
// }
//--------------------------Apply for New Team Page--------------------------
@RequestMapping(value = "/teams/apply_team", method = RequestMethod.GET)
public String teamPageApplyTeam(Model model) {
model.addAttribute("teamPageApplyTeamForm", new TeamPageApplyTeamForm());
return "team_page_apply_team";
}
@RequestMapping(value = "/teams/apply_team", method = RequestMethod.POST)
public String checkApplyTeamInfo(
@Valid TeamPageApplyTeamForm teamPageApplyTeamForm,
BindingResult bindingResult,
HttpSession session,
final RedirectAttributes redirectAttributes) throws WebServiceRuntimeException {
final String logPrefix = "Existing user apply for new team: {}";
if (bindingResult.hasErrors()) {
log.warn(logPrefix, "Application form error " + teamPageApplyTeamForm.toString());
return "team_page_apply_team";
}
// log data to ensure data has been parsed
log.debug(logPrefix, properties.getRegisterRequestToApplyTeam(session.getAttribute("id").toString()));
log.info(logPrefix, teamPageApplyTeamForm.toString());
JSONObject mainObject = new JSONObject();
JSONObject teamFields = new JSONObject();
mainObject.put("team", teamFields);
teamFields.put("name", teamPageApplyTeamForm.getTeamName());
teamFields.put("description", teamPageApplyTeamForm.getTeamDescription());
teamFields.put("website", teamPageApplyTeamForm.getTeamWebsite());
teamFields.put("organisationType", teamPageApplyTeamForm.getTeamOrganizationType());
teamFields.put("visibility", teamPageApplyTeamForm.getIsPublic());
String nclUserId = session.getAttribute("id").toString();
HttpEntity<String> request = createHttpEntityWithBody(mainObject.toString());
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getRegisterRequestToApplyTeam(nclUserId), HttpMethod.POST, request, String.class);
String responseBody = response.getBody().toString();
if (RestUtil.isError(response.getStatusCode())) {
// prepare the exception mapping
EnumMap<ExceptionState, String> exceptionMessageMap = new EnumMap<>(ExceptionState.class);
exceptionMessageMap.put(USER_ID_NULL_OR_EMPTY_EXCEPTION, "User id is null or empty ");
exceptionMessageMap.put(TEAM_NAME_NULL_OR_EMPTY_EXCEPTION, "Team name is null or empty ");
exceptionMessageMap.put(USER_NOT_FOUND_EXCEPTION, "User not found");
exceptionMessageMap.put(TEAM_NAME_ALREADY_EXISTS_EXCEPTION, "Team name already exists");
exceptionMessageMap.put(INVALID_TEAM_NAME_EXCEPTION, "Team name contains invalid characters");
exceptionMessageMap.put(TEAM_MEMBER_ALREADY_EXISTS_EXCEPTION, "Team member already exists");
exceptionMessageMap.put(ADAPTER_CONNECTION_EXCEPTION, "Connection to adapter failed");
exceptionMessageMap.put(ADAPTER_INTERNAL_ERROR_EXCEPTION, "Internal server error on adapter");
exceptionMessageMap.put(DETERLAB_OPERATION_FAILED_EXCEPTION, "Operation failed on DeterLab");
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
final String errorMessage = exceptionMessageMap.containsKey(exceptionState) ? error.getMessage() : ERR_SERVER_OVERLOAD;
log.warn(logPrefix, responseBody);
redirectAttributes.addFlashAttribute("message", errorMessage);
return "redirect:/teams/apply_team";
} else {
// no errors, everything ok
log.info(logPrefix, "Application for team " + teamPageApplyTeamForm.getTeamName() + " submitted");
return "redirect:/teams/team_application_submitted";
}
} catch (ResourceAccessException | IOException e) {
log.error(logPrefix, e);
throw new WebServiceRuntimeException(e.getMessage());
}
}
@RequestMapping(value = "/acceptable_usage_policy", method = RequestMethod.GET)
public String teamOwnerPolicy() {
return "acceptable_usage_policy";
}
@RequestMapping(value = "/terms_and_conditions", method = RequestMethod.GET)
public String termsAndConditions() {
return "terms_and_conditions";
}
//--------------------------Join Team Page--------------------------
@RequestMapping(value = "/teams/join_team", method = RequestMethod.GET)
public String teamPageJoinTeam(Model model) {
model.addAttribute("teamPageJoinTeamForm", new TeamPageJoinTeamForm());
return "team_page_join_team";
}
@RequestMapping(value = "/teams/join_team", method = RequestMethod.POST)
public String checkJoinTeamInfo(
@Valid TeamPageJoinTeamForm teamPageJoinForm,
BindingResult bindingResult,
Model model,
HttpSession session,
final RedirectAttributes redirectAttributes) throws WebServiceRuntimeException {
final String logPrefix = "Existing user join team: {}";
if (bindingResult.hasErrors()) {
log.warn(logPrefix, "Application form error " + teamPageJoinForm.toString());
return "team_page_join_team";
}
JSONObject mainObject = new JSONObject();
JSONObject teamFields = new JSONObject();
JSONObject userFields = new JSONObject();
mainObject.put("team", teamFields);
mainObject.put("user", userFields);
userFields.put("id", session.getAttribute("id")); // ncl-id
teamFields.put("name", teamPageJoinForm.getTeamName());
log.info(logPrefix, "User " + session.getAttribute("id") + ", team " + teamPageJoinForm.getTeamName());
HttpEntity<String> request = createHttpEntityWithBody(mainObject.toString());
ResponseEntity response;
try {
restTemplate.setErrorHandler(new MyResponseErrorHandler());
response = restTemplate.exchange(properties.getJoinRequestExistingUser(), HttpMethod.POST, request, String.class);
String responseBody = response.getBody().toString();
if (RestUtil.isError(response.getStatusCode())) {
// prepare the exception mapping
EnumMap<ExceptionState, String> exceptionMessageMap = new EnumMap<>(ExceptionState.class);
exceptionMessageMap.put(USER_NOT_FOUND_EXCEPTION, "User not found");
exceptionMessageMap.put(USER_ID_NULL_OR_EMPTY_EXCEPTION, "User id is null or empty");
exceptionMessageMap.put(TEAM_NOT_FOUND_EXCEPTION, "Team name not found");
exceptionMessageMap.put(TEAM_NAME_NULL_OR_EMPTY_EXCEPTION, "Team name is null or empty");
exceptionMessageMap.put(USER_ALREADY_IN_TEAM_EXCEPTION, "User already in team");
exceptionMessageMap.put(TEAM_MEMBER_ALREADY_EXISTS_EXCEPTION, "Team member already exists");
exceptionMessageMap.put(ADAPTER_CONNECTION_EXCEPTION, "Connection to adapter failed");
exceptionMessageMap.put(ADAPTER_INTERNAL_ERROR_EXCEPTION, "Internal server error on adapter");
exceptionMessageMap.put(DETERLAB_OPERATION_FAILED_EXCEPTION, "Operation failed on DeterLab");
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
final String errorMessage = exceptionMessageMap.containsKey(exceptionState) ? error.getMessage() : ERR_SERVER_OVERLOAD;
log.warn(logPrefix, responseBody);
redirectAttributes.addFlashAttribute("message", errorMessage);
return "redirect:/teams/join_team";
} else {
log.info(logPrefix, "Application for join team " + teamPageJoinForm.getTeamName() + " submitted");
return "redirect:/teams/join_application_submitted/" + teamPageJoinForm.getTeamName();
}
} catch (ResourceAccessException | IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
}
//--------------------------Experiment Page--------------------------
@RequestMapping(value = "/experiments", method = RequestMethod.GET)
public String experiments(Model model, HttpSession session) throws WebServiceRuntimeException {
// long start = System.currentTimeMillis();
List<Experiment2> experimentList = new ArrayList<>();
Map<Long, Realization> realizationMap = new HashMap<>();
HttpEntity<String> request = createHttpEntityHeaderOnly();
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = restTemplate.exchange(properties.getDeterUid(session.getAttribute("id").toString()), HttpMethod.GET, request, String.class);
String responseBody = response.getBody().toString();
try {
if (RestUtil.isError(response.getStatusCode())) {
log.error("No user to get experiment: {}", session.getAttribute("id"));
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
log.info("experiment error: {} - {} - {} - user token:{}", error.getError(), error.getMessage(), error.getLocalizedMessage(), httpScopedSession.getAttribute(webProperties.getSessionJwtToken()));
model.addAttribute(DETER_UID, CONNECTION_ERROR);
} else {
log.info("Show the deter user id: {}", responseBody);
model.addAttribute(DETER_UID, responseBody);
}
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
// get list of teamids
ResponseEntity userRespEntity = restTemplate.exchange(properties.getUser(session.getAttribute("id").toString()), HttpMethod.GET, request, String.class);
JSONObject object = new JSONObject(userRespEntity.getBody().toString());
JSONArray teamIdsJsonArray = object.getJSONArray("teams");
for (int i = 0; i < teamIdsJsonArray.length(); i++) {
String teamId = teamIdsJsonArray.get(i).toString();
HttpEntity<String> teamRequest = createHttpEntityHeaderOnly();
ResponseEntity teamResponse = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, teamRequest, String.class);
String teamResponseBody = teamResponse.getBody().toString();
if (!isMemberJoinRequestPending(session.getAttribute("id").toString(), teamResponseBody)) {
// get experiments lists of the teams
HttpEntity<String> expRequest = createHttpEntityHeaderOnly();
ResponseEntity expRespEntity = restTemplate.exchange(properties.getExpListByTeamId(teamId), HttpMethod.GET, expRequest, String.class);
JSONArray experimentsArray = new JSONArray(expRespEntity.getBody().toString());
for (int k = 0; k < experimentsArray.length(); k++) {
Experiment2 experiment2 = extractExperiment(experimentsArray.getJSONObject(k).toString());
Realization realization = invokeAndExtractRealization(experiment2.getTeamName(), experiment2.getId());
realizationMap.put(experiment2.getId(), realization);
experimentList.add(experiment2);
}
}
}
model.addAttribute("experimentList", experimentList);
model.addAttribute("realizationMap", realizationMap);
// System.out.println("Elapsed time to get experiment page:" + (System.currentTimeMillis() - start));
return "experiments";
}
@RequestMapping(value = "/experiments/create", method = RequestMethod.GET)
public String createExperiment(Model model, HttpSession session) throws WebServiceRuntimeException {
log.info("Loading create experiment page");
// a list of teams that the logged in user is in
List<String> scenarioFileNameList = getScenarioFileNameList();
List<Team2> userTeamsList = new ArrayList<>();
// get list of teamids
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response = restTemplate.exchange(properties.getUser(session.getAttribute("id").toString()), HttpMethod.GET, request, String.class);
String responseBody = response.getBody().toString();
JSONObject object = new JSONObject(responseBody);
JSONArray teamIdsJsonArray = object.getJSONArray("teams");
for (int i = 0; i < teamIdsJsonArray.length(); i++) {
String teamId = teamIdsJsonArray.get(i).toString();
HttpEntity<String> teamRequest = createHttpEntityHeaderOnly();
ResponseEntity teamResponse = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, teamRequest, String.class);
String teamResponseBody = teamResponse.getBody().toString();
Team2 team2 = extractTeamInfo(teamResponseBody);
userTeamsList.add(team2);
}
model.addAttribute("scenarioFileNameList", scenarioFileNameList);
model.addAttribute("experimentForm", new ExperimentForm());
model.addAttribute("userTeamsList", userTeamsList);
return "experiment_page_create_experiment";
}
@RequestMapping(value = "/experiments/create", method = RequestMethod.POST)
public String validateExperiment(
@ModelAttribute("experimentForm") ExperimentForm experimentForm,
HttpSession session,
BindingResult bindingResult,
final RedirectAttributes redirectAttributes) throws WebServiceRuntimeException {
if (bindingResult.hasErrors()) {
log.info("Create experiment - form has errors");
return "redirect:/experiments/create";
}
if (experimentForm.getName() == null || experimentForm.getName().isEmpty()) {
redirectAttributes.addFlashAttribute(MESSAGE, "Experiment Name cannot be empty");
return "redirect:/experiments/create";
}
if (experimentForm.getDescription() == null || experimentForm.getDescription().isEmpty()) {
redirectAttributes.addFlashAttribute(MESSAGE, "Description cannot be empty");
return "redirect:/experiments/create";
}
experimentForm.setScenarioContents(getScenarioContentsFromFile(experimentForm.getScenarioFileName()));
JSONObject experimentObject = new JSONObject();
experimentObject.put("userId", session.getAttribute("id").toString());
experimentObject.put(TEAM_ID, experimentForm.getTeamId());
experimentObject.put(TEAM_NAME, experimentForm.getTeamName());
experimentObject.put("name", experimentForm.getName().replaceAll("\\s+", "")); // truncate whitespaces and non-visible characters like \n
experimentObject.put("description", experimentForm.getDescription());
experimentObject.put("nsFile", "file");
experimentObject.put("nsFileContent", experimentForm.getNsFileContent());
experimentObject.put("idleSwap", "240");
experimentObject.put("maxDuration", "960");
log.info("Calling service to create experiment");
HttpEntity<String> request = createHttpEntityWithBody(experimentObject.toString());
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = restTemplate.exchange(properties.getSioExpUrl(), HttpMethod.POST, request, String.class);
String responseBody = response.getBody().toString();
try {
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case NS_FILE_PARSE_EXCEPTION:
log.warn("Ns file error");
redirectAttributes.addFlashAttribute(MESSAGE, "There is an error when parsing the NS File.");
break;
case EXPERIMENT_NAME_ALREADY_EXISTS_EXCEPTION:
log.warn("Exp name already exists");
redirectAttributes.addFlashAttribute(MESSAGE, "Experiment name already exists.");
break;
default:
log.warn("Exp service or adapter fail");
// possible sio or adapter connection fail
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
break;
}
log.info("Experiment {} created", experimentForm);
return "redirect:/experiments/create";
}
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
//
// TODO Uploaded function for network configuration and optional dataset
// if (!networkFile.isEmpty()) {
// try {
// String networkFileName = getSessionIdOfLoggedInUser(session) + "-networkconfig-" + networkFile.getOriginalFilename();
// BufferedOutputStream stream = new BufferedOutputStream(
// new FileOutputStream(new File(App.EXP_CONFIG_DIR + "/" + networkFileName)));
// FileCopyUtils.copy(networkFile.getInputStream(), stream);
// stream.close();
// redirectAttributes.addFlashAttribute(MESSAGE,
// "You successfully uploaded " + networkFile.getOriginalFilename() + "!");
// // remember network file name here
// }
// catch (Exception e) {
// redirectAttributes.addFlashAttribute(MESSAGE,
// "You failed to upload " + networkFile.getOriginalFilename() + " => " + e.getMessage());
// return "redirect:/experiments/create";
// }
// }
//
// if (!dataFile.isEmpty()) {
// try {
// String dataFileName = getSessionIdOfLoggedInUser(session) + "-data-" + dataFile.getOriginalFilename();
// BufferedOutputStream stream = new BufferedOutputStream(
// new FileOutputStream(new File(App.EXP_CONFIG_DIR + "/" + dataFileName)));
// FileCopyUtils.copy(dataFile.getInputStream(), stream);
// stream.close();
// redirectAttributes.addFlashAttribute("message2",
// "You successfully uploaded " + dataFile.getOriginalFilename() + "!");
// // remember data file name here
// }
// catch (Exception e) {
// redirectAttributes.addFlashAttribute("message2",
// "You failed to upload " + dataFile.getOriginalFilename() + " => " + e.getMessage());
// }
// }
//
// // add current experiment to experiment manager
// experimentManager.addExperiment(getSessionIdOfLoggedInUser(session), experiment);
// // increase exp count to be display on Teams page
// teamManager.incrementExperimentCount(experiment.getTeamId());
return "redirect:/experiments";
}
@RequestMapping(value = "/experiments/save_image/{teamId}/{expId}/{nodeId}", method = RequestMethod.GET)
public String saveExperimentImage(@PathVariable String teamId, @PathVariable String expId, @PathVariable String nodeId, Model model) {
Map<String, Map<String, String>> singleNodeInfoMap = new HashMap<>();
Image saveImageForm = new Image();
String teamName = invokeAndExtractTeamInfo(teamId).getName();
Realization realization = invokeAndExtractRealization(teamName, Long.parseLong(expId));
// experiment may have many nodes
// extract just the particular node details to display
for (Map.Entry<String, Map<String, String>> nodesInfo : realization.getNodesInfoMap().entrySet()) {
String nodeName = nodesInfo.getKey();
Map<String, String> singleNodeDetailsMap = nodesInfo.getValue();
if (singleNodeDetailsMap.get(NODE_ID).equals(nodeId)) {
singleNodeInfoMap.put(nodeName, singleNodeDetailsMap);
// store the current os of the node into the form also
// have to pass the the services
saveImageForm.setCurrentOS(singleNodeDetailsMap.get("os"));
}
}
saveImageForm.setTeamId(teamId);
saveImageForm.setNodeId(nodeId);
model.addAttribute("teamName", teamName);
model.addAttribute("singleNodeInfoMap", singleNodeInfoMap);
model.addAttribute("pathTeamId", teamId);
model.addAttribute("pathExperimentId", expId);
model.addAttribute("pathNodeId", nodeId);
model.addAttribute("experimentName", realization.getExperimentName());
model.addAttribute("saveImageForm", saveImageForm);
return "save_experiment_image";
}
// bindingResult is required in the method signature to perform the JSR303 validation for Image object
@RequestMapping(value = "/experiments/save_image/{teamId}/{expId}/{nodeId}", method = RequestMethod.POST)
public String saveExperimentImage(
@Valid @ModelAttribute("saveImageForm") Image saveImageForm,
BindingResult bindingResult,
RedirectAttributes redirectAttributes,
@PathVariable String teamId,
@PathVariable String expId,
@PathVariable String nodeId) throws IOException {
if (saveImageForm.getImageName().length() < 2) {
log.warn("Save image form has errors {}", saveImageForm);
redirectAttributes.addFlashAttribute("message", "Image name too short, minimum 2 characters");
return "redirect:/experiments/save_image/" + teamId + "/" + expId + "/" + nodeId;
}
log.info("Saving image: team {}, experiment {}, node {}", teamId, expId, nodeId);
ObjectMapper mapper = new ObjectMapper();
HttpEntity<String> request = createHttpEntityWithBody(mapper.writeValueAsString(saveImageForm));
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = restTemplate.exchange(properties.saveImage(), HttpMethod.POST, request, String.class);
String responseBody = response.getBody().toString();
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
log.warn("Save image: error with exception {}", exceptionState);
switch (exceptionState) {
case DETERLAB_OPERATION_FAILED_EXCEPTION:
log.warn("Save image: error, operation failed on DeterLab");
redirectAttributes.addFlashAttribute("message", error.getMessage());
break;
case ADAPTER_CONNECTION_EXCEPTION:
log.warn("Save image: error, cannot connect to adapter");
redirectAttributes.addFlashAttribute("message", "connection to adapter failed");
break;
case ADAPTER_INTERNAL_ERROR_EXCEPTION:
log.warn("Save image: error, adapter internal server error");
redirectAttributes.addFlashAttribute("message", "internal error was found on the adapter");
break;
default:
log.warn("Save image: other error");
redirectAttributes.addFlashAttribute("message", ERR_SERVER_OVERLOAD);
}
return "redirect:/experiments/save_image/" + teamId + "/" + expId + "/" + nodeId;
}
// everything looks ok
log.info("Save image in progress: team {}, experiment {}, node {}, image {}", teamId, expId, nodeId, saveImageForm.getImageName());
return "redirect:/experiments";
}
/*
private String processSaveImageRequest(@Valid @ModelAttribute("saveImageForm") Image saveImageForm, RedirectAttributes redirectAttributes, @PathVariable String teamId, @PathVariable String expId, @PathVariable String nodeId, ResponseEntity response, String responseBody) throws IOException {
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
log.warn("Save image exception: {}", exceptionState);
switch (exceptionState) {
case DETERLAB_OPERATION_FAILED_EXCEPTION:
log.warn("adapter deterlab operation failed exception");
redirectAttributes.addFlashAttribute("message", error.getMessage());
break;
default:
log.warn("Image service or adapter fail");
// possible sio or adapter connection fail
redirectAttributes.addFlashAttribute("message", ERR_SERVER_OVERLOAD);
break;
}
return "redirect:/experiments/save_image/" + teamId + "/" + expId + "/" + nodeId;
} else {
// everything ok
log.info("Image service in progress for Team: {}, Exp: {}, Node: {}, Image: {}", teamId, expId, nodeId, saveImageForm.getImageName());
return "redirect:/experiments";
}
}
*/
// @RequestMapping("/experiments/configuration/{expId}")
// public String viewExperimentConfiguration(@PathVariable Integer expId, Model model) {
// // get experiment from expid
// // retrieve the scenario contents to be displayed
// Experiment currExp = experimentManager.getExperimentByExpId(expId);
// model.addAttribute("scenarioContents", currExp.getScenarioContents());
// return "experiment_scenario_contents";
// }
@RequestMapping("/remove_experiment/{teamName}/{teamId}/{expId}")
public String removeExperiment(@PathVariable String teamName, @PathVariable String teamId, @PathVariable String expId, final RedirectAttributes redirectAttributes, HttpSession session) throws WebServiceRuntimeException {
// ensure experiment is stopped first
Realization realization = invokeAndExtractRealization(teamName, Long.parseLong(expId));
Team2 team = invokeAndExtractTeamInfo(teamId);
// check valid authentication to remove experiments
// either admin, experiment creator or experiment owner
if (!validateIfAdmin(session) && !realization.getUserId().equals(session.getAttribute("id").toString()) && !team.getOwner().getId().equals(session.getAttribute(webProperties.getSessionUserId()))) {
log.warn("Permission denied when remove Team:{}, Experiment: {} with User: {}, Role:{}", teamId, expId, session.getAttribute("id"), session.getAttribute(webProperties.getSessionRoles()));
redirectAttributes.addFlashAttribute(MESSAGE, "An error occurred while trying to remove experiment;" + permissionDeniedMessage);
return "redirect:/experiments";
}
if (!realization.getState().equals(RealizationState.NOT_RUNNING.toString())) {
log.warn("Trying to remove Team: {}, Experiment: {} with State: {} that is still in progress?", teamId, expId, realization.getState());
redirectAttributes.addFlashAttribute(MESSAGE, "An error occurred while trying to remove Exp: " + realization.getExperimentName() + ". Please refresh the page again. If the error persists, please contact " + CONTACT_EMAIL);
return "redirect:/experiments";
}
log.info("Removing experiment: at " + properties.getDeleteExperiment(teamId, expId));
HttpEntity<String> request = createHttpEntityHeaderOnly();
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getDeleteExperiment(teamId, expId), HttpMethod.DELETE, request, String.class);
} catch (Exception e) {
log.warn("Error connecting to experiment service to remove experiment", e.getMessage());
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
return "redirect:/experiments";
}
String responseBody = response.getBody().toString();
try {
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case EXPERIMENT_DELETE_EXCEPTION:
case FORBIDDEN_EXCEPTION:
log.warn("remove experiment failed for Team: {}, Exp: {}", teamId, expId);
redirectAttributes.addFlashAttribute(MESSAGE, error.getMessage());
break;
case OBJECT_OPTIMISTIC_LOCKING_FAILURE_EXCEPTION:
// do nothing
log.info("remove experiment database locking failure");
break;
default:
// do nothing
break;
}
return "redirect:/experiments";
} else {
// everything ok
log.info("remove experiment success for Team: {}, Exp: {}", teamId, expId);
redirectAttributes.addFlashAttribute("exp_remove_message", "Team: " + teamName + " has removed Exp: " + realization.getExperimentName());
return "redirect:/experiments";
}
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
}
@RequestMapping("/start_experiment/{teamName}/{expId}")
public String startExperiment(
@PathVariable String teamName,
@PathVariable String expId,
final RedirectAttributes redirectAttributes, Model model, HttpSession session) throws WebServiceRuntimeException {
// ensure experiment is stopped first before starting
Realization realization = invokeAndExtractRealization(teamName, Long.parseLong(expId));
if (!checkPermissionRealizeExperiment(realization, session)) {
log.warn("Permission denied to start experiment: {} for team: {}", realization.getExperimentName(), teamName);
redirectAttributes.addFlashAttribute(MESSAGE, permissionDeniedMessage);
return "redirect:/experiments";
}
String teamStatus = getTeamStatus(realization.getTeamId());
if (!teamStatus.equals(TeamStatus.APPROVED.name())) {
log.warn("Error: trying to realize an experiment {} on team {} with status {}", realization.getExperimentName(), realization.getTeamId(), teamStatus);
redirectAttributes.addFlashAttribute(MESSAGE, teamName + " is in " + teamStatus + " status and does not have permission to start experiment. Please contact " + CONTACT_EMAIL);
return "redirect:/experiments";
}
if (!realization.getState().equals(RealizationState.NOT_RUNNING.toString())) {
log.warn("Trying to start Team: {}, Experiment: {} with State: {} that is not running?", teamName, expId, realization.getState());
redirectAttributes.addFlashAttribute(MESSAGE, "An error occurred while trying to start Exp: " + realization.getExperimentName() + ". Please refresh the page again. If the error persists, please contact " + CONTACT_EMAIL);
return "redirect:/experiments";
}
log.info("Starting experiment: at " + properties.getStartExperiment(teamName, expId));
HttpEntity<String> request = createHttpEntityHeaderOnly();
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getStartExperiment(teamName, expId), HttpMethod.POST, request, String.class);
} catch (Exception e) {
log.warn("Error connecting to experiment service to start experiment", e.getMessage());
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
return "redirect:/experiments";
}
String responseBody = response.getBody().toString();
try {
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case EXPERIMENT_START_EXCEPTION:
case FORBIDDEN_EXCEPTION:
log.warn("start experiment failed for Team: {}, Exp: {}", teamName, expId);
redirectAttributes.addFlashAttribute(MESSAGE, error.getMessage());
return "redirect:/experiments";
case OBJECT_OPTIMISTIC_LOCKING_FAILURE_EXCEPTION:
// do nothing
log.info("start experiment database locking failure");
break;
default:
// do nothing
break;
}
log.warn("start experiment some other error occurred exception: {}", exceptionState);
// possible for it to be error but experiment has started up finish
// if user clicks on start but reloads the page
// model.addAttribute(EXPERIMENT_MESSAGE, "Team: " + teamName + " has started Exp: " + realization.getExperimentName());
return "experiments";
} else {
// everything ok
log.info("start experiment success for Team: {}, Exp: {}", teamName, expId);
redirectAttributes.addFlashAttribute(EXPERIMENT_MESSAGE, "Experiment " + realization.getExperimentName() + " in team " + teamName + " is starting. This may take up to 10 minutes depending on the scale of your experiment. Please refresh this page later.");
return "redirect:/experiments";
}
} catch (IOException e) {
log.warn("start experiment error: {]", e.getMessage());
throw new WebServiceRuntimeException(e.getMessage());
}
}
@RequestMapping("/stop_experiment/{teamName}/{expId}")
public String stopExperiment(@PathVariable String teamName, @PathVariable String expId, Model model, final RedirectAttributes redirectAttributes, HttpSession session) throws WebServiceRuntimeException {
// ensure experiment is active first before stopping
Realization realization = invokeAndExtractRealization(teamName, Long.parseLong(expId));
if (isNotAdminAndNotInTeam(session, realization)) {
log.warn("Permission denied to stop experiment: {} for team: {}", realization.getExperimentName(), teamName);
redirectAttributes.addFlashAttribute(MESSAGE, permissionDeniedMessage);
return "redirect:/experiments";
}
if (!realization.getState().equals(RealizationState.RUNNING.toString())) {
log.warn("Trying to stop Team: {}, Experiment: {} with State: {} that is still in progress?", teamName, expId, realization.getState());
redirectAttributes.addFlashAttribute(MESSAGE, "An error occurred while trying to stop Exp: " + realization.getExperimentName() + ". Please refresh the page again. If the error persists, please contact " + CONTACT_EMAIL);
return "redirect:/experiments";
}
log.info("Stopping experiment: at " + properties.getStopExperiment(teamName, expId));
HttpEntity<String> request = createHttpEntityHeaderOnly();
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response;
return abc(teamName, expId, redirectAttributes, realization, request);
}
@RequestMapping("/get_topology/{teamName}/{expId}")
@ResponseBody
public String getTopology(@PathVariable String teamName, @PathVariable String expId) {
try {
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response = restTemplate.exchange(properties.getTopology(teamName, expId), HttpMethod.GET, request, String.class);
log.info("Retrieve experiment topo success");
return "data:image/png;base64," + response.getBody();
} catch (Exception e) {
log.error("Error getting topology thumbnail", e.getMessage());
return "";
}
}
private String abc(@PathVariable String teamName, @PathVariable String expId, RedirectAttributes redirectAttributes, Realization realization, HttpEntity<String> request) throws WebServiceRuntimeException {
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getStopExperiment(teamName, expId), HttpMethod.POST, request, String.class);
} catch (Exception e) {
log.warn("Error connecting to experiment service to stop experiment", e.getMessage());
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
return "redirect:/experiments";
}
String responseBody = response.getBody().toString();
try {
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
if (exceptionState == ExceptionState.FORBIDDEN_EXCEPTION) {
log.warn("Permission denied to stop experiment: {} for team: {}", realization.getExperimentName(), teamName);
redirectAttributes.addFlashAttribute(MESSAGE, permissionDeniedMessage);
}
if (exceptionState == ExceptionState.OBJECT_OPTIMISTIC_LOCKING_FAILURE_EXCEPTION) {
log.info("stop experiment database locking failure");
}
} else {
// everything ok
log.info("stop experiment success for Team: {}, Exp: {}", teamName, expId);
redirectAttributes.addFlashAttribute(EXPERIMENT_MESSAGE, "Experiment " + realization.getExperimentName() + " in team " + teamName + " is stopping. Please refresh this page in a few minutes.");
}
return "redirect:/experiments";
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
}
private boolean isNotAdminAndNotInTeam(HttpSession session, Realization realization) {
return !validateIfAdmin(session) && !checkPermissionRealizeExperiment(realization, session);
}
//-----------------------------------------------------------------------
//--------------------------Admin Revamp---------------------------------
//-----------------------------------------------------------------------
//---------------------------------Admin---------------------------------
@RequestMapping("/admin")
public String admin(Model model, HttpSession session) {
if (!validateIfAdmin(session)) {
return NO_PERMISSION_PAGE;
}
TeamManager2 teamManager2 = new TeamManager2();
Map<String, List<String>> userToTeamMap = new HashMap<>(); // userId : list of team names
List<Team2> pendingApprovalTeamsList = new ArrayList<>();
//------------------------------------
// get list of teams
// get list of teams pending for approval
//------------------------------------
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity responseEntity = restTemplate.exchange(properties.getSioTeamsUrl(), HttpMethod.GET, request, String.class);
JSONArray jsonArray = new JSONArray(responseEntity.getBody().toString());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Team2 one = extractTeamInfo(jsonObject.toString());
teamManager2.addTeamToTeamMap(one);
if (one.getStatus().equals(TeamStatus.PENDING.name())) {
pendingApprovalTeamsList.add(one);
}
}
//------------------------------------
// get list of users
//------------------------------------
ResponseEntity response2 = restTemplate.exchange(properties.getSioUsersUrl(), HttpMethod.GET, request, String.class);
String responseBody2 = response2.getBody().toString();
JSONArray jsonUserArray = new JSONArray(responseBody2);
List<User2> usersList = new ArrayList<>();
for (int i = 0; i < jsonUserArray.length(); i++) {
JSONObject userObject = jsonUserArray.getJSONObject(i);
User2 user = extractUserInfo(userObject.toString());
usersList.add(user);
// get list of teams' names for each user
List<String> perUserTeamList = new ArrayList<>();
if (userObject.get("teams") != null) {
JSONArray teamJsonArray = userObject.getJSONArray("teams");
for (int k = 0; k < teamJsonArray.length(); k++) {
Team2 team = invokeAndExtractTeamInfo(teamJsonArray.get(k).toString());
perUserTeamList.add(team.getName());
}
userToTeamMap.put(user.getId(), perUserTeamList);
}
}
model.addAttribute("teamsMap", teamManager2.getTeamMap());
model.addAttribute("pendingApprovalTeamsList", pendingApprovalTeamsList);
model.addAttribute("usersList", usersList);
model.addAttribute("userToTeamMap", userToTeamMap);
return "admin2";
}
@RequestMapping("/admin/data")
public String adminDataManagement(Model model, HttpSession session) {
if (!validateIfAdmin(session)) {
return NO_PERMISSION_PAGE;
}
//------------------------------------
// get list of datasets
//------------------------------------
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response = restTemplate.exchange(properties.getData(), HttpMethod.GET, request, String.class);
String responseBody = response.getBody().toString();
List<Dataset> datasetsList = new ArrayList<>();
JSONArray dataJsonArray = new JSONArray(responseBody);
for (int i = 0; i < dataJsonArray.length(); i++) {
JSONObject dataInfoObject = dataJsonArray.getJSONObject(i);
Dataset dataset = extractDataInfo(dataInfoObject.toString());
datasetsList.add(dataset);
}
ResponseEntity response4 = restTemplate.exchange(properties.getDownloadStat(), HttpMethod.GET, request, String.class);
String responseBody4 = response4.getBody().toString();
Map<Integer, Long> dataDownloadStats = new HashMap<>();
JSONArray statJsonArray = new JSONArray(responseBody4);
for (int i = 0; i < statJsonArray.length(); i++) {
JSONObject statInfoObject = statJsonArray.getJSONObject(i);
dataDownloadStats.put(statInfoObject.getInt("dataId"), statInfoObject.getLong("count"));
}
model.addAttribute("dataList", datasetsList);
model.addAttribute("downloadStats", dataDownloadStats);
return "data_dashboard";
}
@RequestMapping("/admin/experiments")
public String adminExperimentsManagement(Model model, HttpSession session) {
if (!validateIfAdmin(session)) {
return NO_PERMISSION_PAGE;
}
//------------------------------------
// get list of experiments
//------------------------------------
HttpEntity<String> expRequest = createHttpEntityHeaderOnly();
ResponseEntity expResponseEntity = restTemplate.exchange(properties.getSioExpUrl(), HttpMethod.GET, expRequest, String.class);
//------------------------------------
// get list of realizations
//------------------------------------
HttpEntity<String> realizationRequest = createHttpEntityHeaderOnly();
ResponseEntity realizationResponseEntity = restTemplate.exchange(properties.getAllRealizations(), HttpMethod.GET, realizationRequest, String.class);
JSONArray jsonExpArray = new JSONArray(expResponseEntity.getBody().toString());
JSONArray jsonRealizationArray = new JSONArray(realizationResponseEntity.getBody().toString());
Map<Experiment2, Realization> experiment2Map = new HashMap<>(); // exp id, experiment
Map<Long, Realization> realizationMap = new HashMap<>(); // exp id, realization
for (int k = 0; k < jsonRealizationArray.length(); k++) {
Realization realization;
try {
realization = extractRealization(jsonRealizationArray.getJSONObject(k).toString());
} catch (JSONException e) {
log.debug("Admin extract realization {}", e);
realization = getCleanRealization();
}
if (realization.getState().equals(RealizationState.RUNNING.name())) {
realizationMap.put(realization.getExperimentId(), realization);
}
}
for (int i = 0; i < jsonExpArray.length(); i++) {
Experiment2 experiment2 = extractExperiment(jsonExpArray.getJSONObject(i).toString());
if (realizationMap.containsKey(experiment2.getId())) {
experiment2Map.put(experiment2, realizationMap.get(experiment2.getId()));
}
}
model.addAttribute("runningExpMap", experiment2Map);
return "experiment_dashboard";
}
@RequestMapping("/admin/usage")
public String adminTeamUsage(Model model,
@RequestParam(value = "team", required = false) String team,
@RequestParam(value = "start", required = false) String start,
@RequestParam(value = "end", required = false) String end,
HttpSession session) {
if (!validateIfAdmin(session)) {
return NO_PERMISSION_PAGE;
}
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
ZonedDateTime now = ZonedDateTime.now();
if (start == null) {
ZonedDateTime startDate = now.with(firstDayOfMonth());
start = startDate.format(formatter);
}
if (end == null) {
ZonedDateTime endDate = now.with(lastDayOfMonth());
end = endDate.format(formatter);
}
// get list of teamids
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity responseEntity = restTemplate.exchange(properties.getSioTeamsUrl(), HttpMethod.GET, request, String.class);
JSONArray jsonArray = new JSONArray(responseEntity.getBody().toString());
TeamManager2 teamManager2 = new TeamManager2();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Team2 one = extractTeamInfo(jsonObject.toString());
teamManager2.addTeamToTeamMap(one);
}
if (team != null) {
responseEntity = restTemplate.exchange(properties.getUsageStat(team, "startDate=" + start, "endDate=" + end), HttpMethod.GET, request, String.class);
String usage = responseEntity.getBody().toString();
model.addAttribute("usage", usage);
}
model.addAttribute("teamsMap", teamManager2.getTeamMap());
model.addAttribute("start", start);
model.addAttribute("end", end);
model.addAttribute("team", team);
return "usage_statistics";
}
// @RequestMapping(value="/admin/domains/add", method=RequestMethod.POST)
// public String addDomain(@Valid Domain domain, BindingResult bindingResult) {
// if (bindingResult.hasErrors()) {
// return "redirect:/admin";
// } else {
// domainManager.addDomains(domain.getDomainName());
// }
// return "redirect:/admin";
// }
// @RequestMapping("/admin/domains/remove/{domainKey}")
// public String removeDomain(@PathVariable String domainKey) {
// domainManager.removeDomains(domainKey);
// return "redirect:/admin";
// }
@RequestMapping("/admin/teams/accept/{teamId}/{teamOwnerId}")
public String approveTeam(
@PathVariable String teamId,
@PathVariable String teamOwnerId,
final RedirectAttributes redirectAttributes,
HttpSession session
) throws WebServiceRuntimeException {
if (!validateIfAdmin(session)) {
return NO_PERMISSION_PAGE;
}
//FIXME require approver info
log.info("Approving new team {}, team owner {}", teamId, teamOwnerId);
HttpEntity<String> request = createHttpEntityHeaderOnly();
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = restTemplate.exchange(
properties.getApproveTeam(teamId, teamOwnerId, TeamStatus.APPROVED), HttpMethod.POST, request, String.class);
String responseBody = response.getBody().toString();
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error;
try {
error = objectMapper.readValue(responseBody, MyErrorResource.class);
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case TEAM_ID_NULL_OR_EMPTY_EXCEPTION:
log.warn("Approve team: TeamId cannot be null or empty: {}",
teamId);
redirectAttributes.addFlashAttribute(MESSAGE, "TeamId cannot be null or empty");
break;
case USER_ID_NULL_OR_EMPTY_EXCEPTION:
log.warn("Approve team: UserId cannot be null or empty: {}",
teamOwnerId);
redirectAttributes.addFlashAttribute(MESSAGE, "UserId cannot be null or empty");
break;
case INVALID_TEAM_STATUS_EXCEPTION:
log.warn("Approve team: TeamStatus is invalid");
redirectAttributes.addFlashAttribute(MESSAGE, "Team status is invalid");
break;
case TEAM_NOT_FOUND_EXCEPTION:
log.warn("Approve team: Team {} not found", teamId);
redirectAttributes.addFlashAttribute(MESSAGE, "Team does not exist");
break;
case DETERLAB_OPERATION_FAILED_EXCEPTION:
log.warn("Approve team: Team {} fail", teamId);
redirectAttributes.addFlashAttribute(MESSAGE, "Approve team request fail on Deterlab");
break;
default:
log.warn("Approve team : sio or deterlab adapter connection error");
// possible sio or adapter connection fail
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
break;
}
return "redirect:/admin";
}
// http status code is OK, then need to check the response message
String msg = new JSONObject(responseBody).getString("msg");
if ("approve project OK".equals(msg)) {
log.info("Approve team {} OK", teamId);
} else {
log.warn("Approve team {} FAIL", teamId);
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
}
return "redirect:/admin";
}
@RequestMapping("/admin/teams/reject/{teamId}/{teamOwnerId}")
public String rejectTeam(
@PathVariable String teamId,
@PathVariable String teamOwnerId,
final RedirectAttributes redirectAttributes,
HttpSession session
) throws WebServiceRuntimeException {
if (!validateIfAdmin(session)) {
return NO_PERMISSION_PAGE;
}
//FIXME require approver info
log.info("Rejecting new team {}, team owner {}", teamId, teamOwnerId);
HttpEntity<String> request = createHttpEntityHeaderOnly();
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = restTemplate.exchange(
properties.getApproveTeam(teamId, teamOwnerId, TeamStatus.REJECTED), HttpMethod.POST, request, String.class);
String responseBody = response.getBody().toString();
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error;
try {
error = objectMapper.readValue(responseBody, MyErrorResource.class);
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case TEAM_ID_NULL_OR_EMPTY_EXCEPTION:
log.warn("Reject team: TeamId cannot be null or empty: {}",
teamId);
redirectAttributes.addFlashAttribute(MESSAGE, "TeamId cannot be null or empty");
break;
case USER_ID_NULL_OR_EMPTY_EXCEPTION:
log.warn("Reject team: UserId cannot be null or empty: {}",
teamOwnerId);
redirectAttributes.addFlashAttribute(MESSAGE, "UserId cannot be null or empty");
break;
case INVALID_TEAM_STATUS_EXCEPTION:
log.warn("Reject team: TeamStatus is invalid");
redirectAttributes.addFlashAttribute(MESSAGE, "Team status is invalid");
break;
case TEAM_NOT_FOUND_EXCEPTION:
log.warn("Reject team: Team {} not found", teamId);
redirectAttributes.addFlashAttribute(MESSAGE, "Team does not exist");
break;
case DETERLAB_OPERATION_FAILED_EXCEPTION:
log.warn("Reject team: Team {} fail", teamId);
redirectAttributes.addFlashAttribute(MESSAGE, "Reject team request fail on Deterlab");
break;
default:
log.warn("Reject team : sio or deterlab adapter connection error");
// possible sio or adapter connection fail
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
break;
}
return "redirect:/admin";
}
// http status code is OK, then need to check the response message
String msg = new JSONObject(responseBody).getString("msg");
if ("reject project OK".equals(msg)) {
log.info("Reject team {} OK", teamId);
} else {
log.warn("Reject team {} FAIL", teamId);
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
}
return "redirect:/admin";
}
@RequestMapping("/admin/teams/{teamId}")
public String setupTeamRestriction(
@PathVariable final String teamId,
@RequestParam(value = "action", required = true) final String action,
final RedirectAttributes redirectAttributes,
HttpSession session) throws IOException {
final String logMessage = "Updating restriction settings for team {}: {}";
// check if admin
if (!validateIfAdmin(session)) {
log.warn(logMessage, teamId, PERMISSION_DENIED);
return NO_PERMISSION_PAGE;
}
Team2 team = invokeAndExtractTeamInfo(teamId);
// check if team is approved before restricted
if ("restrict".equals(action) && team.getStatus().equals(TeamStatus.APPROVED.name())) {
return restrictTeam(team, redirectAttributes);
}
// check if team is restricted before freeing it back to approved
else if ("free".equals(action) && team.getStatus().equals(TeamStatus.RESTRICTED.name())) {
return freeTeam(team, redirectAttributes);
} else {
log.warn(logMessage, teamId, "Cannot " + action + " team with status " + team.getStatus());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + "Cannot " + action + " team " + team.getName() + " with status " + team.getStatus());
return "redirect:/admin";
}
}
private String restrictTeam(final Team2 team, RedirectAttributes redirectAttributes) throws IOException {
log.info("Restricting team {}", team.getId());
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response = restTemplate.exchange(
properties.getSioTeamsStatusUrl(team.getId(), TeamStatus.RESTRICTED),
HttpMethod.PUT, request, String.class);
String responseBody = response.getBody().toString();
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
String logMessage = "Failed to restrict team {}: {}";
switch (exceptionState) {
case TEAM_NOT_FOUND_EXCEPTION:
log.warn(logMessage, team.getId(), TEAM_NOT_FOUND);
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + TEAM_NOT_FOUND);
break;
case INVALID_STATUS_TRANSITION_EXCEPTION:
log.warn(logMessage, team.getId(), error.getMessage());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage());
break;
case INVALID_TEAM_STATUS_EXCEPTION:
log.warn(logMessage, team.getId(), error.getMessage());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage());
break;
case FORBIDDEN_EXCEPTION:
log.warn(logMessage, team.getId(), PERMISSION_DENIED);
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + PERMISSION_DENIED);
break;
default:
log.warn(logMessage, team.getId(), exceptionState.getExceptionName());
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
}
return "redirect:/admin";
} else {
// good
log.info("Team {} has been restricted", team.getId());
redirectAttributes.addFlashAttribute(MESSAGE_SUCCESS, "Team " + team.getName() + " status has been changed to " + TeamStatus.RESTRICTED.name());
return "redirect:/admin";
}
}
private String freeTeam(final Team2 team, RedirectAttributes redirectAttributes) throws IOException {
log.info("Freeing team {}", team.getId());
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response = restTemplate.exchange(
properties.getSioTeamsStatusUrl(team.getId(), TeamStatus.APPROVED),
HttpMethod.PUT, request, String.class);
String responseBody = response.getBody().toString();
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
String logMessage = "Failed to free team {}: {}";
switch (exceptionState) {
case TEAM_NOT_FOUND_EXCEPTION:
log.warn(logMessage, team.getId(), TEAM_NOT_FOUND);
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + TEAM_NOT_FOUND);
break;
case INVALID_STATUS_TRANSITION_EXCEPTION:
log.warn(logMessage, team.getId(), error.getMessage());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage());
break;
case INVALID_TEAM_STATUS_EXCEPTION:
log.warn(logMessage, team.getId(), error.getMessage());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage());
break;
case FORBIDDEN_EXCEPTION:
log.warn(logMessage, team.getId(), PERMISSION_DENIED);
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + PERMISSION_DENIED);
break;
default:
log.warn(logMessage, team.getId(), exceptionState.getExceptionName());
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
}
return "redirect:/admin";
} else {
// good
log.info("Team {} has been freed", team.getId());
redirectAttributes.addFlashAttribute(MESSAGE_SUCCESS, "Team " + team.getName() + " status has been changed to " + TeamStatus.APPROVED.name());
return "redirect:/admin";
}
}
@RequestMapping("/admin/users/{userId}")
public String freezeUnfreezeUsers(
@PathVariable final String userId,
@RequestParam(value = "action", required = true) final String action,
final RedirectAttributes redirectAttributes,
HttpSession session) throws IOException {
User2 user = invokeAndExtractUserInfo(userId);
// check if admin
if (!validateIfAdmin(session)) {
log.warn("Access denied when trying to freeze/unfreeze user {}: must be admin!", userId);
return NO_PERMISSION_PAGE;
}
// check if user status is approved before freeze
if ("freeze".equals(action) && user.getStatus().equals(UserStatus.APPROVED.toString())) {
return freezeUser(user, redirectAttributes);
}
// check if user status is frozen before unfreeze
else if ("unfreeze".equals(action) && user.getStatus().equals(UserStatus.FROZEN.toString())) {
return unfreezeUser(user, redirectAttributes);
} else {
log.warn("Error in freeze/unfreeze user {}: failed to {} user with status {}", userId, action, user.getStatus());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + "failed to " + action + " user " + user.getEmail() + " with status " + user.getStatus());
return "redirect:/admin";
}
}
private String freezeUser(final User2 user, RedirectAttributes redirectAttributes) throws IOException {
log.info("Freezing user {}, email {}", user.getId(), user.getEmail());
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response = restTemplate.exchange(
properties.getSioUsersStatusUrl(user.getId(), UserStatus.FROZEN.toString()),
HttpMethod.PUT, request, String.class);
String responseBody = response.getBody().toString();
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case USER_NOT_FOUND_EXCEPTION:
log.warn("Failed to freeze user {}: user not found", user.getId());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + " user " + user.getEmail() + " not found.");
break;
case INVALID_STATUS_TRANSITION_EXCEPTION:
log.warn("Failed to freeze user {}: invalid status transition {}", user.getId(), error.getMessage());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage() + " is not allowed.");
break;
case INVALID_USER_STATUS_EXCEPTION:
log.warn("Failed to freeze user {}: invalid user status {}", user.getId(), error.getMessage());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage() + " is not a valid status.");
break;
case FORBIDDEN_EXCEPTION:
log.warn("Failed to freeze user {}: must be an Admin", user.getId());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + " permission denied.");
break;
default:
log.warn("Failed to freeze user {}: {}", user.getId(), exceptionState.getExceptionName());
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
break;
}
return "redirect:/admin";
} else {
// good
log.info("User {} has been frozen", user.getId());
redirectAttributes.addFlashAttribute(MESSAGE_SUCCESS, "User " + user.getEmail() + " has been banned.");
return "redirect:/admin";
}
}
private String unfreezeUser(final User2 user, RedirectAttributes redirectAttributes) throws IOException {
log.info("Unfreezing user {}, email {}", user.getId(), user.getEmail());
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response = restTemplate.exchange(
properties.getSioUsersStatusUrl(user.getId(), UserStatus.APPROVED.toString()),
HttpMethod.PUT, request, String.class);
String responseBody = response.getBody().toString();
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case USER_NOT_FOUND_EXCEPTION:
log.warn("Failed to unfreeze user {}: user not found", user.getId());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + " user " + user.getEmail() + " not found.");
break;
case INVALID_STATUS_TRANSITION_EXCEPTION:
log.warn("Failed to unfreeze user {}: invalid status transition {}", user.getId(), error.getMessage());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage() + " is not allowed.");
break;
case INVALID_USER_STATUS_EXCEPTION:
log.warn("Failed to unfreeze user {}: invalid user status {}", user.getId(), error.getMessage());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage() + " is not a valid status.");
break;
case FORBIDDEN_EXCEPTION:
log.warn("Failed to unfreeze user {}: must be an Admin", user.getId());
redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + " permission denied.");
break;
default:
log.warn("Failed to unfreeze user {}: {}", user.getId(), exceptionState.getExceptionName());
redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
break;
}
return "redirect:/admin";
} else {
// good
log.info("User {} has been unfrozen", user.getId());
redirectAttributes.addFlashAttribute(MESSAGE_SUCCESS, "User " + user.getEmail() + " has been unbanned.");
return "redirect:/admin";
}
}
// @RequestMapping("/admin/experiments/remove/{expId}")
// public String adminRemoveExp(@PathVariable Integer expId) {
// int teamId = experimentManager.getExperimentByExpId(expId).getTeamId();
// experimentManager.adminRemoveExperiment(expId);
//
// // decrease exp count to be display on Teams page
// teamManager.decrementExperimentCount(teamId);
// return "redirect:/admin";
// }
// @RequestMapping(value="/admin/data/contribute", method=RequestMethod.GET)
// public String adminContributeDataset(Model model) {
// model.addAttribute("dataset", new Dataset());
//
// File rootFolder = new File(App.ROOT);
// List<String> fileNames = Arrays.stream(rootFolder.listFiles())
// .map(f -> f.getError())
// .collect(Collectors.toList());
//
// model.addAttribute("files",
// Arrays.stream(rootFolder.listFiles())
// .sorted(Comparator.comparingLong(f -> -1 * f.lastModified()))
// .map(f -> f.getError())
// .collect(Collectors.toList())
// );
//
// return "admin_contribute_data";
// }
// @RequestMapping(value="/admin/data/contribute", method=RequestMethod.POST)
// public String validateAdminContributeDataset(@ModelAttribute("dataset") Dataset dataset, HttpSession session, @RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) throws IOException {
// BufferedOutputStream stream = null;
// FileOutputStream fileOutputStream = null;
// // TODO
// // validation
// // get file from user upload to server
// if (!file.isEmpty()) {
// try {
// String fileName = getSessionIdOfLoggedInUser(session) + "-" + file.getOriginalFilename();
// fileOutputStream = new FileOutputStream(new File(App.ROOT + "/" + fileName));
// stream = new BufferedOutputStream(fileOutputStream);
// FileCopyUtils.copy(file.getInputStream(), stream);
// redirectAttributes.addFlashAttribute(MESSAGE,
// "You successfully uploaded " + file.getOriginalFilename() + "!");
// datasetManager.addDataset(getSessionIdOfLoggedInUser(session), dataset, file.getOriginalFilename());
// }
// catch (Exception e) {
// redirectAttributes.addFlashAttribute(MESSAGE,
// "You failed to upload " + file.getOriginalFilename() + " => " + e.getMessage());
// } finally {
// if (stream != null) {
// stream.close();
// }
// if (fileOutputStream != null) {
// fileOutputStream.close();
// }
// }
// }
// else {
// redirectAttributes.addFlashAttribute(MESSAGE,
// "You failed to upload " + file.getOriginalFilename() + " because the file was empty");
// }
// return "redirect:/admin";
// }
// @RequestMapping("/admin/data/remove/{datasetId}")
// public String adminRemoveDataset(@PathVariable Integer datasetId) {
// datasetManager.removeDataset(datasetId);
// return "redirect:/admin";
// }
// @RequestMapping(value="/admin/node/add", method=RequestMethod.GET)
// public String adminAddNode(Model model) {
// model.addAttribute("node", new Node());
// return "admin_add_node";
// }
// @RequestMapping(value="/admin/node/add", method=RequestMethod.POST)
// public String adminAddNode(@ModelAttribute("node") Node node) {
// // TODO
// // validate fields, eg should be integer
// nodeManager.addNode(node);
// return "redirect:/admin";
// }
//--------------------------Static pages for teams--------------------------
@RequestMapping("/teams/team_application_submitted")
public String teamAppSubmitFromTeamsPage() {
return "team_page_application_submitted";
}
@RequestMapping("/teams/join_application_submitted/{teamName}")
public String teamAppJoinFromTeamsPage(@PathVariable String teamName, Model model) throws WebServiceRuntimeException {
log.info("Redirecting to join application submitted page");
HttpEntity<String> request = createHttpEntityHeaderOnly();
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = restTemplate.exchange(properties.getTeamByName(teamName), HttpMethod.GET, request, String.class);
String responseBody = response.getBody().toString();
try {
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());
switch (exceptionState) {
case TEAM_NOT_FOUND_EXCEPTION:
log.warn("submitted join team request : team name error");
break;
default:
log.warn("submitted join team request : some other failure");
// possible sio or adapter connection fail
break;
}
return "redirect:/teams/join_team";
}
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
Team2 one = extractTeamInfo(responseBody);
model.addAttribute("team", one);
return "team_page_join_application_submitted";
}
//--------------------------Static pages for sign up--------------------------
@RequestMapping("/team_application_submitted")
public String teamAppSubmit() {
return "team_application_submitted";
}
/**
* A page to show new users has successfully registered to apply to join an existing team
* The page contains the team owner information which the users requested to join
*
* @param model The model which is passed from signup
* @return A success page otherwise an error page if the user tries to access this page directly
*/
@RequestMapping("/join_application_submitted")
public String joinTeamAppSubmit(Model model) {
// model attribute should be passed from /signup2
// team is required to display the team owner details
if (model.containsAttribute("team")) {
return "join_team_application_submitted";
}
return "error";
}
@RequestMapping("/email_not_validated")
public String emailNotValidated() {
return "email_not_validated";
}
@RequestMapping("/team_application_under_review")
public String teamAppUnderReview() {
return "team_application_under_review";
}
// model attribute name come from /login
@RequestMapping("/email_checklist")
public String emailChecklist(@ModelAttribute("statuschecklist") String status) {
return "email_checklist";
}
@RequestMapping("/join_application_awaiting_approval")
public String joinTeamAppAwaitingApproval(Model model) {
model.addAttribute("loginForm", new LoginForm());
model.addAttribute("signUpMergedForm", new SignUpMergedForm());
return "join_team_application_awaiting_approval";
}
//--------------------------Get List of scenarios filenames--------------------------
private List<String> getScenarioFileNameList() throws WebServiceRuntimeException {
log.info("Retrieving scenario file names");
// List<String> scenarioFileNameList = null;
// try {
// scenarioFileNameList = IOUtils.readLines(getClass().getClassLoader().getResourceAsStream("scenarios"), StandardCharsets.UTF_8);
// } catch (IOException e) {
// throw new WebServiceRuntimeException(e.getMessage());
// }
// File folder = null;
// try {
// folder = new ClassPathResource("scenarios").getFile();
// } catch (IOException e) {
// throw new WebServiceRuntimeException(e.getMessage());
// }
// List<String> scenarioFileNameList = new ArrayList<>();
// File[] files = folder.listFiles();
// for (File file : files) {
// if (file.isFile()) {
// scenarioFileNameList.add(file.getError());
// }
// }
// FIXME: hardcode list of filenames for now
List<String> scenarioFileNameList = new ArrayList<>();
scenarioFileNameList.add("Scenario 1 - Experiment with a single node");
scenarioFileNameList.add("Scenario 2 - Experiment with 2 nodes and 10Gb link");
scenarioFileNameList.add("Scenario 3 - Experiment with 3 nodes in a LAN");
scenarioFileNameList.add("Scenario 4 - Experiment with 2 nodes and customized link property");
// scenarioFileNameList.add("Scenario 4 - Two nodes linked with a 10Gbps SDN switch");
// scenarioFileNameList.add("Scenario 5 - Three nodes with Blockchain capabilities");
log.info("Scenario file list: {}", scenarioFileNameList);
return scenarioFileNameList;
}
private String getScenarioContentsFromFile(String scenarioFileName) throws WebServiceRuntimeException {
// FIXME: switch to better way of referencing scenario descriptions to actual filenames
String actualScenarioFileName;
if (scenarioFileName.contains("Scenario 1")) {
actualScenarioFileName = "basic1.ns";
} else if (scenarioFileName.contains("Scenario 2")) {
actualScenarioFileName = "basic2.ns";
} else if (scenarioFileName.contains("Scenario 3")) {
actualScenarioFileName = "basic3.ns";
} else if (scenarioFileName.contains("Scenario 4")) {
actualScenarioFileName = "basic4.ns";
} else {
// defaults to basic single node
actualScenarioFileName = "basic1.ns";
}
try {
log.info("Retrieving scenario files {}", getClass().getClassLoader().getResourceAsStream("scenarios/" + actualScenarioFileName));
List<String> lines = IOUtils.readLines(getClass().getClassLoader().getResourceAsStream("scenarios/" + actualScenarioFileName), StandardCharsets.UTF_8);
StringBuilder sb = new StringBuilder();
for (String line : lines) {
sb.append(line);
sb.append(System.getProperty("line.separator"));
}
log.info("Experiment ns file contents: {}", sb);
return sb.toString();
} catch (IOException e) {
throw new WebServiceRuntimeException(e.getMessage());
}
}
//---Check if user is a team owner and has any join request waiting for approval----
private boolean hasAnyJoinRequest(HashMap<Integer, Team> teamMapOwnedByUser) {
for (Map.Entry<Integer, Team> entry : teamMapOwnedByUser.entrySet()) {
Team currTeam = entry.getValue();
if (currTeam.isUserJoinRequestEmpty() == false) {
// at least one team has join user request
return true;
}
}
// loop through all teams but never return a single true
// therefore, user's controlled teams has no join request
return false;
}
//--------------------------MISC--------------------------
private int getSessionIdOfLoggedInUser(HttpSession session) {
return Integer.parseInt(session.getAttribute(SESSION_LOGGED_IN_USER_ID).toString());
}
private User2 extractUserInfo(String userJson) {
User2 user2 = new User2();
if (userJson == null) {
// return empty user
return user2;
}
JSONObject object = new JSONObject(userJson);
JSONObject userDetails = object.getJSONObject("userDetails");
JSONObject address = userDetails.getJSONObject("address");
user2.setId(object.getString("id"));
user2.setFirstName(getJSONStr(userDetails.getString("firstName")));
user2.setLastName(getJSONStr(userDetails.getString("lastName")));
user2.setJobTitle(userDetails.getString("jobTitle"));
user2.setEmail(userDetails.getString("email"));
user2.setPhone(userDetails.getString("phone"));
user2.setAddress1(address.getString("address1"));
user2.setAddress2(address.getString("address2"));
user2.setCountry(address.getString("country"));
user2.setRegion(address.getString("region"));
user2.setPostalCode(address.getString("zipCode"));
user2.setCity(address.getString("city"));
user2.setInstitution(userDetails.getString("institution"));
user2.setInstitutionAbbreviation(userDetails.getString("institutionAbbreviation"));
user2.setInstitutionWeb(userDetails.getString("institutionWeb"));
user2.setStatus(object.getString("status"));
user2.setEmailVerified(object.getBoolean("emailVerified"));
return user2;
}
private Team2 extractTeamInfo(String json) {
Team2 team2 = new Team2();
JSONObject object = new JSONObject(json);
JSONArray membersArray = object.getJSONArray("members");
try {
team2.setCreatedDate(formatZonedDateTime(object.get("applicationDate").toString()));
} catch (Exception e) {
log.warn("Error getting team application date {}", e);
team2.setCreatedDate(UNKNOWN);
}
team2.setId(object.getString("id"));
team2.setName(object.getString("name"));
team2.setDescription(object.getString("description"));
team2.setWebsite(object.getString("website"));
team2.setOrganisationType(object.getString("organisationType"));
team2.setStatus(object.getString("status"));
team2.setVisibility(object.getString("visibility"));
for (int i = 0; i < membersArray.length(); i++) {
JSONObject memberObject = membersArray.getJSONObject(i);
String userId = memberObject.getString("userId");
String teamMemberType = memberObject.getString(MEMBER_TYPE);
String teamMemberStatus = memberObject.getString("memberStatus");
User2 myUser = invokeAndExtractUserInfo(userId);
if (teamMemberType.equals(MemberType.MEMBER.name())) {
// add to pending members list for Members Awaiting Approval function
if (teamMemberStatus.equals(MemberStatus.PENDING.name())) {
team2.addPendingMembers(myUser);
}
} else if (teamMemberType.equals(MemberType.OWNER.name())) {
// explicit safer check
team2.setOwner(myUser);
}
team2.addMembersToStatusMap(MemberStatus.valueOf(teamMemberStatus), myUser);
}
team2.setMembersCount(team2.getMembersStatusMap().get(MemberStatus.APPROVED).size());
return team2;
}
// use to extract JSON Strings from services
// in the case where the JSON Strings are null, return "Connection Error"
private String getJSONStr(String jsonString) {
if (jsonString == null || jsonString.isEmpty()) {
return CONNECTION_ERROR;
}
return jsonString;
}
/**
* Checks if user is pending for join request approval from team leader
* Use for fixing bug for view experiment page where users previously can view the experiments just by issuing a join request
*
* @param json the response body after calling team service
* @param loginUserId the current logged in user id
* @return True if the user is anything but APPROVED, false otherwise
*/
private boolean isMemberJoinRequestPending(String loginUserId, String json) {
if (json == null) {
return true;
}
JSONObject object = new JSONObject(json);
JSONArray membersArray = object.getJSONArray("members");
for (int i = 0; i < membersArray.length(); i++) {
JSONObject memberObject = membersArray.getJSONObject(i);
String userId = memberObject.getString("userId");
String teamMemberStatus = memberObject.getString("memberStatus");
if (userId.equals(loginUserId) && !teamMemberStatus.equals(MemberStatus.APPROVED.toString())) {
return true;
}
}
log.info("User: {} is viewing experiment page", loginUserId);
return false;
}
private Team2 extractTeamInfoUserJoinRequest(String userId, String json) {
Team2 team2 = new Team2();
JSONObject object = new JSONObject(json);
JSONArray membersArray = object.getJSONArray("members");
for (int i = 0; i < membersArray.length(); i++) {
JSONObject memberObject = membersArray.getJSONObject(i);
String uid = memberObject.getString("userId");
String teamMemberStatus = memberObject.getString("memberStatus");
if (uid.equals(userId) && teamMemberStatus.equals(MemberStatus.PENDING.toString())) {
team2.setId(object.getString("id"));
team2.setName(object.getString("name"));
team2.setDescription(object.getString("description"));
team2.setWebsite(object.getString("website"));
team2.setOrganisationType(object.getString("organisationType"));
team2.setStatus(object.getString("status"));
team2.setVisibility(object.getString("visibility"));
team2.setMembersCount(membersArray.length());
return team2;
}
}
// no such member in the team found
return null;
}
protected Dataset extractDataInfo(String json) {
log.debug(json);
JSONObject object = new JSONObject(json);
Dataset dataset = new Dataset();
dataset.setId(object.getInt("id"));
dataset.setName(object.getString("name"));
dataset.setDescription(object.getString("description"));
dataset.setContributorId(object.getString("contributorId"));
dataset.addVisibility(object.getString("visibility"));
dataset.addAccessibility(object.getString("accessibility"));
try {
dataset.setReleasedDate(getZonedDateTime(object.get("releasedDate").toString()));
} catch (IOException e) {
log.warn("Error getting released date {}", e);
dataset.setReleasedDate(null);
}
dataset.setContributor(invokeAndExtractUserInfo(dataset.getContributorId()));
JSONArray resources = object.getJSONArray("resources");
for (int i = 0; i < resources.length(); i++) {
JSONObject resource = resources.getJSONObject(i);
DataResource dataResource = new DataResource();
dataResource.setId(resource.getLong("id"));
dataResource.setUri(resource.getString("uri"));
dataset.addResource(dataResource);
}
JSONArray approvedUsers = object.getJSONArray("approvedUsers");
for (int i = 0; i < approvedUsers.length(); i++) {
dataset.addApprovedUser(approvedUsers.getString(0));
}
return dataset;
}
protected User2 invokeAndExtractUserInfo(String userId) {
HttpEntity<String> request = createHttpEntityHeaderOnlyNoAuthHeader();
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getUser(userId), HttpMethod.GET, request, String.class);
} catch (Exception e) {
log.warn("User service not available to retrieve User: {}", userId);
return new User2();
}
return extractUserInfo(response.getBody().toString());
}
private Team2 invokeAndExtractTeamInfo(String teamId) {
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity responseEntity = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, request, String.class);
return extractTeamInfo(responseEntity.getBody().toString());
}
private Experiment2 extractExperiment(String experimentJson) {
Experiment2 experiment2 = new Experiment2();
JSONObject object = new JSONObject(experimentJson);
experiment2.setId(object.getLong("id"));
experiment2.setUserId(object.getString("userId"));
experiment2.setTeamId(object.getString(TEAM_ID));
experiment2.setTeamName(object.getString(TEAM_NAME));
experiment2.setName(object.getString("name"));
experiment2.setDescription(object.getString("description"));
experiment2.setNsFile(object.getString("nsFile"));
experiment2.setNsFileContent(object.getString("nsFileContent"));
experiment2.setIdleSwap(object.getInt("idleSwap"));
experiment2.setMaxDuration(object.getInt("maxDuration"));
return experiment2;
}
private Realization invokeAndExtractRealization(String teamName, Long id) {
HttpEntity<String> request = createHttpEntityHeaderOnly();
restTemplate.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity response = null;
try {
log.info("retrieving the latest exp status: {}", properties.getRealizationByTeam(teamName, id.toString()));
response = restTemplate.exchange(properties.getRealizationByTeam(teamName, id.toString()), HttpMethod.GET, request, String.class);
} catch (Exception e) {
return getCleanRealization();
}
String responseBody;
if (response.getBody() == null) {
return getCleanRealization();
} else {
responseBody = response.getBody().toString();
}
try {
if (RestUtil.isError(response.getStatusCode())) {
MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
log.warn("error in retrieving realization for team: {}, realization: {}", teamName, id);
return getCleanRealization();
} else {
// will throw JSONException if the format return by sio is not a valid JSOn format
// will occur if the realization details are still in the old format
return extractRealization(responseBody);
}
} catch (IOException | JSONException e) {
return getCleanRealization();
}
}
private Realization extractRealization(String json) {
log.info("extracting realization: {}", json);
Realization realization = new Realization();
JSONObject object = new JSONObject(json);
realization.setExperimentId(object.getLong("experimentId"));
realization.setExperimentName(object.getString("experimentName"));
realization.setUserId(object.getString("userId"));
realization.setTeamId(object.getString(TEAM_ID));
realization.setState(object.getString("state"));
String exp_report = "";
Object expDetailsObject = object.get("details");
log.info("exp detail object: {}", expDetailsObject);
if (expDetailsObject == JSONObject.NULL || expDetailsObject.toString().isEmpty()) {
log.info("set details empty");
realization.setDetails("");
realization.setNumberOfNodes(0);
} else {
log.info("exp report to string: {}", expDetailsObject.toString());
exp_report = expDetailsObject.toString();
realization.setDetails(exp_report);
JSONObject nodesInfoObject = new JSONObject(expDetailsObject.toString());
for (Object key : nodesInfoObject.keySet()) {
Map<String, String> nodeDetails = new HashMap<>();
String nodeName = (String) key;
JSONObject nodeDetailsJson = new JSONObject(nodesInfoObject.get(nodeName).toString());
nodeDetails.put("os", nodeDetailsJson.getString("os"));
nodeDetails.put("qualifiedName", nodeDetailsJson.getString("qualifiedName"));
nodeDetails.put(NODE_ID, nodeDetailsJson.getString(NODE_ID));
realization.addNodeDetails(nodeName, nodeDetails);
}
log.info("nodes info object: {}", nodesInfoObject);
realization.setNumberOfNodes(nodesInfoObject.keySet().size());
}
return realization;
}
/**
* @param zonedDateTimeJSON JSON string
* @return a date in the format MMM-d-yyyy
*/
protected String formatZonedDateTime(String zonedDateTimeJSON) throws Exception {
ZonedDateTime zonedDateTime = getZonedDateTime(zonedDateTimeJSON);
DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM-d-yyyy");
return zonedDateTime.format(format);
}
protected ZonedDateTime getZonedDateTime(String zonedDateTimeJSON) throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
return mapper.readValue(zonedDateTimeJSON, ZonedDateTime.class);
}
/**
* Creates a HttpEntity with a request body and header but no authorization header
* To solve the expired jwt token
*
* @param jsonString The JSON request converted to string
* @return A HttpEntity request
* @see HttpEntity createHttpEntityHeaderOnly() for request with only header
*/
protected HttpEntity<String> createHttpEntityWithBodyNoAuthHeader(String jsonString) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
return new HttpEntity<>(jsonString, headers);
}
/**
* Creates a HttpEntity that contains only a header and empty body but no authorization header
* To solve the expired jwt token
*
* @return A HttpEntity request
* @see HttpEntity createHttpEntityWithBody() for request with both body and header
*/
protected HttpEntity<String> createHttpEntityHeaderOnlyNoAuthHeader() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
return new HttpEntity<>(headers);
}
/**
* Creates a HttpEntity with a request body and header
*
* @param jsonString The JSON request converted to string
* @return A HttpEntity request
* @implNote Authorization header must be set to the JwTToken in the format [Bearer: TOKEN_ID]
* @see HttpEntity createHttpEntityHeaderOnly() for request with only header
*/
protected HttpEntity<String> createHttpEntityWithBody(String jsonString) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization", httpScopedSession.getAttribute(webProperties.getSessionJwtToken()).toString());
return new HttpEntity<>(jsonString, headers);
}
/**
* Creates a HttpEntity that contains only a header and empty body
*
* @return A HttpEntity request
* @implNote Authorization header must be set to the JwTToken in the format [Bearer: TOKEN_ID]
* @see HttpEntity createHttpEntityWithBody() for request with both body and header
*/
protected HttpEntity<String> createHttpEntityHeaderOnly() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization", httpScopedSession.getAttribute(webProperties.getSessionJwtToken()).toString());
return new HttpEntity<>(headers);
}
private void setSessionVariables(HttpSession session, String loginEmail, String id, String firstName, String userRoles, String token) {
User2 user = invokeAndExtractUserInfo(id);
session.setAttribute(webProperties.getSessionEmail(), loginEmail);
session.setAttribute(webProperties.getSessionUserId(), id);
session.setAttribute(webProperties.getSessionUserFirstName(), firstName);
session.setAttribute(webProperties.getSessionRoles(), userRoles);
session.setAttribute(webProperties.getSessionJwtToken(), "Bearer " + token);
log.info("Session variables - sessionLoggedEmail: {}, id: {}, name: {}, roles: {}, token: {}", loginEmail, id, user.getFirstName(), userRoles, token);
}
private void removeSessionVariables(HttpSession session) {
log.info("removing session variables: email: {}, userid: {}, user first name: {}", session.getAttribute(webProperties.getSessionEmail()), session.getAttribute(webProperties.getSessionUserId()), session.getAttribute(webProperties.getSessionUserFirstName()));
session.removeAttribute(webProperties.getSessionEmail());
session.removeAttribute(webProperties.getSessionUserId());
session.removeAttribute(webProperties.getSessionUserFirstName());
session.removeAttribute(webProperties.getSessionRoles());
session.removeAttribute(webProperties.getSessionJwtToken());
session.invalidate();
}
protected boolean validateIfAdmin(HttpSession session) {
//log.info("User: {} is logged on as: {}", session.getAttribute(webProperties.getSessionEmail()), session.getAttribute(webProperties.getSessionRoles()));
return session.getAttribute(webProperties.getSessionRoles()).equals(UserType.ADMIN.toString());
}
/**
* Ensure that only users of the team can realize or un-realize experiment
* A pre-condition is that the users must be approved.
* Teams must also be approved.
*
* @return the main experiment page
*/
private boolean checkPermissionRealizeExperiment(Realization realization, HttpSession session) {
// get list of teamids
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity userRespEntity = restTemplate.exchange(properties.getUser(session.getAttribute("id").toString()), HttpMethod.GET, request, String.class);
JSONObject object = new JSONObject(userRespEntity.getBody().toString());
JSONArray teamIdsJsonArray = object.getJSONArray("teams");
for (int i = 0; i < teamIdsJsonArray.length(); i++) {
String teamId = teamIdsJsonArray.get(i).toString();
if (teamId.equals(realization.getTeamId())) {
return true;
}
}
return false;
}
private String getTeamStatus(String teamId) {
Team2 team = invokeAndExtractTeamInfo(teamId);
return team.getStatus();
}
private Realization getCleanRealization() {
Realization realization = new Realization();
realization.setExperimentId(0L);
realization.setExperimentName("");
realization.setUserId("");
realization.setTeamId("");
realization.setState(RealizationState.ERROR.toString());
realization.setDetails("");
realization.setNumberOfNodes(0);
return realization;
}
/**
* Computes the number of teams that the user is in and the number of running experiments to populate data for the user dashboard
*
* @return a map in the form teams: numberOfTeams, experiments: numberOfExperiments
*/
private Map<String, Integer> getUserDashboardStats(String userId) {
int numberOfRunningExperiments = 0;
Map<String, Integer> userDashboardStats = new HashMap<>();
// get list of teamids
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity userRespEntity = restTemplate.exchange(properties.getUser(userId), HttpMethod.GET, request, String.class);
JSONObject object = new JSONObject(userRespEntity.getBody().toString());
JSONArray teamIdsJsonArray = object.getJSONArray("teams");
for (int i = 0; i < teamIdsJsonArray.length(); i++) {
String teamId = teamIdsJsonArray.get(i).toString();
HttpEntity<String> teamRequest = createHttpEntityHeaderOnly();
ResponseEntity teamResponse = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, teamRequest, String.class);
String teamResponseBody = teamResponse.getBody().toString();
if (!isMemberJoinRequestPending(userId, teamResponseBody)) {
// get experiments lists of the teams
HttpEntity<String> expRequest = createHttpEntityHeaderOnly();
ResponseEntity expRespEntity = restTemplate.exchange(properties.getExpListByTeamId(teamId), HttpMethod.GET, expRequest, String.class);
JSONArray experimentsArray = new JSONArray(expRespEntity.getBody().toString());
numberOfRunningExperiments = getNumberOfRunningExperiments(numberOfRunningExperiments, experimentsArray);
}
}
userDashboardStats.put(USER_DASHBOARD_TEAMS, teamIdsJsonArray.length());
userDashboardStats.put(USER_DASHBOARD_RUNNING_EXPERIMENTS, numberOfRunningExperiments);
userDashboardStats.put(USER_DASHBOARD_FREE_NODES, getNodes(NodeType.FREE));
return userDashboardStats;
}
private int getNumberOfRunningExperiments(int numberOfRunningExperiments, JSONArray experimentsArray) {
for (int k = 0; k < experimentsArray.length(); k++) {
Experiment2 experiment2 = extractExperiment(experimentsArray.getJSONObject(k).toString());
Realization realization = invokeAndExtractRealization(experiment2.getTeamName(), experiment2.getId());
if (realization.getState().equals(RealizationState.RUNNING.toString())) {
numberOfRunningExperiments++;
}
}
return numberOfRunningExperiments;
}
private SortedMap<String, Map<String, String>> getGlobalImages() throws IOException {
SortedMap<String, Map<String, String>> globalImagesMap = new TreeMap<>();
log.info("Retrieving list of global images from: {}", properties.getGlobalImages());
try {
HttpEntity<String> request = createHttpEntityHeaderOnlyNoAuthHeader();
ResponseEntity response = restTemplate.exchange(properties.getGlobalImages(), HttpMethod.GET, request, String.class);
ObjectMapper mapper = new ObjectMapper();
String json = new JSONObject(response.getBody().toString()).getString("images");
globalImagesMap = mapper.readValue(json, new TypeReference<SortedMap<String, Map<String, String>>>() {
});
} catch (RestClientException e) {
log.warn("Error connecting to service-image: {}", e);
}
return globalImagesMap;
}
private int getNodes(NodeType nodeType) {
String nodesCount;
log.info("Retrieving number of " + nodeType + " nodes from: {}", properties.getNodes(nodeType));
try {
HttpEntity<String> request = createHttpEntityHeaderOnlyNoAuthHeader();
ResponseEntity response = restTemplate.exchange(properties.getNodes(nodeType), HttpMethod.GET, request, String.class);
JSONObject object = new JSONObject(response.getBody().toString());
nodesCount = object.getString(nodeType.name());
} catch (RestClientException e) {
log.warn("Error connecting to service-telemetry: {}", e);
nodesCount = "0";
}
return Integer.parseInt(nodesCount);
}
private List<TeamUsageInfo> getTeamsUsageStatisticsForUser(String userId) {
List<TeamUsageInfo> usageInfoList = new ArrayList<>();
// get list of teamids
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity userRespEntity = restTemplate.exchange(properties.getUser(userId), HttpMethod.GET, request, String.class);
JSONObject object = new JSONObject(userRespEntity.getBody().toString());
JSONArray teamIdsJsonArray = object.getJSONArray("teams");
// get team info by team id
for (int i = 0; i < teamIdsJsonArray.length(); i++) {
String teamId = teamIdsJsonArray.get(i).toString();
HttpEntity<String> teamRequest = createHttpEntityHeaderOnly();
ResponseEntity teamResponse = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, teamRequest, String.class);
String teamResponseBody = teamResponse.getBody().toString();
if (!isMemberJoinRequestPending(userId, teamResponseBody)) {
TeamUsageInfo usageInfo = new TeamUsageInfo();
usageInfo.setId(teamId);
usageInfo.setName(new JSONObject(teamResponseBody).getString("name"));
usageInfo.setUsage(getUsageStatisticsByTeamId(teamId));
usageInfoList.add(usageInfo);
}
}
return usageInfoList;
}
private String getUsageStatisticsByTeamId(String id) {
log.info("Getting usage statistics for team {}", id);
HttpEntity<String> request = createHttpEntityHeaderOnly();
ResponseEntity response;
try {
response = restTemplate.exchange(properties.getUsageStat(id), HttpMethod.GET, request, String.class);
} catch (RestClientException e) {
log.warn("Error connecting to sio get usage statistics {}", e);
return "?";
}
return response.getBody().toString();
}
private TeamQuota extractTeamQuotaInfo(String responseBody) {
JSONObject object = new JSONObject(responseBody);
TeamQuota teamQuota = new TeamQuota();
Double charges = Double.parseDouble(accountingProperties.getCharges());
// amountUsed from SIO will never be null => not checking for null value
String usage = object.getString("usage"); // getting usage in String
BigDecimal amountUsed = new BigDecimal(usage); // using BigDecimal to handle currency
amountUsed = amountUsed.multiply(new BigDecimal(charges)); // usage X charges
//quota passed from SIO can be null , so we have to check for null value
if (object.has("quota")) {
Object budgetObject = object.optString("quota", null);
if (budgetObject == null) {
teamQuota.setBudget(""); // there is placeholder here
teamQuota.setResourcesLeft("Unlimited"); // not placeholder so can pass string over
} else {
Double budgetInDouble = object.getDouble("quota"); // retrieve budget from SIO in Double
BigDecimal budgetInBD = BigDecimal.valueOf(budgetInDouble); // handling currency using BigDecimal
// calculate resoucesLeft
BigDecimal resourceLeftInBD = budgetInBD.subtract(amountUsed);
resourceLeftInBD = resourceLeftInBD.divide(new BigDecimal(charges), 2, BigDecimal.ROUND_HALF_UP);
// set budget and resourceLeft
budgetInBD = budgetInBD.setScale(2, BigDecimal.ROUND_HALF_UP);
teamQuota.setBudget(budgetInBD.toString());
teamQuota.setResourcesLeft(resourceLeftInBD.toString());
}
}
teamQuota.setTeamId(object.getString(TEAM_ID));
amountUsed = amountUsed.setScale(2, BigDecimal.ROUND_HALF_UP);
teamQuota.setAmountUsed(amountUsed.toString());
return teamQuota;
}
}
|
DEV-919 setting quota
|
src/main/java/sg/ncl/MainController.java
|
DEV-919 setting quota
|
|
Java
|
apache-2.0
|
ee1a3df7cea2ed1b7d41b34d3a76b0e2e545d0ae
| 0
|
GerritCodeReview/plugins_github,GerritCodeReview/plugins_github,GerritCodeReview/plugins_github
|
// Copyright (C) 2015 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.googlesource.gerrit.plugins.github.notification;
import static javax.servlet.http.HttpServletResponse.SC_FORBIDDEN;
import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND;
import static javax.servlet.http.HttpServletResponse.SC_NO_CONTENT;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.io.CharStreams;
import com.google.gerrit.extensions.registration.DynamicItem;
import com.google.gerrit.httpd.WebSession;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gson.Gson;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Singleton;
import com.googlesource.gerrit.plugins.github.GitHubConfig;
import com.googlesource.gerrit.plugins.github.oauth.GitHubLogin;
import com.googlesource.gerrit.plugins.github.oauth.ScopedProvider;
import com.googlesource.gerrit.plugins.github.oauth.UserScopedProvider;
/**
* Handles webhook callbacks sent from Github. Delegates requests to
* implementations of {@link WebhookEventHandler}.
*/
@Singleton
public class WebhookServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Logger logger =
LoggerFactory.getLogger(WebhookServlet.class);
private static final String PACKAGE_NAME =
WebhookServlet.class.getPackage().getName();
private static final String SIGNATURE_PREFIX = "sha1=";
private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";
private final Gson gson;
private final Map<String, WebhookEventHandler<?>> handlerByName =
new ConcurrentHashMap<>();
private final Injector injector;
private final GitHubConfig config;
private final UserScopedProvider<GitHubLogin> loginProvider;
private final ScopedProvider<GitHubLogin> requestScopedLoginProvider;
private final DynamicItem<WebSession> session;
@Inject
public WebhookServlet(UserScopedProvider<GitHubLogin> loginProvider,
ScopedProvider<GitHubLogin> requestScopedLoginProvider,
GitHubConfig config, Gson gson, DynamicItem<WebSession> session,
Injector injector) {
this.loginProvider = loginProvider;
this.requestScopedLoginProvider = requestScopedLoginProvider;
this.injector = injector;
this.config = config;
this.gson = gson;
this.session = session;
}
private WebhookEventHandler<?> getWebhookHandler(String name) {
if (name == null) {
logger.error("Null event name: cannot find any handler for it");
return null;
}
WebhookEventHandler<?> handler = handlerByName.get(name);
if (handler != null) {
return handler;
}
try {
String className = eventClassName(name);
Class<?> clazz = Class.forName(className);
handler = (WebhookEventHandler<?>) injector.getInstance(clazz);
handlerByName.put(name, handler);
logger.info("Loaded {}", clazz.getName());
} catch (ClassNotFoundException e) {
logger.error("Handler '" + name + "' not found. Skipping", e);
}
return handler;
}
private String eventClassName(String name) {
String[] nameParts = name.split("_");
List<String> classNameParts =
Lists.transform(Arrays.asList(nameParts),
new Function<String, String>() {
@Override
public String apply(String part) {
return Character.toUpperCase(part.charAt(0))
+ part.substring(1);
}
});
return PACKAGE_NAME + "." + Joiner.on("").join(classNameParts)
+ "Handler";
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
if (Strings.emptyToNull(config.webhookUser) == null) {
logger.error("No webhookUser defined: cannot process GitHub events");
resp.sendError(SC_INTERNAL_SERVER_ERROR);
return;
}
WebhookEventHandler<?> handler =
getWebhookHandler(req.getHeader("X-Github-Event"));
if (handler == null) {
resp.sendError(SC_NOT_FOUND);
return;
}
BufferedReader reader = req.getReader();
String body = Joiner.on("\n").join(CharStreams.readLines(reader));
if (!validateSignature(req.getHeader("X-Hub-Signature"), body,
req.getCharacterEncoding())) {
logger.error("Signature mismatch to the payload");
resp.sendError(SC_FORBIDDEN);
return;
}
session.get().setUserAccountId(Account.Id.fromRef(config.webhookUser));
GitHubLogin login = loginProvider.get(config.webhookUser);
if (login == null || !login.isLoggedIn()) {
logger.error(
"Cannot login to github as {}. {}.webhookUser is not correctly configured?",
config.webhookUser, GitHubConfig.CONF_SECTION);
resp.setStatus(SC_INTERNAL_SERVER_ERROR);
return;
}
requestScopedLoginProvider.get(req).login(login.getToken());
if (callHander(handler, body)) {
resp.setStatus(SC_NO_CONTENT);
} else {
resp.sendError(SC_INTERNAL_SERVER_ERROR);
}
}
private <T> boolean callHander(WebhookEventHandler<T> handler, String jsonBody)
throws IOException {
T payload = gson.fromJson(jsonBody, handler.getPayloadType());
if (payload != null) {
return handler.doAction(payload);
} else {
logger.error("Cannot decode JSON payload '" + jsonBody + "' into "
+ handler.getPayloadType().getName());
return false;
}
}
/**
* validates callback signature sent from github
*
* @param signatureHeader signature HTTP request header of a github webhook
* @param payload HTTP request body
* @return true if webhook secret is not configured or signatureHeader is
* valid against payload and the secret, false if otherwise.
* @throws UnsupportedEncodingException
*/
private boolean validateSignature(String signatureHeader, String body,
String encoding) throws UnsupportedEncodingException {
byte[] payload = body.getBytes(encoding == null ? "UTF-8" : encoding);
if (config.webhookSecret == null || config.webhookSecret.equals("")) {
logger.debug("{}.webhookSecret not configured. Skip signature validation",
GitHubConfig.CONF_SECTION);
return true;
}
if (!StringUtils.startsWith(signatureHeader, SIGNATURE_PREFIX)) {
logger.error("Unsupported webhook signature type: {}", signatureHeader);
return false;
}
byte[] signature;
try {
signature = Hex.decodeHex(
signatureHeader.substring(SIGNATURE_PREFIX.length()).toCharArray());
} catch (DecoderException e) {
logger.error("Invalid signature: {}", signatureHeader);
return false;
}
return MessageDigest.isEqual(signature, getExpectedSignature(payload));
}
/**
* Calculates the expected signature of the payload
*
* @param payload payload to calculate a signature for
* @return signature of the payload
* @see <a href=
* "https://developer.github.com/webhooks/securing/#validating-payloads-from-github">
* Validating payloads from GitHub</a>
*/
private byte[] getExpectedSignature(byte[] payload) {
SecretKeySpec key =
new SecretKeySpec(config.webhookSecret.getBytes(), HMAC_SHA1_ALGORITHM);
Mac hmac;
try {
hmac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
hmac.init(key);
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("Hmac SHA1 must be supported", e);
} catch (InvalidKeyException e) {
throw new IllegalStateException(
"Hmac SHA1 must be compatible to Hmac SHA1 Secret Key", e);
}
return hmac.doFinal(payload);
}
}
|
github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/notification/WebhookServlet.java
|
// Copyright (C) 2015 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.googlesource.gerrit.plugins.github.notification;
import static javax.servlet.http.HttpServletResponse.SC_FORBIDDEN;
import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND;
import static javax.servlet.http.HttpServletResponse.SC_NO_CONTENT;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.io.CharStreams;
import com.google.gerrit.extensions.registration.DynamicItem;
import com.google.gerrit.httpd.WebSession;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gson.Gson;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Singleton;
import com.googlesource.gerrit.plugins.github.GitHubConfig;
import com.googlesource.gerrit.plugins.github.oauth.GitHubLogin;
import com.googlesource.gerrit.plugins.github.oauth.ScopedProvider;
import com.googlesource.gerrit.plugins.github.oauth.UserScopedProvider;
/**
* Handles webhook callbacks sent from Github. Delegates requests to
* implementations of {@link WebhookEventHandler}.
*/
@Singleton
public class WebhookServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Logger logger =
LoggerFactory.getLogger(WebhookServlet.class);
private static final String PACKAGE_NAME =
WebhookServlet.class.getPackage().getName();
private static final String SIGNATURE_PREFIX = "sha1=";
private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";
private final Gson gson;
private final Map<String, WebhookEventHandler<?>> handlerByName =
new ConcurrentHashMap<>();
private final Injector injector;
private final GitHubConfig config;
private final UserScopedProvider<GitHubLogin> loginProvider;
private final ScopedProvider<GitHubLogin> requestScopedLoginProvider;
private final DynamicItem<WebSession> session;
@Inject
public WebhookServlet(UserScopedProvider<GitHubLogin> loginProvider,
ScopedProvider<GitHubLogin> requestScopedLoginProvider,
GitHubConfig config, Gson gson, DynamicItem<WebSession> session,
Injector injector) {
this.loginProvider = loginProvider;
this.requestScopedLoginProvider = requestScopedLoginProvider;
this.injector = injector;
this.config = config;
this.gson = gson;
this.session = session;
}
private WebhookEventHandler<?> getWebhookHandler(String name) {
if (name == null) {
logger.error("Null event name: cannot find any handler for it");
return null;
}
WebhookEventHandler<?> handler = handlerByName.get(name);
if (handler != null) {
return handler;
}
try {
String className = eventClassName(name);
Class<?> clazz = Class.forName(className);
handler = (WebhookEventHandler<?>) injector.getInstance(clazz);
handlerByName.put(name, handler);
logger.info("Loaded {}", clazz.getName());
} catch (ClassNotFoundException e) {
logger.error("Handler '" + name + "' not found. Skipping", e);
}
return handler;
}
private String eventClassName(String name) {
String[] nameParts = name.split("_");
List<String> classNameParts =
Lists.transform(Arrays.asList(nameParts),
new Function<String, String>() {
@Override
public String apply(String part) {
return Character.toUpperCase(part.charAt(0))
+ part.substring(1);
}
});
return PACKAGE_NAME + "." + Joiner.on("").join(classNameParts)
+ "Handler";
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
if (Strings.emptyToNull(config.webhookUser) == null) {
logger.error("No webhookUser defined: cannot process GitHub events");
resp.sendError(SC_INTERNAL_SERVER_ERROR);
return;
}
WebhookEventHandler<?> handler =
getWebhookHandler(req.getHeader("X-Github-Event"));
if (handler == null) {
resp.sendError(SC_NOT_FOUND);
return;
}
BufferedReader reader = req.getReader();
String body = Joiner.on("\n").join(CharStreams.readLines(reader));
if (!validateSignature(req.getHeader("X-Hub-Signature"), body,
req.getCharacterEncoding())) {
logger.error("Signature mismatch to the payload");
resp.sendError(SC_FORBIDDEN);
return;
}
session.get().setUserAccountId(Account.Id.fromRef(config.webhookUser));
GitHubLogin login = loginProvider.get(config.webhookUser);
if (login == null || !login.isLoggedIn()) {
logger.error(
"Cannot login to github as {}. {}.webhookUser is not correctly configured?",
config.webhookUser, GitHubConfig.CONF_SECTION);
resp.setStatus(SC_INTERNAL_SERVER_ERROR);
return;
}
requestScopedLoginProvider.get(req).login(login.getToken());
if (callHander(handler, body)) {
resp.setStatus(SC_NO_CONTENT);
} else {
resp.sendError(SC_INTERNAL_SERVER_ERROR);
}
}
private <T> boolean callHander(WebhookEventHandler<T> handler, String jsonBody)
throws IOException {
T payload = gson.fromJson(jsonBody, handler.getPayloadType());
if (payload != null) {
return handler.doAction(payload);
} else {
logger.error("Cannot decode JSON payload '" + jsonBody + "' into "
+ handler.getPayloadType().getName());
return false;
}
}
/**
* validates callback signature sent from github
*
* @param signatureHeader signature HTTP request header of a github webhook
* @param payload HTTP request body
* @return true if webhook secret is not configured or signatureHeader is
* valid against payload and the secret, false if otherwise.
* @throws UnsupportedEncodingException
*/
private boolean validateSignature(String signatureHeader, String body,
String encoding) throws UnsupportedEncodingException {
byte[] payload = body.getBytes(encoding == null ? "UTF-8" : encoding);
if (config.webhookSecret == null || config.webhookSecret.equals("")) {
logger.debug("{}.webhookSecret not configured. Skip signature validation",
GitHubConfig.CONF_SECTION);
return true;
}
if (!StringUtils.startsWith(signatureHeader, SIGNATURE_PREFIX)) {
logger.error("Unsupported webhook signature type: {}", signatureHeader);
return false;
}
byte[] signature;
try {
signature = Hex.decodeHex(
signatureHeader.substring(SIGNATURE_PREFIX.length()).toCharArray());
} catch (DecoderException e) {
logger.error("Invalid signature: {}", signatureHeader);
return false;
}
return MessageDigest.isEqual(signature, getExpectedSignature(payload));
}
/**
* Calculates the expected signature of the payload
*
* @param payload payload to calculate a signature for
* @return signature of the payload
* @see <a href=
* "https://developer.github.com/webhooks/securing/#validating-payloads-from-github">
* Validating payloads from GitHub</a>
*/
private byte[] getExpectedSignature(byte[] payload) {
SecretKeySpec key =
new SecretKeySpec(config.webhookSecret.getBytes(), HMAC_SHA1_ALGORITHM);
Mac hmac;
try {
hmac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
hmac.init(key);
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("Hmac SHA1 must be supported", e);
} catch (InvalidKeyException e) {
throw new IllegalStateException(
"Hmac SHA1 must be compatible to Hmac SHA1 Secret Key", e);
}
return hmac.doFinal(payload);
}
}
|
Remove unused import in WebhookServlet
Change-Id: I4c28a926530cede47d64ed1e50cedfcd6ff298ca
|
github-plugin/src/main/java/com/googlesource/gerrit/plugins/github/notification/WebhookServlet.java
|
Remove unused import in WebhookServlet
|
|
Java
|
bsd-2-clause
|
8c39c7f537bff90e4f159203f478c1e7411464d3
| 0
|
andysan/jotify,andysan/jotify
|
package de.felixbruns.jotify.media;
import de.felixbruns.jotify.util.Hex;
/**
* Holds information about a file.
*
* @author Felix Bruns <felixbruns@web.de>
*
* @category Media
*/
public class File implements Comparable<File> {
public static final int BITRATE_96 = 96000;
public static final int BITRATE_160 = 160000;
public static final int BITRATE_320 = 320000;
/**
* The files 40-character hex identifier.
*/
private String id;
/**
* The files format. e.g. Ogg Vorbis,320000,...
*/
private String format;
/**
* Creates an empty {@link File} object.
*/
protected File(){
this.id = null;
this.format = null;
}
/**
* Creates a {@link File} object with the specified {@code id} and {@code format}.
*
* @param id Id of the file.
* @param format Format of the file.
*
* @throws IllegalArgumentException If the given id is invalid.
*/
public File(String id, String format){
/* Check if id string is valid. */
if(id == null || id.length() != 40 || !Hex.isHex(id)){
throw new IllegalArgumentException("Expecting a 40-character hex string.");
}
/* Set object properties. */
this.id = id;
this.format = format;
}
/**
* Get the files identifier.
*
* @return A 40-character identifier.
*/
public String getId(){
return this.id;
}
/**
* Set the files identifier.
*
* @param id A 40-character identifier.
*
* @throws IllegalArgumentException If the given id is invalid.
*/
public void setId(String id){
/* Check if id string is valid. */
if(id == null || id.length() != 40 || !Hex.isHex(id)){
throw new IllegalArgumentException("Expecting a 40-character hex string.");
}
this.id = id;
}
/**
* Get the files format.
*
* @return A format string including codec and bitrate.
*/
public String getFormat(){
return this.format;
}
/**
* Set the files format.
*
* @param format A format string including codec and bitrate.
*/
public void setFormat(String format){
this.format = format;
}
/**
* Get the files bitrate
*
* @return An integer.
*/
public int getBitrate(){
return Integer.parseInt(this.format.split(",")[1]);
}
/**
* Determines if an object is equal to this {@link File} object.
* If both objects are {@link File} objects, it will compare their identifiers.
*
* @param o Another object to compare.
*
* @return true of the objects are equal, false otherwise.
*/
public boolean equals(Object o){
if(o instanceof File){
File f = (File)o;
if(this.id.equals(f.id)){
return true;
}
}
return false;
}
/**
* Return the hash code of this {@link File} object. This will give the value returned
* by the {@code hashCode} method of the identifier string.
*
* @return The {@link File} objects hash code.
*/
public int hashCode(){
return (this.id != null) ? this.id.hashCode() : 0;
}
/**
* Compares two {@link File} objects. A file is considered greater than another file,
* if its bitrate is higher.
*
* @param f Another {@link File} to compare.
*
* @return A negative integer, zero, or a positive integer as this file is less than,
* equal to, or greater than the specified file.
*/
public int compareTo(File f){
return this.getBitrate() - f.getBitrate();
}
public String toString(){
return String.format("[File: %s]", this.format);
}
}
|
src/de/felixbruns/jotify/media/File.java
|
package de.felixbruns.jotify.media;
import de.felixbruns.jotify.util.Hex;
/**
* Holds information about a file.
*
* @author Felix Bruns <felixbruns@web.de>
*
* @category Media
*/
public class File implements Comparable<File> {
/**
* The files 40-character hex identifier.
*/
private String id;
/**
* The files format. e.g. Ogg Vorbis,320000,...
*/
private String format;
/**
* Creates an empty {@link File} object.
*/
protected File(){
this.id = null;
this.format = null;
}
/**
* Creates a {@link File} object with the specified {@code id} and {@code format}.
*
* @param id Id of the file.
* @param format Format of the file.
*
* @throws IllegalArgumentException If the given id is invalid.
*/
public File(String id, String format){
/* Check if id string is valid. */
if(id == null || id.length() != 40 || !Hex.isHex(id)){
throw new IllegalArgumentException("Expecting a 40-character hex string.");
}
/* Set object properties. */
this.id = id;
this.format = format;
}
/**
* Get the files identifier.
*
* @return A 40-character identifier.
*/
public String getId(){
return this.id;
}
/**
* Set the files identifier.
*
* @param id A 40-character identifier.
*
* @throws IllegalArgumentException If the given id is invalid.
*/
public void setId(String id){
/* Check if id string is valid. */
if(id == null || id.length() != 40 || !Hex.isHex(id)){
throw new IllegalArgumentException("Expecting a 40-character hex string.");
}
this.id = id;
}
/**
* Get the files format.
*
* @return A format string including codec and bitrate.
*/
public String getFormat(){
return this.format;
}
/**
* Set the files format.
*
* @param format A format string including codec and bitrate.
*/
public void setFormat(String format){
this.format = format;
}
/**
* Get the files bitrate
*
* @return An integer.
*/
public int getBitrate(){
return Integer.parseInt(this.format.split(",")[1]);
}
/**
* Determines if an object is equal to this {@link File} object.
* If both objects are {@link File} objects, it will compare their identifiers.
*
* @param o Another object to compare.
*
* @return true of the objects are equal, false otherwise.
*/
public boolean equals(Object o){
if(o instanceof File){
File f = (File)o;
if(this.id.equals(f.id)){
return true;
}
}
return false;
}
/**
* Return the hash code of this {@link File} object. This will give the value returned
* by the {@code hashCode} method of the identifier string.
*
* @return The {@link File} objects hash code.
*/
public int hashCode(){
return (this.id != null) ? this.id.hashCode() : 0;
}
/**
* Compares two {@link File} objects. A file is considered greater than another file,
* if its bitrate is higher.
*
* @param f Another {@link File} to compare.
*
* @return A negative integer, zero, or a positive integer as this file is less than,
* equal to, or greater than the specified file.
*/
public int compareTo(File f){
return this.getBitrate() - f.getBitrate();
}
public String toString(){
return String.format("[File: %s]", this.format);
}
}
|
Add bitrate constants to File class.
|
src/de/felixbruns/jotify/media/File.java
|
Add bitrate constants to File class.
|
|
Java
|
bsd-3-clause
|
77aa4a148df5bfb5eec56a0b4d2309bbf469e0e0
| 0
|
nyholku/purejavacomm,gchauvet/purejavacomm,nyholku/purejavacomm,nyholku/purejavacomm,gchauvet/purejavacomm
|
/*
* Copyright (c) 2011, Kustaa Nyholm / SpareTimeLabs
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* Neither the name of the Kustaa Nyholm or SpareTimeLabs nor the names of its
* contributors may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*/
package jtermios.windows;
import java.nio.ByteBuffer;
import java.util.*;
import com.sun.jna.*;
import com.sun.jna.ptr.IntByReference;
import static jtermios.JTermios.*;
import static jtermios.JTermios.JTermiosLogging.*;
import jtermios.*;
import jtermios.windows.WinAPI.*;
import static jtermios.windows.WinAPI.*;
import static jtermios.windows.WinAPI.DCB.*;
public class JTermiosImpl implements jtermios.JTermios.JTermiosInterface {
private volatile int m_ErrNo = 0;
private volatile boolean m_PortFDs[] = new boolean[FDSetImpl.FD_SET_SIZE];
private volatile Hashtable<Integer, Port> m_OpenPorts = new Hashtable<Integer, Port>();
private class Port {
volatile int m_FD = -1;
volatile boolean m_Locked;
volatile HANDLE m_Comm;
volatile int m_OpenFlags;
volatile DCB m_DCB = new DCB();
volatile COMMTIMEOUTS m_Timeouts = new COMMTIMEOUTS();
volatile COMSTAT m_ClearStat = new COMSTAT();
volatile int[] m_ClearErr = { 0 };
volatile Memory m_RdBuffer = new Memory(2048);
volatile COMSTAT m_RdStat = new COMSTAT();
volatile int[] m_RdErr = { 0 };
volatile int m_RdN[] = { 0 };
volatile OVERLAPPED m_RdOVL = new OVERLAPPED();
volatile Memory m_WrBuffer = new Memory(2048);
volatile COMSTAT m_WrStat = new COMSTAT();
volatile int[] m_WrErr = { 0 };
volatile int m_WrN[] = { 0 };
volatile OVERLAPPED m_WrOVL = new OVERLAPPED();
volatile int m_SelN[] = { 0 };
volatile OVERLAPPED m_SelOVL = new OVERLAPPED();
volatile IntByReference m_EvenFlags = new IntByReference();
volatile Termios m_Termios = new Termios();
volatile int MSR; // initial value
synchronized public void fail() throws Fail {
int err = GetLastError();
Memory buffer = new Memory(2048);
int res = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, null, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buffer, (int) buffer.size(), null);
log = log && log(1, "fail() %s, Windows GetLastError()= %d, %s\n", lineno(1), err, buffer.getString(0, true));
// FIXME here convert from Windows error code to 'posix' error code
Fail f = new Fail();
throw f;
}
synchronized public void lock() throws InterruptedException {
if (m_Locked)
wait();
m_Locked = true;
}
synchronized public void unlock() {
if (!m_Locked)
throw new IllegalArgumentException("Port was not locked");
m_Locked = false;
}
public Port() {
synchronized (JTermiosImpl.this) {
m_FD = -1;
for (int i = 0; i < m_PortFDs.length; ++i) {
if (!m_PortFDs[i]) {
m_FD = i;
m_PortFDs[i] = true;
m_OpenPorts.put(m_FD, this);
return;
}
}
throw new RuntimeException("Too many ports open");
}
}
public void close() {
synchronized (JTermiosImpl.this) {
if (m_FD >= 0) {
m_OpenPorts.remove(m_FD);
m_PortFDs[m_FD] = false;
m_FD = -1;
}
HANDLE h; /// 'hEvent' might never have been 'read' so read it to this var first
h = (HANDLE) m_RdOVL.readField("hEvent");
m_RdOVL = null;
if (h != null && !h.equals(NULL) && !h.equals(INVALID_HANDLE_VALUE))
CloseHandle(h);
h = (HANDLE) m_WrOVL.readField("hEvent");
m_WrOVL = null;
if (h != null && !h.equals(NULL) && !h.equals(INVALID_HANDLE_VALUE))
CloseHandle(h);
h = (HANDLE) m_SelOVL.readField("hEvent");
m_WrOVL = m_SelOVL;
if (h != null && !h.equals(NULL) && !h.equals(INVALID_HANDLE_VALUE))
CloseHandle(h);
if (m_Comm != null && m_Comm != NULL && m_Comm != INVALID_HANDLE_VALUE)
CloseHandle(m_Comm);
m_Comm = null;
}
}
};
static class Fail extends Exception {
}
static private class FDSetImpl extends FDSet {
static final int FD_SET_SIZE = 256; // Windows supports max 255 serial ports so this is enough
static final int NFBBITS = 32;
int[] bits = new int[(FD_SET_SIZE + NFBBITS - 1) / NFBBITS];
}
public JTermiosImpl() {
log = log && log(1, "instantiating %s\n", getClass().getCanonicalName());
}
public void cfmakeraw(Termios termios) {
termios.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
termios.c_oflag &= ~OPOST;
termios.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
termios.c_cflag &= ~(CSIZE | PARENB);
termios.c_cflag |= CS8;
}
public int fcntl(int fd, int cmd, int arg) {
Port port = getPort(fd);
if (port == null)
return -1;
if (F_SETFL == cmd)
port.m_OpenFlags = arg;
else if (F_GETFL == cmd)
return port.m_OpenFlags;
else {
m_ErrNo = ENOTSUP;
return -1;
}
return 0;
}
public int tcdrain(int fd) {
Port port = getPort(fd);
if (port == null)
return -1;
try {
synchronized (port.m_WrBuffer) {
if (!FlushFileBuffers(port.m_Comm))
port.fail();
return 0;
}
} catch (Fail f) {
return -1;
}
}
public int cfgetispeed(Termios termios) {
return termios.c_ispeed;
}
public int cfgetospeed(Termios termios) {
return termios.c_ospeed;
}
public int cfsetispeed(Termios termios, int speed) {
termios.c_ispeed = speed;
return 0;
}// Error code for Interrupted = EINTR
public int cfsetospeed(Termios termios, int speed) {
termios.c_ospeed = speed;
return 0;
}
public int open(String filename, int flags) {
Port port = new Port();
port.m_OpenFlags = flags;
try {
if (!filename.startsWith("\\\\"))
filename = "\\\\.\\" + filename;
port.m_Comm = CreateFileW(new WString(filename), GENERIC_READ | GENERIC_WRITE, 0, null, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, null);
if (INVALID_HANDLE_VALUE == port.m_Comm)
port.fail();
if (!SetupComm(port.m_Comm, (int) port.m_RdBuffer.size(), (int) port.m_WrBuffer.size()))
port.fail(); // FIXME what would be appropriate error code here
cfmakeraw(port.m_Termios);
cfsetispeed(port.m_Termios, B9600);
cfsetospeed(port.m_Termios, B9600);
port.m_Termios.c_cc[VTIME] = 0;
port.m_Termios.c_cc[VMIN] = 0;
updateFromTermios(port);
port.m_RdOVL.writeField("hEvent", CreateEventA(null, true, false, null));
if (port.m_RdOVL.hEvent == INVALID_HANDLE_VALUE)
port.fail();
port.m_WrOVL.writeField("hEvent", CreateEventA(null, true, false, null));
if (port.m_WrOVL.hEvent == INVALID_HANDLE_VALUE)
port.fail();
port.m_SelOVL.writeField("hEvent", CreateEventA(null, true, false, null));
if (port.m_SelOVL.hEvent == INVALID_HANDLE_VALUE)
port.fail();
return port.m_FD;
} catch (Exception f) {
if (port != null)
port.close();
return -1;
}
}
private static void nanoSleep(long nsec) throws Fail {
try {
Thread.sleep((int) (nsec / 1000000), (int) (nsec % 1000000));
} catch (InterruptedException ie) {
throw new Fail();
}
}
private int getCharBits(Termios tios) {
int cs = 8; // default to 8
if ((tios.c_cflag & CSIZE) == CS5)
cs = 5;
if ((tios.c_cflag & CSIZE) == CS6)
cs = 6;
if ((tios.c_cflag & CSIZE) == CS7)
cs = 7;
if ((tios.c_cflag & CSIZE) == CS8)
cs = 8;
if ((tios.c_cflag & CSTOPB) != 0)
cs++; // extra stop bit
if ((tios.c_cflag & PARENB) != 0)
cs++; // parity adds an other bit
cs += 1 + 1; // start bit + stop bit
return cs;
}
private static int min(int a, int b) {
return a < b ? a : b;
}
private static int max(int a, int b) {
return a > b ? a : b;
}
public int read(int fd, byte[] buffer, int length) {
Port port = getPort(fd);
if (port == null)
return -1;
synchronized (port.m_RdBuffer) {
try {
// coldly limit reads to internal buffer size
if (length > port.m_RdBuffer.size())
length = (int) port.m_RdBuffer.size();
if (length == 0)
return 0;
int error;
if ((port.m_OpenFlags & O_NONBLOCK) != 0) {
if (!ClearCommError(port.m_Comm, port.m_RdErr, port.m_RdStat))
port.fail();
int available = port.m_RdStat.cbInQue;
if (available == 0) {
m_ErrNo = EAGAIN;
return -1;
}
length = min(length, available);
} else {
int vtime = port.m_Termios.c_cc[VTIME];
int vmin = port.m_Termios.c_cc[VMIN];
if (!ClearCommError(port.m_Comm, port.m_RdErr, port.m_RdStat))
port.fail();
int available = port.m_RdStat.cbInQue;
if (vmin == 0 && vtime == 0) {
if (available == 0)
return 0;
length = min(length, available);
}
if (vmin > 0)
length = min(max(vmin, available), length);
}
if (!ResetEvent(port.m_RdOVL.hEvent))
port.fail();
if (!ReadFile(port.m_Comm, port.m_RdBuffer, length, port.m_RdN, port.m_RdOVL)) {
if (GetLastError() != ERROR_IO_PENDING)
port.fail();
if (WaitForSingleObject(port.m_RdOVL.hEvent, INFINITE) != WAIT_OBJECT_0)
port.fail();
if (!GetOverlappedResult(port.m_Comm, port.m_RdOVL, port.m_RdN, true))
port.fail();
}
port.m_RdBuffer.read(0, buffer, 0, port.m_RdN[0]);
return port.m_RdN[0];
} catch (Fail ie) {
return -1;
}
}
}
public int write(int fd, byte[] buffer, int length) {
Port port = getPort(fd);
if (port == null)
return -1;
synchronized (port.m_WrBuffer) {
try {
if ((port.m_OpenFlags & O_NONBLOCK) != 0) {
if (!ClearCommError(port.m_Comm, port.m_WrErr, port.m_WrStat))
port.fail();
int room = (int) port.m_WrBuffer.size() - port.m_WrStat.cbOutQue;
if (length > room)
length = room;
}
int old_flag;
if (!ResetEvent(port.m_WrOVL.hEvent))
port.fail();
port.m_WrBuffer.write(0, buffer, 0, length); // copy from buffer to Memory
boolean ok = WriteFile(port.m_Comm, port.m_WrBuffer, length, port.m_WrN, port.m_WrOVL);
if (!ok) {
if (GetLastError() != ERROR_IO_PENDING)
port.fail();
while (true) {
// FIXME would need to implement thread interruption
int res = WaitForSingleObject(port.m_WrOVL.hEvent, INFINITE);
if (res == WAIT_TIMEOUT) {
clearCommErrors(port);
log = log && log(1, "write pending, cbInQue %d cbOutQue %d\n", port.m_ClearStat.cbInQue, port.m_ClearStat.cbOutQue);
continue;
}
if (!GetOverlappedResult(port.m_Comm, port.m_WrOVL, port.m_WrN, false))
port.fail();
break;
}
}
return port.m_WrN[0];
} catch (Fail f) {
return -1;
}
}
}
public int close(int fd) {
Port port = getPort(fd);
if (port == null)
return -1;
port.close();
return 0;
}
public int tcflush(int fd, int queue) {
Port port = getPort(fd);
if (port == null)
return -1;
try {
if (queue == TCIFLUSH) {
if (!PurgeComm(port.m_Comm, PURGE_RXABORT))
port.fail();
} else if (queue == TCOFLUSH) {
if (!PurgeComm(port.m_Comm, PURGE_TXABORT))
port.fail();
} else if (queue == TCIOFLUSH) {
if (!PurgeComm(port.m_Comm, PURGE_TXABORT))
port.fail();
if (!PurgeComm(port.m_Comm, PURGE_RXABORT))
port.fail();
} else {
m_ErrNo = ENOTSUP;
return -1;
}
return 0;
} catch (Fail f) {
return -1;
}
}
/*
* (non-Javadoc) Basically this is wrong, as tcsetattr is supposed to set
* only those things it can support and tcgetattr is the used to see that
* what actually happened. In this instance tcsetattr never fails and
* tcgetattr always returns the last settings even though it possible (even
* likely) that tcsetattr was not able to carry out all settings, as there
* is no 1:1 mapping between Windows Comm API and posix/termios API.
*
* @see jtermios.JTermios.JTermiosInterface#tcgetattr(int, jtermios.Termios)
*/
public int tcgetattr(int fd, Termios termios) {
Port port = getPort(fd);
if (port == null)
return -1;
termios.set(port.m_Termios);
return 0;
}
public int tcsendbreak(int fd, int duration) {
Port port = getPort(fd);
if (port == null)
return -1;
try {
if (!SetCommBreak(port.m_Comm))
port.fail();
nanoSleep(duration * 250000000);
if (!ClearCommBreak(port.m_Comm))
port.fail();
return 0;
} catch (Fail f) {
return -1;
}
}
public int tcsetattr(int fd, int cmd, Termios termios) {
if (cmd != TCSANOW)
log(0, "tcsetattr only supports TCSANOW");
Port port = getPort(fd);
if (port == null)
return -1;
synchronized (port.m_Termios) {
try {
port.m_Termios.set(termios);
updateFromTermios(port);
return 0;
} catch (Fail f) {
return -1;
}
}
}
//FIXME this needs serious code review from people who know this stuff...
public int updateFromTermios(Port port) throws Fail {
Termios tios = port.m_Termios;
DCB dcb = port.m_DCB;
dcb.DCBlength = dcb.size();
dcb.BaudRate = tios.c_ospeed;
if (tios.c_ospeed != tios.c_ispeed)
log(0, "c_ospeed (%d) != c_ispeed (%d)\n", tios.c_ospeed, tios.c_ispeed);
int c_cflag = tios.c_cflag;
int c_iflag = tios.c_iflag;
int c_oflag = tios.c_oflag;
int flags = 0;
// rxtx does: if ( s_termios->c_iflag & ISTRIP ) dcb.fBinary = FALSE; but Winapi doc says fBinary always true
flags |= fBinary;
if ((c_cflag & PARENB) != 0)
flags |= fParity;
if ((c_iflag & IXON) != 0)
flags |= fOutX;
if ((c_iflag & IXOFF) != 0)
flags |= fInX;
if ((c_iflag & IXANY) != 0)
flags |= fTXContinueOnXoff;
if ((c_iflag & CRTSCTS) != 0) {
flags |= fRtsControl;
flags |= fOutxCtsFlow;
;
}
// Following have no corresponding functionality in unix termios
//fOutxDsrFlow = 0x00000008;
//fDtrControl = 0x00000030;
//fDsrSensitivity = 0x00000040;
//fErrorChar = 0x00000400;
//fNull = 0x00000800;
//fAbortOnError = 0x00004000;
//fDummy2 = 0xFFFF8000;
dcb.fFlags = flags;
dcb.XonLim = 128; // rxtx sets there to 0 but Windows API doc says must not be 0
dcb.XoffLim = 128;
byte cs = 8;
int csize = c_cflag & CSIZE;
if (csize == CS5)
cs = 5;
if (csize == CS6)
cs = 6;
if (csize == CS7)
cs = 7;
if (csize == CS8)
cs = 8;
dcb.ByteSize = cs;
if ((c_cflag & PARENB) != 0) {
if ((c_cflag & PARODD) != 0 && (c_cflag & CMSPAR) != 0)
dcb.Parity = MARKPARITY;
else if ((c_cflag & PARODD) != 0)
dcb.Parity = ODDPARITY;
else if ((c_cflag & CMSPAR) != 0)
dcb.Parity = SPACEPARITY;
else
dcb.Parity = EVENPARITY;
} else
dcb.Parity = NOPARITY;
dcb.StopBits = (tios.c_cflag & CSTOPB) != 0 ? TWOSTOPBITS : ONESTOPBIT;
dcb.XonChar = tios.c_cc[VSTART];
dcb.XoffChar = tios.c_cc[VSTOP];
dcb.ErrorChar = 0;
// rxtx has some thing like
// if ( EV_BREAK|EV_CTS|EV_DSR|EV_ERR|EV_RING | ( EV_RLSD & EV_RXFLAG ) )
// dcb.EvtChar = '\n';
//else
// dcb.EvtChar = '\0';
// But those are all defines so there is something fishy there?
dcb.EvtChar = '\n';
dcb.EofChar = tios.c_cc[VEOF];
int vmin = port.m_Termios.c_cc[VMIN] & 0xFF;
int vtime = (port.m_Termios.c_cc[VTIME] & 0xFF) * 100;
COMMTIMEOUTS touts = port.m_Timeouts;
// There are really no write timeouts in classic unix termios
// FIXME test that we can still interrupt the tread
touts.WriteTotalTimeoutConstant = 0;
touts.WriteTotalTimeoutMultiplier = 0;
if (vmin == 0 && vtime == 0) {
// VMIN = 0 and VTIME = 0 => totally non blocking,if data is
// available, return it, ie this is poll operation
touts.ReadIntervalTimeout = MAXDWORD;
touts.ReadTotalTimeoutConstant = 0;
touts.ReadTotalTimeoutMultiplier = 0;
}
if (vmin == 0 && vtime > 0) {
// VMIN = 0 and VTIME > 0 => timed read, return as soon as data is
// available, VTIME = total time
touts.ReadIntervalTimeout = MAXDWORD;
touts.ReadTotalTimeoutConstant = vtime;
touts.ReadTotalTimeoutMultiplier = MAXDWORD;
}
if (vmin > 0 && vtime > 0) {
// VMIN > 0 and VTIME > 0 => blocks until VMIN chars has arrived or
// VTIME between chars expired
// 1) will block if nothing arrives
touts.ReadIntervalTimeout = vtime;
touts.ReadTotalTimeoutConstant = 0;
touts.ReadTotalTimeoutMultiplier = 0;
}
if (vmin > 0 && vtime == 0) {
// VMIN > 0 and VTIME = 0 => blocks until VMIN characters have been
// received
touts.ReadIntervalTimeout = 0;
touts.ReadTotalTimeoutConstant = 0;
touts.ReadTotalTimeoutMultiplier = 0;
}
if (!SetCommState(port.m_Comm, dcb))
port.fail();
if (!SetCommTimeouts(port.m_Comm, port.m_Timeouts))
port.fail();
return 0;
}
private void maskToFDSets(Port port, FDSet readfds, FDSet writefds, FDSet exceptfds) {
int emask = port.m_EvenFlags.getValue();
int fd = port.m_FD;
if ((emask & EV_RXCHAR) != 0)
FD_SET(fd, readfds);
if ((emask & EV_TXEMPTY) != 0)
FD_SET(fd, writefds);
}
private void clearCommErrors(Port port) throws Fail {
synchronized (port.m_ClearErr) {
if (!ClearCommError(port.m_Comm, port.m_ClearErr, port.m_ClearStat))
port.fail();
}
}
public int select(int n, FDSet readfds, FDSet writefds, FDSet exceptfds, TimeVal timeout) {
int ready = 0;
while (ready == 0) {
LinkedList<Port> locked = new LinkedList<Port>();
try {
try {
LinkedList<Port> waiting = new LinkedList<Port>();
for (int fd = 0; fd < n; fd++) {
boolean rd = FD_ISSET(fd, readfds);
boolean wr = FD_ISSET(fd, writefds);
FD_CLR(fd, readfds);
FD_CLR(fd, writefds);
if (rd || wr) {
Port port = getPort(fd);
if (port == null)
return -1;
try {
port.lock();
locked.add(port);
clearCommErrors(port);
if (!ResetEvent(port.m_SelOVL.hEvent))
port.fail();
int flags = 0;
if (rd)
flags |= EV_RXCHAR;
if (wr)
flags |= EV_TXEMPTY;
if (!SetCommMask(port.m_Comm, flags))
port.fail();
if (WaitCommEvent(port.m_Comm, port.m_EvenFlags, port.m_SelOVL)) {
// actually it seems that overlapped WaitCommEvent never returns true so we never get here
clearCommErrors(port);
if (!(((port.m_EvenFlags.getValue() & EV_RXCHAR) != 0) && port.m_ClearStat.cbInQue == 0)) {
maskToFDSets(port, readfds, writefds, exceptfds);
ready++;
}
} else {
// FIXME if the port dies on us what happens
if (GetLastError() != ERROR_IO_PENDING)
port.fail();
waiting.add(port);
}
} catch (InterruptedException ie) {
m_ErrNo = 777; // FIXME figure out the proper unit
// error code
return -1;
}
}
}
int waitn = waiting.size();
if (ready == 0 && waitn > 0) {
HANDLE[] wobj = new HANDLE[waiting.size()];
int i = 0;
for (Port port : waiting)
wobj[i++] = port.m_SelOVL.hEvent;
int tout = timeout != null ? (int) (timeout.tv_sec * 1000 + timeout.tv_usec / 1000) : INFINITE;
//int res = WaitForSingleObject(wobj[0], tout);
int res = WaitForMultipleObjects(waitn, wobj, false, tout);
if (res == WAIT_TIMEOUT) {
// work around the fact that sometimes we miss events
for (Port port : waiting) {
clearCommErrors(port);
int[] mask = { 0 };
if (!GetCommMask(port.m_Comm, mask))
port.fail();
if (port.m_ClearStat.cbInQue > 0 && ((mask[0] & EV_RXCHAR) != 0)) {
FD_SET(port.m_FD, readfds);
log = log && log(1, "missed EV_RXCHAR event\n");
return 1;
}
if (port.m_ClearStat.cbOutQue == 0 && ((mask[0] & EV_TXEMPTY) != 0)) {
FD_SET(port.m_FD, writefds);
log = log && log(1, "missed EV_TXEMPTY event\n");
return 1;
}
}
}
if (res != WAIT_TIMEOUT) {
i = res - WAIT_OBJECT_0;
if (i < 0 || i >= waitn)
throw new Fail();
Port port = waiting.get(i);
if (!GetOverlappedResult(port.m_Comm, port.m_SelOVL, port.m_SelN, false))
port.fail();
// following checking is needed because EV_RXCHAR can be set even if nothing is available for reading
clearCommErrors(port);
if (!(((port.m_EvenFlags.getValue() & EV_RXCHAR) != 0) && port.m_ClearStat.cbInQue == 0)) {
maskToFDSets(port, readfds, writefds, exceptfds);
ready = 1;
}
}
} else {
if (timeout != null)
nanoSleep(timeout.tv_sec * 1000000000L + timeout.tv_usec * 1000);
else {
m_ErrNo = EINVAL;
return -1;
}
return 0;
}
} catch (Fail f) {
return -1;
}
} finally {
for (Port port : locked)
port.unlock();
}
}
return ready;
}
public int poll(Pollfd fds[], int nfds, int timeout) {
return 0;
}
public void perror(String msg) {
if (msg != null && msg.length() > 0)
System.out.print(msg + ": ");
System.out.printf("%d\n", m_ErrNo);
}
// This is a bit pointless function as Windows baudrate constants are
// just the baudrates so basically this is a no-op, it returns what it gets
// Note this assumes that the Bxxxx constants in JTermios have the default
// values ie the values are the baudrates.
private static int baudToDCB(int baud) {
switch (baud) {
case 110:
return CBR_110;
case 300:
return CBR_300;
case 600:
return CBR_600;
case 1200:
return CBR_1200;
case 2400:
return CBR_2400;
case 4800:
return CBR_4800;
case 9600:
return CBR_9600;
case 14400:
return CBR_14400;
case 19200:
return CBR_19200;
case 38400:
return CBR_38400;
case 57600:
return CBR_57600;
case 115200:
return CBR_115200;
case 128000:
return CBR_128000;
case 256000:
return CBR_256000;
default:
return baud;
}
}
public FDSet newFDSet() {
return new FDSetImpl();
}
public void FD_CLR(int fd, FDSet set) {
if (set == null)
return;
FDSetImpl p = (FDSetImpl) set;
p.bits[fd / FDSetImpl.NFBBITS] &= ~(1 << (fd % FDSetImpl.NFBBITS));
}
public boolean FD_ISSET(int fd, FDSet set) {
if (set == null)
return false;
FDSetImpl p = (FDSetImpl) set;
return (p.bits[fd / FDSetImpl.NFBBITS] & (1 << (fd % FDSetImpl.NFBBITS))) != 0;
}
public void FD_SET(int fd, FDSet set) {
if (set == null)
return;
FDSetImpl p = (FDSetImpl) set;
p.bits[fd / FDSetImpl.NFBBITS] |= 1 << (fd % FDSetImpl.NFBBITS);
}
public void FD_ZERO(FDSet set) {
if (set == null)
return;
FDSetImpl p = (FDSetImpl) set;
java.util.Arrays.fill(p.bits, 0);
}
public int ioctl(int fd, int cmd, int[] arg) {
Port port = getPort(fd);
if (port == null)
return -1;
try {
if (cmd == FIONREAD) {
clearCommErrors(port);
arg[0] = port.m_ClearStat.cbInQue;
return 0;
} else if (cmd == TIOCMSET) {
int a = arg[0];
if ((a & TIOCM_DTR) != 0)
port.MSR |= TIOCM_DTR;
else
port.MSR &= ~TIOCM_DTR;
if (!EscapeCommFunction(port.m_Comm, ((a & TIOCM_DTR) != 0) ? SETDTR : CLRDTR))
port.fail();
if ((a & TIOCM_RTS) != 0)
port.MSR |= TIOCM_RTS;
else
port.MSR &= ~TIOCM_RTS;
if (!EscapeCommFunction(port.m_Comm, ((a & TIOCM_RTS) != 0) ? SETRTS : CLRRTS))
port.fail();
return 0;
} else if (cmd == TIOCMGET) {
int[] stat = { 0 };
if (!GetCommModemStatus(port.m_Comm, stat))
port.fail();
int s = stat[0];
int a = arg[0];
if ((s & MS_RLSD_ON) != 0)
a |= TIOCM_CAR;
else
a &= ~TIOCM_CAR;
if ((s & MS_RING_ON) != 0)
a |= TIOCM_RNG;
else
a &= ~TIOCM_RNG;
if ((s & MS_DSR_ON) != 0)
a |= TIOCM_DSR;
else
a &= ~TIOCM_DSR;
if ((s & MS_CTS_ON) != 0)
a |= TIOCM_CTS;
else
a &= ~TIOCM_CTS;
if ((port.MSR & TIOCM_DTR) != 0)
a |= TIOCM_DTR;
else
a &= ~TIOCM_DTR;
if ((port.MSR & TIOCM_RTS) != 0)
a |= TIOCM_RTS;
else
a &= ~TIOCM_RTS;
arg[0] = a;
return 0;
} else {
m_ErrNo = ENOTSUP;
return -1;
}
} catch (Fail f) {
return -1;
}
}
private void set_errno(int x) {
m_ErrNo = x;
}
private void report(String msg) {
System.err.print(msg);
}
private Port getPort(int fd) {
synchronized (this) {
Port port = m_OpenPorts.get(fd);
if (port == null)
m_ErrNo = EBADF;
return port;
}
}
private static String getString(char[] buffer, int offset) {
StringBuffer s = new StringBuffer();
char c;
while ((c = buffer[offset++]) != 0)
s.append((char) c);
return s.toString();
}
public List<String> getPortList() {
char[] buffer;
for (int size = 8 * 1024; size < 256 * 1024; size *= 2) {
buffer = new char[size];
int res = QueryDosDeviceW(null, buffer, buffer.length);
if (res > 0 && (GetLastError() != ERROR_INSUFFICIENT_BUFFER)) { //
LinkedList<String> list = new LinkedList<String>();
int offset = 0;
String port;
while ((port = getString(buffer, offset)).length() > 0) {
if (port.startsWith("COM"))
list.add(port);
offset += port.length() + 1;
}
return list;
}
}
log = log && log(1, "QueryDosDeviceW() failed to return the device list\n");
return null;
}
public void shutDown() {
for (Port port : m_OpenPorts.values()) {
try {
log = log && log(1, "shutDown() closing port %d\n", port.m_FD);
port.close();
} catch (Exception e) {
// should never happen
e.printStackTrace();
}
}
}
}
|
src/jtermios/windows/JTermiosImpl.java
|
/*
* Copyright (c) 2011, Kustaa Nyholm / SpareTimeLabs
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* Neither the name of the Kustaa Nyholm or SpareTimeLabs nor the names of its
* contributors may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*/
package jtermios.windows;
import java.nio.ByteBuffer;
import java.util.*;
import com.sun.jna.*;
import com.sun.jna.ptr.IntByReference;
import static jtermios.JTermios.*;
import static jtermios.JTermios.JTermiosLogging.*;
import jtermios.*;
import jtermios.windows.WinAPI.*;
import static jtermios.windows.WinAPI.*;
import static jtermios.windows.WinAPI.DCB.*;
public class JTermiosImpl implements jtermios.JTermios.JTermiosInterface {
private volatile int m_ErrNo = 0;
private volatile boolean m_PortFDs[] = new boolean[FDSetImpl.FD_SET_SIZE];
private volatile Hashtable<Integer, Port> m_OpenPorts = new Hashtable<Integer, Port>();
private class Port {
volatile int m_FD = -1;
volatile boolean m_Locked;
volatile HANDLE m_Comm;
volatile int m_OpenFlags;
volatile DCB m_DCB = new DCB();
volatile COMMTIMEOUTS m_Timeouts = new COMMTIMEOUTS();
volatile COMSTAT m_ClearStat = new COMSTAT();
volatile int[] m_ClearErr = { 0 };
volatile Memory m_RdBuffer = new Memory(2048);
volatile COMSTAT m_RdStat = new COMSTAT();
volatile int[] m_RdErr = { 0 };
volatile int m_RdN[] = { 0 };
volatile OVERLAPPED m_RdOVL = new OVERLAPPED();
volatile Memory m_WrBuffer = new Memory(2048);
volatile COMSTAT m_WrStat = new COMSTAT();
volatile int[] m_WrErr = { 0 };
volatile int m_WrN[] = { 0 };
volatile OVERLAPPED m_WrOVL = new OVERLAPPED();
volatile int m_SelN[] = { 0 };
volatile OVERLAPPED m_SelOVL = new OVERLAPPED();
volatile IntByReference m_EvenFlags = new IntByReference();
volatile Termios m_Termios = new Termios();
volatile int MSR; // initial value
synchronized public void fail() throws Fail {
int err = GetLastError();
Memory buffer = new Memory(2048);
int res = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, null, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buffer, (int) buffer.size(), null);
log = log && log(1, "fail() %s, Windows GetLastError()= %d, %s\n", lineno(1), err, buffer.getString(0, true));
// FIXME here convert from Windows error code to 'posix' error code
Fail f = new Fail();
throw f;
}
synchronized public void lock() throws InterruptedException {
if (m_Locked)
wait();
m_Locked = true;
}
synchronized public void unlock() {
if (!m_Locked)
throw new IllegalArgumentException("Port was not locked");
m_Locked = false;
}
public Port() {
synchronized (JTermiosImpl.this) {
m_FD = -1;
for (int i = 0; i < m_PortFDs.length; ++i) {
if (!m_PortFDs[i]) {
m_FD = i;
m_PortFDs[i] = true;
m_OpenPorts.put(m_FD, this);
return;
}
}
throw new RuntimeException("Too many ports open");
}
}
public void close() {
synchronized (JTermiosImpl.this) {
if (m_FD >= 0) {
m_OpenPorts.remove(m_FD);
m_PortFDs[m_FD] = false;
m_FD = -1;
}
HANDLE h; /// 'hEvent' might never have been 'read' so read it to this var first
h = (HANDLE) m_RdOVL.readField("hEvent");
m_RdOVL = null;
if (h != null && !h.equals(NULL) && !h.equals(INVALID_HANDLE_VALUE))
CloseHandle(h);
h = (HANDLE) m_WrOVL.readField("hEvent");
m_WrOVL = null;
if (h != null && !h.equals(NULL) && !h.equals(INVALID_HANDLE_VALUE))
CloseHandle(h);
h = (HANDLE) m_SelOVL.readField("hEvent");
m_WrOVL = m_SelOVL;
if (h != null && !h.equals(NULL) && !h.equals(INVALID_HANDLE_VALUE))
CloseHandle(h);
if (m_Comm != null && m_Comm != NULL && m_Comm != INVALID_HANDLE_VALUE)
CloseHandle(m_Comm);
m_Comm = null;
}
}
};
static class Fail extends Exception {
}
static private class FDSetImpl extends FDSet {
static final int FD_SET_SIZE = 256; // Windows supports max 255 serial ports so this is enough
static final int NFBBITS = 32;
int[] bits = new int[(FD_SET_SIZE + NFBBITS - 1) / NFBBITS];
}
public JTermiosImpl() {
log = log && log(1, "instantiating %s\n", getClass().getCanonicalName());
}
public void cfmakeraw(Termios termios) {
termios.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
termios.c_oflag &= ~OPOST;
termios.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
termios.c_cflag &= ~(CSIZE | PARENB);
termios.c_cflag |= CS8;
}
public int fcntl(int fd, int cmd, int[] arg) {
Port port = getPort(fd);
if (port == null)
return -1;
if (F_GETFL == cmd)
arg[0] = port.m_OpenFlags;
else {
m_ErrNo = ENOTSUP;
return -1;
}
return 0;
}
public int fcntl(int fd, int cmd, int arg) {
Port port = getPort(fd);
if (port == null)
return -1;
if (F_SETFL == cmd)
port.m_OpenFlags = arg;
else {
m_ErrNo = ENOTSUP;
return -1;
}
return 0;
}
public int tcdrain(int fd) {
Port port = getPort(fd);
if (port == null)
return -1;
try {
synchronized (port.m_WrBuffer) {
if (!FlushFileBuffers(port.m_Comm))
port.fail();
return 0;
}
} catch (Fail f) {
return -1;
}
}
public int cfgetispeed(Termios termios) {
return termios.c_ispeed;
}
public int cfgetospeed(Termios termios) {
return termios.c_ospeed;
}
public int cfsetispeed(Termios termios, int speed) {
termios.c_ispeed = speed;
return 0;
}// Error code for Interrupted = EINTR
public int cfsetospeed(Termios termios, int speed) {
termios.c_ospeed = speed;
return 0;
}
public int open(String filename, int flags) {
Port port = new Port();
port.m_OpenFlags = flags;
try {
if (!filename.startsWith("\\\\"))
filename = "\\\\.\\" + filename;
port.m_Comm = CreateFileW(new WString(filename), GENERIC_READ | GENERIC_WRITE, 0, null, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, null);
if (INVALID_HANDLE_VALUE == port.m_Comm)
port.fail();
if (!SetupComm(port.m_Comm, (int) port.m_RdBuffer.size(), (int) port.m_WrBuffer.size()))
port.fail(); // FIXME what would be appropriate error code here
cfmakeraw(port.m_Termios);
cfsetispeed(port.m_Termios, B9600);
cfsetospeed(port.m_Termios, B9600);
port.m_Termios.c_cc[VTIME] = 0;
port.m_Termios.c_cc[VMIN] = 0;
updateFromTermios(port);
port.m_RdOVL.writeField("hEvent", CreateEventA(null, true, false, null));
if (port.m_RdOVL.hEvent == INVALID_HANDLE_VALUE)
port.fail();
port.m_WrOVL.writeField("hEvent", CreateEventA(null, true, false, null));
if (port.m_WrOVL.hEvent == INVALID_HANDLE_VALUE)
port.fail();
port.m_SelOVL.writeField("hEvent", CreateEventA(null, true, false, null));
if (port.m_SelOVL.hEvent == INVALID_HANDLE_VALUE)
port.fail();
return port.m_FD;
} catch (Exception f) {
if (port != null)
port.close();
return -1;
}
}
private static void nanoSleep(long nsec) throws Fail {
try {
Thread.sleep((int) (nsec / 1000000), (int) (nsec % 1000000));
} catch (InterruptedException ie) {
throw new Fail();
}
}
private int getCharBits(Termios tios) {
int cs = 8; // default to 8
if ((tios.c_cflag & CSIZE) == CS5)
cs = 5;
if ((tios.c_cflag & CSIZE) == CS6)
cs = 6;
if ((tios.c_cflag & CSIZE) == CS7)
cs = 7;
if ((tios.c_cflag & CSIZE) == CS8)
cs = 8;
if ((tios.c_cflag & CSTOPB) != 0)
cs++; // extra stop bit
if ((tios.c_cflag & PARENB) != 0)
cs++; // parity adds an other bit
cs += 1 + 1; // start bit + stop bit
return cs;
}
private static int min(int a, int b) {
return a < b ? a : b;
}
private static int max(int a, int b) {
return a > b ? a : b;
}
public int read(int fd, byte[] buffer, int length) {
Port port = getPort(fd);
if (port == null)
return -1;
synchronized (port.m_RdBuffer) {
try {
// coldly limit reads to internal buffer size
if (length > port.m_RdBuffer.size())
length = (int) port.m_RdBuffer.size();
if (length == 0)
return 0;
int error;
if ((port.m_OpenFlags & O_NONBLOCK) != 0) {
if (!ClearCommError(port.m_Comm, port.m_RdErr, port.m_RdStat))
port.fail();
int available = port.m_RdStat.cbInQue;
if (available == 0) {
m_ErrNo = EAGAIN;
return -1;
}
length = min(length, available);
} else {
int vtime = port.m_Termios.c_cc[VTIME];
int vmin = port.m_Termios.c_cc[VMIN];
if (!ClearCommError(port.m_Comm, port.m_RdErr, port.m_RdStat))
port.fail();
int available = port.m_RdStat.cbInQue;
if (vmin == 0 && vtime == 0) {
if (available == 0)
return 0;
length = min(length, available);
}
if (vmin > 0)
length = min(max(vmin, available), length);
}
if (!ResetEvent(port.m_RdOVL.hEvent))
port.fail();
if (!ReadFile(port.m_Comm, port.m_RdBuffer, length, port.m_RdN, port.m_RdOVL)) {
if (GetLastError() != ERROR_IO_PENDING)
port.fail();
if (WaitForSingleObject(port.m_RdOVL.hEvent, INFINITE) != WAIT_OBJECT_0)
port.fail();
if (!GetOverlappedResult(port.m_Comm, port.m_RdOVL, port.m_RdN, true))
port.fail();
}
port.m_RdBuffer.read(0, buffer, 0, port.m_RdN[0]);
return port.m_RdN[0];
} catch (Fail ie) {
return -1;
}
}
}
public int write(int fd, byte[] buffer, int length) {
Port port = getPort(fd);
if (port == null)
return -1;
synchronized (port.m_WrBuffer) {
try {
if ((port.m_OpenFlags & O_NONBLOCK) != 0) {
if (!ClearCommError(port.m_Comm, port.m_WrErr, port.m_WrStat))
port.fail();
int room = (int) port.m_WrBuffer.size() - port.m_WrStat.cbOutQue;
if (length > room)
length = room;
}
int old_flag;
if (!ResetEvent(port.m_WrOVL.hEvent))
port.fail();
port.m_WrBuffer.write(0, buffer, 0, length); // copy from buffer to Memory
boolean ok = WriteFile(port.m_Comm, port.m_WrBuffer, length, port.m_WrN, port.m_WrOVL);
if (!ok) {
if (GetLastError() != ERROR_IO_PENDING)
port.fail();
while (true) {
// FIXME would need to implement thread interruption
int res = WaitForSingleObject(port.m_WrOVL.hEvent, INFINITE);
if (res == WAIT_TIMEOUT) {
clearCommErrors(port);
log = log && log(1, "write pending, cbInQue %d cbOutQue %d\n", port.m_ClearStat.cbInQue, port.m_ClearStat.cbOutQue);
continue;
}
if (!GetOverlappedResult(port.m_Comm, port.m_WrOVL, port.m_WrN, false))
port.fail();
break;
}
}
return port.m_WrN[0];
} catch (Fail f) {
return -1;
}
}
}
public int close(int fd) {
Port port = getPort(fd);
if (port == null)
return -1;
port.close();
return 0;
}
public int tcflush(int fd, int queue) {
Port port = getPort(fd);
if (port == null)
return -1;
try {
if (queue == TCIFLUSH) {
if (!PurgeComm(port.m_Comm, PURGE_RXABORT))
port.fail();
} else if (queue == TCOFLUSH) {
if (!PurgeComm(port.m_Comm, PURGE_TXABORT))
port.fail();
} else if (queue == TCIOFLUSH) {
if (!PurgeComm(port.m_Comm, PURGE_TXABORT))
port.fail();
if (!PurgeComm(port.m_Comm, PURGE_RXABORT))
port.fail();
} else {
m_ErrNo = ENOTSUP;
return -1;
}
return 0;
} catch (Fail f) {
return -1;
}
}
/*
* (non-Javadoc) Basically this is wrong, as tcsetattr is supposed to set
* only those things it can support and tcgetattr is the used to see that
* what actually happened. In this instance tcsetattr never fails and
* tcgetattr always returns the last settings even though it possible (even
* likely) that tcsetattr was not able to carry out all settings, as there
* is no 1:1 mapping between Windows Comm API and posix/termios API.
*
* @see jtermios.JTermios.JTermiosInterface#tcgetattr(int, jtermios.Termios)
*/
public int tcgetattr(int fd, Termios termios) {
Port port = getPort(fd);
if (port == null)
return -1;
termios.set(port.m_Termios);
return 0;
}
public int tcsendbreak(int fd, int duration) {
Port port = getPort(fd);
if (port == null)
return -1;
try {
if (!SetCommBreak(port.m_Comm))
port.fail();
nanoSleep(duration * 250000000);
if (!ClearCommBreak(port.m_Comm))
port.fail();
return 0;
} catch (Fail f) {
return -1;
}
}
public int tcsetattr(int fd, int cmd, Termios termios) {
if (cmd != TCSANOW)
log(0, "tcsetattr only supports TCSANOW");
Port port = getPort(fd);
if (port == null)
return -1;
synchronized (port.m_Termios) {
try {
port.m_Termios.set(termios);
updateFromTermios(port);
return 0;
} catch (Fail f) {
return -1;
}
}
}
//FIXME this needs serious code review from people who know this stuff...
public int updateFromTermios(Port port) throws Fail {
Termios tios = port.m_Termios;
DCB dcb = port.m_DCB;
dcb.DCBlength = dcb.size();
dcb.BaudRate = tios.c_ospeed;
if (tios.c_ospeed != tios.c_ispeed)
log(0, "c_ospeed (%d) != c_ispeed (%d)\n", tios.c_ospeed, tios.c_ispeed);
int c_cflag = tios.c_cflag;
int c_iflag = tios.c_iflag;
int c_oflag = tios.c_oflag;
int flags = 0;
// rxtx does: if ( s_termios->c_iflag & ISTRIP ) dcb.fBinary = FALSE; but Winapi doc says fBinary always true
flags |= fBinary;
if ((c_cflag & PARENB) != 0)
flags |= fParity;
if ((c_iflag & IXON) != 0)
flags |= fOutX;
if ((c_iflag & IXOFF) != 0)
flags |= fInX;
if ((c_iflag & IXANY) != 0)
flags |= fTXContinueOnXoff;
if ((c_iflag & CRTSCTS) != 0) {
flags |= fRtsControl;
flags |= fOutxCtsFlow;
;
}
// Following have no corresponding functionality in unix termios
//fOutxDsrFlow = 0x00000008;
//fDtrControl = 0x00000030;
//fDsrSensitivity = 0x00000040;
//fErrorChar = 0x00000400;
//fNull = 0x00000800;
//fAbortOnError = 0x00004000;
//fDummy2 = 0xFFFF8000;
dcb.fFlags = flags;
dcb.XonLim = 128; // rxtx sets there to 0 but Windows API doc says must not be 0
dcb.XoffLim = 128;
byte cs = 8;
int csize = c_cflag & CSIZE;
if (csize == CS5)
cs = 5;
if (csize == CS6)
cs = 6;
if (csize == CS7)
cs = 7;
if (csize == CS8)
cs = 8;
dcb.ByteSize = cs;
if ((c_cflag & PARENB) != 0) {
if ((c_cflag & PARODD) != 0 && (c_cflag & CMSPAR) != 0)
dcb.Parity = MARKPARITY;
else if ((c_cflag & PARODD) != 0)
dcb.Parity = ODDPARITY;
else if ((c_cflag & CMSPAR) != 0)
dcb.Parity = SPACEPARITY;
else
dcb.Parity = EVENPARITY;
} else
dcb.Parity = NOPARITY;
dcb.StopBits = (tios.c_cflag & CSTOPB) != 0 ? TWOSTOPBITS : ONESTOPBIT;
dcb.XonChar = tios.c_cc[VSTART];
dcb.XoffChar = tios.c_cc[VSTOP];
dcb.ErrorChar = 0;
// rxtx has some thing like
// if ( EV_BREAK|EV_CTS|EV_DSR|EV_ERR|EV_RING | ( EV_RLSD & EV_RXFLAG ) )
// dcb.EvtChar = '\n';
//else
// dcb.EvtChar = '\0';
// But those are all defines so there is something fishy there?
dcb.EvtChar = '\n';
dcb.EofChar = tios.c_cc[VEOF];
int vmin = port.m_Termios.c_cc[VMIN] & 0xFF;
int vtime = (port.m_Termios.c_cc[VTIME] & 0xFF) * 100;
COMMTIMEOUTS touts = port.m_Timeouts;
// There are really no write timeouts in classic unix termios
// FIXME test that we can still interrupt the tread
touts.WriteTotalTimeoutConstant = 0;
touts.WriteTotalTimeoutMultiplier = 0;
if (vmin == 0 && vtime == 0) {
// VMIN = 0 and VTIME = 0 => totally non blocking,if data is
// available, return it, ie this is poll operation
touts.ReadIntervalTimeout = MAXDWORD;
touts.ReadTotalTimeoutConstant = 0;
touts.ReadTotalTimeoutMultiplier = 0;
}
if (vmin == 0 && vtime > 0) {
// VMIN = 0 and VTIME > 0 => timed read, return as soon as data is
// available, VTIME = total time
touts.ReadIntervalTimeout = MAXDWORD;
touts.ReadTotalTimeoutConstant = vtime;
touts.ReadTotalTimeoutMultiplier = MAXDWORD;
}
if (vmin > 0 && vtime > 0) {
// VMIN > 0 and VTIME > 0 => blocks until VMIN chars has arrived or
// VTIME between chars expired
// 1) will block if nothing arrives
touts.ReadIntervalTimeout = vtime;
touts.ReadTotalTimeoutConstant = 0;
touts.ReadTotalTimeoutMultiplier = 0;
}
if (vmin > 0 && vtime == 0) {
// VMIN > 0 and VTIME = 0 => blocks until VMIN characters have been
// received
touts.ReadIntervalTimeout = 0;
touts.ReadTotalTimeoutConstant = 0;
touts.ReadTotalTimeoutMultiplier = 0;
}
if (!SetCommState(port.m_Comm, dcb))
port.fail();
if (!SetCommTimeouts(port.m_Comm, port.m_Timeouts))
port.fail();
return 0;
}
private void maskToFDSets(Port port, FDSet readfds, FDSet writefds, FDSet exceptfds) {
int emask = port.m_EvenFlags.getValue();
int fd = port.m_FD;
if ((emask & EV_RXCHAR) != 0)
FD_SET(fd, readfds);
if ((emask & EV_TXEMPTY) != 0)
FD_SET(fd, writefds);
}
private void clearCommErrors(Port port) throws Fail {
synchronized (port.m_ClearErr) {
if (!ClearCommError(port.m_Comm, port.m_ClearErr, port.m_ClearStat))
port.fail();
}
}
public int select(int n, FDSet readfds, FDSet writefds, FDSet exceptfds, TimeVal timeout) {
int ready = 0;
while (ready == 0) {
LinkedList<Port> locked = new LinkedList<Port>();
try {
try {
LinkedList<Port> waiting = new LinkedList<Port>();
for (int fd = 0; fd < n; fd++) {
boolean rd = FD_ISSET(fd, readfds);
boolean wr = FD_ISSET(fd, writefds);
FD_CLR(fd, readfds);
FD_CLR(fd, writefds);
if (rd || wr) {
Port port = getPort(fd);
if (port == null)
return -1;
try {
port.lock();
locked.add(port);
clearCommErrors(port);
if (!ResetEvent(port.m_SelOVL.hEvent))
port.fail();
int flags = 0;
if (rd)
flags |= EV_RXCHAR;
if (wr)
flags |= EV_TXEMPTY;
if (!SetCommMask(port.m_Comm, flags))
port.fail();
if (WaitCommEvent(port.m_Comm, port.m_EvenFlags, port.m_SelOVL)) {
// actually it seems that overlapped WaitCommEvent never returns true so we never get here
clearCommErrors(port);
if (!(((port.m_EvenFlags.getValue() & EV_RXCHAR) != 0) && port.m_ClearStat.cbInQue == 0)) {
maskToFDSets(port, readfds, writefds, exceptfds);
ready++;
}
} else {
// FIXME if the port dies on us what happens
if (GetLastError() != ERROR_IO_PENDING)
port.fail();
waiting.add(port);
}
} catch (InterruptedException ie) {
m_ErrNo = 777; // FIXME figure out the proper unit
// error code
return -1;
}
}
}
int waitn = waiting.size();
if (ready == 0 && waitn > 0) {
HANDLE[] wobj = new HANDLE[waiting.size()];
int i = 0;
for (Port port : waiting)
wobj[i++] = port.m_SelOVL.hEvent;
int tout = timeout != null ? (int) (timeout.tv_sec * 1000 + timeout.tv_usec / 1000) : INFINITE;
//int res = WaitForSingleObject(wobj[0], tout);
int res = WaitForMultipleObjects(waitn, wobj, false, tout);
if (res == WAIT_TIMEOUT) {
// work around the fact that sometimes we miss events
for (Port port : waiting) {
clearCommErrors(port);
int[] mask = { 0 };
if (!GetCommMask(port.m_Comm, mask))
port.fail();
if (port.m_ClearStat.cbInQue > 0 && ((mask[0] & EV_RXCHAR) != 0)) {
FD_SET(port.m_FD, readfds);
log = log && log(1, "missed EV_RXCHAR event\n");
return 1;
}
if (port.m_ClearStat.cbOutQue == 0 && ((mask[0] & EV_TXEMPTY) != 0)) {
FD_SET(port.m_FD, writefds);
log = log && log(1, "missed EV_TXEMPTY event\n");
return 1;
}
}
}
if (res != WAIT_TIMEOUT) {
i = res - WAIT_OBJECT_0;
if (i < 0 || i >= waitn)
throw new Fail();
Port port = waiting.get(i);
if (!GetOverlappedResult(port.m_Comm, port.m_SelOVL, port.m_SelN, false))
port.fail();
// following checking is needed because EV_RXCHAR can be set even if nothing is available for reading
clearCommErrors(port);
if (!(((port.m_EvenFlags.getValue() & EV_RXCHAR) != 0) && port.m_ClearStat.cbInQue == 0)) {
maskToFDSets(port, readfds, writefds, exceptfds);
ready = 1;
}
}
} else {
if (timeout != null)
nanoSleep(timeout.tv_sec * 1000000000L + timeout.tv_usec * 1000);
else {
m_ErrNo = EINVAL;
return -1;
}
return 0;
}
} catch (Fail f) {
return -1;
}
} finally {
for (Port port : locked)
port.unlock();
}
}
return ready;
}
public int poll(Pollfd fds[], int nfds, int timeout) {
return 0;
}
public void perror(String msg) {
if (msg != null && msg.length() > 0)
System.out.print(msg + ": ");
System.out.printf("%d\n", m_ErrNo);
}
// This is a bit pointless function as Windows baudrate constants are
// just the baudrates so basically this is a no-op, it returns what it gets
// Note this assumes that the Bxxxx constants in JTermios have the default
// values ie the values are the baudrates.
private static int baudToDCB(int baud) {
switch (baud) {
case 110:
return CBR_110;
case 300:
return CBR_300;
case 600:
return CBR_600;
case 1200:
return CBR_1200;
case 2400:
return CBR_2400;
case 4800:
return CBR_4800;
case 9600:
return CBR_9600;
case 14400:
return CBR_14400;
case 19200:
return CBR_19200;
case 38400:
return CBR_38400;
case 57600:
return CBR_57600;
case 115200:
return CBR_115200;
case 128000:
return CBR_128000;
case 256000:
return CBR_256000;
default:
return baud;
}
}
public FDSet newFDSet() {
return new FDSetImpl();
}
public void FD_CLR(int fd, FDSet set) {
if (set == null)
return;
FDSetImpl p = (FDSetImpl) set;
p.bits[fd / FDSetImpl.NFBBITS] &= ~(1 << (fd % FDSetImpl.NFBBITS));
}
public boolean FD_ISSET(int fd, FDSet set) {
if (set == null)
return false;
FDSetImpl p = (FDSetImpl) set;
return (p.bits[fd / FDSetImpl.NFBBITS] & (1 << (fd % FDSetImpl.NFBBITS))) != 0;
}
public void FD_SET(int fd, FDSet set) {
if (set == null)
return;
FDSetImpl p = (FDSetImpl) set;
p.bits[fd / FDSetImpl.NFBBITS] |= 1 << (fd % FDSetImpl.NFBBITS);
}
public void FD_ZERO(FDSet set) {
if (set == null)
return;
FDSetImpl p = (FDSetImpl) set;
java.util.Arrays.fill(p.bits, 0);
}
public int ioctl(int fd, int cmd, int[] arg) {
Port port = getPort(fd);
if (port == null)
return -1;
try {
if (cmd == FIONREAD) {
clearCommErrors(port);
arg[0] = port.m_ClearStat.cbInQue;
return 0;
} else if (cmd == TIOCMSET) {
int a = arg[0];
if ((a & TIOCM_DTR) != 0)
port.MSR |= TIOCM_DTR;
else
port.MSR &= ~TIOCM_DTR;
if (!EscapeCommFunction(port.m_Comm, ((a & TIOCM_DTR) != 0) ? SETDTR : CLRDTR))
port.fail();
if ((a & TIOCM_RTS) != 0)
port.MSR |= TIOCM_RTS;
else
port.MSR &= ~TIOCM_RTS;
if (!EscapeCommFunction(port.m_Comm, ((a & TIOCM_RTS) != 0) ? SETRTS : CLRRTS))
port.fail();
return 0;
} else if (cmd == TIOCMGET) {
int[] stat = { 0 };
if (!GetCommModemStatus(port.m_Comm, stat))
port.fail();
int s = stat[0];
int a = arg[0];
if ((s & MS_RLSD_ON) != 0)
a |= TIOCM_CAR;
else
a &= ~TIOCM_CAR;
if ((s & MS_RING_ON) != 0)
a |= TIOCM_RNG;
else
a &= ~TIOCM_RNG;
if ((s & MS_DSR_ON) != 0)
a |= TIOCM_DSR;
else
a &= ~TIOCM_DSR;
if ((s & MS_CTS_ON) != 0)
a |= TIOCM_CTS;
else
a &= ~TIOCM_CTS;
if ((port.MSR & TIOCM_DTR) != 0)
a |= TIOCM_DTR;
else
a &= ~TIOCM_DTR;
if ((port.MSR & TIOCM_RTS) != 0)
a |= TIOCM_RTS;
else
a &= ~TIOCM_RTS;
arg[0] = a;
return 0;
} else {
m_ErrNo = ENOTSUP;
return -1;
}
} catch (Fail f) {
return -1;
}
}
private void set_errno(int x) {
m_ErrNo = x;
}
private void report(String msg) {
System.err.print(msg);
}
private Port getPort(int fd) {
synchronized (this) {
Port port = m_OpenPorts.get(fd);
if (port == null)
m_ErrNo = EBADF;
return port;
}
}
private static String getString(char[] buffer, int offset) {
StringBuffer s = new StringBuffer();
char c;
while ((c = buffer[offset++]) != 0)
s.append((char) c);
return s.toString();
}
public List<String> getPortList() {
char[] buffer;
for (int size = 8 * 1024; size < 256 * 1024; size *= 2) {
buffer = new char[size];
int res = QueryDosDeviceW(null, buffer, buffer.length);
if (res > 0 && (GetLastError() != ERROR_INSUFFICIENT_BUFFER)) { //
LinkedList<String> list = new LinkedList<String>();
int offset = 0;
String port;
while ((port = getString(buffer, offset)).length() > 0) {
if (port.startsWith("COM"))
list.add(port);
offset += port.length() + 1;
}
return list;
}
}
log = log && log(1, "QueryDosDeviceW() failed to return the device list\n");
return null;
}
public void shutDown() {
for (Port port : m_OpenPorts.values()) {
try {
log = log && log(1, "shutDown() closing port %d\n", port.m_FD);
port.close();
} catch (Exception e) {
// should never happen
e.printStackTrace();
}
}
}
}
|
Implemented F_GETFL for fcntl()
|
src/jtermios/windows/JTermiosImpl.java
|
Implemented F_GETFL for fcntl()
|
|
Java
|
bsd-3-clause
|
f78ddf3c19e75c16e053e98339b2b4cfd2a8b048
| 0
|
asamgir/openspecimen,NCIP/catissue-core,krishagni/openspecimen,asamgir/openspecimen,NCIP/catissue-core,asamgir/openspecimen,NCIP/catissue-core,krishagni/openspecimen,krishagni/openspecimen
|
import java.text.ParseException;
import java.util.Collection;
import java.util.HashSet;
import edu.wustl.catissuecore.domain.Address;
import edu.wustl.catissuecore.domain.Biohazard;
import edu.wustl.catissuecore.domain.CancerResearchGroup;
import edu.wustl.catissuecore.domain.Capacity;
import edu.wustl.catissuecore.domain.ClinicalReport;
import edu.wustl.catissuecore.domain.CollectionEventParameters;
import edu.wustl.catissuecore.domain.CollectionProtocol;
import edu.wustl.catissuecore.domain.CollectionProtocolEvent;
import edu.wustl.catissuecore.domain.CollectionProtocolRegistration;
import edu.wustl.catissuecore.domain.Department;
import edu.wustl.catissuecore.domain.DistributedItem;
import edu.wustl.catissuecore.domain.Distribution;
import edu.wustl.catissuecore.domain.DistributionProtocol;
import edu.wustl.catissuecore.domain.ExternalIdentifier;
import edu.wustl.catissuecore.domain.Institution;
import edu.wustl.catissuecore.domain.MolecularSpecimen;
import edu.wustl.catissuecore.domain.Participant;
import edu.wustl.catissuecore.domain.Quantity;
import edu.wustl.catissuecore.domain.ReceivedEventParameters;
import edu.wustl.catissuecore.domain.Site;
import edu.wustl.catissuecore.domain.Specimen;
import edu.wustl.catissuecore.domain.SpecimenArray;
import edu.wustl.catissuecore.domain.SpecimenArrayContent;
import edu.wustl.catissuecore.domain.SpecimenArrayType;
import edu.wustl.catissuecore.domain.SpecimenCharacteristics;
import edu.wustl.catissuecore.domain.SpecimenCollectionGroup;
import edu.wustl.catissuecore.domain.SpecimenRequirement;
import edu.wustl.catissuecore.domain.StorageContainer;
import edu.wustl.catissuecore.domain.StorageType;
import edu.wustl.catissuecore.domain.User;
import edu.wustl.common.util.Utility;
import edu.wustl.common.util.global.Constants;
/**
* @author ashish_gupta
*
*/
public class APIDemo
{
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception
{
/*
Variables.applicationHome = System.getProperty("user.dir");
Logger.out = org.apache.log4j.Logger.getLogger("");
PropertyConfigurator.configure(Variables.applicationHome + "\\WEB-INF\\src\\"
+ "ApplicationResources.properties");
System
.setProperty("gov.nih.nci.security.configFile",
"C:/jboss-4.0.0/server/default/catissuecore-properties/ApplicationSecurityConfig.xml");
System
.setProperty("app.propertiesFile",
"C:/jboss-4.0.0/server/default/catissuecore-properties/caTissueCore_Properties.xml");
CDEManager.init();
XMLPropertyHandler.init("caTissueCore_Properties.xml");
ApplicationProperties.initBundle("ApplicationResources");
APIDemo apiDemo = new APIDemo();
SessionDataBean sessionDataBean = new SessionDataBean();
sessionDataBean.setUserName("admin@admin.com");
BizLogicFactory bizLogicFactory = BizLogicFactory.getInstance();
// Department dept = apiDemo.initDepartment();
// apiDemo.addData(bizLogicFactory, sessionDataBean, dept);
//
// Biohazard hazardObj=apiDemo.initBioHazard();
// apiDemo.addData(bizLogicFactory, sessionDataBean, hazardObj);
//
// CancerResearchGroup cancerResearchGroup = apiDemo.initCancerResearchGroup();
// apiDemo.addData(bizLogicFactory, sessionDataBean, cancerResearchGroup);
//
// Institution institution = apiDemo.initInstitution();
// apiDemo.addData(bizLogicFactory, sessionDataBean, institution);
//
// Site site = apiDemo.initSite();
// apiDemo.addData(bizLogicFactory, sessionDataBean, site);
//
// StorageType storageType = apiDemo.initStorageType();
// apiDemo.addData(bizLogicFactory, sessionDataBean, storageType);
//
// SpecimenArrayType specimenArrayType = apiDemo.initSpecimenArrayType();
// apiDemo.addData(bizLogicFactory, sessionDataBean, specimenArrayType);
//
// User user = apiDemo.initUser();
// apiDemo.addData(bizLogicFactory, sessionDataBean, user);
//
// Participant participant = apiDemo.initParticipant();
// apiDemo.addData(bizLogicFactory, sessionDataBean, participant);
//
// StorageContainer storageContainer = apiDemo.initStorageContainer();
// apiDemo.addData(bizLogicFactory, sessionDataBean, storageContainer);
//
// CollectionProtocol collectionProtocol = apiDemo.initCollectionProtocol();
// apiDemo.addData(bizLogicFactory, sessionDataBean, collectionProtocol);
//
// DistributionProtocol distributionProtocol = apiDemo.initDistributionProtocol();
// apiDemo.addData(bizLogicFactory, sessionDataBean, distributionProtocol);
//
// CollectionProtocolRegistration collectionProtocolRegistration = apiDemo.initCollectionProtocolRegistration();
// apiDemo.addData(bizLogicFactory, sessionDataBean, collectionProtocolRegistration);
// SpecimenCollectionGroup specimenCollectionGroup = apiDemo.initSpecimenCollectionGroup();
// apiDemo.addData(bizLogicFactory, sessionDataBean, specimenCollectionGroup);
// Specimen specimen = apiDemo.initSpecimen();
// apiDemo.addData(bizLogicFactory, sessionDataBean, specimen);
Distribution distribution = apiDemo.initDistribution();
apiDemo.addData(bizLogicFactory, sessionDataBean, distribution);
*/
}
/**
* @param bizLogicFactory
* @param sessionDataBean
* @param obj
* @throws Exception
private void addData(BizLogicFactory bizLogicFactory, SessionDataBean sessionDataBean,
Object obj) throws Exception
{
IBizLogic bizLogic = bizLogicFactory.getBizLogic(obj.getClass().getName());
bizLogic.insert(obj, sessionDataBean, Constants.HIBERNATE_DAO);
}
*/
/**
* @return Department
*/
public Department initDepartment()
{
Department dept = new Department();
dept.setName("dt" + UniqueKeyGeneratorUtil.getUniqueKey());
return dept;
}
/**
* @return Biohazard
*/
public Biohazard initBioHazard()
{
Biohazard bioHazard = new Biohazard();
bioHazard.setComments("NueroToxicProtein");
bioHazard.setName("bh" + UniqueKeyGeneratorUtil.getUniqueKey());
bioHazard.setType("Toxic");
return bioHazard;
}
/**
* @return CancerResearchGroup
*/
public CancerResearchGroup initCancerResearchGroup()
{
CancerResearchGroup cancerResearchGroup = new CancerResearchGroup();
cancerResearchGroup.setName("crg" + UniqueKeyGeneratorUtil.getUniqueKey());
return cancerResearchGroup;
}
/**
* @return Institution
*/
public Institution initInstitution()
{
Institution institutionObj = new Institution();
institutionObj.setName("inst" + UniqueKeyGeneratorUtil.getUniqueKey());
return institutionObj;
}
/**
* @return User
*/
public User initUser()
{
User userObj = new User();
userObj.setEmailAddress(UniqueKeyGeneratorUtil.getUniqueKey()+ "@admin.com");
userObj.setLoginName(userObj.getEmailAddress());
userObj.setLastName("last" + UniqueKeyGeneratorUtil.getUniqueKey());
userObj.setFirstName("name" + UniqueKeyGeneratorUtil.getUniqueKey());
Address address = new Address();
address.setStreet("Main street");
address.setCity("New hampshier");
address.setState("D.C.");
address.setZipCode("12345");
address.setCountry("United States");
address.setPhoneNumber("21222324");
address.setFaxNumber("21222324");
userObj.setAddress(address);
// Institution institution = new Institution();
// institution.setId(new Long(1));
Institution institution = (Institution) ClientDemo.dataModelObjectMap.get("Institution");
userObj.setInstitution(institution);
// Department department = new Department();
// department.setId(new Long(1));
Department department = (Department)ClientDemo.dataModelObjectMap.get("Department");
userObj.setDepartment(department);
// CancerResearchGroup cancerResearchGroup = new CancerResearchGroup();
// cancerResearchGroup.setId(new Long(1));
CancerResearchGroup cancerResearchGroup = (CancerResearchGroup)ClientDemo.dataModelObjectMap.get("CancerResearchGroup");
userObj.setCancerResearchGroup(cancerResearchGroup);
//userObj.setRoleId("1");
//userObj.setComments("");
userObj.setPageOf(Constants.PAGEOF_SIGNUP);
//userObj.setActivityStatus("Active");
//userObj.setCsmUserId(new Long(1));
//userObj.setFirstTimeLogin(Boolean.valueOf(false));
return userObj;
}
public User initAdminUser()
{
User userObj = new User();
userObj.setEmailAddress(UniqueKeyGeneratorUtil.getUniqueKey()+ "@admin.com");
userObj.setLoginName(userObj.getEmailAddress());
userObj.setLastName("last" + UniqueKeyGeneratorUtil.getUniqueKey());
userObj.setFirstName("name" + UniqueKeyGeneratorUtil.getUniqueKey());
Address address = new Address();
address.setStreet("Main street");
address.setCity("New hampshier");
address.setState("D.C.");
address.setZipCode("12345");
address.setCountry("United States");
address.setPhoneNumber("21222324");
address.setFaxNumber("21222324");
userObj.setAddress(address);
// Institution institution = new Institution();
// institution.setId(new Long(1));
Institution institution = (Institution) ClientDemo.dataModelObjectMap.get("Institution");
userObj.setInstitution(institution);
// Department department = new Department();
// department.setId(new Long(1));
Department department = (Department)ClientDemo.dataModelObjectMap.get("Department");
userObj.setDepartment(department);
// CancerResearchGroup cancerResearchGroup = new CancerResearchGroup();
// cancerResearchGroup.setId(new Long(1));
CancerResearchGroup cancerResearchGroup = (CancerResearchGroup)ClientDemo.dataModelObjectMap.get("CancerResearchGroup");
userObj.setCancerResearchGroup(cancerResearchGroup);
userObj.setRoleId("1");
userObj.setActivityStatus("Active");
//userObj.setComments("");
userObj.setPageOf(Constants.PAGEOF_USER_ADMIN);
//userObj.setCsmUserId(new Long(1));
//userObj.setFirstTimeLogin(Boolean.valueOf(false));
return userObj;
}
/**
* @return StorageType
*/
public StorageType initStorageType()
{
StorageType storageTypeObj = new StorageType();
Capacity capacity = new Capacity();
storageTypeObj.setName("st" + UniqueKeyGeneratorUtil.getUniqueKey());
storageTypeObj.setDefaultTempratureInCentigrade(new Double(-30));
storageTypeObj.setOneDimensionLabel("label 1");
storageTypeObj.setTwoDimensionLabel("label 2");
capacity.setOneDimensionCapacity(new Integer(3));
capacity.setTwoDimensionCapacity(new Integer(3));
storageTypeObj.setCapacity(capacity);
//storageTypeObj.setId(new Long(20));
Collection holdsStorageTypeCollection = new HashSet();
holdsStorageTypeCollection.add(storageTypeObj);
storageTypeObj.setHoldsStorageTypeCollection(holdsStorageTypeCollection);
storageTypeObj.setActivityStatus("Active");
Collection holdsSpecimenClassCollection = new HashSet();
holdsSpecimenClassCollection.add("Tissue");
holdsSpecimenClassCollection.add("Fluid");
holdsSpecimenClassCollection.add("Molecular");
storageTypeObj.setHoldsSpecimenClassCollection(holdsSpecimenClassCollection);
return storageTypeObj;
}
/**
* @return SpecimenArrayType
*/
public SpecimenArrayType initSpecimenArrayType()
{
SpecimenArrayType specimenArrayType = new SpecimenArrayType();
specimenArrayType.setName("sat" + UniqueKeyGeneratorUtil.getUniqueKey());
specimenArrayType.setSpecimenClass("Molecular");
Collection specimenTypeCollection = new HashSet();
specimenTypeCollection.add("DNA");
specimenTypeCollection.add("RNA");
specimenArrayType.setSpecimenTypeCollection(specimenTypeCollection);
specimenArrayType.setComment("");
Capacity capacity = new Capacity();
capacity.setOneDimensionCapacity(new Integer(4));
capacity.setTwoDimensionCapacity(new Integer(4));
specimenArrayType.setCapacity(capacity);
return specimenArrayType;
}
/**
* @return StorageContainer
*/
public StorageContainer initStorageContainer()
{
StorageContainer storageContainer = new StorageContainer();
storageContainer.setName("sc" + UniqueKeyGeneratorUtil.getUniqueKey());
StorageType storageType = (StorageType) ClientDemo.dataModelObjectMap.get("StorageType");
/*
new StorageType();
storageType.setId(new Long(4));
*/
storageContainer.setStorageType(storageType);
Site site = (Site) ClientDemo.dataModelObjectMap.get("Site");
/*new Site();
site.setId(new Long(1));
*/
storageContainer.setSite(site);
Integer conts = new Integer(1);
storageContainer.setNoOfContainers(conts);
storageContainer.setTempratureInCentigrade(new Double(-30));
storageContainer.setBarcode("barc" + UniqueKeyGeneratorUtil.getUniqueKey());
Capacity capacity = new Capacity();
capacity.setOneDimensionCapacity(new Integer(1));
capacity.setTwoDimensionCapacity(new Integer(2));
storageContainer.setCapacity(capacity);
CollectionProtocol collectionProtocol = (CollectionProtocol) ClientDemo.dataModelObjectMap.get("CollectionProtocol");
/*
new CollectionProtocol();
collectionProtocol.setId(new Long(3));
*/
Collection collectionProtocolCollection = new HashSet();
collectionProtocolCollection.add(collectionProtocol);
storageContainer.setCollectionProtocolCollection(collectionProtocolCollection);
Collection holdsStorageTypeCollection = new HashSet();
holdsStorageTypeCollection.add(storageType);
storageContainer.setHoldsStorageTypeCollection(holdsStorageTypeCollection);
Collection holdsSpecimenClassCollection = new HashSet();
holdsSpecimenClassCollection.add("Tissue");
holdsSpecimenClassCollection.add("Molecular");
storageContainer.setHoldsSpecimenClassCollection(holdsSpecimenClassCollection);
/* Container parent = new Container();
parent.setId(new Long(2));
storageContainer.setParent(parent);
*/
storageContainer.setPositionDimensionOne(new Integer(1));
storageContainer.setPositionDimensionTwo(new Integer(2));
storageContainer.setActivityStatus("Active");
storageContainer.setFull(Boolean.valueOf(false));
return storageContainer;
}
/**
* @return Site
*/
public Site initSite()
{
Site siteObj = new Site();
// User userObj = new User();
// userObj.setId(new Long(1));
User userObj = (User) ClientDemo.dataModelObjectMap.get("User");
siteObj.setEmailAddress("admin@admin.com");
siteObj.setName("sit" + UniqueKeyGeneratorUtil.getUniqueKey());
siteObj.setType("Laboratory");
siteObj.setActivityStatus("Active");
siteObj.setCoordinator(userObj);
Address addressObj = new Address();
addressObj.setCity("Saint Louis");
addressObj.setCountry("United States");
addressObj.setFaxNumber("555-55-5555");
addressObj.setPhoneNumber("123678");
addressObj.setState("Missouri");
addressObj.setStreet("4939 Children's Place");
addressObj.setZipCode("63110");
siteObj.setAddress(addressObj);
return siteObj;
}
/**
* @return Participant
*/
public Participant initParticipant()
{
Participant participant = new Participant();
participant.setLastName("last" + UniqueKeyGeneratorUtil.getUniqueKey());
participant.setFirstName("frst" + UniqueKeyGeneratorUtil.getUniqueKey());
participant.setMiddleName("mdl" + UniqueKeyGeneratorUtil.getUniqueKey());
/*try
{
System.out.println("-----------------------");
participant.setBirthDate(Utility.parseDate("08/15/1975", Utility
.datePattern("08/15/1975")));
}
catch (ParseException e)
{
// TODO Auto-generated catch block
System.out.println("-----------------------"+e);
e.printStackTrace();
}
try
{
System.out.println("-----------------------");
participant.setDeathDate(Utility.parseDate("08/15/1974", Utility
.datePattern("08/15/1974")));
}
catch (ParseException e)
{
// TODO Auto-generated catch block
System.out.println("-----------------------"+e);
e.printStackTrace();
}*/
participant.setVitalStatus("Dead");
participant.setGender("Female");
participant.setSexGenotype("XX");
Collection raceCollection = new HashSet();
raceCollection.add("White");
raceCollection.add("Asian");
participant.setRaceCollection(raceCollection);
participant.setActivityStatus("Active");
participant.setEthnicity("Hispanic or Latino");
//participant.setSocialSecurityNumber("333-33-3333");
// Collection participantMedicalIdentifierCollection = new HashSet();
// /*participantMedicalIdentifierCollection.add("Washington University School of Medicine");
// participantMedicalIdentifierCollection.add("1111");
// */
// participant.setParticipantMedicalIdentifierCollection(participantMedicalIdentifierCollection);
return participant;
}
/**
* @return CollectionProtocol
*/
public CollectionProtocol initCollectionProtocol()
{
CollectionProtocol collectionProtocol = new CollectionProtocol();
collectionProtocol.setAliqoutInSameContainer(new Boolean(true));
collectionProtocol.setDescriptionURL("");
collectionProtocol.setActivityStatus("Active");
collectionProtocol.setEndDate(null);
collectionProtocol.setEnrollment(null);
collectionProtocol.setIrbIdentifier("77777");
collectionProtocol.setTitle("cp" + UniqueKeyGeneratorUtil.getUniqueKey());
collectionProtocol.setShortTitle("pc!");
try
{
collectionProtocol.setStartDate(Utility.parseDate("08/15/1975", Utility
.datePattern("08/15/1975")));
}
catch (ParseException e)
{
e.printStackTrace();
}
Collection collectionProtocolEventCollectionSet = new HashSet();
// CollectionProtocolEvent collectionProtocolEvent = new CollectionProtocolEvent();
CollectionProtocolEvent collectionProtocolEvent = (CollectionProtocolEvent)ClientDemo.dataModelObjectMap.get("CollectionProtocolEvent");
collectionProtocolEvent.setClinicalStatus("New Diagnosis");
collectionProtocolEvent.setStudyCalendarEventPoint(new Double(1));
Collection specimenRequirementCollection = new HashSet();
// SpecimenRequirement specimenRequirement = new SpecimenRequirement();
// specimenRequirement.setSpecimenClass("Molecular");
// specimenRequirement.setSpecimenType("DNA");
// specimenRequirement.setTissueSite("Placenta");
// specimenRequirement.setPathologyStatus("Malignant");
// Quantity quantity = new Quantity();
// quantity.setValue(new Double(10));
// specimenRequirement.setQuantity(quantity);
SpecimenRequirement specimenRequirement =(SpecimenRequirement)ClientDemo.dataModelObjectMap.get("SpecimenRequirement");
specimenRequirementCollection.add(specimenRequirement);
collectionProtocolEvent.setSpecimenRequirementCollection(specimenRequirementCollection);
collectionProtocolEventCollectionSet.add(collectionProtocolEvent);
collectionProtocol
.setCollectionProtocolEventCollection(collectionProtocolEventCollectionSet);
// User principalInvestigator = new User();
// principalInvestigator.setId(new Long(1));
User principalInvestigator = (User)ClientDemo.dataModelObjectMap.get("User");
collectionProtocol.setPrincipalInvestigator(principalInvestigator);
// User protocolCordinator = new User();
// protocolCordinator.setId(new Long(principalInvestigator.getId().longValue()-1));
User protocolCordinator = (User)ClientDemo.dataModelObjectMap.get("User1");
Collection protocolCordinatorCollection = new HashSet();
protocolCordinatorCollection.add(protocolCordinator);
collectionProtocol.setUserCollection(protocolCordinatorCollection);
return collectionProtocol;
}
/**
* @return Specimen
*/
public Specimen initSpecimen()
{
MolecularSpecimen molecularSpecimen = new MolecularSpecimen();
// SpecimenCollectionGroup specimenCollectionGroup = new SpecimenCollectionGroup();
// specimenCollectionGroup.setId(new Long(2));
SpecimenCollectionGroup specimenCollectionGroup = (SpecimenCollectionGroup)ClientDemo.dataModelObjectMap.get("SpecimenCollectionGroup");
molecularSpecimen.setSpecimenCollectionGroup(specimenCollectionGroup);
molecularSpecimen.setLabel("spec" + UniqueKeyGeneratorUtil.getUniqueKey());
molecularSpecimen.setBarcode("bar" + UniqueKeyGeneratorUtil.getUniqueKey());
molecularSpecimen.setType("DNA");
molecularSpecimen.setAvailable(new Boolean(true));
molecularSpecimen.setActivityStatus("Active");
// SpecimenCharacteristics specimenCharacteristics = new SpecimenCharacteristics();
// specimenCharacteristics.setTissueSide("Left");
// specimenCharacteristics.setTissueSite("Placenta");
// specimenCharacteristics.setId(new Long(1));
SpecimenCharacteristics specimenCharacteristics = (SpecimenCharacteristics)ClientDemo.dataModelObjectMap.get("SpecimenCharacteristics");
molecularSpecimen.setSpecimenCharacteristics(specimenCharacteristics);
molecularSpecimen.setPathologicalStatus("Malignant");
Quantity quantity = new Quantity();
quantity.setValue(new Double(10));
molecularSpecimen.setQuantity(quantity);
molecularSpecimen.setAvailableQuantity(quantity);
molecularSpecimen.setConcentrationInMicrogramPerMicroliter(new Double(10));
molecularSpecimen.setComments("");
molecularSpecimen.setLineage("Aliquot");
// Is virtually located
// StorageContainer sto = new StorageContainer();
// sto.setId(new Long("1"));
molecularSpecimen.setStorageContainer(null);
molecularSpecimen.setPositionDimensionOne(null);
molecularSpecimen.setPositionDimensionTwo(null);
Collection externalIdentifierCollection = new HashSet();
ExternalIdentifier externalIdentifier = new ExternalIdentifier();
externalIdentifier.setName("eid" + UniqueKeyGeneratorUtil.getUniqueKey());
externalIdentifier.setValue("11");
externalIdentifier.setSpecimen(molecularSpecimen);
externalIdentifierCollection.add(externalIdentifier);
molecularSpecimen.setExternalIdentifierCollection(externalIdentifierCollection);
CollectionEventParameters collectionEventParameters = new CollectionEventParameters();
collectionEventParameters.setComments("");
// User user = new User();
// user.setId(new Long(1));
// collectionEventParameters.setId(new Long(0));
User user = (User)ClientDemo.dataModelObjectMap.get("User");
collectionEventParameters.setUser(user);
try
{
collectionEventParameters.setTimestamp(Utility.parseDate("08/15/1975", Utility
.datePattern("08/15/1975")));
}
catch (ParseException e1)
{
System.out.println(" exception in APIDemo");
e1.printStackTrace();
}
collectionEventParameters.setContainer("No Additive Vacutainer");
collectionEventParameters.setCollectionProcedure("Needle Core Biopsy");
ReceivedEventParameters receivedEventParameters = new ReceivedEventParameters();
receivedEventParameters.setUser(user);
//receivedEventParameters.setId(new Long(0));
try
{
System.out.println("--- Start ---- 10");
receivedEventParameters.setTimestamp(Utility.parseDate("08/15/1975", Utility
.datePattern("08/15/1975")));
}
catch (ParseException e)
{
System.out.println("APIDemo");
e.printStackTrace();
}
receivedEventParameters.setReceivedQuality("Acceptable");
receivedEventParameters.setComments("");
Collection specimenEventCollection = new HashSet();
specimenEventCollection.add(collectionEventParameters);
specimenEventCollection.add(receivedEventParameters);
molecularSpecimen.setSpecimenEventCollection(specimenEventCollection);
// Biohazard biohazard = new Biohazard();
// biohazard.setName("Biohazard1");
// biohazard.setType("Toxic");
// biohazard.setId(new Long(1));
Biohazard biohazard = (Biohazard)ClientDemo.dataModelObjectMap.get("Biohazard");
Collection biohazardCollection = new HashSet();
biohazardCollection.add(biohazard);
molecularSpecimen.setBiohazardCollection(biohazardCollection);
System.out.println(" -------- end -----------");
return molecularSpecimen;
}
/**
* @return SpecimenCollectionGroup
*/
public SpecimenCollectionGroup initSpecimenCollectionGroup()
{
SpecimenCollectionGroup specimenCollectionGroup = new SpecimenCollectionGroup();
// Site site = new Site();
// site.setId(new Long(1));
Site site = (Site)ClientDemo.dataModelObjectMap.get("Site");
specimenCollectionGroup.setSite(site);
specimenCollectionGroup.setClinicalDiagnosis("Abdominal fibromatosis");
specimenCollectionGroup.setClinicalStatus("Operative");
specimenCollectionGroup.setActivityStatus("Active");
// CollectionProtocolEvent collectionProtocol = new CollectionProtocolEvent();
// collectionProtocol.setId(new Long(1));
CollectionProtocolEvent collectionProtocolEvent = (CollectionProtocolEvent)ClientDemo.dataModelObjectMap.get("CollectionProtocolEvent");
specimenCollectionGroup.setCollectionProtocolEvent(collectionProtocolEvent);
// CollectionProtocolRegistration collectionProtocolRegistration = new CollectionProtocolRegistration();
// Participant participant = new Participant();
// participant.setId(new Long(1));
// collectionProtocolRegistration.setParticipant(participant);
// collectionProtocolRegistration.setId(new Long(1));
//collectionProtocolRegistration.setProtocolParticipantIdentifier("");
CollectionProtocolRegistration collectionProtocolRegistration = (CollectionProtocolRegistration)ClientDemo.dataModelObjectMap.get("CollectionProtocolRegistration");
// CollectionProtocolRegistration collectionProtocolRegistration = new CollectionProtocolRegistration();
// CollectionProtocol collectionProtocol = new CollectionProtocol();
// collectionProtocol.setId(new Long("1000"));
// Participant participant = new Participant();
// participant.setId(new Long("1000"));
// collectionProtocolRegistration.setCollectionProtocol(collectionProtocol);
// collectionProtocolRegistration.setParticipant(participant);
specimenCollectionGroup.setCollectionProtocolRegistration(collectionProtocolRegistration);
specimenCollectionGroup.setName("scg" + UniqueKeyGeneratorUtil.getUniqueKey());
ClinicalReport clinicalReport = new ClinicalReport();
clinicalReport.setSurgicalPathologyNumber("");
//clinicalReport.setId(new Long(1));
specimenCollectionGroup.setClinicalReport(clinicalReport);
return specimenCollectionGroup;
}
/**
* @return Distribution
*/
public Distribution initDistribution()
{
Distribution distribution = new Distribution();
distribution.setActivityStatus("Active");
Specimen specimen = (Specimen) ClientDemo.dataModelObjectMap.get("Specimen");
/*
= new MolecularSpecimen();
// specimen.setBarcode("");
// specimen.setLabel("new label");
specimen.setId(new Long(10));
Quantity quantity = new Quantity();
quantity.setValue(new Double(15));
specimen.setAvailableQuantity(quantity);
*/
DistributedItem distributedItem = new DistributedItem();
distributedItem.setQuantity(new Double(10));
distributedItem.setSpecimen(specimen);
Collection distributedItemCollection = new HashSet();
distributedItemCollection.add(distributedItem);
distribution.setDistributedItemCollection(distributedItemCollection);
DistributionProtocol distributionProtocol = (DistributionProtocol) ClientDemo.dataModelObjectMap.get("DistributionProtocol");
distribution.setDistributionProtocol(distributionProtocol);
Site toSite = (Site) ClientDemo.dataModelObjectMap.get("Site");
//toSite.setId(new Long("1000"));
distribution.setToSite(toSite);
/*
new Site();
toSite.setId(new Long(1));
distribution.setToSite(toSite);
*/
/*
try
{
distribution.setTimestamp(Utility.parseDate("08/15/1975", Utility
.datePattern("08/15/1975")));
}
catch (ParseException e)
{
e.printStackTrace();
}
*/
distribution.setComments("");
User user = (User) ClientDemo.dataModelObjectMap.get("User");
/*
new User();
user.setId(new Long(1));
*/
distribution.setUser(user);
return distribution;
}
/**
* @return DistributionProtocol
*/
public DistributionProtocol initDistributionProtocol()
{
DistributionProtocol distributionProtocol = new DistributionProtocol();
User principalInvestigator = (User) ClientDemo.dataModelObjectMap.get("User");
/*
new User();
principalInvestigator.setId(new Long(1));
*/
distributionProtocol.setPrincipalInvestigator(principalInvestigator);
distributionProtocol.setTitle("DP"+ UniqueKeyGeneratorUtil.getUniqueKey());
distributionProtocol.setShortTitle("DP1");
distributionProtocol.setIrbIdentifier("55555");
try
{
distributionProtocol.setStartDate(Utility.parseDate("08/15/1975", Utility
.datePattern("08/15/1975")));
}
catch (ParseException e)
{
e.printStackTrace();
}
distributionProtocol.setDescriptionURL("");
distributionProtocol.setEnrollment(new Integer(10));
SpecimenRequirement specimenRequirement = (SpecimenRequirement) ClientDemo.dataModelObjectMap.get("SpecimenRequirement");
/*
new SpecimenRequirement();
specimenRequirement.setPathologyStatus("Malignant");
specimenRequirement.setTissueSite("Placenta");
specimenRequirement.setSpecimenType("DNA");
specimenRequirement.setSpecimenClass("Molecular");
Quantity quantity = new Quantity();
quantity.setValue(new Double(10));
specimenRequirement.setQuantity(quantity);
*/
Collection specimenRequirementCollection = new HashSet();
specimenRequirementCollection.add(specimenRequirement);
distributionProtocol.setSpecimenRequirementCollection(specimenRequirementCollection);
distributionProtocol.setActivityStatus("Active");
return distributionProtocol;
}
/**
* @return CollectionProtocolRegistration
*/
public CollectionProtocolRegistration initCollectionProtocolRegistration()
{
CollectionProtocolRegistration collectionProtocolRegistration = new CollectionProtocolRegistration();
// CollectionProtocol collectionProtocol = new CollectionProtocol();
// collectionProtocol.setId(new Long(1));
CollectionProtocol collectionProtocol = (CollectionProtocol)ClientDemo.dataModelObjectMap.get("CollectionProtocol");
collectionProtocolRegistration.setCollectionProtocol(collectionProtocol);
// Participant participant = new Participant();
// participant.setId(new Long(1));
Participant participant = (Participant)ClientDemo.dataModelObjectMap.get("Participant");
collectionProtocolRegistration.setParticipant(participant);
collectionProtocolRegistration.setProtocolParticipantIdentifier("");
collectionProtocolRegistration.setActivityStatus("Active");
/*
try
{
collectionProtocolRegistration.setRegistrationDate(Utility.parseDate("08/15/1975",
Utility.datePattern("08/15/1975")));
}
catch (ParseException e)
{
e.printStackTrace();
}
*/
return collectionProtocolRegistration;
}
public SpecimenArray initSpecimenArray()
{
SpecimenArray specimenArray = new SpecimenArray();
SpecimenArrayType specimenArrayType = (SpecimenArrayType) ClientDemo.dataModelObjectMap.get("SpecimenArrayType");
/*
new SpecimenArrayType();
specimenArrayType.setId(new Long(9));
*/
specimenArray.setSpecimenArrayType(specimenArrayType);
specimenArray.setBarcode("bar" + UniqueKeyGeneratorUtil.getUniqueKey());
specimenArray.setName("sa" + UniqueKeyGeneratorUtil.getUniqueKey());
User createdBy = (User) ClientDemo.dataModelObjectMap.get("User");
/*
new User();
createdBy.setId(new Long(1));
*/
specimenArray.setCreatedBy(createdBy);
Capacity capacity = specimenArrayType.getCapacity();
/* capacity.setOneDimensionCapacity(1);
capacity.setTwoDimensionCapacity(2);
*/ specimenArray.setCapacity(capacity);
specimenArray.setComment("");
StorageContainer storageContainer = (StorageContainer) ClientDemo.dataModelObjectMap.get("StorageContainer");
/*
new StorageContainer();
storageContainer.setId(new Long(1));
*/
storageContainer=new StorageContainer();
storageContainer.setId(new Long(1));
specimenArray.setStorageContainer(storageContainer);
specimenArray.setPositionDimensionOne(new Integer(1));
specimenArray.setPositionDimensionTwo(new Integer(1));
Collection specimenArrayContentCollection = new HashSet();
SpecimenArrayContent specimenArrayContent = new SpecimenArrayContent();
Specimen specimen = (Specimen) ClientDemo.dataModelObjectMap.get("Specimen");
/* specimen.setLabel("Specimen 12");
//specimen.setType("DNA");
specimen.setId(new Long(10));
*/
specimenArrayContent.setSpecimen(specimen);
specimenArrayContent.setPositionDimensionOne(new Integer(1));
specimenArrayContent.setPositionDimensionTwo(new Integer(1));
Quantity quantity = new Quantity();
quantity.setValue(new Double(2));
specimenArrayContent.setInitialQuantity(quantity);
specimenArrayContentCollection.add(specimenArrayContent);
specimenArray.setSpecimenArrayContentCollection(specimenArrayContentCollection);
return specimenArray;
}
public SpecimenCharacteristics initSpecimenCharacteristics()
{
SpecimenCharacteristics specimenCharacteristics = new SpecimenCharacteristics();
specimenCharacteristics.setTissueSide("Left");
specimenCharacteristics.setTissueSite("Placenta");
specimenCharacteristics.setId(new Long(1));
return specimenCharacteristics;
}
public SpecimenRequirement initSpecimenRequirement()
{
SpecimenRequirement specimenRequirement = new SpecimenRequirement();
specimenRequirement.setSpecimenClass("Molecular");
specimenRequirement.setSpecimenType("DNA");
specimenRequirement.setTissueSite("Placenta");
specimenRequirement.setPathologyStatus("Malignant");
Quantity quantity = new Quantity();
quantity.setValue(new Double(10));
specimenRequirement.setQuantity(quantity);
return specimenRequirement;
}
public CollectionProtocolEvent initCollectionProtocolEvent()
{
CollectionProtocolEvent collectionProtocolEvent = new CollectionProtocolEvent();
collectionProtocolEvent.setId(new Long(1));
return collectionProtocolEvent;
}
//Update methods starts
public void updateInstitution(Institution institution)
{
institution.setName("inst"+UniqueKeyGeneratorUtil.getUniqueKey());
}
public void updateDepartment(Department department)
{
department.setName("dt"+UniqueKeyGeneratorUtil.getUniqueKey());
}
public void updateCancerResearchGroup(CancerResearchGroup cancerResearchGroup)
{
cancerResearchGroup.setName("crg"+UniqueKeyGeneratorUtil.getUniqueKey());
}
public void updateBiohazard(Biohazard bioHazard)
{
bioHazard.setComments("Radioactive");
bioHazard.setName("bh" + UniqueKeyGeneratorUtil.getUniqueKey());
bioHazard.setType("Radioactive"); //Toxic
}
public void updateSite(Site siteObj)
{
siteObj.setEmailAddress("admin1@admin.com");
siteObj.setName("sit" + UniqueKeyGeneratorUtil.getUniqueKey());
siteObj.setType("Repository");
siteObj.setActivityStatus("Active");
siteObj.getAddress().setCity("Saint Louis1");
siteObj.getAddress().setCountry("United States");
siteObj.getAddress().setFaxNumber("555-55-55551");
siteObj.getAddress().setPhoneNumber("1236781");
siteObj.getAddress().setState("Missouri");
siteObj.getAddress().setStreet("4939 Children's Place1");
siteObj.getAddress().setZipCode("63111");
}
public void updateCollectionProtocolRegistration(CollectionProtocolRegistration collectionProtocolRegistration)
{
CollectionProtocol collectionProtocol = (CollectionProtocol)ClientDemo.dataModelObjectMap.get("CollectionProtocol");
collectionProtocolRegistration.setCollectionProtocol(collectionProtocol);
Participant participant = (Participant)ClientDemo.dataModelObjectMap.get("Participant");
collectionProtocolRegistration.setParticipant(null);
collectionProtocolRegistration.setProtocolParticipantIdentifier("11111");
collectionProtocolRegistration.setActivityStatus("Active");
}
public void updateSpecimenCollectionGroup(SpecimenCollectionGroup specimenCollectionGroup)
{
Site site = (Site)ClientDemo.dataModelObjectMap.get("Site");
specimenCollectionGroup.setSite(site);
specimenCollectionGroup.setClinicalDiagnosis("Dentinoma");//Abdominal fibromatosis
specimenCollectionGroup.setClinicalStatus("New Diagnosis"); //Operative
specimenCollectionGroup.setActivityStatus("Active");
CollectionProtocolEvent collectionProtocolEvent = (CollectionProtocolEvent)ClientDemo.dataModelObjectMap.get("CollectionProtocolEvent");
specimenCollectionGroup.setCollectionProtocolEvent(collectionProtocolEvent);
CollectionProtocolRegistration collectionProtocolRegistration = (CollectionProtocolRegistration)ClientDemo.dataModelObjectMap.get("CollectionProtocolRegistration");
specimenCollectionGroup.setCollectionProtocolRegistration(collectionProtocolRegistration);
specimenCollectionGroup.setName("scg" + UniqueKeyGeneratorUtil.getUniqueKey());
//clinicalReport = new ClinicalReport();
//clinicalReport.setSurgicalPathologyNumber("123");
specimenCollectionGroup.getClinicalReport().setSurgicalPathologyNumber("1234");
}
public void updateParticipant(Participant participant)
{
participant.setLastName("last" + UniqueKeyGeneratorUtil.getUniqueKey());
participant.setFirstName("frst" + UniqueKeyGeneratorUtil.getUniqueKey());
participant.setMiddleName("mdl" + UniqueKeyGeneratorUtil.getUniqueKey());
/*try
{
System.out.println("-----------------------");
participant.setBirthDate(Utility.parseDate("08/15/1975", Utility
.datePattern("08/15/1975")));
}
catch (ParseException e)
{
// TODO Auto-generated catch block
System.out.println("-----------------------"+e);
e.printStackTrace();
}
try
{
System.out.println("-----------------------");
participant.setDeathDate(Utility.parseDate("08/15/1974", Utility
.datePattern("08/15/1974")));
}
catch (ParseException e)
{
// TODO Auto-generated catch block
System.out.println("-----------------------"+e);
e.printStackTrace();
}*/
participant.setVitalStatus("Alive"); //Dead
participant.setGender("Male"); //
participant.setSexGenotype(""); //XX
Collection raceCollection = new HashSet();
raceCollection.add("Black or African American"); //White
raceCollection.add("Unknown"); //Asian
participant.setRaceCollection(raceCollection);
participant.setActivityStatus("Active"); //Active
participant.setEthnicity("Unknown"); //Hispanic or Latino
//participant.setSocialSecurityNumber("333-33-3333");
Collection participantMedicalIdentifierCollection = new HashSet();
/*participantMedicalIdentifierCollection.add("Washington University School of Medicine");
participantMedicalIdentifierCollection.add("1111");
*/
participant
.setParticipantMedicalIdentifierCollection(participantMedicalIdentifierCollection);
}
public void updateDistributionProtocol(DistributionProtocol distributionProtocol)
{
User principalInvestigator = (User) ClientDemo.dataModelObjectMap.get("User");
/*
new User();
principalInvestigator.setId(new Long(1));
*/
distributionProtocol.setPrincipalInvestigator(principalInvestigator);
distributionProtocol.setTitle("DP"+ UniqueKeyGeneratorUtil.getUniqueKey());
distributionProtocol.setShortTitle("DP"); //DP1
distributionProtocol.setIrbIdentifier("11111");//55555
try
{
distributionProtocol.setStartDate(Utility.parseDate("08/15/1976", Utility
.datePattern("08/15/1976"))); //08/15/1975
}
catch (ParseException e)
{
e.printStackTrace();
}
distributionProtocol.setDescriptionURL("");
distributionProtocol.setEnrollment(new Integer(20)); //10
SpecimenRequirement specimenRequirement = (SpecimenRequirement) ClientDemo.dataModelObjectMap.get("SpecimenRequirement");
specimenRequirement.setPathologyStatus("Non-Malignant"); //Malignant
specimenRequirement.setTissueSite("Anal canal"); //Placenta
specimenRequirement.setSpecimenType("Bile"); //DNA
specimenRequirement.setSpecimenClass("Fluid"); //Molecular
Quantity quantity = new Quantity();
quantity.setValue(new Double(20)); //10
specimenRequirement.setQuantity(quantity);
Collection specimenRequirementCollection = new HashSet();
specimenRequirementCollection.add(specimenRequirement);
distributionProtocol.setSpecimenRequirementCollection(specimenRequirementCollection);
distributionProtocol.setActivityStatus("Active"); //Active
}
public void updateCollectionProtocol(CollectionProtocol collectionProtocol)
{
collectionProtocol.setAliqoutInSameContainer(new Boolean(false)); //true
collectionProtocol.setDescriptionURL("");
collectionProtocol.setActivityStatus("Active"); //Active
collectionProtocol.setEndDate(null);
collectionProtocol.setEnrollment(null);
collectionProtocol.setIrbIdentifier("11111");//77777
collectionProtocol.setTitle("cp" + UniqueKeyGeneratorUtil.getUniqueKey());
collectionProtocol.setShortTitle("cp"); //pc!
try
{
collectionProtocol.setStartDate(Utility.parseDate("08/15/1975", Utility
.datePattern("08/15/1975")));
}
catch (ParseException e)
{
e.printStackTrace();
}
Collection collectionProtocolEventCollectionSet = new HashSet();
//CollectionProtocolEvent collectionProtocolEvent = new CollectionProtocolEvent();
CollectionProtocolEvent collectionProtocolEvent = (CollectionProtocolEvent)ClientDemo.dataModelObjectMap.get("CollectionProtocolEvent");
collectionProtocolEvent.setClinicalStatus("Not Specified");//New Diagnosis
collectionProtocolEvent.setStudyCalendarEventPoint(new Double(2)); //1
Collection specimenRequirementCollection = new HashSet();
//SpecimenRequirement specimenRequirement = new SpecimenRequirement();
//specimenRequirement.setSpecimenClass("Molecular");
//specimenRequirement.setSpecimenType("DNA");
//specimenRequirement.setTissueSite("Placenta");
//specimenRequirement.setPathologyStatus("Malignant");
//Quantity quantity = new Quantity();
//quantity.setValue(new Double(10));
//specimenRequirement.setQuantity(quantity);
SpecimenRequirement specimenRequirement =(SpecimenRequirement)ClientDemo.dataModelObjectMap.get("SpecimenRequirement");
specimenRequirement.setSpecimenClass("Fluid"); //Molecular
specimenRequirement.setSpecimenType("Bile"); //DNA
specimenRequirement.setTissueSite("Anal canal"); //Placenta
specimenRequirement.setPathologyStatus("Non-Malignant");//Malignant
specimenRequirementCollection.add(specimenRequirement);
collectionProtocolEvent.setSpecimenRequirementCollection(specimenRequirementCollection);
collectionProtocolEventCollectionSet.add(collectionProtocolEvent);
collectionProtocol
.setCollectionProtocolEventCollection(collectionProtocolEventCollectionSet);
//User principalInvestigator = new User();
//principalInvestigator.setId(new Long(1));
User principalInvestigator = (User)ClientDemo.dataModelObjectMap.get("User");
collectionProtocol.setPrincipalInvestigator(principalInvestigator);
User protocolCordinator = new User();
protocolCordinator.setId(new Long(principalInvestigator.getId().longValue()-1));
Collection protocolCordinatorCollection = new HashSet();
protocolCordinatorCollection.add(protocolCordinator);
collectionProtocol.setUserCollection(protocolCordinatorCollection);
}
public void updateSpecimen(Specimen updateSpecimen)
{
SpecimenCollectionGroup specimenCollectionGroup = (SpecimenCollectionGroup)ClientDemo.dataModelObjectMap.get("SpecimenCollectionGroup");
updateSpecimen.setSpecimenCollectionGroup(specimenCollectionGroup);
updateSpecimen.setLabel("spec" + UniqueKeyGeneratorUtil.getUniqueKey());
updateSpecimen.setBarcode("bar" + UniqueKeyGeneratorUtil.getUniqueKey());
updateSpecimen.setType("DNA");
updateSpecimen.setAvailable(new Boolean(true));
updateSpecimen.setActivityStatus("Active");
SpecimenCharacteristics specimenCharacteristics = (SpecimenCharacteristics)ClientDemo.dataModelObjectMap.get("SpecimenCharacteristics");
updateSpecimen.setSpecimenCharacteristics(specimenCharacteristics);
updateSpecimen.setPathologicalStatus("Non-Malignant"); //Malignant
//updateSpecimen.setAvailableQuantity(quantity);
//updateSpecimen.setConcentrationInMicrogramPerMicroliter(new Double(10));
updateSpecimen.setComments("");
updateSpecimen.setStorageContainer(null);
updateSpecimen.setPositionDimensionOne(null);
updateSpecimen.setPositionDimensionTwo(null);
Collection externalIdentifierCollection = new HashSet();
ExternalIdentifier externalIdentifier = new ExternalIdentifier();
externalIdentifier.setName("eid" + UniqueKeyGeneratorUtil.getUniqueKey());
externalIdentifier.setValue("11");
externalIdentifier.setSpecimen(updateSpecimen);
externalIdentifierCollection.add(externalIdentifier);
updateSpecimen.setExternalIdentifierCollection(externalIdentifierCollection);
CollectionEventParameters collectionEventParameters = new CollectionEventParameters();
collectionEventParameters.setComments("");
User user = (User)ClientDemo.dataModelObjectMap.get("User");
collectionEventParameters.setUser(user);
try
{
collectionEventParameters.setTimestamp(Utility.parseDate("08/15/1976", Utility
.datePattern("08/15/1976"))); //08/15/1975
}
catch (ParseException e1)
{
System.out.println(" exception in APIDemo");
e1.printStackTrace();
}
collectionEventParameters.setContainer("ACD Vacutainer"); //No Additive Vacutainer
collectionEventParameters.setCollectionProcedure("Lavage");
ReceivedEventParameters receivedEventParameters = new ReceivedEventParameters();
receivedEventParameters.setUser(user);
try
{
System.out.println("--- Start ---- 10");
receivedEventParameters.setTimestamp(Utility.parseDate("08/15/1976", Utility
.datePattern("08/15/1976"))); //08/15/1976
}
catch (ParseException e)
{
System.out.println("APIDemo");
e.printStackTrace();
}
receivedEventParameters.setReceivedQuality("Clotted"); //Acceptable
receivedEventParameters.setComments("");
Collection specimenEventCollection = new HashSet();
specimenEventCollection.add(collectionEventParameters);
specimenEventCollection.add(receivedEventParameters);
updateSpecimen.setSpecimenEventCollection(specimenEventCollection);
Biohazard biohazard = (Biohazard)ClientDemo.dataModelObjectMap.get("Biohazard");
Collection biohazardCollection = new HashSet();
biohazardCollection.add(biohazard);
updateSpecimen.setBiohazardCollection(biohazardCollection);
}
private int getUniqueId()
{
return 1;
}
}
|
caTissueCore_caCORE_Client/APIDemo.java
|
import java.text.ParseException;
import java.util.Collection;
import java.util.HashSet;
import edu.wustl.catissuecore.domain.Address;
import edu.wustl.catissuecore.domain.Biohazard;
import edu.wustl.catissuecore.domain.CancerResearchGroup;
import edu.wustl.catissuecore.domain.Capacity;
import edu.wustl.catissuecore.domain.ClinicalReport;
import edu.wustl.catissuecore.domain.CollectionEventParameters;
import edu.wustl.catissuecore.domain.CollectionProtocol;
import edu.wustl.catissuecore.domain.CollectionProtocolEvent;
import edu.wustl.catissuecore.domain.CollectionProtocolRegistration;
import edu.wustl.catissuecore.domain.Department;
import edu.wustl.catissuecore.domain.DistributedItem;
import edu.wustl.catissuecore.domain.Distribution;
import edu.wustl.catissuecore.domain.DistributionProtocol;
import edu.wustl.catissuecore.domain.ExternalIdentifier;
import edu.wustl.catissuecore.domain.Institution;
import edu.wustl.catissuecore.domain.MolecularSpecimen;
import edu.wustl.catissuecore.domain.Participant;
import edu.wustl.catissuecore.domain.Quantity;
import edu.wustl.catissuecore.domain.ReceivedEventParameters;
import edu.wustl.catissuecore.domain.Site;
import edu.wustl.catissuecore.domain.Specimen;
import edu.wustl.catissuecore.domain.SpecimenArray;
import edu.wustl.catissuecore.domain.SpecimenArrayContent;
import edu.wustl.catissuecore.domain.SpecimenArrayType;
import edu.wustl.catissuecore.domain.SpecimenCharacteristics;
import edu.wustl.catissuecore.domain.SpecimenCollectionGroup;
import edu.wustl.catissuecore.domain.SpecimenRequirement;
import edu.wustl.catissuecore.domain.StorageContainer;
import edu.wustl.catissuecore.domain.StorageType;
import edu.wustl.catissuecore.domain.User;
import edu.wustl.common.util.Utility;
import edu.wustl.common.util.global.Constants;
/**
* @author ashish_gupta
*
*/
public class APIDemo
{
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception
{
/*
Variables.applicationHome = System.getProperty("user.dir");
Logger.out = org.apache.log4j.Logger.getLogger("");
PropertyConfigurator.configure(Variables.applicationHome + "\\WEB-INF\\src\\"
+ "ApplicationResources.properties");
System
.setProperty("gov.nih.nci.security.configFile",
"C:/jboss-4.0.0/server/default/catissuecore-properties/ApplicationSecurityConfig.xml");
System
.setProperty("app.propertiesFile",
"C:/jboss-4.0.0/server/default/catissuecore-properties/caTissueCore_Properties.xml");
CDEManager.init();
XMLPropertyHandler.init("caTissueCore_Properties.xml");
ApplicationProperties.initBundle("ApplicationResources");
APIDemo apiDemo = new APIDemo();
SessionDataBean sessionDataBean = new SessionDataBean();
sessionDataBean.setUserName("admin@admin.com");
BizLogicFactory bizLogicFactory = BizLogicFactory.getInstance();
// Department dept = apiDemo.initDepartment();
// apiDemo.addData(bizLogicFactory, sessionDataBean, dept);
//
// Biohazard hazardObj=apiDemo.initBioHazard();
// apiDemo.addData(bizLogicFactory, sessionDataBean, hazardObj);
//
// CancerResearchGroup cancerResearchGroup = apiDemo.initCancerResearchGroup();
// apiDemo.addData(bizLogicFactory, sessionDataBean, cancerResearchGroup);
//
// Institution institution = apiDemo.initInstitution();
// apiDemo.addData(bizLogicFactory, sessionDataBean, institution);
//
// Site site = apiDemo.initSite();
// apiDemo.addData(bizLogicFactory, sessionDataBean, site);
//
// StorageType storageType = apiDemo.initStorageType();
// apiDemo.addData(bizLogicFactory, sessionDataBean, storageType);
//
// SpecimenArrayType specimenArrayType = apiDemo.initSpecimenArrayType();
// apiDemo.addData(bizLogicFactory, sessionDataBean, specimenArrayType);
//
// User user = apiDemo.initUser();
// apiDemo.addData(bizLogicFactory, sessionDataBean, user);
//
// Participant participant = apiDemo.initParticipant();
// apiDemo.addData(bizLogicFactory, sessionDataBean, participant);
//
// StorageContainer storageContainer = apiDemo.initStorageContainer();
// apiDemo.addData(bizLogicFactory, sessionDataBean, storageContainer);
//
// CollectionProtocol collectionProtocol = apiDemo.initCollectionProtocol();
// apiDemo.addData(bizLogicFactory, sessionDataBean, collectionProtocol);
//
// DistributionProtocol distributionProtocol = apiDemo.initDistributionProtocol();
// apiDemo.addData(bizLogicFactory, sessionDataBean, distributionProtocol);
//
// CollectionProtocolRegistration collectionProtocolRegistration = apiDemo.initCollectionProtocolRegistration();
// apiDemo.addData(bizLogicFactory, sessionDataBean, collectionProtocolRegistration);
// SpecimenCollectionGroup specimenCollectionGroup = apiDemo.initSpecimenCollectionGroup();
// apiDemo.addData(bizLogicFactory, sessionDataBean, specimenCollectionGroup);
// Specimen specimen = apiDemo.initSpecimen();
// apiDemo.addData(bizLogicFactory, sessionDataBean, specimen);
Distribution distribution = apiDemo.initDistribution();
apiDemo.addData(bizLogicFactory, sessionDataBean, distribution);
*/
}
/**
* @param bizLogicFactory
* @param sessionDataBean
* @param obj
* @throws Exception
private void addData(BizLogicFactory bizLogicFactory, SessionDataBean sessionDataBean,
Object obj) throws Exception
{
IBizLogic bizLogic = bizLogicFactory.getBizLogic(obj.getClass().getName());
bizLogic.insert(obj, sessionDataBean, Constants.HIBERNATE_DAO);
}
*/
/**
* @return Department
*/
public Department initDepartment()
{
Department dept = new Department();
dept.setName("dt" + UniqueKeyGeneratorUtil.getUniqueKey());
return dept;
}
/**
* @return Biohazard
*/
public Biohazard initBioHazard()
{
Biohazard bioHazard = new Biohazard();
bioHazard.setComments("NueroToxicProtein");
bioHazard.setName("bh" + UniqueKeyGeneratorUtil.getUniqueKey());
bioHazard.setType("Toxic");
return bioHazard;
}
/**
* @return CancerResearchGroup
*/
public CancerResearchGroup initCancerResearchGroup()
{
CancerResearchGroup cancerResearchGroup = new CancerResearchGroup();
cancerResearchGroup.setName("crg" + UniqueKeyGeneratorUtil.getUniqueKey());
return cancerResearchGroup;
}
/**
* @return Institution
*/
public Institution initInstitution()
{
Institution institutionObj = new Institution();
institutionObj.setName("inst" + UniqueKeyGeneratorUtil.getUniqueKey());
return institutionObj;
}
/**
* @return User
*/
public User initUser()
{
User userObj = new User();
userObj.setEmailAddress(UniqueKeyGeneratorUtil.getUniqueKey()+ "@admin.com");
userObj.setLoginName(userObj.getEmailAddress());
userObj.setLastName("last" + UniqueKeyGeneratorUtil.getUniqueKey());
userObj.setFirstName("name" + UniqueKeyGeneratorUtil.getUniqueKey());
Address address = new Address();
address.setStreet("Main street");
address.setCity("New hampshier");
address.setState("D.C.");
address.setZipCode("12345");
address.setCountry("United States");
address.setPhoneNumber("21222324");
address.setFaxNumber("21222324");
userObj.setAddress(address);
// Institution institution = new Institution();
// institution.setId(new Long(1));
Institution institution = (Institution) ClientDemo.dataModelObjectMap.get("Institution");
userObj.setInstitution(institution);
// Department department = new Department();
// department.setId(new Long(1));
Department department = (Department)ClientDemo.dataModelObjectMap.get("Department");
userObj.setDepartment(department);
// CancerResearchGroup cancerResearchGroup = new CancerResearchGroup();
// cancerResearchGroup.setId(new Long(1));
CancerResearchGroup cancerResearchGroup = (CancerResearchGroup)ClientDemo.dataModelObjectMap.get("CancerResearchGroup");
userObj.setCancerResearchGroup(cancerResearchGroup);
//userObj.setRoleId("1");
//userObj.setComments("");
userObj.setPageOf(Constants.PAGEOF_SIGNUP);
//userObj.setActivityStatus("Active");
//userObj.setCsmUserId(new Long(1));
//userObj.setFirstTimeLogin(Boolean.valueOf(false));
return userObj;
}
public User initAdminUser()
{
User userObj = new User();
userObj.setEmailAddress(UniqueKeyGeneratorUtil.getUniqueKey()+ "@admin.com");
userObj.setLoginName(userObj.getEmailAddress());
userObj.setLastName("last" + UniqueKeyGeneratorUtil.getUniqueKey());
userObj.setFirstName("name" + UniqueKeyGeneratorUtil.getUniqueKey());
Address address = new Address();
address.setStreet("Main street");
address.setCity("New hampshier");
address.setState("D.C.");
address.setZipCode("12345");
address.setCountry("United States");
address.setPhoneNumber("21222324");
address.setFaxNumber("21222324");
userObj.setAddress(address);
// Institution institution = new Institution();
// institution.setId(new Long(1));
Institution institution = (Institution) ClientDemo.dataModelObjectMap.get("Institution");
userObj.setInstitution(institution);
// Department department = new Department();
// department.setId(new Long(1));
Department department = (Department)ClientDemo.dataModelObjectMap.get("Department");
userObj.setDepartment(department);
// CancerResearchGroup cancerResearchGroup = new CancerResearchGroup();
// cancerResearchGroup.setId(new Long(1));
CancerResearchGroup cancerResearchGroup = (CancerResearchGroup)ClientDemo.dataModelObjectMap.get("CancerResearchGroup");
userObj.setCancerResearchGroup(cancerResearchGroup);
userObj.setRoleId("1");
userObj.setActivityStatus("Active");
//userObj.setComments("");
userObj.setPageOf(Constants.PAGEOF_USER_ADMIN);
//userObj.setCsmUserId(new Long(1));
//userObj.setFirstTimeLogin(Boolean.valueOf(false));
return userObj;
}
/**
* @return StorageType
*/
public StorageType initStorageType()
{
StorageType storageTypeObj = new StorageType();
Capacity capacity = new Capacity();
storageTypeObj.setName("st" + UniqueKeyGeneratorUtil.getUniqueKey());
storageTypeObj.setDefaultTempratureInCentigrade(new Double(-30));
storageTypeObj.setOneDimensionLabel("label 1");
storageTypeObj.setTwoDimensionLabel("label 2");
capacity.setOneDimensionCapacity(new Integer(3));
capacity.setTwoDimensionCapacity(new Integer(3));
storageTypeObj.setCapacity(capacity);
//storageTypeObj.setId(new Long(20));
Collection holdsStorageTypeCollection = new HashSet();
holdsStorageTypeCollection.add(storageTypeObj);
storageTypeObj.setHoldsStorageTypeCollection(holdsStorageTypeCollection);
storageTypeObj.setActivityStatus("Active");
Collection holdsSpecimenClassCollection = new HashSet();
holdsSpecimenClassCollection.add("Tissue");
holdsSpecimenClassCollection.add("Fluid");
holdsSpecimenClassCollection.add("Molecular");
storageTypeObj.setHoldsSpecimenClassCollection(holdsSpecimenClassCollection);
return storageTypeObj;
}
/**
* @return SpecimenArrayType
*/
public SpecimenArrayType initSpecimenArrayType()
{
SpecimenArrayType specimenArrayType = new SpecimenArrayType();
specimenArrayType.setName("sat" + UniqueKeyGeneratorUtil.getUniqueKey());
specimenArrayType.setSpecimenClass("Molecular");
Collection specimenTypeCollection = new HashSet();
specimenTypeCollection.add("DNA");
specimenTypeCollection.add("RNA");
specimenArrayType.setSpecimenTypeCollection(specimenTypeCollection);
specimenArrayType.setComment("");
Capacity capacity = new Capacity();
capacity.setOneDimensionCapacity(new Integer(4));
capacity.setTwoDimensionCapacity(new Integer(4));
specimenArrayType.setCapacity(capacity);
return specimenArrayType;
}
/**
* @return StorageContainer
*/
public StorageContainer initStorageContainer()
{
StorageContainer storageContainer = new StorageContainer();
storageContainer.setName("sc" + UniqueKeyGeneratorUtil.getUniqueKey());
StorageType storageType = (StorageType) ClientDemo.dataModelObjectMap.get("StorageType");
/*
new StorageType();
storageType.setId(new Long(4));
*/
storageContainer.setStorageType(storageType);
Site site = (Site) ClientDemo.dataModelObjectMap.get("Site");
/*new Site();
site.setId(new Long(1));
*/
storageContainer.setSite(site);
Integer conts = new Integer(1);
storageContainer.setNoOfContainers(conts);
storageContainer.setTempratureInCentigrade(new Double(-30));
storageContainer.setBarcode("barc" + UniqueKeyGeneratorUtil.getUniqueKey());
Capacity capacity = new Capacity();
capacity.setOneDimensionCapacity(new Integer(1));
capacity.setTwoDimensionCapacity(new Integer(2));
storageContainer.setCapacity(capacity);
CollectionProtocol collectionProtocol = (CollectionProtocol) ClientDemo.dataModelObjectMap.get("CollectionProtocol");
/*
new CollectionProtocol();
collectionProtocol.setId(new Long(3));
*/
Collection collectionProtocolCollection = new HashSet();
collectionProtocolCollection.add(collectionProtocol);
storageContainer.setCollectionProtocolCollection(collectionProtocolCollection);
Collection holdsStorageTypeCollection = new HashSet();
holdsStorageTypeCollection.add(storageType);
storageContainer.setHoldsStorageTypeCollection(holdsStorageTypeCollection);
Collection holdsSpecimenClassCollection = new HashSet();
holdsSpecimenClassCollection.add("Tissue");
holdsSpecimenClassCollection.add("Molecular");
storageContainer.setHoldsSpecimenClassCollection(holdsSpecimenClassCollection);
/* Container parent = new Container();
parent.setId(new Long(2));
storageContainer.setParent(parent);
*/
storageContainer.setPositionDimensionOne(new Integer(1));
storageContainer.setPositionDimensionTwo(new Integer(2));
storageContainer.setActivityStatus("Active");
storageContainer.setFull(Boolean.valueOf(false));
return storageContainer;
}
/**
* @return Site
*/
public Site initSite()
{
Site siteObj = new Site();
// User userObj = new User();
// userObj.setId(new Long(1));
User userObj = (User) ClientDemo.dataModelObjectMap.get("User");
siteObj.setEmailAddress("admin@admin.com");
siteObj.setName("sit" + UniqueKeyGeneratorUtil.getUniqueKey());
siteObj.setType("Laboratory");
siteObj.setActivityStatus("Active");
siteObj.setCoordinator(userObj);
Address addressObj = new Address();
addressObj.setCity("Saint Louis");
addressObj.setCountry("United States");
addressObj.setFaxNumber("555-55-5555");
addressObj.setPhoneNumber("123678");
addressObj.setState("Missouri");
addressObj.setStreet("4939 Children's Place");
addressObj.setZipCode("63110");
siteObj.setAddress(addressObj);
return siteObj;
}
/**
* @return Participant
*/
public Participant initParticipant()
{
Participant participant = new Participant();
participant.setLastName("last" + UniqueKeyGeneratorUtil.getUniqueKey());
participant.setFirstName("frst" + UniqueKeyGeneratorUtil.getUniqueKey());
participant.setMiddleName("mdl" + UniqueKeyGeneratorUtil.getUniqueKey());
/*try
{
System.out.println("-----------------------");
participant.setBirthDate(Utility.parseDate("08/15/1975", Utility
.datePattern("08/15/1975")));
}
catch (ParseException e)
{
// TODO Auto-generated catch block
System.out.println("-----------------------"+e);
e.printStackTrace();
}
try
{
System.out.println("-----------------------");
participant.setDeathDate(Utility.parseDate("08/15/1974", Utility
.datePattern("08/15/1974")));
}
catch (ParseException e)
{
// TODO Auto-generated catch block
System.out.println("-----------------------"+e);
e.printStackTrace();
}*/
participant.setVitalStatus("Dead");
participant.setGender("Female");
participant.setSexGenotype("XX");
Collection raceCollection = new HashSet();
raceCollection.add("White");
raceCollection.add("Asian");
participant.setRaceCollection(raceCollection);
participant.setActivityStatus("Active");
participant.setEthnicity("Hispanic or Latino");
//participant.setSocialSecurityNumber("333-33-3333");
// Collection participantMedicalIdentifierCollection = new HashSet();
// /*participantMedicalIdentifierCollection.add("Washington University School of Medicine");
// participantMedicalIdentifierCollection.add("1111");
// */
// participant.setParticipantMedicalIdentifierCollection(participantMedicalIdentifierCollection);
return participant;
}
/**
* @return CollectionProtocol
*/
public CollectionProtocol initCollectionProtocol()
{
CollectionProtocol collectionProtocol = new CollectionProtocol();
collectionProtocol.setAliqoutInSameContainer(new Boolean(true));
collectionProtocol.setDescriptionURL("");
collectionProtocol.setActivityStatus("Active");
collectionProtocol.setEndDate(null);
collectionProtocol.setEnrollment(null);
collectionProtocol.setIrbIdentifier("77777");
collectionProtocol.setTitle("cp" + UniqueKeyGeneratorUtil.getUniqueKey());
collectionProtocol.setShortTitle("pc!");
try
{
collectionProtocol.setStartDate(Utility.parseDate("08/15/1975", Utility
.datePattern("08/15/1975")));
}
catch (ParseException e)
{
e.printStackTrace();
}
Collection collectionProtocolEventCollectionSet = new HashSet();
// CollectionProtocolEvent collectionProtocolEvent = new CollectionProtocolEvent();
CollectionProtocolEvent collectionProtocolEvent = (CollectionProtocolEvent)ClientDemo.dataModelObjectMap.get("CollectionProtocolEvent");
collectionProtocolEvent.setClinicalStatus("New Diagnosis");
collectionProtocolEvent.setStudyCalendarEventPoint(new Double(1));
Collection specimenRequirementCollection = new HashSet();
// SpecimenRequirement specimenRequirement = new SpecimenRequirement();
// specimenRequirement.setSpecimenClass("Molecular");
// specimenRequirement.setSpecimenType("DNA");
// specimenRequirement.setTissueSite("Placenta");
// specimenRequirement.setPathologyStatus("Malignant");
// Quantity quantity = new Quantity();
// quantity.setValue(new Double(10));
// specimenRequirement.setQuantity(quantity);
SpecimenRequirement specimenRequirement =(SpecimenRequirement)ClientDemo.dataModelObjectMap.get("SpecimenRequirement");
specimenRequirementCollection.add(specimenRequirement);
collectionProtocolEvent.setSpecimenRequirementCollection(specimenRequirementCollection);
collectionProtocolEventCollectionSet.add(collectionProtocolEvent);
collectionProtocol
.setCollectionProtocolEventCollection(collectionProtocolEventCollectionSet);
// User principalInvestigator = new User();
// principalInvestigator.setId(new Long(1));
User principalInvestigator = (User)ClientDemo.dataModelObjectMap.get("User");
collectionProtocol.setPrincipalInvestigator(principalInvestigator);
// User protocolCordinator = new User();
// protocolCordinator.setId(new Long(principalInvestigator.getId().longValue()-1));
User protocolCordinator = (User)ClientDemo.dataModelObjectMap.get("User1");
Collection protocolCordinatorCollection = new HashSet();
protocolCordinatorCollection.add(protocolCordinator);
collectionProtocol.setUserCollection(protocolCordinatorCollection);
return collectionProtocol;
}
/**
* @return Specimen
*/
public Specimen initSpecimen()
{
MolecularSpecimen molecularSpecimen = new MolecularSpecimen();
// SpecimenCollectionGroup specimenCollectionGroup = new SpecimenCollectionGroup();
// specimenCollectionGroup.setId(new Long(2));
SpecimenCollectionGroup specimenCollectionGroup = (SpecimenCollectionGroup)ClientDemo.dataModelObjectMap.get("SpecimenCollectionGroup");
molecularSpecimen.setSpecimenCollectionGroup(specimenCollectionGroup);
molecularSpecimen.setLabel("spec" + UniqueKeyGeneratorUtil.getUniqueKey());
molecularSpecimen.setBarcode("bar" + UniqueKeyGeneratorUtil.getUniqueKey());
molecularSpecimen.setType("DNA");
molecularSpecimen.setAvailable(new Boolean(true));
molecularSpecimen.setActivityStatus("Active");
// SpecimenCharacteristics specimenCharacteristics = new SpecimenCharacteristics();
// specimenCharacteristics.setTissueSide("Left");
// specimenCharacteristics.setTissueSite("Placenta");
// specimenCharacteristics.setId(new Long(1));
SpecimenCharacteristics specimenCharacteristics = (SpecimenCharacteristics)ClientDemo.dataModelObjectMap.get("SpecimenCharacteristics");
molecularSpecimen.setSpecimenCharacteristics(specimenCharacteristics);
molecularSpecimen.setPathologicalStatus("Malignant");
Quantity quantity = new Quantity();
quantity.setValue(new Double(10));
molecularSpecimen.setQuantity(quantity);
molecularSpecimen.setAvailableQuantity(quantity);
molecularSpecimen.setConcentrationInMicrogramPerMicroliter(new Double(10));
molecularSpecimen.setComments("");
molecularSpecimen.setLineage("Aliquot");
// Is virtually located
// StorageContainer sto = new StorageContainer();
// sto.setId(new Long("1"));
molecularSpecimen.setStorageContainer(null);
molecularSpecimen.setPositionDimensionOne(null);
molecularSpecimen.setPositionDimensionTwo(null);
Collection externalIdentifierCollection = new HashSet();
ExternalIdentifier externalIdentifier = new ExternalIdentifier();
externalIdentifier.setName("eid" + UniqueKeyGeneratorUtil.getUniqueKey());
externalIdentifier.setValue("11");
externalIdentifier.setSpecimen(molecularSpecimen);
externalIdentifierCollection.add(externalIdentifier);
molecularSpecimen.setExternalIdentifierCollection(externalIdentifierCollection);
CollectionEventParameters collectionEventParameters = new CollectionEventParameters();
collectionEventParameters.setComments("");
// User user = new User();
// user.setId(new Long(1));
// collectionEventParameters.setId(new Long(0));
User user = (User)ClientDemo.dataModelObjectMap.get("User");
collectionEventParameters.setUser(user);
try
{
collectionEventParameters.setTimestamp(Utility.parseDate("08/15/1975", Utility
.datePattern("08/15/1975")));
}
catch (ParseException e1)
{
System.out.println(" exception in APIDemo");
e1.printStackTrace();
}
collectionEventParameters.setContainer("No Additive Vacutainer");
collectionEventParameters.setCollectionProcedure("Needle Core Biopsy");
ReceivedEventParameters receivedEventParameters = new ReceivedEventParameters();
receivedEventParameters.setUser(user);
//receivedEventParameters.setId(new Long(0));
try
{
System.out.println("--- Start ---- 10");
receivedEventParameters.setTimestamp(Utility.parseDate("08/15/1975", Utility
.datePattern("08/15/1975")));
}
catch (ParseException e)
{
System.out.println("APIDemo");
e.printStackTrace();
}
receivedEventParameters.setReceivedQuality("Acceptable");
receivedEventParameters.setComments("");
Collection specimenEventCollection = new HashSet();
specimenEventCollection.add(collectionEventParameters);
specimenEventCollection.add(receivedEventParameters);
molecularSpecimen.setSpecimenEventCollection(specimenEventCollection);
// Biohazard biohazard = new Biohazard();
// biohazard.setName("Biohazard1");
// biohazard.setType("Toxic");
// biohazard.setId(new Long(1));
Biohazard biohazard = (Biohazard)ClientDemo.dataModelObjectMap.get("Biohazard");
Collection biohazardCollection = new HashSet();
biohazardCollection.add(biohazard);
molecularSpecimen.setBiohazardCollection(biohazardCollection);
System.out.println(" -------- end -----------");
return molecularSpecimen;
}
/**
* @return SpecimenCollectionGroup
*/
public SpecimenCollectionGroup initSpecimenCollectionGroup()
{
SpecimenCollectionGroup specimenCollectionGroup = new SpecimenCollectionGroup();
// Site site = new Site();
// site.setId(new Long(1));
Site site = (Site)ClientDemo.dataModelObjectMap.get("Site");
specimenCollectionGroup.setSite(site);
specimenCollectionGroup.setClinicalDiagnosis("Abdominal fibromatosis");
specimenCollectionGroup.setClinicalStatus("Operative");
specimenCollectionGroup.setActivityStatus("Active");
// CollectionProtocolEvent collectionProtocol = new CollectionProtocolEvent();
// collectionProtocol.setId(new Long(1));
CollectionProtocolEvent collectionProtocolEvent = (CollectionProtocolEvent)ClientDemo.dataModelObjectMap.get("CollectionProtocolEvent");
specimenCollectionGroup.setCollectionProtocolEvent(collectionProtocolEvent);
// CollectionProtocolRegistration collectionProtocolRegistration = new CollectionProtocolRegistration();
// Participant participant = new Participant();
// participant.setId(new Long(1));
// collectionProtocolRegistration.setParticipant(participant);
// collectionProtocolRegistration.setId(new Long(1));
//collectionProtocolRegistration.setProtocolParticipantIdentifier("");
CollectionProtocolRegistration collectionProtocolRegistration = (CollectionProtocolRegistration)ClientDemo.dataModelObjectMap.get("CollectionProtocolRegistration");
// CollectionProtocolRegistration collectionProtocolRegistration = new CollectionProtocolRegistration();
// CollectionProtocol collectionProtocol = new CollectionProtocol();
// collectionProtocol.setId(new Long("1000"));
// Participant participant = new Participant();
// participant.setId(new Long("1000"));
// collectionProtocolRegistration.setCollectionProtocol(collectionProtocol);
// collectionProtocolRegistration.setParticipant(participant);
specimenCollectionGroup.setCollectionProtocolRegistration(collectionProtocolRegistration);
specimenCollectionGroup.setName("scg" + UniqueKeyGeneratorUtil.getUniqueKey());
ClinicalReport clinicalReport = new ClinicalReport();
clinicalReport.setSurgicalPathologyNumber("");
//clinicalReport.setId(new Long(1));
specimenCollectionGroup.setClinicalReport(clinicalReport);
return specimenCollectionGroup;
}
/**
* @return Distribution
*/
public Distribution initDistribution()
{
Distribution distribution = new Distribution();
distribution.setActivityStatus("Active");
Specimen specimen = (Specimen) ClientDemo.dataModelObjectMap.get("Specimen");
/*
= new MolecularSpecimen();
// specimen.setBarcode("");
// specimen.setLabel("new label");
specimen.setId(new Long(10));
Quantity quantity = new Quantity();
quantity.setValue(new Double(15));
specimen.setAvailableQuantity(quantity);
*/
DistributedItem distributedItem = new DistributedItem();
distributedItem.setQuantity(new Double(10));
distributedItem.setSpecimen(specimen);
Collection distributedItemCollection = new HashSet();
distributedItemCollection.add(distributedItem);
distribution.setDistributedItemCollection(distributedItemCollection);
DistributionProtocol distributionProtocol = (DistributionProtocol) ClientDemo.dataModelObjectMap.get("DistributionProtocol");
distribution.setDistributionProtocol(distributionProtocol);
Site toSite = (Site) ClientDemo.dataModelObjectMap.get("Site");
//toSite.setId(new Long("1000"));
distribution.setToSite(toSite);
/*
new Site();
toSite.setId(new Long(1));
distribution.setToSite(toSite);
*/
/*
try
{
distribution.setTimestamp(Utility.parseDate("08/15/1975", Utility
.datePattern("08/15/1975")));
}
catch (ParseException e)
{
e.printStackTrace();
}
*/
distribution.setComments("");
User user = (User) ClientDemo.dataModelObjectMap.get("User");
/*
new User();
user.setId(new Long(1));
*/
distribution.setUser(user);
return distribution;
}
/**
* @return DistributionProtocol
*/
public DistributionProtocol initDistributionProtocol()
{
DistributionProtocol distributionProtocol = new DistributionProtocol();
User principalInvestigator = (User) ClientDemo.dataModelObjectMap.get("User");
/*
new User();
principalInvestigator.setId(new Long(1));
*/
distributionProtocol.setPrincipalInvestigator(principalInvestigator);
distributionProtocol.setTitle("DP"+ UniqueKeyGeneratorUtil.getUniqueKey());
distributionProtocol.setShortTitle("DP1");
distributionProtocol.setIrbIdentifier("55555");
try
{
distributionProtocol.setStartDate(Utility.parseDate("08/15/1975", Utility
.datePattern("08/15/1975")));
}
catch (ParseException e)
{
e.printStackTrace();
}
distributionProtocol.setDescriptionURL("");
distributionProtocol.setEnrollment(new Integer(10));
SpecimenRequirement specimenRequirement = (SpecimenRequirement) ClientDemo.dataModelObjectMap.get("SpecimenRequirement");
/*
new SpecimenRequirement();
specimenRequirement.setPathologyStatus("Malignant");
specimenRequirement.setTissueSite("Placenta");
specimenRequirement.setSpecimenType("DNA");
specimenRequirement.setSpecimenClass("Molecular");
Quantity quantity = new Quantity();
quantity.setValue(new Double(10));
specimenRequirement.setQuantity(quantity);
*/
Collection specimenRequirementCollection = new HashSet();
specimenRequirementCollection.add(specimenRequirement);
distributionProtocol.setSpecimenRequirementCollection(specimenRequirementCollection);
distributionProtocol.setActivityStatus("Active");
return distributionProtocol;
}
/**
* @return CollectionProtocolRegistration
*/
public CollectionProtocolRegistration initCollectionProtocolRegistration()
{
CollectionProtocolRegistration collectionProtocolRegistration = new CollectionProtocolRegistration();
// CollectionProtocol collectionProtocol = new CollectionProtocol();
// collectionProtocol.setId(new Long(1));
CollectionProtocol collectionProtocol = (CollectionProtocol)ClientDemo.dataModelObjectMap.get("CollectionProtocol");
collectionProtocolRegistration.setCollectionProtocol(collectionProtocol);
// Participant participant = new Participant();
// participant.setId(new Long(1));
Participant participant = (Participant)ClientDemo.dataModelObjectMap.get("Participant");
collectionProtocolRegistration.setParticipant(participant);
collectionProtocolRegistration.setProtocolParticipantIdentifier("");
collectionProtocolRegistration.setActivityStatus("Active");
/*
try
{
collectionProtocolRegistration.setRegistrationDate(Utility.parseDate("08/15/1975",
Utility.datePattern("08/15/1975")));
}
catch (ParseException e)
{
e.printStackTrace();
}
*/
return collectionProtocolRegistration;
}
public SpecimenArray initSpecimenArray()
{
SpecimenArray specimenArray = new SpecimenArray();
SpecimenArrayType specimenArrayType = (SpecimenArrayType) ClientDemo.dataModelObjectMap.get("SpecimenArrayType");
/*
new SpecimenArrayType();
specimenArrayType.setId(new Long(9));
*/
specimenArray.setSpecimenArrayType(specimenArrayType);
specimenArray.setBarcode("bar" + UniqueKeyGeneratorUtil.getUniqueKey());
specimenArray.setName("sa" + UniqueKeyGeneratorUtil.getUniqueKey());
User createdBy = (User) ClientDemo.dataModelObjectMap.get("User");
/*
new User();
createdBy.setId(new Long(1));
*/
specimenArray.setCreatedBy(createdBy);
Capacity capacity = specimenArrayType.getCapacity();
/* capacity.setOneDimensionCapacity(1);
capacity.setTwoDimensionCapacity(2);
*/ specimenArray.setCapacity(capacity);
specimenArray.setComment("");
StorageContainer storageContainer = (StorageContainer) ClientDemo.dataModelObjectMap.get("StorageContainer");
/*
new StorageContainer();
storageContainer.setId(new Long(1));
*/
storageContainer=new StorageContainer();
storageContainer.setId(new Long(1));
specimenArray.setStorageContainer(storageContainer);
specimenArray.setPositionDimensionOne(new Integer(1));
specimenArray.setPositionDimensionTwo(new Integer(1));
Collection specimenArrayContentCollection = new HashSet();
SpecimenArrayContent specimenArrayContent = new SpecimenArrayContent();
Specimen specimen = (Specimen) ClientDemo.dataModelObjectMap.get("Specimen");
/* specimen.setLabel("Specimen 12");
//specimen.setType("DNA");
specimen.setId(new Long(10));
*/
specimenArrayContent.setSpecimen(specimen);
Quantity quantity = new Quantity();
quantity.setValue(new Double(2));
specimenArrayContent.setInitialQuantity(quantity);
specimenArrayContentCollection.add(specimenArrayContent);
specimenArray.setSpecimenArrayContentCollection(specimenArrayContentCollection);
return specimenArray;
}
public SpecimenCharacteristics initSpecimenCharacteristics()
{
SpecimenCharacteristics specimenCharacteristics = new SpecimenCharacteristics();
specimenCharacteristics.setTissueSide("Left");
specimenCharacteristics.setTissueSite("Placenta");
specimenCharacteristics.setId(new Long(1));
return specimenCharacteristics;
}
public SpecimenRequirement initSpecimenRequirement()
{
SpecimenRequirement specimenRequirement = new SpecimenRequirement();
specimenRequirement.setSpecimenClass("Molecular");
specimenRequirement.setSpecimenType("DNA");
specimenRequirement.setTissueSite("Placenta");
specimenRequirement.setPathologyStatus("Malignant");
Quantity quantity = new Quantity();
quantity.setValue(new Double(10));
specimenRequirement.setQuantity(quantity);
return specimenRequirement;
}
public CollectionProtocolEvent initCollectionProtocolEvent()
{
CollectionProtocolEvent collectionProtocolEvent = new CollectionProtocolEvent();
collectionProtocolEvent.setId(new Long(1));
return collectionProtocolEvent;
}
//Update methods starts
public void updateInstitution(Institution institution)
{
institution.setName("inst"+UniqueKeyGeneratorUtil.getUniqueKey());
}
public void updateDepartment(Department department)
{
department.setName("dt"+UniqueKeyGeneratorUtil.getUniqueKey());
}
public void updateCancerResearchGroup(CancerResearchGroup cancerResearchGroup)
{
cancerResearchGroup.setName("crg"+UniqueKeyGeneratorUtil.getUniqueKey());
}
public void updateBiohazard(Biohazard bioHazard)
{
bioHazard.setComments("Radioactive");
bioHazard.setName("bh" + UniqueKeyGeneratorUtil.getUniqueKey());
bioHazard.setType("Radioactive"); //Toxic
}
public void updateSite(Site siteObj)
{
siteObj.setEmailAddress("admin1@admin.com");
siteObj.setName("sit" + UniqueKeyGeneratorUtil.getUniqueKey());
siteObj.setType("Repository");
siteObj.setActivityStatus("Active");
siteObj.getAddress().setCity("Saint Louis1");
siteObj.getAddress().setCountry("United States");
siteObj.getAddress().setFaxNumber("555-55-55551");
siteObj.getAddress().setPhoneNumber("1236781");
siteObj.getAddress().setState("Missouri");
siteObj.getAddress().setStreet("4939 Children's Place1");
siteObj.getAddress().setZipCode("63111");
}
public void updateCollectionProtocolRegistration(CollectionProtocolRegistration collectionProtocolRegistration)
{
CollectionProtocol collectionProtocol = (CollectionProtocol)ClientDemo.dataModelObjectMap.get("CollectionProtocol");
collectionProtocolRegistration.setCollectionProtocol(collectionProtocol);
Participant participant = (Participant)ClientDemo.dataModelObjectMap.get("Participant");
collectionProtocolRegistration.setParticipant(null);
collectionProtocolRegistration.setProtocolParticipantIdentifier("11111");
collectionProtocolRegistration.setActivityStatus("Active");
}
public void updateSpecimenCollectionGroup(SpecimenCollectionGroup specimenCollectionGroup)
{
Site site = (Site)ClientDemo.dataModelObjectMap.get("Site");
specimenCollectionGroup.setSite(site);
specimenCollectionGroup.setClinicalDiagnosis("Dentinoma");//Abdominal fibromatosis
specimenCollectionGroup.setClinicalStatus("New Diagnosis"); //Operative
specimenCollectionGroup.setActivityStatus("Active");
CollectionProtocolEvent collectionProtocolEvent = (CollectionProtocolEvent)ClientDemo.dataModelObjectMap.get("CollectionProtocolEvent");
specimenCollectionGroup.setCollectionProtocolEvent(collectionProtocolEvent);
CollectionProtocolRegistration collectionProtocolRegistration = (CollectionProtocolRegistration)ClientDemo.dataModelObjectMap.get("CollectionProtocolRegistration");
specimenCollectionGroup.setCollectionProtocolRegistration(collectionProtocolRegistration);
specimenCollectionGroup.setName("scg" + UniqueKeyGeneratorUtil.getUniqueKey());
//clinicalReport = new ClinicalReport();
//clinicalReport.setSurgicalPathologyNumber("123");
specimenCollectionGroup.getClinicalReport().setSurgicalPathologyNumber("1234");
}
public void updateParticipant(Participant participant)
{
participant.setLastName("last" + UniqueKeyGeneratorUtil.getUniqueKey());
participant.setFirstName("frst" + UniqueKeyGeneratorUtil.getUniqueKey());
participant.setMiddleName("mdl" + UniqueKeyGeneratorUtil.getUniqueKey());
/*try
{
System.out.println("-----------------------");
participant.setBirthDate(Utility.parseDate("08/15/1975", Utility
.datePattern("08/15/1975")));
}
catch (ParseException e)
{
// TODO Auto-generated catch block
System.out.println("-----------------------"+e);
e.printStackTrace();
}
try
{
System.out.println("-----------------------");
participant.setDeathDate(Utility.parseDate("08/15/1974", Utility
.datePattern("08/15/1974")));
}
catch (ParseException e)
{
// TODO Auto-generated catch block
System.out.println("-----------------------"+e);
e.printStackTrace();
}*/
participant.setVitalStatus("Alive"); //Dead
participant.setGender("Male"); //
participant.setSexGenotype(""); //XX
Collection raceCollection = new HashSet();
raceCollection.add("Black or African American"); //White
raceCollection.add("Unknown"); //Asian
participant.setRaceCollection(raceCollection);
participant.setActivityStatus("Active"); //Active
participant.setEthnicity("Unknown"); //Hispanic or Latino
//participant.setSocialSecurityNumber("333-33-3333");
Collection participantMedicalIdentifierCollection = new HashSet();
/*participantMedicalIdentifierCollection.add("Washington University School of Medicine");
participantMedicalIdentifierCollection.add("1111");
*/
participant
.setParticipantMedicalIdentifierCollection(participantMedicalIdentifierCollection);
}
public void updateDistributionProtocol(DistributionProtocol distributionProtocol)
{
User principalInvestigator = (User) ClientDemo.dataModelObjectMap.get("User");
/*
new User();
principalInvestigator.setId(new Long(1));
*/
distributionProtocol.setPrincipalInvestigator(principalInvestigator);
distributionProtocol.setTitle("DP"+ UniqueKeyGeneratorUtil.getUniqueKey());
distributionProtocol.setShortTitle("DP"); //DP1
distributionProtocol.setIrbIdentifier("11111");//55555
try
{
distributionProtocol.setStartDate(Utility.parseDate("08/15/1976", Utility
.datePattern("08/15/1976"))); //08/15/1975
}
catch (ParseException e)
{
e.printStackTrace();
}
distributionProtocol.setDescriptionURL("");
distributionProtocol.setEnrollment(new Integer(20)); //10
SpecimenRequirement specimenRequirement = (SpecimenRequirement) ClientDemo.dataModelObjectMap.get("SpecimenRequirement");
specimenRequirement.setPathologyStatus("Non-Malignant"); //Malignant
specimenRequirement.setTissueSite("Anal canal"); //Placenta
specimenRequirement.setSpecimenType("Bile"); //DNA
specimenRequirement.setSpecimenClass("Fluid"); //Molecular
Quantity quantity = new Quantity();
quantity.setValue(new Double(20)); //10
specimenRequirement.setQuantity(quantity);
Collection specimenRequirementCollection = new HashSet();
specimenRequirementCollection.add(specimenRequirement);
distributionProtocol.setSpecimenRequirementCollection(specimenRequirementCollection);
distributionProtocol.setActivityStatus("Active"); //Active
}
public void updateCollectionProtocol(CollectionProtocol collectionProtocol)
{
collectionProtocol.setAliqoutInSameContainer(new Boolean(false)); //true
collectionProtocol.setDescriptionURL("");
collectionProtocol.setActivityStatus("Active"); //Active
collectionProtocol.setEndDate(null);
collectionProtocol.setEnrollment(null);
collectionProtocol.setIrbIdentifier("11111");//77777
collectionProtocol.setTitle("cp" + UniqueKeyGeneratorUtil.getUniqueKey());
collectionProtocol.setShortTitle("cp"); //pc!
try
{
collectionProtocol.setStartDate(Utility.parseDate("08/15/1975", Utility
.datePattern("08/15/1975")));
}
catch (ParseException e)
{
e.printStackTrace();
}
Collection collectionProtocolEventCollectionSet = new HashSet();
//CollectionProtocolEvent collectionProtocolEvent = new CollectionProtocolEvent();
CollectionProtocolEvent collectionProtocolEvent = (CollectionProtocolEvent)ClientDemo.dataModelObjectMap.get("CollectionProtocolEvent");
collectionProtocolEvent.setClinicalStatus("Not Specified");//New Diagnosis
collectionProtocolEvent.setStudyCalendarEventPoint(new Double(2)); //1
Collection specimenRequirementCollection = new HashSet();
//SpecimenRequirement specimenRequirement = new SpecimenRequirement();
//specimenRequirement.setSpecimenClass("Molecular");
//specimenRequirement.setSpecimenType("DNA");
//specimenRequirement.setTissueSite("Placenta");
//specimenRequirement.setPathologyStatus("Malignant");
//Quantity quantity = new Quantity();
//quantity.setValue(new Double(10));
//specimenRequirement.setQuantity(quantity);
SpecimenRequirement specimenRequirement =(SpecimenRequirement)ClientDemo.dataModelObjectMap.get("SpecimenRequirement");
specimenRequirement.setSpecimenClass("Fluid"); //Molecular
specimenRequirement.setSpecimenType("Bile"); //DNA
specimenRequirement.setTissueSite("Anal canal"); //Placenta
specimenRequirement.setPathologyStatus("Non-Malignant");//Malignant
specimenRequirementCollection.add(specimenRequirement);
collectionProtocolEvent.setSpecimenRequirementCollection(specimenRequirementCollection);
collectionProtocolEventCollectionSet.add(collectionProtocolEvent);
collectionProtocol
.setCollectionProtocolEventCollection(collectionProtocolEventCollectionSet);
//User principalInvestigator = new User();
//principalInvestigator.setId(new Long(1));
User principalInvestigator = (User)ClientDemo.dataModelObjectMap.get("User");
collectionProtocol.setPrincipalInvestigator(principalInvestigator);
User protocolCordinator = new User();
protocolCordinator.setId(new Long(principalInvestigator.getId().longValue()-1));
Collection protocolCordinatorCollection = new HashSet();
protocolCordinatorCollection.add(protocolCordinator);
collectionProtocol.setUserCollection(protocolCordinatorCollection);
}
public void updateSpecimen(Specimen updateSpecimen)
{
SpecimenCollectionGroup specimenCollectionGroup = (SpecimenCollectionGroup)ClientDemo.dataModelObjectMap.get("SpecimenCollectionGroup");
updateSpecimen.setSpecimenCollectionGroup(specimenCollectionGroup);
updateSpecimen.setLabel("spec" + UniqueKeyGeneratorUtil.getUniqueKey());
updateSpecimen.setBarcode("bar" + UniqueKeyGeneratorUtil.getUniqueKey());
updateSpecimen.setType("DNA");
updateSpecimen.setAvailable(new Boolean(true));
updateSpecimen.setActivityStatus("Active");
SpecimenCharacteristics specimenCharacteristics = (SpecimenCharacteristics)ClientDemo.dataModelObjectMap.get("SpecimenCharacteristics");
updateSpecimen.setSpecimenCharacteristics(specimenCharacteristics);
updateSpecimen.setPathologicalStatus("Non-Malignant"); //Malignant
//updateSpecimen.setAvailableQuantity(quantity);
//updateSpecimen.setConcentrationInMicrogramPerMicroliter(new Double(10));
updateSpecimen.setComments("");
updateSpecimen.setStorageContainer(null);
updateSpecimen.setPositionDimensionOne(null);
updateSpecimen.setPositionDimensionTwo(null);
Collection externalIdentifierCollection = new HashSet();
ExternalIdentifier externalIdentifier = new ExternalIdentifier();
externalIdentifier.setName("eid" + UniqueKeyGeneratorUtil.getUniqueKey());
externalIdentifier.setValue("11");
externalIdentifier.setSpecimen(updateSpecimen);
externalIdentifierCollection.add(externalIdentifier);
updateSpecimen.setExternalIdentifierCollection(externalIdentifierCollection);
CollectionEventParameters collectionEventParameters = new CollectionEventParameters();
collectionEventParameters.setComments("");
User user = (User)ClientDemo.dataModelObjectMap.get("User");
collectionEventParameters.setUser(user);
try
{
collectionEventParameters.setTimestamp(Utility.parseDate("08/15/1976", Utility
.datePattern("08/15/1976"))); //08/15/1975
}
catch (ParseException e1)
{
System.out.println(" exception in APIDemo");
e1.printStackTrace();
}
collectionEventParameters.setContainer("ACD Vacutainer"); //No Additive Vacutainer
collectionEventParameters.setCollectionProcedure("Lavage");
ReceivedEventParameters receivedEventParameters = new ReceivedEventParameters();
receivedEventParameters.setUser(user);
try
{
System.out.println("--- Start ---- 10");
receivedEventParameters.setTimestamp(Utility.parseDate("08/15/1976", Utility
.datePattern("08/15/1976"))); //08/15/1976
}
catch (ParseException e)
{
System.out.println("APIDemo");
e.printStackTrace();
}
receivedEventParameters.setReceivedQuality("Clotted"); //Acceptable
receivedEventParameters.setComments("");
Collection specimenEventCollection = new HashSet();
specimenEventCollection.add(collectionEventParameters);
specimenEventCollection.add(receivedEventParameters);
updateSpecimen.setSpecimenEventCollection(specimenEventCollection);
Biohazard biohazard = (Biohazard)ClientDemo.dataModelObjectMap.get("Biohazard");
Collection biohazardCollection = new HashSet();
biohazardCollection.add(biohazard);
updateSpecimen.setBiohazardCollection(biohazardCollection);
}
private int getUniqueId()
{
return 1;
}
}
|
added dimension position for array
SVN-Revision: 5145
|
caTissueCore_caCORE_Client/APIDemo.java
|
added dimension position for array
|
|
Java
|
bsd-3-clause
|
8466b25c6b161402f35c0254ca47491fe8fb7334
| 0
|
atomixnmc/jmonkeyengine,jMonkeyEngine/jmonkeyengine,yetanotherindie/jMonkey-Engine,davidB/jmonkeyengine,GreenCubes/jmonkeyengine,mbenson/jmonkeyengine,weilichuang/jmonkeyengine,d235j/jmonkeyengine,delftsre/jmonkeyengine,phr00t/jmonkeyengine,Georgeto/jmonkeyengine,delftsre/jmonkeyengine,atomixnmc/jmonkeyengine,weilichuang/jmonkeyengine,weilichuang/jmonkeyengine,mbenson/jmonkeyengine,olafmaas/jmonkeyengine,atomixnmc/jmonkeyengine,bsmr-java/jmonkeyengine,nickschot/jmonkeyengine,shurun19851206/jMonkeyEngine,weilichuang/jmonkeyengine,danteinforno/jmonkeyengine,delftsre/jmonkeyengine,InShadow/jmonkeyengine,yetanotherindie/jMonkey-Engine,nickschot/jmonkeyengine,zzuegg/jmonkeyengine,aaronang/jmonkeyengine,danteinforno/jmonkeyengine,rbottema/jmonkeyengine,davidB/jmonkeyengine,zzuegg/jmonkeyengine,OpenGrabeso/jmonkeyengine,sandervdo/jmonkeyengine,bertleft/jmonkeyengine,amit2103/jmonkeyengine,aaronang/jmonkeyengine,g-rocket/jmonkeyengine,InShadow/jmonkeyengine,phr00t/jmonkeyengine,g-rocket/jmonkeyengine,amit2103/jmonkeyengine,skapi1992/jmonkeyengine,shurun19851206/jMonkeyEngine,g-rocket/jmonkeyengine,tr0k/jmonkeyengine,OpenGrabeso/jmonkeyengine,rbottema/jmonkeyengine,Georgeto/jmonkeyengine,amit2103/jmonkeyengine,GreenCubes/jmonkeyengine,yetanotherindie/jMonkey-Engine,Georgeto/jmonkeyengine,tr0k/jmonkeyengine,davidB/jmonkeyengine,mbenson/jmonkeyengine,wrvangeest/jmonkeyengine,OpenGrabeso/jmonkeyengine,OpenGrabeso/jmonkeyengine,aaronang/jmonkeyengine,shurun19851206/jMonkeyEngine,shurun19851206/jMonkeyEngine,d235j/jmonkeyengine,danteinforno/jmonkeyengine,olafmaas/jmonkeyengine,yetanotherindie/jMonkey-Engine,tr0k/jmonkeyengine,wrvangeest/jmonkeyengine,davidB/jmonkeyengine,atomixnmc/jmonkeyengine,danteinforno/jmonkeyengine,GreenCubes/jmonkeyengine,sandervdo/jmonkeyengine,jMonkeyEngine/jmonkeyengine,mbenson/jmonkeyengine,g-rocket/jmonkeyengine,aaronang/jmonkeyengine,bsmr-java/jmonkeyengine,olafmaas/jmonkeyengine,davidB/jmonkeyengine,GreenCubes/jmonkeyengine,OpenGrabeso/jmonkeyengine,amit2103/jmonkeyengine,bsmr-java/jmonkeyengine,Georgeto/jmonkeyengine,skapi1992/jmonkeyengine,jMonkeyEngine/jmonkeyengine,bsmr-java/jmonkeyengine,mbenson/jmonkeyengine,tr0k/jmonkeyengine,wrvangeest/jmonkeyengine,phr00t/jmonkeyengine,amit2103/jmonkeyengine,d235j/jmonkeyengine,rbottema/jmonkeyengine,sandervdo/jmonkeyengine,delftsre/jmonkeyengine,phr00t/jmonkeyengine,bertleft/jmonkeyengine,d235j/jmonkeyengine,skapi1992/jmonkeyengine,weilichuang/jmonkeyengine,wrvangeest/jmonkeyengine,olafmaas/jmonkeyengine,davidB/jmonkeyengine,sandervdo/jmonkeyengine,yetanotherindie/jMonkey-Engine,amit2103/jmonkeyengine,d235j/jmonkeyengine,InShadow/jmonkeyengine,shurun19851206/jMonkeyEngine,jMonkeyEngine/jmonkeyengine,d235j/jmonkeyengine,Georgeto/jmonkeyengine,skapi1992/jmonkeyengine,g-rocket/jmonkeyengine,shurun19851206/jMonkeyEngine,Georgeto/jmonkeyengine,weilichuang/jmonkeyengine,nickschot/jmonkeyengine,yetanotherindie/jMonkey-Engine,bertleft/jmonkeyengine,zzuegg/jmonkeyengine,danteinforno/jmonkeyengine,bertleft/jmonkeyengine,OpenGrabeso/jmonkeyengine,zzuegg/jmonkeyengine,danteinforno/jmonkeyengine,g-rocket/jmonkeyengine,InShadow/jmonkeyengine,atomixnmc/jmonkeyengine,rbottema/jmonkeyengine,atomixnmc/jmonkeyengine,nickschot/jmonkeyengine,mbenson/jmonkeyengine
|
/*
* Copyright (c) 2009-2012 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jme3.audio.openal;
import com.jme3.audio.AudioSource.Status;
import com.jme3.audio.*;
import com.jme3.math.Vector3f;
import com.jme3.util.BufferUtils;
import com.jme3.util.NativeObjectManager;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;
import static com.jme3.audio.openal.AL.*;
import static com.jme3.audio.openal.ALC.*;
import static com.jme3.audio.openal.EFX.*;
public class ALAudioRenderer implements AudioRenderer, Runnable {
private static final Logger logger = Logger.getLogger(ALAudioRenderer.class.getName());
private final NativeObjectManager objManager = new NativeObjectManager();
// When multiplied by STREAMING_BUFFER_COUNT, will equal 44100 * 2 * 2
// which is exactly 1 second of audio.
private static final int BUFFER_SIZE = 35280;
private static final int STREAMING_BUFFER_COUNT = 5;
private final static int MAX_NUM_CHANNELS = 64;
private IntBuffer ib = BufferUtils.createIntBuffer(1);
private final FloatBuffer fb = BufferUtils.createVector3Buffer(2);
private final ByteBuffer nativeBuf = BufferUtils.createByteBuffer(BUFFER_SIZE);
private final byte[] arrayBuf = new byte[BUFFER_SIZE];
private int[] channels;
private AudioSource[] chanSrcs;
private int nextChan = 0;
private final ArrayList<Integer> freeChans = new ArrayList<Integer>();
private Listener listener;
private boolean audioDisabled = false;
private boolean supportEfx = false;
private boolean supportPauseDevice = false;
private int auxSends = 0;
private int reverbFx = -1;
private int reverbFxSlot = -1;
// Fill streaming sources every 50 ms
private static final float UPDATE_RATE = 0.05f;
private final Thread decoderThread = new Thread(this, "jME3 Audio Decoding Thread");
private final Object threadLock = new Object();
private final AL al;
private final ALC alc;
private final EFX efx;
public ALAudioRenderer(AL al, ALC alc, EFX efx) {
this.al = al;
this.alc = alc;
this.efx = efx;
}
private void initOpenAL() {
try {
if (!alc.isCreated()) {
alc.createALC();
}
} catch (UnsatisfiedLinkError ex) {
logger.log(Level.SEVERE, "Failed to load audio library", ex);
audioDisabled = true;
return;
}
String deviceName = alc.alcGetString(ALC.ALC_DEVICE_SPECIFIER);
logger.log(Level.INFO, "Audio Device: {0}", deviceName);
logger.log(Level.INFO, "Audio Vendor: {0}", al.alGetString(AL_VENDOR));
logger.log(Level.INFO, "Audio Renderer: {0}", al.alGetString(AL_RENDERER));
logger.log(Level.INFO, "Audio Version: {0}", al.alGetString(AL_VERSION));
logger.log(Level.INFO, "ALC extensions: {0}", alc.alcGetString(ALC.ALC_EXTENSIONS));
logger.log(Level.INFO, "AL extensions: {0}", al.alGetString(AL_EXTENSIONS));
// Find maximum # of sources supported by this implementation
ArrayList<Integer> channelList = new ArrayList<Integer>();
for (int i = 0; i < MAX_NUM_CHANNELS; i++) {
int chan = al.alGenSources();
if (al.alGetError() != 0) {
break;
} else {
channelList.add(chan);
}
}
channels = new int[channelList.size()];
for (int i = 0; i < channels.length; i++) {
channels[i] = channelList.get(i);
}
ib = BufferUtils.createIntBuffer(channels.length);
chanSrcs = new AudioSource[channels.length];
logger.log(Level.INFO, "AudioRenderer supports {0} channels", channels.length);
// Pause device is a feature used specifically on Android
// where the application could be closed but still running,
// thus the audio context remains open but no audio should be playing.
supportPauseDevice = alc.alcIsExtensionPresent("ALC_SOFT_pause_device");
if (!supportPauseDevice) {
logger.log(Level.WARNING, "Pausing audio device not supported.");
}
supportEfx = alc.alcIsExtensionPresent("ALC_EXT_EFX");
if (supportEfx) {
ib.position(0).limit(1);
alc.alcGetInteger(EFX.ALC_EFX_MAJOR_VERSION, ib, 1);
int major = ib.get(0);
ib.position(0).limit(1);
alc.alcGetInteger(EFX.ALC_EFX_MINOR_VERSION, ib, 1);
int minor = ib.get(0);
logger.log(Level.INFO, "Audio effect extension version: {0}.{1}", new Object[]{major, minor});
alc.alcGetInteger(EFX.ALC_MAX_AUXILIARY_SENDS, ib, 1);
auxSends = ib.get(0);
logger.log(Level.INFO, "Audio max auxilary sends: {0}", auxSends);
// create slot
ib.position(0).limit(1);
efx.alGenAuxiliaryEffectSlots(1, ib);
reverbFxSlot = ib.get(0);
// create effect
ib.position(0).limit(1);
efx.alGenEffects(1, ib);
reverbFx = ib.get(0);
efx.alEffecti(reverbFx, EFX.AL_EFFECT_TYPE, EFX.AL_EFFECT_REVERB);
// attach reverb effect to effect slot
efx.alAuxiliaryEffectSloti(reverbFxSlot, EFX.AL_EFFECTSLOT_EFFECT, reverbFx);
} else {
logger.log(Level.WARNING, "OpenAL EFX not available! Audio effects won't work.");
}
}
private void destroyOpenAL() {
if (audioDisabled) {
alc.destroyALC();
return;
}
// stop any playing channels
for (int i = 0; i < chanSrcs.length; i++) {
if (chanSrcs[i] != null) {
clearChannel(i);
}
}
// delete channel-based sources
ib.clear();
ib.put(channels);
ib.flip();
al.alDeleteSources(channels.length, ib);
// delete audio buffers and filters
objManager.deleteAllObjects(this);
if (supportEfx) {
ib.position(0).limit(1);
ib.put(0, reverbFx);
efx.alDeleteEffects(1, ib);
// If this is not allocated, why is it deleted?
// Commented out to fix native crash in OpenAL.
ib.position(0).limit(1);
ib.put(0, reverbFxSlot);
efx.alDeleteAuxiliaryEffectSlots(1, ib);
}
alc.destroyALC();
}
public void initialize() {
if (decoderThread.isAlive()) {
throw new IllegalStateException("Initialize already called");
}
// Initialize OpenAL context.
initOpenAL();
// Initialize decoder thread.
// Set high priority to avoid buffer starvation.
decoderThread.setDaemon(true);
decoderThread.setPriority(Thread.NORM_PRIORITY + 1);
decoderThread.start();
}
private void checkDead() {
if (decoderThread.getState() == Thread.State.TERMINATED) {
throw new IllegalStateException("Decoding thread is terminated");
}
}
public void run() {
long updateRateNanos = (long) (UPDATE_RATE * 1000000000);
mainloop:
while (true) {
long startTime = System.nanoTime();
if (Thread.interrupted()) {
break;
}
synchronized (threadLock) {
updateInDecoderThread(UPDATE_RATE);
}
long endTime = System.nanoTime();
long diffTime = endTime - startTime;
if (diffTime < updateRateNanos) {
long desiredEndTime = startTime + updateRateNanos;
while (System.nanoTime() < desiredEndTime) {
try {
Thread.sleep(1);
} catch (InterruptedException ex) {
break mainloop;
}
}
}
}
}
public void cleanup() {
// kill audio thread
if (!decoderThread.isAlive()) {
return;
}
decoderThread.interrupt();
try {
decoderThread.join();
} catch (InterruptedException ex) {
}
// destroy OpenAL context
destroyOpenAL();
}
private void updateFilter(Filter f) {
int id = f.getId();
if (id == -1) {
ib.position(0).limit(1);
efx.alGenFilters(1, ib);
id = ib.get(0);
f.setId(id);
objManager.registerObject(f);
}
if (f instanceof LowPassFilter) {
LowPassFilter lpf = (LowPassFilter) f;
efx.alFilteri(id, EFX.AL_FILTER_TYPE, EFX.AL_FILTER_LOWPASS);
efx.alFilterf(id, EFX.AL_LOWPASS_GAIN, lpf.getVolume());
efx.alFilterf(id, EFX.AL_LOWPASS_GAINHF, lpf.getHighFreqVolume());
} else {
throw new UnsupportedOperationException("Filter type unsupported: "
+ f.getClass().getName());
}
f.clearUpdateNeeded();
}
public void updateSourceParam(AudioSource src, AudioParam param) {
checkDead();
synchronized (threadLock) {
if (audioDisabled) {
return;
}
// There is a race condition in AudioSource that can
// cause this to be called for a node that has been
// detached from its channel. For example, setVolume()
// called from the render thread may see that that AudioSource
// still has a channel value but the audio thread may
// clear that channel before setVolume() gets to call
// updateSourceParam() (because the audio stopped playing
// on its own right as the volume was set). In this case,
// it should be safe to just ignore the update
if (src.getChannel() < 0) {
return;
}
assert src.getChannel() >= 0;
int id = channels[src.getChannel()];
switch (param) {
case Position:
if (!src.isPositional()) {
return;
}
Vector3f pos = src.getPosition();
al.alSource3f(id, AL_POSITION, pos.x, pos.y, pos.z);
break;
case Velocity:
if (!src.isPositional()) {
return;
}
Vector3f vel = src.getVelocity();
al.alSource3f(id, AL_VELOCITY, vel.x, vel.y, vel.z);
break;
case MaxDistance:
if (!src.isPositional()) {
return;
}
al.alSourcef(id, AL_MAX_DISTANCE, src.getMaxDistance());
break;
case RefDistance:
if (!src.isPositional()) {
return;
}
al.alSourcef(id, AL_REFERENCE_DISTANCE, src.getRefDistance());
break;
case ReverbFilter:
if (!supportEfx || !src.isPositional() || !src.isReverbEnabled()) {
return;
}
int filter = EFX.AL_FILTER_NULL;
if (src.getReverbFilter() != null) {
Filter f = src.getReverbFilter();
if (f.isUpdateNeeded()) {
updateFilter(f);
}
filter = f.getId();
}
al.alSource3i(id, EFX.AL_AUXILIARY_SEND_FILTER, reverbFxSlot, 0, filter);
break;
case ReverbEnabled:
if (!supportEfx || !src.isPositional()) {
return;
}
if (src.isReverbEnabled()) {
updateSourceParam(src, AudioParam.ReverbFilter);
} else {
al.alSource3i(id, EFX.AL_AUXILIARY_SEND_FILTER, 0, 0, EFX.AL_FILTER_NULL);
}
break;
case IsPositional:
if (!src.isPositional()) {
// Play in headspace
al.alSourcei(id, AL_SOURCE_RELATIVE, AL_TRUE);
al.alSource3f(id, AL_POSITION, 0, 0, 0);
al.alSource3f(id, AL_VELOCITY, 0, 0, 0);
// Disable reverb
al.alSource3i(id, EFX.AL_AUXILIARY_SEND_FILTER, 0, 0, EFX.AL_FILTER_NULL);
} else {
al.alSourcei(id, AL_SOURCE_RELATIVE, AL_FALSE);
updateSourceParam(src, AudioParam.Position);
updateSourceParam(src, AudioParam.Velocity);
updateSourceParam(src, AudioParam.MaxDistance);
updateSourceParam(src, AudioParam.RefDistance);
updateSourceParam(src, AudioParam.ReverbEnabled);
}
break;
case Direction:
if (!src.isDirectional()) {
return;
}
Vector3f dir = src.getDirection();
al.alSource3f(id, AL_DIRECTION, dir.x, dir.y, dir.z);
break;
case InnerAngle:
if (!src.isDirectional()) {
return;
}
al.alSourcef(id, AL_CONE_INNER_ANGLE, src.getInnerAngle());
break;
case OuterAngle:
if (!src.isDirectional()) {
return;
}
al.alSourcef(id, AL_CONE_OUTER_ANGLE, src.getOuterAngle());
break;
case IsDirectional:
if (src.isDirectional()) {
updateSourceParam(src, AudioParam.Direction);
updateSourceParam(src, AudioParam.InnerAngle);
updateSourceParam(src, AudioParam.OuterAngle);
al.alSourcef(id, AL_CONE_OUTER_GAIN, 0);
} else {
al.alSourcef(id, AL_CONE_INNER_ANGLE, 360);
al.alSourcef(id, AL_CONE_OUTER_ANGLE, 360);
al.alSourcef(id, AL_CONE_OUTER_GAIN, 1f);
}
break;
case DryFilter:
if (!supportEfx) {
return;
}
if (src.getDryFilter() != null) {
Filter f = src.getDryFilter();
if (f.isUpdateNeeded()) {
updateFilter(f);
// NOTE: must re-attach filter for changes to apply.
al.alSourcei(id, EFX.AL_DIRECT_FILTER, f.getId());
}
} else {
al.alSourcei(id, EFX.AL_DIRECT_FILTER, EFX.AL_FILTER_NULL);
}
break;
case Looping:
if (src.isLooping() && !(src.getAudioData() instanceof AudioStream)) {
al.alSourcei(id, AL_LOOPING, AL_TRUE);
} else {
al.alSourcei(id, AL_LOOPING, AL_FALSE);
}
break;
case Volume:
al.alSourcef(id, AL_GAIN, src.getVolume());
break;
case Pitch:
al.alSourcef(id, AL_PITCH, src.getPitch());
break;
}
}
}
private void setSourceParams(int id, AudioSource src, boolean forceNonLoop) {
if (src.isPositional()) {
Vector3f pos = src.getPosition();
Vector3f vel = src.getVelocity();
al.alSource3f(id, AL_POSITION, pos.x, pos.y, pos.z);
al.alSource3f(id, AL_VELOCITY, vel.x, vel.y, vel.z);
al.alSourcef(id, AL_MAX_DISTANCE, src.getMaxDistance());
al.alSourcef(id, AL_REFERENCE_DISTANCE, src.getRefDistance());
al.alSourcei(id, AL_SOURCE_RELATIVE, AL_FALSE);
if (src.isReverbEnabled() && supportEfx) {
int filter = EFX.AL_FILTER_NULL;
if (src.getReverbFilter() != null) {
Filter f = src.getReverbFilter();
if (f.isUpdateNeeded()) {
updateFilter(f);
}
filter = f.getId();
}
al.alSource3i(id, EFX.AL_AUXILIARY_SEND_FILTER, reverbFxSlot, 0, filter);
}
} else {
// play in headspace
al.alSourcei(id, AL_SOURCE_RELATIVE, AL_TRUE);
al.alSource3f(id, AL_POSITION, 0, 0, 0);
al.alSource3f(id, AL_VELOCITY, 0, 0, 0);
}
if (src.getDryFilter() != null && supportEfx) {
Filter f = src.getDryFilter();
if (f.isUpdateNeeded()) {
updateFilter(f);
// NOTE: must re-attach filter for changes to apply.
al.alSourcei(id, EFX.AL_DIRECT_FILTER, f.getId());
}
}
if (forceNonLoop || src.getAudioData() instanceof AudioStream) {
al.alSourcei(id, AL_LOOPING, AL_FALSE);
} else {
al.alSourcei(id, AL_LOOPING, src.isLooping() ? AL_TRUE : AL_FALSE);
}
al.alSourcef(id, AL_GAIN, src.getVolume());
al.alSourcef(id, AL_PITCH, src.getPitch());
al.alSourcef(id, AL_SEC_OFFSET, src.getTimeOffset());
if (src.isDirectional()) {
Vector3f dir = src.getDirection();
al.alSource3f(id, AL_DIRECTION, dir.x, dir.y, dir.z);
al.alSourcef(id, AL_CONE_INNER_ANGLE, src.getInnerAngle());
al.alSourcef(id, AL_CONE_OUTER_ANGLE, src.getOuterAngle());
al.alSourcef(id, AL_CONE_OUTER_GAIN, 0);
} else {
al.alSourcef(id, AL_CONE_INNER_ANGLE, 360);
al.alSourcef(id, AL_CONE_OUTER_ANGLE, 360);
al.alSourcef(id, AL_CONE_OUTER_GAIN, 1f);
}
}
public void updateListenerParam(Listener listener, ListenerParam param) {
checkDead();
synchronized (threadLock) {
if (audioDisabled) {
return;
}
switch (param) {
case Position:
Vector3f pos = listener.getLocation();
al.alListener3f(AL_POSITION, pos.x, pos.y, pos.z);
break;
case Rotation:
Vector3f dir = listener.getDirection();
Vector3f up = listener.getUp();
fb.rewind();
fb.put(dir.x).put(dir.y).put(dir.z);
fb.put(up.x).put(up.y).put(up.z);
fb.flip();
al.alListener(AL_ORIENTATION, fb);
break;
case Velocity:
Vector3f vel = listener.getVelocity();
al.alListener3f(AL_VELOCITY, vel.x, vel.y, vel.z);
break;
case Volume:
al.alListenerf(AL_GAIN, listener.getVolume());
break;
}
}
}
private void setListenerParams(Listener listener) {
Vector3f pos = listener.getLocation();
Vector3f vel = listener.getVelocity();
Vector3f dir = listener.getDirection();
Vector3f up = listener.getUp();
al.alListener3f(AL_POSITION, pos.x, pos.y, pos.z);
al.alListener3f(AL_VELOCITY, vel.x, vel.y, vel.z);
fb.rewind();
fb.put(dir.x).put(dir.y).put(dir.z);
fb.put(up.x).put(up.y).put(up.z);
fb.flip();
al.alListener(AL_ORIENTATION, fb);
al.alListenerf(AL_GAIN, listener.getVolume());
}
private int newChannel() {
if (freeChans.size() > 0) {
return freeChans.remove(0);
} else if (nextChan < channels.length) {
return nextChan++;
} else {
return -1;
}
}
private void freeChannel(int index) {
if (index == nextChan - 1) {
nextChan--;
} else {
freeChans.add(index);
}
}
public void setEnvironment(Environment env) {
checkDead();
synchronized (threadLock) {
if (audioDisabled || !supportEfx) {
return;
}
efx.alEffectf(reverbFx, EFX.AL_REVERB_DENSITY, env.getDensity());
efx.alEffectf(reverbFx, EFX.AL_REVERB_DIFFUSION, env.getDiffusion());
efx.alEffectf(reverbFx, EFX.AL_REVERB_GAIN, env.getGain());
efx.alEffectf(reverbFx, EFX.AL_REVERB_GAINHF, env.getGainHf());
efx.alEffectf(reverbFx, EFX.AL_REVERB_DECAY_TIME, env.getDecayTime());
efx.alEffectf(reverbFx, EFX.AL_REVERB_DECAY_HFRATIO, env.getDecayHFRatio());
efx.alEffectf(reverbFx, EFX.AL_REVERB_REFLECTIONS_GAIN, env.getReflectGain());
efx.alEffectf(reverbFx, EFX.AL_REVERB_REFLECTIONS_DELAY, env.getReflectDelay());
efx.alEffectf(reverbFx, EFX.AL_REVERB_LATE_REVERB_GAIN, env.getLateReverbGain());
efx.alEffectf(reverbFx, EFX.AL_REVERB_LATE_REVERB_DELAY, env.getLateReverbDelay());
efx.alEffectf(reverbFx, EFX.AL_REVERB_AIR_ABSORPTION_GAINHF, env.getAirAbsorbGainHf());
efx.alEffectf(reverbFx, EFX.AL_REVERB_ROOM_ROLLOFF_FACTOR, env.getRoomRolloffFactor());
// attach effect to slot
efx.alAuxiliaryEffectSloti(reverbFxSlot, EFX.AL_EFFECTSLOT_EFFECT, reverbFx);
}
}
private boolean fillBuffer(AudioStream stream, int id) {
int size = 0;
int result;
while (size < arrayBuf.length) {
result = stream.readSamples(arrayBuf, size, arrayBuf.length - size);
if (result > 0) {
size += result;
} else {
break;
}
}
if (size == 0) {
return false;
}
nativeBuf.clear();
nativeBuf.put(arrayBuf, 0, size);
nativeBuf.flip();
al.alBufferData(id, convertFormat(stream), nativeBuf, size, stream.getSampleRate());
return true;
}
private boolean fillStreamingSource(int sourceId, AudioStream stream, boolean looping) {
boolean success = false;
int processed = al.alGetSourcei(sourceId, AL_BUFFERS_PROCESSED);
for (int i = 0; i < processed; i++) {
int buffer;
ib.position(0).limit(1);
al.alSourceUnqueueBuffers(sourceId, 1, ib);
buffer = ib.get(0);
boolean active = fillBuffer(stream, buffer);
if (!active && !stream.isEOF()) {
throw new AssertionError();
}
if (!active && looping) {
stream.setTime(0);
active = fillBuffer(stream, buffer);
if (!active) {
throw new IllegalStateException("Looping streaming source " +
"was rewinded but could not be filled");
}
}
if (active) {
ib.position(0).limit(1);
ib.put(0, buffer);
al.alSourceQueueBuffers(sourceId, 1, ib);
// At least one buffer enqueued = success.
success = true;
} else {
// No more data left to process.
break;
}
}
return success;
}
private void attachStreamToSource(int sourceId, AudioStream stream, boolean looping) {
boolean success = false;
// Reset the stream. Typically happens if it finished playing on
// its own and got reclaimed.
// Note that AudioNode.stop() already resets the stream
// since it might not be in EOF when stopped.
if (stream.isEOF()) {
stream.setTime(0);
}
for (int id : stream.getIds()) {
boolean active = fillBuffer(stream, id);
if (!active && !stream.isEOF()) {
throw new AssertionError();
}
if (!active && looping) {
stream.setTime(0);
active = fillBuffer(stream, id);
if (!active) {
throw new IllegalStateException("Looping streaming source " +
"was rewinded but could not be filled");
}
}
if (active) {
ib.position(0).limit(1);
ib.put(id).flip();
al.alSourceQueueBuffers(sourceId, 1, ib);
success = true;
}
}
if (!success) {
// should never happen
throw new IllegalStateException("No valid data could be read from stream");
}
}
private boolean attachBufferToSource(int sourceId, AudioBuffer buffer) {
al.alSourcei(sourceId, AL_BUFFER, buffer.getId());
return true;
}
private void attachAudioToSource(int sourceId, AudioData data, boolean looping) {
if (data instanceof AudioBuffer) {
attachBufferToSource(sourceId, (AudioBuffer) data);
} else if (data instanceof AudioStream) {
attachStreamToSource(sourceId, (AudioStream) data, looping);
} else {
throw new UnsupportedOperationException();
}
}
private void clearChannel(int index) {
// make room at this channel
if (chanSrcs[index] != null) {
AudioSource src = chanSrcs[index];
int sourceId = channels[index];
al.alSourceStop(sourceId);
// For streaming sources, this will clear all queued buffers.
al.alSourcei(sourceId, AL_BUFFER, 0);
if (src.getDryFilter() != null && supportEfx) {
// detach filter
al.alSourcei(sourceId, EFX.AL_DIRECT_FILTER, EFX.AL_FILTER_NULL);
}
if (src.isPositional()) {
AudioSource pas = (AudioSource) src;
if (pas.isReverbEnabled() && supportEfx) {
al.alSource3i(sourceId, EFX.AL_AUXILIARY_SEND_FILTER, 0, 0, EFX.AL_FILTER_NULL);
}
}
chanSrcs[index] = null;
}
}
private AudioSource.Status convertStatus(int oalStatus) {
switch (oalStatus) {
case AL_INITIAL:
case AL_STOPPED:
return Status.Stopped;
case AL_PAUSED:
return Status.Paused;
case AL_PLAYING:
return Status.Playing;
default:
throw new UnsupportedOperationException("Unrecognized OAL state: " + oalStatus);
}
}
public void update(float tpf) {
synchronized (threadLock) {
updateInRenderThread(tpf);
}
}
public void updateInRenderThread(float tpf) {
if (audioDisabled) {
return;
}
for (int i = 0; i < channels.length; i++) {
AudioSource src = chanSrcs[i];
if (src == null) {
continue;
}
int sourceId = channels[i];
boolean boundSource = i == src.getChannel();
boolean reclaimChannel = false;
Status oalStatus = convertStatus(al.alGetSourcei(sourceId, AL_SOURCE_STATE));
if (!boundSource) {
// Rules for instanced playback vary significantly.
// Handle it here.
if (oalStatus == Status.Stopped) {
// Instanced audio stopped playing. Reclaim channel.
clearChannel(i);
freeChannel(i);
} else if (oalStatus == Status.Paused) {
throw new AssertionError("Instanced audio cannot be paused");
}
continue;
}
Status jmeStatus = src.getStatus();
// Check if we need to sync JME status with OAL status.
if (oalStatus != jmeStatus) {
if (oalStatus == Status.Stopped && jmeStatus == Status.Playing) {
// Maybe we need to reclaim the channel.
if (src.getAudioData() instanceof AudioStream) {
AudioStream stream = (AudioStream) src.getAudioData();
if (stream.isEOF() && !src.isLooping()) {
// Stream finished playing
reclaimChannel = true;
} else {
// Stream still has data.
// Buffer starvation occured.
// Audio decoder thread will fill the data
// and start the channel again.
}
} else {
// Buffer finished playing.
if (src.isLooping()) {
throw new AssertionError("Unexpected state: " +
"A looping sound has stopped playing");
} else {
reclaimChannel = true;
}
}
if (reclaimChannel) {
src.setStatus(Status.Stopped);
src.setChannel(-1);
clearChannel(i);
freeChannel(i);
}
} else {
// jME3 state does not match OAL state.
// This is only relevant for bound sources.
throw new AssertionError("Unexpected sound status. "
+ "OAL: " + oalStatus
+ ", JME: " + jmeStatus);
}
} else {
// Stopped channel was not cleared correctly.
if (oalStatus == Status.Stopped) {
throw new AssertionError("Channel " + i + " was not reclaimed");
}
}
}
}
public void updateInDecoderThread(float tpf) {
if (audioDisabled) {
return;
}
for (int i = 0; i < channels.length; i++) {
AudioSource src = chanSrcs[i];
if (src == null || !(src.getAudioData() instanceof AudioStream)) {
continue;
}
int sourceId = channels[i];
AudioStream stream = (AudioStream) src.getAudioData();
Status oalStatus = convertStatus(al.alGetSourcei(sourceId, AL_SOURCE_STATE));
Status jmeStatus = src.getStatus();
// Keep filling data (even if we are stopped / paused)
boolean buffersWereFilled = fillStreamingSource(sourceId, stream, src.isLooping());
if (buffersWereFilled) {
if (oalStatus == Status.Stopped && jmeStatus == Status.Playing) {
// The source got stopped due to buffer starvation.
// Start it again.
logger.log(Level.WARNING, "Buffer starvation "
+ "occurred while playing stream");
al.alSourcePlay(sourceId);
} else {
// Buffers were filled, stream continues to play.
if (oalStatus == Status.Playing && jmeStatus == Status.Playing) {
// Nothing to do.
} else {
throw new AssertionError();
}
}
}
}
// Delete any unused objects.
objManager.deleteUnused(this);
}
public void setListener(Listener listener) {
checkDead();
synchronized (threadLock) {
if (audioDisabled) {
return;
}
if (this.listener != null) {
// previous listener no longer associated with current
// renderer
this.listener.setRenderer(null);
}
this.listener = listener;
this.listener.setRenderer(this);
setListenerParams(listener);
}
}
public void pauseAll() {
if (!supportPauseDevice) {
throw new UnsupportedOperationException("Pause device is NOT supported!");
}
alc.alcDevicePauseSOFT();
}
public void resumeAll() {
if (!supportPauseDevice) {
throw new UnsupportedOperationException("Pause device is NOT supported!");
}
alc.alcDeviceResumeSOFT();
}
public void playSourceInstance(AudioSource src) {
checkDead();
synchronized (threadLock) {
if (audioDisabled) {
return;
}
if (src.getAudioData() instanceof AudioStream) {
throw new UnsupportedOperationException(
"Cannot play instances "
+ "of audio streams. Use play() instead.");
}
if (src.getAudioData().isUpdateNeeded()) {
updateAudioData(src.getAudioData());
}
// create a new index for an audio-channel
int index = newChannel();
if (index == -1) {
return;
}
int sourceId = channels[index];
clearChannel(index);
// set parameters, like position and max distance
setSourceParams(sourceId, src, true);
attachAudioToSource(sourceId, src.getAudioData(), false);
chanSrcs[index] = src;
// play the channel
al.alSourcePlay(sourceId);
}
}
public void playSource(AudioSource src) {
checkDead();
synchronized (threadLock) {
if (audioDisabled) {
return;
}
if (src.getStatus() == Status.Playing) {
return;
} else if (src.getStatus() == Status.Stopped) {
//Assertion removed as it seems it's not possible to have
//something different than =1 when first playing an AudioNode
// assert src.getChannel() != -1;
// allocate channel to this source
int index = newChannel();
if (index == -1) {
logger.log(Level.WARNING, "No channel available to play {0}", src);
return;
}
clearChannel(index);
src.setChannel(index);
AudioData data = src.getAudioData();
if (data.isUpdateNeeded()) {
updateAudioData(data);
}
chanSrcs[index] = src;
setSourceParams(channels[index], src, false);
attachAudioToSource(channels[index], data, src.isLooping());
}
al.alSourcePlay(channels[src.getChannel()]);
src.setStatus(Status.Playing);
}
}
public void pauseSource(AudioSource src) {
checkDead();
synchronized (threadLock) {
if (audioDisabled) {
return;
}
if (src.getStatus() == Status.Playing) {
assert src.getChannel() != -1;
al.alSourcePause(channels[src.getChannel()]);
src.setStatus(Status.Paused);
}
}
}
public void stopSource(AudioSource src) {
synchronized (threadLock) {
if (audioDisabled) {
return;
}
if (src.getStatus() != Status.Stopped) {
int chan = src.getChannel();
assert chan != -1; // if it's not stopped, must have id
src.setStatus(Status.Stopped);
src.setChannel(-1);
clearChannel(chan);
freeChannel(chan);
if (src.getAudioData() instanceof AudioStream) {
// If the stream is seekable, then rewind it.
// Otherwise, close it, as it is no longer valid.
AudioStream stream = (AudioStream)src.getAudioData();
if (stream.isSeekable()) {
stream.setTime(0);
} else {
stream.close();
}
}
}
}
}
private int convertFormat(AudioData ad) {
switch (ad.getBitsPerSample()) {
case 8:
if (ad.getChannels() == 1) {
return AL_FORMAT_MONO8;
} else if (ad.getChannels() == 2) {
return AL_FORMAT_STEREO8;
}
break;
case 16:
if (ad.getChannels() == 1) {
return AL_FORMAT_MONO16;
} else {
return AL_FORMAT_STEREO16;
}
}
throw new UnsupportedOperationException("Unsupported channels/bits combination: "
+ "bits=" + ad.getBitsPerSample() + ", channels=" + ad.getChannels());
}
private void updateAudioBuffer(AudioBuffer ab) {
int id = ab.getId();
if (ab.getId() == -1) {
ib.position(0).limit(1);
al.alGenBuffers(1, ib);
id = ib.get(0);
ab.setId(id);
objManager.registerObject(ab);
}
ab.getData().clear();
al.alBufferData(id, convertFormat(ab), ab.getData(), ab.getData().capacity(), ab.getSampleRate());
ab.clearUpdateNeeded();
}
private void updateAudioStream(AudioStream as) {
if (as.getIds() != null) {
deleteAudioData(as);
}
int[] ids = new int[STREAMING_BUFFER_COUNT];
ib.position(0).limit(STREAMING_BUFFER_COUNT);
al.alGenBuffers(STREAMING_BUFFER_COUNT, ib);
ib.position(0).limit(STREAMING_BUFFER_COUNT);
ib.get(ids);
// Not registered with object manager.
// AudioStreams can be handled without object manager
// since their lifecycle is known to the audio renderer.
as.setIds(ids);
as.clearUpdateNeeded();
}
private void updateAudioData(AudioData ad) {
if (ad instanceof AudioBuffer) {
updateAudioBuffer((AudioBuffer) ad);
} else if (ad instanceof AudioStream) {
updateAudioStream((AudioStream) ad);
}
}
public void deleteFilter(Filter filter) {
int id = filter.getId();
if (id != -1) {
ib.position(0).limit(1);
ib.put(id).flip();
efx.alDeleteFilters(1, ib);
filter.resetObject();
}
}
public void deleteAudioData(AudioData ad) {
synchronized (threadLock) {
if (audioDisabled) {
return;
}
if (ad instanceof AudioBuffer) {
AudioBuffer ab = (AudioBuffer) ad;
int id = ab.getId();
if (id != -1) {
ib.put(0, id);
ib.position(0).limit(1);
al.alDeleteBuffers(1, ib);
ab.resetObject();
}
} else if (ad instanceof AudioStream) {
AudioStream as = (AudioStream) ad;
int[] ids = as.getIds();
if (ids != null) {
ib.clear();
ib.put(ids).flip();
al.alDeleteBuffers(ids.length, ib);
as.resetObject();
}
}
}
}
}
|
jme3-core/src/main/java/com/jme3/audio/openal/ALAudioRenderer.java
|
/*
* Copyright (c) 2009-2012 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jme3.audio.openal;
import com.jme3.audio.AudioSource.Status;
import com.jme3.audio.*;
import com.jme3.math.Vector3f;
import com.jme3.util.BufferUtils;
import com.jme3.util.NativeObjectManager;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;
import static com.jme3.audio.openal.AL.*;
import static com.jme3.audio.openal.ALC.*;
import static com.jme3.audio.openal.EFX.*;
public class ALAudioRenderer implements AudioRenderer, Runnable {
private static final Logger logger = Logger.getLogger(ALAudioRenderer.class.getName());
private final NativeObjectManager objManager = new NativeObjectManager();
// When multiplied by STREAMING_BUFFER_COUNT, will equal 44100 * 2 * 2
// which is exactly 1 second of audio.
private static final int BUFFER_SIZE = 35280;
private static final int STREAMING_BUFFER_COUNT = 5;
private final static int MAX_NUM_CHANNELS = 64;
private IntBuffer ib = BufferUtils.createIntBuffer(1);
private final FloatBuffer fb = BufferUtils.createVector3Buffer(2);
private final ByteBuffer nativeBuf = BufferUtils.createByteBuffer(BUFFER_SIZE);
private final byte[] arrayBuf = new byte[BUFFER_SIZE];
private int[] channels;
private AudioSource[] chanSrcs;
private int nextChan = 0;
private final ArrayList<Integer> freeChans = new ArrayList<Integer>();
private Listener listener;
private boolean audioDisabled = false;
private boolean supportEfx = false;
private boolean supportPauseDevice = false;
private int auxSends = 0;
private int reverbFx = -1;
private int reverbFxSlot = -1;
// Fill streaming sources every 50 ms
private static final float UPDATE_RATE = 0.05f;
private final Thread decoderThread = new Thread(this, "jME3 Audio Decoding Thread");
private final Object threadLock = new Object();
private final AL al;
private final ALC alc;
private final EFX efx;
public ALAudioRenderer(AL al, ALC alc, EFX efx) {
this.al = al;
this.alc = alc;
this.efx = efx;
}
private void initOpenAL() {
try {
if (!alc.isCreated()) {
alc.createALC();
}
} catch (UnsatisfiedLinkError ex) {
logger.log(Level.SEVERE, "Failed to load audio library", ex);
audioDisabled = true;
return;
}
String deviceName = alc.alcGetString(ALC.ALC_DEVICE_SPECIFIER);
logger.log(Level.INFO, "Audio Device: {0}", deviceName);
logger.log(Level.INFO, "Audio Vendor: {0}", al.alGetString(AL_VENDOR));
logger.log(Level.INFO, "Audio Renderer: {0}", al.alGetString(AL_RENDERER));
logger.log(Level.INFO, "Audio Version: {0}", al.alGetString(AL_VERSION));
logger.log(Level.INFO, "ALC extensions: {0}", alc.alcGetString(ALC.ALC_EXTENSIONS));
logger.log(Level.INFO, "AL extensions: {0}", al.alGetString(AL_EXTENSIONS));
// Find maximum # of sources supported by this implementation
ArrayList<Integer> channelList = new ArrayList<Integer>();
for (int i = 0; i < MAX_NUM_CHANNELS; i++) {
int chan = al.alGenSources();
if (al.alGetError() != 0) {
break;
} else {
channelList.add(chan);
}
}
channels = new int[channelList.size()];
for (int i = 0; i < channels.length; i++) {
channels[i] = channelList.get(i);
}
ib = BufferUtils.createIntBuffer(channels.length);
chanSrcs = new AudioSource[channels.length];
logger.log(Level.INFO, "AudioRenderer supports {0} channels", channels.length);
// Pause device is a feature used specifically on Android
// where the application could be closed but still running,
// thus the audio context remains open but no audio should be playing.
supportPauseDevice = alc.alcIsExtensionPresent("ALC_SOFT_pause_device");
if (!supportPauseDevice) {
logger.log(Level.WARNING, "Pausing audio device not supported.");
}
supportEfx = alc.alcIsExtensionPresent("ALC_EXT_EFX");
if (supportEfx) {
ib.position(0).limit(1);
alc.alcGetInteger(EFX.ALC_EFX_MAJOR_VERSION, ib, 1);
int major = ib.get(0);
ib.position(0).limit(1);
alc.alcGetInteger(EFX.ALC_EFX_MINOR_VERSION, ib, 1);
int minor = ib.get(0);
logger.log(Level.INFO, "Audio effect extension version: {0}.{1}", new Object[]{major, minor});
alc.alcGetInteger(EFX.ALC_MAX_AUXILIARY_SENDS, ib, 1);
auxSends = ib.get(0);
logger.log(Level.INFO, "Audio max auxilary sends: {0}", auxSends);
// create slot
ib.position(0).limit(1);
efx.alGenAuxiliaryEffectSlots(1, ib);
reverbFxSlot = ib.get(0);
// create effect
ib.position(0).limit(1);
efx.alGenEffects(1, ib);
reverbFx = ib.get(0);
efx.alEffecti(reverbFx, EFX.AL_EFFECT_TYPE, EFX.AL_EFFECT_REVERB);
// attach reverb effect to effect slot
efx.alAuxiliaryEffectSloti(reverbFxSlot, EFX.AL_EFFECTSLOT_EFFECT, reverbFx);
} else {
logger.log(Level.WARNING, "OpenAL EFX not available! Audio effects won't work.");
}
}
private void destroyOpenAL() {
if (audioDisabled) {
alc.destroyALC();
return;
}
// stop any playing channels
for (int i = 0; i < chanSrcs.length; i++) {
if (chanSrcs[i] != null) {
clearChannel(i);
}
}
// delete channel-based sources
ib.clear();
ib.put(channels);
ib.flip();
al.alDeleteSources(channels.length, ib);
// delete audio buffers and filters
objManager.deleteAllObjects(this);
if (supportEfx) {
ib.position(0).limit(1);
ib.put(0, reverbFx);
efx.alDeleteEffects(1, ib);
// If this is not allocated, why is it deleted?
// Commented out to fix native crash in OpenAL.
ib.position(0).limit(1);
ib.put(0, reverbFxSlot);
efx.alDeleteAuxiliaryEffectSlots(1, ib);
}
alc.destroyALC();
}
public void initialize() {
if (decoderThread.isAlive()) {
throw new IllegalStateException("Initialize already called");
}
// Initialize OpenAL context.
initOpenAL();
// Initialize decoder thread.
// Set high priority to avoid buffer starvation.
decoderThread.setDaemon(true);
decoderThread.setPriority(Thread.NORM_PRIORITY + 1);
decoderThread.start();
}
private void checkDead() {
if (decoderThread.getState() == Thread.State.TERMINATED) {
throw new IllegalStateException("Decoding thread is terminated");
}
}
public void run() {
long updateRateNanos = (long) (UPDATE_RATE * 1000000000);
mainloop:
while (true) {
long startTime = System.nanoTime();
if (Thread.interrupted()) {
break;
}
synchronized (threadLock) {
updateInDecoderThread(UPDATE_RATE);
}
long endTime = System.nanoTime();
long diffTime = endTime - startTime;
if (diffTime < updateRateNanos) {
long desiredEndTime = startTime + updateRateNanos;
while (System.nanoTime() < desiredEndTime) {
try {
Thread.sleep(1);
} catch (InterruptedException ex) {
break mainloop;
}
}
}
}
}
public void cleanup() {
// kill audio thread
if (!decoderThread.isAlive()) {
return;
}
decoderThread.interrupt();
try {
decoderThread.join();
} catch (InterruptedException ex) {
}
// destroy OpenAL context
destroyOpenAL();
}
private void updateFilter(Filter f) {
int id = f.getId();
if (id == -1) {
ib.position(0).limit(1);
efx.alGenFilters(1, ib);
id = ib.get(0);
f.setId(id);
objManager.registerObject(f);
}
if (f instanceof LowPassFilter) {
LowPassFilter lpf = (LowPassFilter) f;
efx.alFilteri(id, EFX.AL_FILTER_TYPE, EFX.AL_FILTER_LOWPASS);
efx.alFilterf(id, EFX.AL_LOWPASS_GAIN, lpf.getVolume());
efx.alFilterf(id, EFX.AL_LOWPASS_GAINHF, lpf.getHighFreqVolume());
} else {
throw new UnsupportedOperationException("Filter type unsupported: "
+ f.getClass().getName());
}
f.clearUpdateNeeded();
}
public void updateSourceParam(AudioSource src, AudioParam param) {
checkDead();
synchronized (threadLock) {
if (audioDisabled) {
return;
}
// There is a race condition in AudioSource that can
// cause this to be called for a node that has been
// detached from its channel. For example, setVolume()
// called from the render thread may see that that AudioSource
// still has a channel value but the audio thread may
// clear that channel before setVolume() gets to call
// updateSourceParam() (because the audio stopped playing
// on its own right as the volume was set). In this case,
// it should be safe to just ignore the update
if (src.getChannel() < 0) {
return;
}
assert src.getChannel() >= 0;
int id = channels[src.getChannel()];
switch (param) {
case Position:
if (!src.isPositional()) {
return;
}
Vector3f pos = src.getPosition();
al.alSource3f(id, AL_POSITION, pos.x, pos.y, pos.z);
break;
case Velocity:
if (!src.isPositional()) {
return;
}
Vector3f vel = src.getVelocity();
al.alSource3f(id, AL_VELOCITY, vel.x, vel.y, vel.z);
break;
case MaxDistance:
if (!src.isPositional()) {
return;
}
al.alSourcef(id, AL_MAX_DISTANCE, src.getMaxDistance());
break;
case RefDistance:
if (!src.isPositional()) {
return;
}
al.alSourcef(id, AL_REFERENCE_DISTANCE, src.getRefDistance());
break;
case ReverbFilter:
if (!supportEfx || !src.isPositional() || !src.isReverbEnabled()) {
return;
}
int filter = EFX.AL_FILTER_NULL;
if (src.getReverbFilter() != null) {
Filter f = src.getReverbFilter();
if (f.isUpdateNeeded()) {
updateFilter(f);
}
filter = f.getId();
}
al.alSource3i(id, EFX.AL_AUXILIARY_SEND_FILTER, reverbFxSlot, 0, filter);
break;
case ReverbEnabled:
if (!supportEfx || !src.isPositional()) {
return;
}
if (src.isReverbEnabled()) {
updateSourceParam(src, AudioParam.ReverbFilter);
} else {
al.alSource3i(id, EFX.AL_AUXILIARY_SEND_FILTER, 0, 0, EFX.AL_FILTER_NULL);
}
break;
case IsPositional:
if (!src.isPositional()) {
// Play in headspace
al.alSourcei(id, AL_SOURCE_RELATIVE, AL_TRUE);
al.alSource3f(id, AL_POSITION, 0, 0, 0);
al.alSource3f(id, AL_VELOCITY, 0, 0, 0);
// Disable reverb
al.alSource3i(id, EFX.AL_AUXILIARY_SEND_FILTER, 0, 0, EFX.AL_FILTER_NULL);
} else {
al.alSourcei(id, AL_SOURCE_RELATIVE, AL_FALSE);
updateSourceParam(src, AudioParam.Position);
updateSourceParam(src, AudioParam.Velocity);
updateSourceParam(src, AudioParam.MaxDistance);
updateSourceParam(src, AudioParam.RefDistance);
updateSourceParam(src, AudioParam.ReverbEnabled);
}
break;
case Direction:
if (!src.isDirectional()) {
return;
}
Vector3f dir = src.getDirection();
al.alSource3f(id, AL_DIRECTION, dir.x, dir.y, dir.z);
break;
case InnerAngle:
if (!src.isDirectional()) {
return;
}
al.alSourcef(id, AL_CONE_INNER_ANGLE, src.getInnerAngle());
break;
case OuterAngle:
if (!src.isDirectional()) {
return;
}
al.alSourcef(id, AL_CONE_OUTER_ANGLE, src.getOuterAngle());
break;
case IsDirectional:
if (src.isDirectional()) {
updateSourceParam(src, AudioParam.Direction);
updateSourceParam(src, AudioParam.InnerAngle);
updateSourceParam(src, AudioParam.OuterAngle);
al.alSourcef(id, AL_CONE_OUTER_GAIN, 0);
} else {
al.alSourcef(id, AL_CONE_INNER_ANGLE, 360);
al.alSourcef(id, AL_CONE_OUTER_ANGLE, 360);
al.alSourcef(id, AL_CONE_OUTER_GAIN, 1f);
}
break;
case DryFilter:
if (!supportEfx) {
return;
}
if (src.getDryFilter() != null) {
Filter f = src.getDryFilter();
if (f.isUpdateNeeded()) {
updateFilter(f);
// NOTE: must re-attach filter for changes to apply.
al.alSourcei(id, EFX.AL_DIRECT_FILTER, f.getId());
}
} else {
al.alSourcei(id, EFX.AL_DIRECT_FILTER, EFX.AL_FILTER_NULL);
}
break;
case Looping:
if (src.isLooping() && !(src.getAudioData() instanceof AudioStream)) {
al.alSourcei(id, AL_LOOPING, AL_TRUE);
} else {
al.alSourcei(id, AL_LOOPING, AL_FALSE);
}
break;
case Volume:
al.alSourcef(id, AL_GAIN, src.getVolume());
break;
case Pitch:
al.alSourcef(id, AL_PITCH, src.getPitch());
break;
}
}
}
private void setSourceParams(int id, AudioSource src, boolean forceNonLoop) {
if (src.isPositional()) {
Vector3f pos = src.getPosition();
Vector3f vel = src.getVelocity();
al.alSource3f(id, AL_POSITION, pos.x, pos.y, pos.z);
al.alSource3f(id, AL_VELOCITY, vel.x, vel.y, vel.z);
al.alSourcef(id, AL_MAX_DISTANCE, src.getMaxDistance());
al.alSourcef(id, AL_REFERENCE_DISTANCE, src.getRefDistance());
al.alSourcei(id, AL_SOURCE_RELATIVE, AL_FALSE);
if (src.isReverbEnabled() && supportEfx) {
int filter = EFX.AL_FILTER_NULL;
if (src.getReverbFilter() != null) {
Filter f = src.getReverbFilter();
if (f.isUpdateNeeded()) {
updateFilter(f);
}
filter = f.getId();
}
al.alSource3i(id, EFX.AL_AUXILIARY_SEND_FILTER, reverbFxSlot, 0, filter);
}
} else {
// play in headspace
al.alSourcei(id, AL_SOURCE_RELATIVE, AL_TRUE);
al.alSource3f(id, AL_POSITION, 0, 0, 0);
al.alSource3f(id, AL_VELOCITY, 0, 0, 0);
}
if (src.getDryFilter() != null && supportEfx) {
Filter f = src.getDryFilter();
if (f.isUpdateNeeded()) {
updateFilter(f);
// NOTE: must re-attach filter for changes to apply.
al.alSourcei(id, EFX.AL_DIRECT_FILTER, f.getId());
}
}
if (forceNonLoop || src.getAudioData() instanceof AudioStream) {
al.alSourcei(id, AL_LOOPING, AL_FALSE);
} else {
al.alSourcei(id, AL_LOOPING, src.isLooping() ? AL_TRUE : AL_FALSE);
}
al.alSourcef(id, AL_GAIN, src.getVolume());
al.alSourcef(id, AL_PITCH, src.getPitch());
al.alSourcef(id, AL_SEC_OFFSET, src.getTimeOffset());
if (src.isDirectional()) {
Vector3f dir = src.getDirection();
al.alSource3f(id, AL_DIRECTION, dir.x, dir.y, dir.z);
al.alSourcef(id, AL_CONE_INNER_ANGLE, src.getInnerAngle());
al.alSourcef(id, AL_CONE_OUTER_ANGLE, src.getOuterAngle());
al.alSourcef(id, AL_CONE_OUTER_GAIN, 0);
} else {
al.alSourcef(id, AL_CONE_INNER_ANGLE, 360);
al.alSourcef(id, AL_CONE_OUTER_ANGLE, 360);
al.alSourcef(id, AL_CONE_OUTER_GAIN, 1f);
}
}
public void updateListenerParam(Listener listener, ListenerParam param) {
checkDead();
synchronized (threadLock) {
if (audioDisabled) {
return;
}
switch (param) {
case Position:
Vector3f pos = listener.getLocation();
al.alListener3f(AL_POSITION, pos.x, pos.y, pos.z);
break;
case Rotation:
Vector3f dir = listener.getDirection();
Vector3f up = listener.getUp();
fb.rewind();
fb.put(dir.x).put(dir.y).put(dir.z);
fb.put(up.x).put(up.y).put(up.z);
fb.flip();
al.alListener(AL_ORIENTATION, fb);
break;
case Velocity:
Vector3f vel = listener.getVelocity();
al.alListener3f(AL_VELOCITY, vel.x, vel.y, vel.z);
break;
case Volume:
al.alListenerf(AL_GAIN, listener.getVolume());
break;
}
}
}
private void setListenerParams(Listener listener) {
Vector3f pos = listener.getLocation();
Vector3f vel = listener.getVelocity();
Vector3f dir = listener.getDirection();
Vector3f up = listener.getUp();
al.alListener3f(AL_POSITION, pos.x, pos.y, pos.z);
al.alListener3f(AL_VELOCITY, vel.x, vel.y, vel.z);
fb.rewind();
fb.put(dir.x).put(dir.y).put(dir.z);
fb.put(up.x).put(up.y).put(up.z);
fb.flip();
al.alListener(AL_ORIENTATION, fb);
al.alListenerf(AL_GAIN, listener.getVolume());
}
private int newChannel() {
if (freeChans.size() > 0) {
return freeChans.remove(0);
} else if (nextChan < channels.length) {
return nextChan++;
} else {
return -1;
}
}
private void freeChannel(int index) {
if (index == nextChan - 1) {
nextChan--;
} else {
freeChans.add(index);
}
}
public void setEnvironment(Environment env) {
checkDead();
synchronized (threadLock) {
if (audioDisabled || !supportEfx) {
return;
}
efx.alEffectf(reverbFx, EFX.AL_REVERB_DENSITY, env.getDensity());
efx.alEffectf(reverbFx, EFX.AL_REVERB_DIFFUSION, env.getDiffusion());
efx.alEffectf(reverbFx, EFX.AL_REVERB_GAIN, env.getGain());
efx.alEffectf(reverbFx, EFX.AL_REVERB_GAINHF, env.getGainHf());
efx.alEffectf(reverbFx, EFX.AL_REVERB_DECAY_TIME, env.getDecayTime());
efx.alEffectf(reverbFx, EFX.AL_REVERB_DECAY_HFRATIO, env.getDecayHFRatio());
efx.alEffectf(reverbFx, EFX.AL_REVERB_REFLECTIONS_GAIN, env.getReflectGain());
efx.alEffectf(reverbFx, EFX.AL_REVERB_REFLECTIONS_DELAY, env.getReflectDelay());
efx.alEffectf(reverbFx, EFX.AL_REVERB_LATE_REVERB_GAIN, env.getLateReverbGain());
efx.alEffectf(reverbFx, EFX.AL_REVERB_LATE_REVERB_DELAY, env.getLateReverbDelay());
efx.alEffectf(reverbFx, EFX.AL_REVERB_AIR_ABSORPTION_GAINHF, env.getAirAbsorbGainHf());
efx.alEffectf(reverbFx, EFX.AL_REVERB_ROOM_ROLLOFF_FACTOR, env.getRoomRolloffFactor());
// attach effect to slot
efx.alAuxiliaryEffectSloti(reverbFxSlot, EFX.AL_EFFECTSLOT_EFFECT, reverbFx);
}
}
private boolean fillBuffer(AudioStream stream, int id) {
int size = 0;
int result;
while (size < arrayBuf.length) {
result = stream.readSamples(arrayBuf, size, arrayBuf.length - size);
if (result > 0) {
size += result;
} else {
break;
}
}
if (size == 0) {
return false;
}
nativeBuf.clear();
nativeBuf.put(arrayBuf, 0, size);
nativeBuf.flip();
al.alBufferData(id, convertFormat(stream), nativeBuf, size, stream.getSampleRate());
return true;
}
private boolean fillStreamingSource(int sourceId, AudioStream stream, boolean looping) {
boolean success = false;
int processed = al.alGetSourcei(sourceId, AL_BUFFERS_PROCESSED);
for (int i = 0; i < processed; i++) {
int buffer;
ib.position(0).limit(1);
al.alSourceUnqueueBuffers(sourceId, 1, ib);
buffer = ib.get(0);
boolean active = fillBuffer(stream, buffer);
if (!active && !stream.isEOF()) {
throw new AssertionError();
}
if (!active && looping) {
stream.setTime(0);
active = fillBuffer(stream, buffer);
if (!active) {
throw new IllegalStateException("Looping streaming source " +
"was rewinded but could not be filled");
}
}
if (active) {
ib.position(0).limit(1);
ib.put(0, buffer);
al.alSourceQueueBuffers(sourceId, 1, ib);
// At least one buffer enqueued = success.
success = true;
} else {
// No more data left to process.
break;
}
}
return success;
}
private void attachStreamToSource(int sourceId, AudioStream stream, boolean looping) {
boolean success = false;
// Reset the stream. Typically happens if it finished playing on
// its own and got reclaimed.
// Note that AudioNode.stop() already resets the stream
// since it might not be in EOF when stopped.
if (stream.isEOF()) {
stream.setTime(0);
}
for (int id : stream.getIds()) {
boolean active = fillBuffer(stream, id);
if (!active && !stream.isEOF()) {
throw new AssertionError();
}
if (!active && looping) {
stream.setTime(0);
active = fillBuffer(stream, id);
if (!active) {
throw new IllegalStateException("Looping streaming source " +
"was rewinded but could not be filled");
}
}
if (active) {
ib.position(0).limit(1);
ib.put(id).flip();
al.alSourceQueueBuffers(sourceId, 1, ib);
success = true;
}
}
if (!success) {
// should never happen
throw new IllegalStateException("No valid data could be read from stream");
}
}
private boolean attachBufferToSource(int sourceId, AudioBuffer buffer) {
al.alSourcei(sourceId, AL_BUFFER, buffer.getId());
return true;
}
private void attachAudioToSource(int sourceId, AudioData data, boolean looping) {
if (data instanceof AudioBuffer) {
attachBufferToSource(sourceId, (AudioBuffer) data);
} else if (data instanceof AudioStream) {
attachStreamToSource(sourceId, (AudioStream) data, looping);
} else {
throw new UnsupportedOperationException();
}
}
private void clearChannel(int index) {
// make room at this channel
if (chanSrcs[index] != null) {
AudioSource src = chanSrcs[index];
int sourceId = channels[index];
al.alSourceStop(sourceId);
// For streaming sources, this will clear all queued buffers.
al.alSourcei(sourceId, AL_BUFFER, 0);
if (src.getDryFilter() != null && supportEfx) {
// detach filter
al.alSourcei(sourceId, EFX.AL_DIRECT_FILTER, EFX.AL_FILTER_NULL);
}
if (src.isPositional()) {
AudioSource pas = (AudioSource) src;
if (pas.isReverbEnabled() && supportEfx) {
al.alSource3i(sourceId, EFX.AL_AUXILIARY_SEND_FILTER, 0, 0, EFX.AL_FILTER_NULL);
}
}
chanSrcs[index] = null;
}
}
private AudioSource.Status convertStatus(int oalStatus) {
switch (oalStatus) {
case AL_INITIAL:
case AL_STOPPED:
return Status.Stopped;
case AL_PAUSED:
return Status.Paused;
case AL_PLAYING:
return Status.Playing;
default:
throw new UnsupportedOperationException("Unrecognized OAL state: " + oalStatus);
}
}
public void update(float tpf) {
synchronized (threadLock) {
updateInRenderThread(tpf);
}
}
public void updateInRenderThread(float tpf) {
if (audioDisabled) {
return;
}
for (int i = 0; i < channels.length; i++) {
AudioSource src = chanSrcs[i];
if (src == null) {
continue;
}
int sourceId = channels[i];
boolean boundSource = i == src.getChannel();
boolean reclaimChannel = false;
Status oalStatus = convertStatus(al.alGetSourcei(sourceId, AL_SOURCE_STATE));
if (!boundSource) {
// Rules for instanced playback vary significantly.
// Handle it here.
if (oalStatus == Status.Stopped) {
// Instanced audio stopped playing. Reclaim channel.
clearChannel(i);
freeChannel(i);
} else if (oalStatus == Status.Paused) {
throw new AssertionError("Instanced audio cannot be paused");
}
continue;
}
Status jmeStatus = src.getStatus();
// Check if we need to sync JME status with OAL status.
if (oalStatus != jmeStatus) {
if (oalStatus == Status.Stopped && jmeStatus == Status.Playing) {
// Maybe we need to reclaim the channel.
if (src.getAudioData() instanceof AudioStream) {
AudioStream stream = (AudioStream) src.getAudioData();
if (stream.isEOF() && !src.isLooping()) {
// Stream finished playing
reclaimChannel = true;
} else {
// Stream still has data.
// Buffer starvation occured.
// Audio decoder thread will fill the data
// and start the channel again.
}
} else {
// Buffer finished playing.
if (src.isLooping()) {
throw new AssertionError("Unexpected state: " +
"A looping sound has stopped playing");
} else {
reclaimChannel = true;
}
}
if (reclaimChannel) {
src.setStatus(Status.Stopped);
src.setChannel(-1);
clearChannel(i);
freeChannel(i);
}
} else {
// jME3 state does not match OAL state.
// This is only relevant for bound sources.
throw new AssertionError("Unexpected sound status. "
+ "OAL: " + oalStatus
+ ", JME: " + jmeStatus);
}
} else {
// Stopped channel was not cleared correctly.
if (oalStatus == Status.Stopped) {
throw new AssertionError("Channel " + i + " was not reclaimed");
}
}
}
}
public void updateInDecoderThread(float tpf) {
if (audioDisabled) {
return;
}
for (int i = 0; i < channels.length; i++) {
AudioSource src = chanSrcs[i];
if (src == null || !(src.getAudioData() instanceof AudioStream)) {
continue;
}
int sourceId = channels[i];
AudioStream stream = (AudioStream) src.getAudioData();
Status oalStatus = convertStatus(al.alGetSourcei(sourceId, AL_SOURCE_STATE));
Status jmeStatus = src.getStatus();
// Keep filling data (even if we are stopped / paused)
boolean buffersWereFilled = fillStreamingSource(sourceId, stream, src.isLooping());
if (buffersWereFilled) {
if (oalStatus == Status.Stopped && jmeStatus == Status.Playing) {
// The source got stopped due to buffer starvation.
// Start it again.
logger.log(Level.WARNING, "Buffer starvation "
+ "occurred while playing stream");
al.alSourcePlay(sourceId);
} else {
// Buffers were filled, stream continues to play.
if (oalStatus == Status.Playing && jmeStatus == Status.Playing) {
// Nothing to do.
} else {
throw new AssertionError();
}
}
}
}
// Delete any unused objects.
objManager.deleteUnused(this);
}
public void setListener(Listener listener) {
checkDead();
synchronized (threadLock) {
if (audioDisabled) {
return;
}
if (this.listener != null) {
// previous listener no longer associated with current
// renderer
this.listener.setRenderer(null);
}
this.listener = listener;
this.listener.setRenderer(this);
setListenerParams(listener);
}
}
public void pauseAll() {
if (!supportPauseDevice) {
throw new UnsupportedOperationException("Pause device is NOT supported!");
}
alc.alcDevicePauseSOFT();
}
public void resumeAll() {
if (!supportPauseDevice) {
throw new UnsupportedOperationException("Pause device is NOT supported!");
}
alc.alcDeviceResumeSOFT();
}
public void playSourceInstance(AudioSource src) {
checkDead();
synchronized (threadLock) {
if (audioDisabled) {
return;
}
if (src.getAudioData() instanceof AudioStream) {
throw new UnsupportedOperationException(
"Cannot play instances "
+ "of audio streams. Use play() instead.");
}
if (src.getAudioData().isUpdateNeeded()) {
updateAudioData(src.getAudioData());
}
// create a new index for an audio-channel
int index = newChannel();
if (index == -1) {
return;
}
int sourceId = channels[index];
clearChannel(index);
// set parameters, like position and max distance
setSourceParams(sourceId, src, true);
attachAudioToSource(sourceId, src.getAudioData(), false);
chanSrcs[index] = src;
// play the channel
al.alSourcePlay(sourceId);
}
}
public void playSource(AudioSource src) {
checkDead();
synchronized (threadLock) {
if (audioDisabled) {
return;
}
if (src.getStatus() == Status.Playing) {
return;
} else if (src.getStatus() == Status.Stopped) {
//Assertion removed as it seems it's not possible to have
//something different than =1 when first playing an AudioNode
// assert src.getChannel() != -1;
// allocate channel to this source
int index = newChannel();
if (index == -1) {
logger.log(Level.WARNING, "No channel available to play {0}", src);
return;
}
clearChannel(index);
src.setChannel(index);
AudioData data = src.getAudioData();
if (data.isUpdateNeeded()) {
updateAudioData(data);
}
chanSrcs[index] = src;
setSourceParams(channels[index], src, false);
attachAudioToSource(channels[index], data, src.isLooping());
}
al.alSourcePlay(channels[src.getChannel()]);
src.setStatus(Status.Playing);
}
}
public void pauseSource(AudioSource src) {
checkDead();
synchronized (threadLock) {
if (audioDisabled) {
return;
}
if (src.getStatus() == Status.Playing) {
assert src.getChannel() != -1;
al.alSourcePause(channels[src.getChannel()]);
src.setStatus(Status.Paused);
}
}
}
public void stopSource(AudioSource src) {
synchronized (threadLock) {
if (audioDisabled) {
return;
}
if (src.getStatus() != Status.Stopped) {
int chan = src.getChannel();
assert chan != -1; // if it's not stopped, must have id
src.setStatus(Status.Stopped);
src.setChannel(-1);
clearChannel(chan);
freeChannel(chan);
if (src.getAudioData() instanceof AudioStream) {
// If the stream is seekable, then rewind it.
// Otherwise, close it, as it is no longer valid.
AudioStream stream = (AudioStream)src.getAudioData();
if (stream.isSeekable()) {
stream.setTime(0);
} else {
stream.close();
}
}
}
}
}
private int convertFormat(AudioData ad) {
switch (ad.getBitsPerSample()) {
case 8:
if (ad.getChannels() == 1) {
return AL_FORMAT_MONO8;
} else if (ad.getChannels() == 2) {
return AL_FORMAT_STEREO8;
}
break;
case 16:
if (ad.getChannels() == 1) {
return AL_FORMAT_MONO16;
} else {
return AL_FORMAT_STEREO16;
}
}
throw new UnsupportedOperationException("Unsupported channels/bits combination: "
+ "bits=" + ad.getBitsPerSample() + ", channels=" + ad.getChannels());
}
private void updateAudioBuffer(AudioBuffer ab) {
int id = ab.getId();
if (ab.getId() == -1) {
ib.position(0).limit(1);
al.alGenBuffers(1, ib);
id = ib.get(0);
ab.setId(id);
objManager.registerObject(ab);
}
ab.getData().clear();
al.alBufferData(id, convertFormat(ab), ab.getData(), ab.getData().capacity(), ab.getSampleRate());
ab.clearUpdateNeeded();
}
private void updateAudioStream(AudioStream as) {
if (as.getIds() != null) {
deleteAudioData(as);
}
int[] ids = new int[STREAMING_BUFFER_COUNT];
ib.position(0).limit(STREAMING_BUFFER_COUNT);
al.alGenBuffers(STREAMING_BUFFER_COUNT, ib);
ib.position(0).limit(STREAMING_BUFFER_COUNT);
ib.get(ids);
// Not registered with object manager.
// AudioStreams can be handled without object manager
// since their lifecycle is known to the audio renderer.
as.setIds(ids);
as.clearUpdateNeeded();
}
private void updateAudioData(AudioData ad) {
if (ad instanceof AudioBuffer) {
updateAudioBuffer((AudioBuffer) ad);
} else if (ad instanceof AudioStream) {
updateAudioStream((AudioStream) ad);
}
}
public void deleteFilter(Filter filter) {
int id = filter.getId();
if (id != -1) {
ib.position(0).limit(1);
ib.put(id).flip();
efx.alDeleteFilters(1, ib);
}
}
public void deleteAudioData(AudioData ad) {
synchronized (threadLock) {
if (audioDisabled) {
return;
}
if (ad instanceof AudioBuffer) {
AudioBuffer ab = (AudioBuffer) ad;
int id = ab.getId();
if (id != -1) {
ib.put(0, id);
ib.position(0).limit(1);
al.alDeleteBuffers(1, ib);
ab.resetObject();
}
} else if (ad instanceof AudioStream) {
AudioStream as = (AudioStream) ad;
int[] ids = as.getIds();
if (ids != null) {
ib.clear();
ib.put(ids).flip();
al.alDeleteBuffers(ids.length, ib);
as.resetObject();
}
}
}
}
}
|
ALAudioRenderer: fix issue #244
|
jme3-core/src/main/java/com/jme3/audio/openal/ALAudioRenderer.java
|
ALAudioRenderer: fix issue #244
|
|
Java
|
bsd-3-clause
|
5f5e98f1ed7d68a514e6226023ec6a9a12d85220
| 0
|
songfj/curn,bmc/curn,bmc/curn,bmc/curn,bmc/curn,bmc/curn,songfj/curn,songfj/curn,songfj/curn,songfj/curn
|
/*---------------------------------------------------------------------------*\
$Id$
---------------------------------------------------------------------------
This software is released under a BSD-style license:
Copyright (c) 2004-2006 Brian M. Clapper. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. The end-user documentation included with the redistribution, if any,
must include the following acknowlegement:
"This product includes software developed by Brian M. Clapper
(bmc@clapper.org, http://www.clapper.org/bmc/). That software is
copyright (c) 2004-2006 Brian M. Clapper."
Alternately, this acknowlegement may appear in the software itself,
if wherever such third-party acknowlegements normally appear.
3. Neither the names "clapper.org", "clapper.org Java Utility Library",
nor any of the names of the project contributors may be used to
endorse or promote products derived from this software without prior
written permission. For written permission, please contact
bmc@clapper.org.
4. Products derived from this software may not be called "clapper.org
Java Utility Library", nor may "clapper.org" appear in their names
without prior written permission of Brian M.a Clapper.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
NO EVENT SHALL BRIAN M. CLAPPER BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
\*---------------------------------------------------------------------------*/
package org.clapper.curn.parser;
import org.clapper.util.text.TextUtil;
import java.util.Collection;
import java.util.Date;
import java.util.Map;
import java.util.HashMap;
/**
* This abstract class defines a simplified view of an RSS item, providing
* only the methods necessary for <i>curn</i> to work. <i>curn</i> uses the
* {@link RSSParserFactory} class to get a specific implementation of
* <tt>RSSParser</tt>, which returns <tt>RSSChannel</tt>-conforming objects
* that, in turn, return item objects that subclass <tt>RSSItem</tt>. This
* strategy isolates the bulk of the code from the underlying RSS parser,
* making it easier to substitute different parsers as more of them become
* available. <tt>RSSItem</tt>. This strategy isolates the bulk of the code
* from the underlying RSS parser, making it easier to substitute different
* parsers as more of them become available.
*
* @see RSSParserFactory
* @see RSSParser
* @see RSSChannel
*
* @version <tt>$Revision$</tt>
*/
public abstract class RSSItem
extends RSSElement
implements Cloneable, Comparable
{
/*----------------------------------------------------------------------*\
Constants
\*----------------------------------------------------------------------*/
/**
* Constant defining the pseudo-MIME type to use for default content.
*/
public static final String DEFAULT_CONTENT_TYPE = "*";
/**
* Unlimited summary size
*/
public static final int NO_SUMMARY_LIMIT = 0;
/*----------------------------------------------------------------------*\
Private Instance Data
\*----------------------------------------------------------------------*/
private Map<String,String> contentMap = new HashMap<String,String>();
/*----------------------------------------------------------------------*\
Constructor
\*----------------------------------------------------------------------*/
/**
* Default constructor
*/
protected RSSItem()
{
// nothing to do
}
/*----------------------------------------------------------------------*\
Public Methods
\*----------------------------------------------------------------------*/
/**
* Clone this channel. This method simply calls the type-safe
* {@link #makeCopy} method. The clone is a deep-clone (i.e., the items
* are cloned, too).
*
* @return the cloned <tt>RSSChannel</tt>
*
* @throws CloneNotSupportedException doesn't, actually, but the
* <tt>Cloneable</tt> interface
* requires that this exception
* be declared
*
* @see #makeCopy
*/
public Object clone()
throws CloneNotSupportedException
{
return makeCopy(getParentChannel());
}
/**
* Make a deep copy of this <tt>RSSItem</tt> object.
*
* @param parentChannel the parent channel to assign to the new instance
*
* @return the copy
*/
public RSSItem makeCopy (RSSChannel parentChannel)
{
RSSItem copy = newInstance (parentChannel);
for (String key : this.contentMap.keySet())
copy.contentMap.put(key, this.contentMap.get(key));
copy.setTitle(this.getTitle());
copy.setSummary(this.getSummary());
copy.setLinks(this.getLinks());
copy.setCategories(this.getCategories());
copy.setPublicationDate(this.getPublicationDate());
copy.setID(this.getID());
Collection<String> authors = this.getAuthors();
if (authors != null)
{
for (String author : authors)
{
if (author != null)
copy.addAuthor(author);
}
}
return copy;
}
/**
* Get the item's content, if available. Some feed types (e.g., Atom)
* support multiple content sections, each with its own MIME type; the
* <tt>mimeType</tt> parameter specifies the caller's desired MIME
* type.
*
* @param mimeType the desired MIME type
*
* @return the content (or the default content), or null if no content
* of the desired MIME type is available
*
* @see #clearContent
* @see #getFirstContentOfType
* @see #setContent
*/
public String getContent (String mimeType)
{
String result = null;
result = (String) contentMap.get (mimeType);
if (result == null)
result = (String) contentMap.get (DEFAULT_CONTENT_TYPE);
return result;
}
/**
* Get the first content item that matches one of a list of MIME types.
*
* @param mimeTypes an array of MIME types to match, in order
*
* @return the first matching content string, or null if none was found.
* Returns the default content (if set), if there's no exact
* match.
*
* @see #getContent
* @see #clearContent
* @see #setContent
*/
public final String getFirstContentOfType (String ... mimeTypes)
{
String result = null;
for (int i = 0; i < mimeTypes.length; i++)
{
result = (String) contentMap.get (mimeTypes[i]);
if (! TextUtil.stringIsEmpty (result))
break;
}
if (result == null)
result = (String) contentMap.get (DEFAULT_CONTENT_TYPE);
return result;
}
/**
* Set the content for a specific MIME type. If the
* <tt>isDefault</tt> flag is <tt>true</tt>, then this content
* is served up as the default whenever content for a specific MIME type
* is requested but isn't available.
*
* @param content the content string
* @param mimeType the MIME type to associate with the content
*
* @see #getContent
* @see #getFirstContentOfType
* @see #clearContent
*/
public void setContent (String content, String mimeType)
{
contentMap.put (mimeType, content);
}
/**
* Clear the stored content for all MIME types, without clearing any
* other fields. (In particular, the summary is not cleared.)
*
* @see #getContent
* @see #getFirstContentOfType
* @see #setContent
*/
public void clearContent()
{
contentMap.clear();
}
/**
* Compare two items for order. The channels are ordered first by
* publication date (if any), then by title, then by unique ID,
* then by hash code (if all else is equal).
*
* @param other the other object
*
* @return negative number: this item is less than <tt>other</tt>;<br>
* 0: this item is equivalent to <tt>other</tt><br>
* positive unmber: this item is greater than <tt>other</tt>
*/
public int compareTo (Object other)
{
RSSItem otherItem = (RSSItem) other;
Date otherDate = otherItem.getPublicationDate();
Date thisDate = this.getPublicationDate();
Date now = new Date();
if (otherDate == null)
otherDate = now;
if (thisDate == null)
thisDate = now;
int cmp = thisDate.compareTo (otherDate);
if (cmp == 0)
{
String otherTitle = otherItem.getTitle();
String thisTitle = this.getTitle();
if (otherTitle == null)
otherTitle = "";
if (thisTitle == null)
thisTitle = "";
if ((cmp = thisTitle.compareTo (otherTitle)) == 0)
{
String otherID = otherItem.getID();
String thisID = this.getID();
if (otherID == null)
otherID = "";
if (thisID == null)
thisID = "";
if ((cmp = thisID.compareTo (otherID)) == 0)
cmp = this.hashCode() - other.hashCode();
}
}
return cmp;
}
/**
* Generate a hash code for this item.
*
* @return the hash code
*/
public int hashCode()
{
return getIdentifier().hashCode();
}
/**
* Compare this item to some other object for equality.
*
* @param o the object
*
* @return <tt>true</tt> if the objects are equal, <tt>false</tt> if not
*/
public boolean equals(Object o)
{
boolean eq = false;
if (o instanceof RSSItem)
eq = getIdentifier().equals(((RSSItem) o).getIdentifier());
return eq;
}
/**
* Return the string value of the item (which, right now, is its
* title).
*
* @return the title
*/
public String toString()
{
String title = getTitle();
return (title == null) ? "" : title;
}
/*----------------------------------------------------------------------*\
Public Abstract Methods
\*----------------------------------------------------------------------*/
/**
* Create a new, empty instance of the underlying concrete
* class.
*
* @param channel the parent channel
*
* @return the new instance
*/
public abstract RSSItem newInstance (RSSChannel channel);
/**
* Get the parent channel
*
* @return the parent channel
*/
public abstract RSSChannel getParentChannel();
/**
* Get the item's title
*
* @return the item's title, or null if there isn't one
*
* @see #setTitle
*/
public abstract String getTitle();
/**
* Set the item's title
*
* @param newTitle the item's title, or null if there isn't one
*
* @see #getTitle
*/
public abstract void setTitle (String newTitle);
/**
* Get the item's summary (also sometimes called the description or
* synopsis).
*
* @return the summary, or null if not available
*
* @see #setSummary
*/
public abstract String getSummary();
/**
* Set the item's summary (also sometimes called the description or
* synopsis).
*
* @param newSummary the summary, or null if not available
*
* @see #getSummary
*/
public abstract void setSummary (String newSummary);
/**
* Get the item's author list.
*
* @return the authors, or null (or an empty <tt>Collection</tt>) if
* not available
*
* @see #addAuthor
* @see #clearAuthors
* @see #setAuthors
*/
public abstract Collection<String> getAuthors();
/**
* Add to the item's author list.
*
* @param author another author string to add
*
* @see #getAuthors
* @see #clearAuthors
* @see #setAuthors
*/
public abstract void addAuthor (String author);
/**
* Clear the authors list.
*
* @see #getAuthors
* @see #addAuthor
* @see #setAuthors
*/
public abstract void clearAuthors();
/**
* Get the item's published links.
*
* @return the collection of links, or an empty collection
*
* @see #setLinks
*/
public abstract Collection<RSSLink> getLinks();
/**
* Set the item's published links.
*
* @param links the collection of links, or an empty collection (or null)
*
* @see #getLinks
*/
public abstract void setLinks (Collection<RSSLink> links);
/**
* Get the categories the item belongs to.
*
* @return a <tt>Collection</tt> of category strings (<tt>String</tt>
* objects) or null if not applicable
*
* @see #setCategories
*/
public abstract Collection<String> getCategories();
/**
* Set the categories the item belongs to.
*
* @param categories a <tt>Collection</tt> of category strings
* or null if not applicable
*
* @see #getCategories
*/
public abstract void setCategories (Collection<String> categories);
/**
* Get the item's publication date.
*
* @return the date, or null if not available
*
* @see #getPublicationDate
*/
public abstract Date getPublicationDate();
/**
* Set the item's publication date.
*
* @see #getPublicationDate
*/
public abstract void setPublicationDate (Date date);
/**
* Get the item's ID field, if any.
*
* @return the ID field, or null if not set
*
* @see #setID
*/
public abstract String getID();
/**
* Set the item's ID field, if any.
*
* @param id the ID field, or null
*/
public abstract void setID (String id);
/*----------------------------------------------------------------------*\
Private Methods
\*----------------------------------------------------------------------*/
/**
* Get a unique identifier for this RSSItem. This method will return the
* ID (see getID()), if it's set; otherwise, it'll return the URL.
*
* @return a unique identifier
*/
private String getIdentifier()
{
String id = getID();
if (id == null)
{
RSSLink url = getURL();
if (url != null)
id = url.toString();
else
{
// No URL. Use the hash code of the title, if present.
String title = getTitle();
if (title == null)
title = "";
id = String.valueOf(title.hashCode());
}
}
return id;
}
}
|
src/org/clapper/curn/parser/RSSItem.java
|
/*---------------------------------------------------------------------------*\
$Id$
---------------------------------------------------------------------------
This software is released under a BSD-style license:
Copyright (c) 2004-2006 Brian M. Clapper. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. The end-user documentation included with the redistribution, if any,
must include the following acknowlegement:
"This product includes software developed by Brian M. Clapper
(bmc@clapper.org, http://www.clapper.org/bmc/). That software is
copyright (c) 2004-2006 Brian M. Clapper."
Alternately, this acknowlegement may appear in the software itself,
if wherever such third-party acknowlegements normally appear.
3. Neither the names "clapper.org", "clapper.org Java Utility Library",
nor any of the names of the project contributors may be used to
endorse or promote products derived from this software without prior
written permission. For written permission, please contact
bmc@clapper.org.
4. Products derived from this software may not be called "clapper.org
Java Utility Library", nor may "clapper.org" appear in their names
without prior written permission of Brian M.a Clapper.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
NO EVENT SHALL BRIAN M. CLAPPER BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
\*---------------------------------------------------------------------------*/
package org.clapper.curn.parser;
import org.clapper.util.text.TextUtil;
import java.util.Collection;
import java.util.Date;
import java.util.Map;
import java.util.HashMap;
/**
* This abstract class defines a simplified view of an RSS item, providing
* only the methods necessary for <i>curn</i> to work. <i>curn</i> uses the
* {@link RSSParserFactory} class to get a specific implementation of
* <tt>RSSParser</tt>, which returns <tt>RSSChannel</tt>-conforming objects
* that, in turn, return item objects that subclass <tt>RSSItem</tt>. This
* strategy isolates the bulk of the code from the underlying RSS parser,
* making it easier to substitute different parsers as more of them become
* available. <tt>RSSItem</tt>. This strategy isolates the bulk of the code
* from the underlying RSS parser, making it easier to substitute different
* parsers as more of them become available.
*
* @see RSSParserFactory
* @see RSSParser
* @see RSSChannel
*
* @version <tt>$Revision$</tt>
*/
public abstract class RSSItem
extends RSSElement
implements Cloneable, Comparable
{
/*----------------------------------------------------------------------*\
Constants
\*----------------------------------------------------------------------*/
/**
* Constant defining the pseudo-MIME type to use for default content.
*/
public static final String DEFAULT_CONTENT_TYPE = "*";
/**
* Unlimited summary size
*/
public static final int NO_SUMMARY_LIMIT = 0;
/*----------------------------------------------------------------------*\
Private Instance Data
\*----------------------------------------------------------------------*/
private Map<String,String> contentMap = new HashMap<String,String>();
/*----------------------------------------------------------------------*\
Constructor
\*----------------------------------------------------------------------*/
/**
* Default constructor
*/
protected RSSItem()
{
// nothing to do
}
/*----------------------------------------------------------------------*\
Public Methods
\*----------------------------------------------------------------------*/
/**
* Clone this channel. This method simply calls the type-safe
* {@link #makeCopy} method. The clone is a deep-clone (i.e., the items
* are cloned, too).
*
* @return the cloned <tt>RSSChannel</tt>
*
* @throws CloneNotSupportedException doesn't, actually, but the
* <tt>Cloneable</tt> interface
* requires that this exception
* be declared
*
* @see #makeCopy
*/
public Object clone()
throws CloneNotSupportedException
{
return makeCopy(getParentChannel());
}
/**
* Make a deep copy of this <tt>RSSItem</tt> object.
*
* @param parentChannel the parent channel to assign to the new instance
*
* @return the copy
*/
public RSSItem makeCopy (RSSChannel parentChannel)
{
RSSItem copy = newInstance (parentChannel);
for (String key : this.contentMap.keySet())
copy.contentMap.put(key, this.contentMap.get(key));
copy.setTitle(this.getTitle());
copy.setSummary(this.getSummary());
copy.setLinks(this.getLinks());
copy.setCategories(this.getCategories());
copy.setPublicationDate(this.getPublicationDate());
copy.setID(this.getID());
Collection<String> authors = this.getAuthors();
if (authors != null)
{
for (String author : authors)
{
if (author != null)
copy.addAuthor(author);
}
}
return copy;
}
/**
* Get the item's content, if available. Some feed types (e.g., Atom)
* support multiple content sections, each with its own MIME type; the
* <tt>mimeType</tt> parameter specifies the caller's desired MIME
* type.
*
* @param mimeType the desired MIME type
*
* @return the content (or the default content), or null if no content
* of the desired MIME type is available
*
* @see #clearContent
* @see #getFirstContentOfType
* @see #setContent
*/
public String getContent (String mimeType)
{
String result = null;
result = (String) contentMap.get (mimeType);
if (result == null)
result = (String) contentMap.get (DEFAULT_CONTENT_TYPE);
return result;
}
/**
* Get the first content item that matches one of a list of MIME types.
*
* @param mimeTypes an array of MIME types to match, in order
*
* @return the first matching content string, or null if none was found.
* Returns the default content (if set), if there's no exact
* match.
*
* @see #getContent
* @see #clearContent
* @see #setContent
*/
public final String getFirstContentOfType (String ... mimeTypes)
{
String result = null;
for (int i = 0; i < mimeTypes.length; i++)
{
result = (String) contentMap.get (mimeTypes[i]);
if (! TextUtil.stringIsEmpty (result))
break;
}
if (result == null)
result = (String) contentMap.get (DEFAULT_CONTENT_TYPE);
return result;
}
/**
* Set the content for a specific MIME type. If the
* <tt>isDefault</tt> flag is <tt>true</tt>, then this content
* is served up as the default whenever content for a specific MIME type
* is requested but isn't available.
*
* @param content the content string
* @param mimeType the MIME type to associate with the content
*
* @see #getContent
* @see #getFirstContentOfType
* @see #clearContent
*/
public void setContent (String content, String mimeType)
{
contentMap.put (mimeType, content);
}
/**
* Clear the stored content for all MIME types, without clearing any
* other fields. (In particular, the summary is not cleared.)
*
* @see #getContent
* @see #getFirstContentOfType
* @see #setContent
*/
public void clearContent()
{
contentMap.clear();
}
/**
* Compare two items for order. The channels are ordered first by
* publication date (if any), then by title, then by unique ID,
* then by hash code (if all else is equal).
*
* @param other the other object
*
* @return negative number: this item is less than <tt>other</tt>;<br>
* 0: this item is equivalent to <tt>other</tt><br>
* positive unmber: this item is greater than <tt>other</tt>
*/
public int compareTo (Object other)
{
RSSItem otherItem = (RSSItem) other;
Date otherDate = otherItem.getPublicationDate();
Date thisDate = this.getPublicationDate();
Date now = new Date();
if (otherDate == null)
otherDate = now;
if (thisDate == null)
thisDate = now;
int cmp = thisDate.compareTo (otherDate);
if (cmp == 0)
{
String otherTitle = otherItem.getTitle();
String thisTitle = this.getTitle();
if (otherTitle == null)
otherTitle = "";
if (thisTitle == null)
thisTitle = "";
if ((cmp = thisTitle.compareTo (otherTitle)) == 0)
{
String otherID = otherItem.getID();
String thisID = this.getID();
if (otherID == null)
otherID = "";
if (thisID == null)
thisID = "";
if ((cmp = thisID.compareTo (otherID)) == 0)
cmp = this.hashCode() - other.hashCode();
}
}
return cmp;
}
/**
* Generate a hash code for this item.
*
* @return the hash code
*/
public int hashCode()
{
return getIdentifier().hashCode();
}
/**
* Compare this item to some other object for equality.
*
* @param o the object
*
* @return <tt>true</tt> if the objects are equal, <tt>false</tt> if not
*/
public boolean equals(Object o)
{
boolean eq = false;
if (o instanceof RSSItem)
eq = getIdentifier().equals(((RSSItem) o).getIdentifier());
return eq;
}
/**
* Return the string value of the item (which, right now, is its
* title).
*
* @return the title
*/
public String toString()
{
String title = getTitle();
return (title == null) ? "" : title;
}
/*----------------------------------------------------------------------*\
Public Abstract Methods
\*----------------------------------------------------------------------*/
/**
* Create a new, empty instance of the underlying concrete
* class.
*
* @param channel the parent channel
*
* @return the new instance
*/
public abstract RSSItem newInstance (RSSChannel channel);
/**
* Get the parent channel
*
* @return the parent channel
*/
public abstract RSSChannel getParentChannel();
/**
* Get the item's title
*
* @return the item's title, or null if there isn't one
*
* @see #setTitle
*/
public abstract String getTitle();
/**
* Set the item's title
*
* @param newTitle the item's title, or null if there isn't one
*
* @see #getTitle
*/
public abstract void setTitle (String newTitle);
/**
* Get the item's summary (also sometimes called the description or
* synopsis).
*
* @return the summary, or null if not available
*
* @see #setSummary
*/
public abstract String getSummary();
/**
* Set the item's summary (also sometimes called the description or
* synopsis).
*
* @param newSummary the summary, or null if not available
*
* @see #getSummary
*/
public abstract void setSummary (String newSummary);
/**
* Get the item's author list.
*
* @return the authors, or null (or an empty <tt>Collection</tt>) if
* not available
*
* @see #addAuthor
* @see #clearAuthors
* @see #setAuthors
*/
public abstract Collection<String> getAuthors();
/**
* Add to the item's author list.
*
* @param author another author string to add
*
* @see #getAuthors
* @see #clearAuthors
* @see #setAuthors
*/
public abstract void addAuthor (String author);
/**
* Clear the authors list.
*
* @see #getAuthors
* @see #addAuthor
* @see #setAuthors
*/
public abstract void clearAuthors();
/**
* Get the item's published links.
*
* @return the collection of links, or an empty collection
*
* @see #setLinks
*/
public abstract Collection<RSSLink> getLinks();
/**
* Set the item's published links.
*
* @param links the collection of links, or an empty collection (or null)
*
* @see #getLinks
*/
public abstract void setLinks (Collection<RSSLink> links);
/**
* Get the categories the item belongs to.
*
* @return a <tt>Collection</tt> of category strings (<tt>String</tt>
* objects) or null if not applicable
*
* @see #setCategories
*/
public abstract Collection<String> getCategories();
/**
* Set the categories the item belongs to.
*
* @param categories a <tt>Collection</tt> of category strings
* or null if not applicable
*
* @see #getCategories
*/
public abstract void setCategories (Collection<String> categories);
/**
* Get the item's publication date.
*
* @return the date, or null if not available
*
* @see #getPublicationDate
*/
public abstract Date getPublicationDate();
/**
* Set the item's publication date.
*
* @see #getPublicationDate
*/
public abstract void setPublicationDate (Date date);
/**
* Get the item's ID field, if any.
*
* @return the ID field, or null if not set
*
* @see #setID
*/
public abstract String getID();
/**
* Set the item's ID field, if any.
*
* @param id the ID field, or null
*/
public abstract void setID (String id);
/*----------------------------------------------------------------------*\
Private Methods
\*----------------------------------------------------------------------*/
/**
* Get a unique identifier for this RSSItem. This method will return the
* ID (see getID()), if it's set; otherwise, it'll return the URL.
*
* @return a unique identifier
*/
private String getIdentifier()
{
String id = getID();
if (id == null)
id = getURL().toString();
return id;
}
}
|
Fixed null pointer exception when item has no URL.
|
src/org/clapper/curn/parser/RSSItem.java
|
Fixed null pointer exception when item has no URL.
|
|
Java
|
mit
|
f776fc0ab81d57d25a4aceda93805a97c613155a
| 0
|
CobbleWorksMC/CobbleWorks
|
java/curtis/Cobbleworks/LootHandler.java
|
package curtis.Cobbleworks;
import java.util.List;
import com.google.common.collect.ImmutableList;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.storage.loot.LootEntry;
import net.minecraft.world.storage.loot.LootEntryTable;
import net.minecraft.world.storage.loot.LootPool;
import net.minecraft.world.storage.loot.LootTableList;
import net.minecraft.world.storage.loot.RandomValueRange;
import net.minecraft.world.storage.loot.conditions.LootCondition;
import net.minecraftforge.event.LootTableLoadEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
//I had to look specifically at Botania to see how this was done. Shoutout to Vazkii for having legible code.
public class LootHandler {
public static final List<String> lootList = ImmutableList.of(
"loot/stronghold_corridor",
"loot/jungle_temple",
"loot/nether_bridge",
"loot/end_city_treasure",
"loot/desert_pyramid"
);
public LootHandler() {
for (String str : lootList) {
LootTableList.register(new ResourceLocation(Cobbleworks.MODID, str));
}
}
@SubscribeEvent
public void lootLoad(LootTableLoadEvent e) {
String prefix = "minecraft:chests/";
String name = e.getName().toString();
if (name.startsWith(prefix)) {
String file = name.substring(name.indexOf(prefix) + prefix.length());
//System.out.println("WATCH FOR THIS YOU MORON");
//System.out.println(file);
switch (file) {
case "stronghold_corridor": e.getTable().addPool(getPool(file)); break;
case "jungle_temple": e.getTable().addPool(getPool(file)); break;
case "nether_bridge" : e.getTable().addPool(getPool(file)); break;
case "end_city_treasure": e.getTable().addPool(getPool(file)); break;
case "desert_pyramid": e.getTable().addPool(getPool(file)); break;
default: break;
}
}
}
private LootPool getPool(String file) {
return new LootPool(new LootEntry[] {getLootEntry(file, 1) }, new LootCondition[0], new RandomValueRange(1), new RandomValueRange(0, 1), Cobbleworks.MODID + "_loot_pool");
}
private LootEntry getLootEntry(String file, int i) {
return new LootEntryTable(new ResourceLocation(Cobbleworks.MODID, "loot/" + file), i, 0, new LootCondition[0], Cobbleworks.MODID + "_loot_pool");
}
}
|
Delete LootHandler.java
|
java/curtis/Cobbleworks/LootHandler.java
|
Delete LootHandler.java
|
||
Java
|
cc0-1.0
|
2f5d1f614ac1511eb46f6a3b52e997f5b4e6c4c4
| 0
|
wasner/AscenceurJava,wasner/AscenseurJava
|
ascenseur/src/affichage/te1.java
|
package affichage;
/**
* Created by w14007405 on 08/01/16.
*/
public class te1 {
}
|
Delete te1.java
|
ascenseur/src/affichage/te1.java
|
Delete te1.java
|
||
Java
|
epl-1.0
|
d4e18ecab7f2979f84da3064455c45199dfe139e
| 0
|
pecko/debrief,alastrina123/debrief,debrief/debrief,alastrina123/debrief,theanuradha/debrief,debrief/debrief,theanuradha/debrief,pecko/debrief,pecko/debrief,theanuradha/debrief,debrief/debrief,theanuradha/debrief,debrief/debrief,alastrina123/debrief,theanuradha/debrief,pecko/debrief,alastrina123/debrief,theanuradha/debrief,alastrina123/debrief,debrief/debrief,pecko/debrief,pecko/debrief,pecko/debrief,alastrina123/debrief,debrief/debrief,theanuradha/debrief,alastrina123/debrief
|
trunk/org.mwc.debrief.core/src/org/mwc/debrief/core/wizards/FlatFile/ExportFlatFileDataPage.java
|
package org.mwc.debrief.core.wizards.FlatFile;
import java.beans.PropertyDescriptor;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.swt.widgets.Text;
import org.mwc.cmap.core.wizards.CoreEditableWizardPage;
import MWC.GUI.Editable;
public class ExportFlatFileDataPage extends CoreEditableWizardPage
{
public static String NAME = "Export details";
public static class ExportDataItem implements Editable
{
private String _filePath;
private String _sensorType;
public String getFilePath()
{
return _filePath;
}
public void setFilePath(String filePath)
{
_filePath = filePath;
}
public String getSensorType()
{
return _sensorType;
}
public void setSensorType(String sensorType)
{
_sensorType = sensorType;
}
public EditorType getInfo()
{
return null;
}
public String getName()
{
return "File export details";
}
public boolean hasEditor()
{
return false;
}
}
ExportDataItem _myWrapper;
Text secondNameText;
protected ExportFlatFileDataPage(ISelection selection, String helpContext)
{
super(selection, NAME, "Export to flat file data",
"This page lets you enter further details to support the flat file export",
"images/grid_wizard.gif", helpContext, false);
_myWrapper = new ExportDataItem();
}
protected PropertyDescriptor[] getPropertyDescriptors()
{
PropertyDescriptor[] descriptors =
{ prop("FilePath", "where to place the exported file", getEditable()),
prop("SensorType", "the type of sensor", getEditable()) };
return descriptors;
}
protected Editable createMe()
{
return _myWrapper;
}
}
|
Ditch unused class
|
trunk/org.mwc.debrief.core/src/org/mwc/debrief/core/wizards/FlatFile/ExportFlatFileDataPage.java
|
Ditch unused class
|
||
Java
|
mit
|
7459d9531d15270ff8ca03b5b9881d2e4b9c0e1b
| 0
|
inaturalist/iNaturalistAndroid,inaturalist/iNaturalistAndroid,inaturalist/iNaturalistAndroid,inaturalist/iNaturalistAndroid
|
package org.inaturalist.android;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import android.text.Html;
import android.text.InputType;
import android.text.format.DateFormat;
import android.util.Log;
import android.util.Pair;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.ScrollView;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;
import android.widget.Toast;
import com.ablanco.zoomy.TapListener;
import com.ablanco.zoomy.ZoomListener;
import com.ablanco.zoomy.Zoomy;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.RequestManager;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.gif.GifDrawable;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.cocosw.bottomsheet.BottomSheet;
import com.evernote.android.state.State;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.koushikdutta.urlimageviewhelper.UrlImageViewCallback;
import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper;
import com.livefront.bridge.Bridge;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import com.viewpagerindicator.CirclePageIndicator;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.tinylog.Logger;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ObservationViewerActivity extends AppCompatActivity implements AnnotationsAdapter.OnAnnotationActions {
private static final int NEW_ID_REQUEST_CODE = 0x101;
private static final int REQUEST_CODE_LOGIN = 0x102;
private static final int REQUEST_CODE_EDIT_OBSERVATION = 0x103;
private static final int SHARE_REQUEST_CODE = 0x104;
private static final int OBSERVATION_PHOTOS_REQUEST_CODE = 0x105;
public static final int RESULT_FLAGGED_AS_CAPTIVE = 0x300;
public static final int RESULT_OBSERVATION_CHANGED = 0x301;
private static String TAG = "ObservationViewerActivity";
public final static String SHOW_COMMENTS = "show_comments";
public final static String SCROLL_TO_COMMENTS_BOTTOM = "scroll_to_comments_bottom";
private static int DATA_QUALITY_CASUAL_GRADE = 0;
private static int DATA_QUALITY_NEEDS_ID = 1;
private static int DATA_QUALITY_RESEARCH_GRADE = 2;
private static String QUALITY_GRADE_RESEARCH = "research";
private static String QUALITY_GRADE_NEEDS_ID = "needs_id";
private static String QUALITY_GRADE_CASUAL_GRADE = "casual";
private INaturalistApp mApp;
private ActivityHelper mHelper;
@State(AndroidStateBundlers.SerializableBundler.class) public Observation mObservation;
@State public boolean mFlagAsCaptive;
private Uri mUri;
private Cursor mCursor;
private TextView mUserName;
private ImageView mUserPic;
private TextView mObservedOn;
private ViewPager mPhotosViewPager;
private CirclePageIndicator mIndicator;
private ImageView mSharePhoto;
private ImageView mIdPic;
private TextView mIdName;
private TextView mTaxonicName;
private ViewGroup mIdRow;
@State(AndroidStateBundlers.JSONObjectBundler.class) public JSONObject mTaxon;
private TabHost mTabHost;
private final static String VIEW_TYPE_INFO = "info";
private final static String VIEW_TYPE_COMMENTS_IDS = "comments_ids";
private final static String VIEW_TYPE_FAVS = "favs";
private GoogleMap mMap;
private ViewGroup mLocationMapContainer;
private ImageView mUnknownLocationIcon;
private TextView mLocationText;
private ImageView mLocationPrivate;
private TextView mCasualGradeText;
private ImageView mCasualGradeIcon;
private View mNeedsIdLine;
private View mResearchGradeLine;
private TextView mNeedsIdText;
private ImageView mNeedsIdIcon;
private TextView mResearchGradeText;
private ImageView mResearchGradeIcon;
private TextView mTipText;
private ViewGroup mDataQualityReason;
private ViewGroup mDataQualityGraph;
private TextView mIncludedInProjects;
private ViewGroup mIncludedInProjectsContainer;
private ProgressBar mLoadingPhotos;
private ProgressBar mLoadingMap;
private ObservationReceiver mObservationReceiver;
@State(AndroidStateBundlers.BetterJSONListBundler.class) public ArrayList<BetterJSONObject> mFavorites = null;
@State(AndroidStateBundlers.BetterJSONListBundler.class) public ArrayList<BetterJSONObject> mCommentsIds = null;
@State public int mIdCount = 0;
private ArrayList<Integer> mProjectIds;
private ViewGroup mActivityTabContainer;
private ViewGroup mInfoTabContainer;
private ListView mCommentsIdsList;
private ProgressBar mLoadingActivity;
private CommentsIdsAdapter mAdapter;
private ViewGroup mAddId;
private ViewGroup mActivityButtons;
private ViewGroup mAddComment;
private ViewGroup mFavoritesTabContainer;
private ProgressBar mLoadingFavs;
private ListView mFavoritesList;
private ViewGroup mAddFavorite;
private FavoritesAdapter mFavoritesAdapter;
private ViewGroup mRemoveFavorite;
private int mFavIndex;
private TextView mNoFavsMessage;
private TextView mNoActivityMessage;
private ViewGroup mNotesContainer;
private TextView mNotes;
private TextView mLoginToAddCommentId;
private Button mActivitySignUp;
private Button mActivityLogin;
private ViewGroup mActivityLoginSignUpButtons;
private TextView mLoginToAddFave;
private Button mFavesSignUp;
private Button mFavesLogin;
private ViewGroup mFavesLoginSignUpButtons;
private TextView mSyncToAddCommentsIds;
private TextView mSyncToAddFave;
private ImageView mIdPicBig;
private ViewGroup mNoPhotosContainer;
private ViewGroup mLocationLabelContainer;
private PhotosViewPagerAdapter mPhotosAdapter = null;
@State(AndroidStateBundlers.BetterJSONListBundler.class) public ArrayList<BetterJSONObject> mProjects;
private ImageView mIdArrow;
private ViewGroup mUnknownLocationContainer;
@State public boolean mReadOnly;
private boolean mLoadingObservation;
@State public String mObsJson;
@State public String mTaxonJson;
private boolean mShowComments;
@State public int mCommentCount;
@State public String mTaxonImage;
@State public String mTaxonIdName;
@State public String mTaxonScientificName;
@State public int mTaxonRankLevel;
@State public String mTaxonRank;
@State public String mActiveTab;
private boolean mReloadObs;
private boolean mLoadObsJson = false;
private ViewGroup mPhotosContainer;
@State public boolean mReloadTaxon;
private boolean mScrollToCommentsBottom;
private ScrollView mScrollView;
private ViewGroup mTaxonInactive;
private View mAddCommentBackground;
private ViewGroup mAddCommentContainer;
private EditText mAddCommentText;
private View mAddCommentDone;
private MentionsAutoComplete mCommentMentions;
private AttributesReceiver mAttributesReceiver;
private ChangeAttributesReceiver mChangeAttributesReceiver;
@State public SerializableJSONArray mAttributes;
private ViewGroup mAnnotationSection;
private ListView mAnnotationsList;
private ProgressBar mLoadingAnnotations;
private ViewGroup mAnnotationsContent;
private DownloadObservationReceiver mDownloadObservationReceiver;
private ObservationSubscriptionsReceiver mObservationSubscriptionsReceiver;
private ObservationFollowReceiver mObservationFollowReceiver;
private Menu mMenu;
@State(AndroidStateBundlers.JSONArrayBundler.class) public JSONArray mObservationSubscriptions = null;
@State public boolean mFollowingObservation = false;
private TextView mMetadataObservationID;
private ViewGroup mMetadataObservationIDRow;
private TextView mMetadataObservationUUID;
private TextView mMetadataObservationURL;
private ViewGroup mMetadataObservationURLRow;
@Override
protected void onStart() {
super.onStart();
}
@Override
protected void onStop() {
super.onStop();
}
@Override
public void onAnnotationCollapsedExpanded() {
// Annotation has been expanded / collapsed - resize the list to show it
(new Handler()).postDelayed(new Runnable() {
@Override
public void run() {
ActivityHelper.setListViewHeightBasedOnItems(mAnnotationsList);
mAnnotationsList.requestLayout();
}
}, 50);
}
@Override
public void onDeleteAnnotationValue(String uuid) {
Intent serviceIntent = new Intent(INaturalistService.ACTION_DELETE_ANNOTATION, null, ObservationViewerActivity.this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.UUID, uuid);
ContextCompat.startForegroundService(this, serviceIntent);
}
@Override
public void onAnnotationAgree(String uuid) {
Intent serviceIntent = new Intent(INaturalistService.ACTION_AGREE_ANNOTATION, null, ObservationViewerActivity.this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.UUID, uuid);
ContextCompat.startForegroundService(this, serviceIntent);
}
@Override
public void onAnnotationDisagree(String uuid) {
Intent serviceIntent = new Intent(INaturalistService.ACTION_DISAGREE_ANNOTATION, null, ObservationViewerActivity.this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.UUID, uuid);
ContextCompat.startForegroundService(this, serviceIntent);
}
@Override
public void onAnnotationVoteDelete(String uuid) {
Intent serviceIntent = new Intent(INaturalistService.ACTION_DELETE_ANNOTATION_VOTE, null, ObservationViewerActivity.this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.UUID, uuid);
ContextCompat.startForegroundService(this, serviceIntent);
}
@Override
public void onSetAnnotationValue(int annotationId, int valueId) {
Intent serviceIntent = new Intent(INaturalistService.ACTION_SET_ANNOTATION_VALUE, null, ObservationViewerActivity.this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.ATTRIBUTE_ID, annotationId);
serviceIntent.putExtra(INaturalistService.VALUE_ID, valueId);
serviceIntent.putExtra(INaturalistService.OBSERVATION_ID, mObservation.id);
ContextCompat.startForegroundService(this, serviceIntent);
}
private class PhotosViewPagerAdapter extends PagerAdapter implements SoundPlayer.OnPlayerStatusChange {
private Cursor mImageCursor = null;
private Cursor mSoundCursor = null;
private List<SoundPlayer> mPlayers = new ArrayList<>();
private HashMap<Integer, Bitmap> mBitmaps = new HashMap<>();
public void refreshPhotoPositions(Integer position, boolean doNotUpdate) {
int currentPosition = position == null ? 0 : 1;
int count = mImageCursor.getCount();
if (count == 0) return;
mImageCursor.moveToPosition(0);
do {
if ((position == null) || (mImageCursor.getPosition() != position.intValue())) {
ObservationPhoto currentOp = new ObservationPhoto(mImageCursor);
currentOp.position = currentPosition;
ContentValues cv = currentOp.getContentValues();
if (doNotUpdate && currentOp._synced_at != null) {
cv.put(ObservationPhoto._SYNCED_AT, currentOp._synced_at.getTime());
}
if (currentOp.photo_filename != null) {
getContentResolver().update(ObservationPhoto.CONTENT_URI, cv, "photo_filename = '" + currentOp.photo_filename + "'", null);
} else {
getContentResolver().update(ObservationPhoto.CONTENT_URI, cv, "photo_url = '" + currentOp.photo_url + "'", null);
}
currentPosition++;
}
} while (mImageCursor.moveToNext());
}
public PhotosViewPagerAdapter() {
if (!mReadOnly && mObservation != null && mObservation.uuid != null) {
mImageCursor = getContentResolver().query(ObservationPhoto.CONTENT_URI,
ObservationPhoto.PROJECTION,
"(observation_uuid=?) and ((is_deleted = 0) OR (is_deleted IS NULL))",
new String[]{mObservation.uuid},
ObservationPhoto.DEFAULT_SORT_ORDER);
mSoundCursor = getContentResolver().query(ObservationSound.CONTENT_URI,
ObservationSound.PROJECTION,
"(observation_uuid=?) and ((is_deleted = 0) OR (is_deleted IS NULL))",
new String[]{mObservation.uuid},
ObservationSound.DEFAULT_SORT_ORDER);
mImageCursor.moveToFirst();
}
}
public Cursor getCursor() {
return mImageCursor;
}
@Override
public int getCount() {
return mReadOnly ?
(mObservation.photos.size() + mObservation.sounds.size()) :
(mImageCursor != null ? mImageCursor.getCount() : 0) +
(mSoundCursor != null ? mSoundCursor.getCount() : 0);
}
public int getPhotoCount() {
return mReadOnly ? mObservation.photos.size() : mImageCursor.getCount();
}
public void setAsFirstPhoto(int position) {
// Set current photo to be positioned first
mImageCursor.moveToPosition(position);
ObservationPhoto op = new ObservationPhoto(mImageCursor);
op.position = 0;
if (op.photo_filename != null) {
getContentResolver().update(ObservationPhoto.CONTENT_URI, op.getContentValues(), "photo_filename = '" + op.photo_filename + "'", null);
} else {
getContentResolver().update(ObservationPhoto.CONTENT_URI, op.getContentValues(), "photo_url = '" + op.photo_url + "'", null);
}
// Update the rest of the photos to be positioned afterwards
refreshPhotoPositions(position, false);
reloadPhotos();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public Object instantiateItem(ViewGroup container, final int position) {
ImageView imageView = new ImageView(ObservationViewerActivity.this);
imageView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
int imageId = 0;
String photoFilename = null;
String imageUrl = null;
ObservationSound sound = null;
if (!mReadOnly) {
if (position >= mImageCursor.getCount()) {
// Sound
mSoundCursor.moveToPosition(position - mImageCursor.getCount());
sound = new ObservationSound(mSoundCursor);
Logger.tag(TAG).info("Observation: " + mObservation);
Logger.tag(TAG).info("Sound: " + sound);
} else {
// Photo
mImageCursor.moveToPosition(position);
imageUrl = mImageCursor.getString(mImageCursor.getColumnIndexOrThrow(ObservationPhoto.PHOTO_URL));
photoFilename = mImageCursor.getString(mImageCursor.getColumnIndexOrThrow(ObservationPhoto.PHOTO_FILENAME));
}
} else {
if (position >= mObservation.photos.size()) {
// Show sound
sound = mObservation.sounds.get(position - mObservation.photos.size());
} else {
imageUrl = mObservation.photos.get(position).photo_url;
}
}
if (sound != null) {
// Sound - show a sound player interface
SoundPlayer player = new SoundPlayer(ObservationViewerActivity.this, container, sound, this);
View view = player.getView();
((ViewPager)container).addView(view, 0);
view.setTag(player);
mPlayers.add(player);
return view;
}
if (imageUrl != null) {
// Online photo
imageView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
String extension = imageUrl.substring(imageUrl.lastIndexOf('.'));
String thumbnailUrl, largeSizeUrl;
// Deduce the original-sized URL
if (imageUrl.substring(0, imageUrl.lastIndexOf('/')).endsWith("assets")) {
// It's an assets default URL - e.g. https://www.inaturalist.org/assets/copyright-infringement-square.png
largeSizeUrl = imageUrl.substring(0, imageUrl.lastIndexOf('-') + 1) + "original" + extension;
thumbnailUrl = imageUrl.substring(0, imageUrl.lastIndexOf('-') + 1) + "small" + extension;
} else {
// "Regular" observation photo
largeSizeUrl = imageUrl.substring(0, imageUrl.lastIndexOf('/') + 1) + "original" + extension;
thumbnailUrl = imageUrl.substring(0, imageUrl.lastIndexOf('/') + 1) + "small" + extension;
}
RequestBuilder thumbnailRequest = Glide.with(ObservationViewerActivity.this)
.load(thumbnailUrl);
Glide.with(ObservationViewerActivity.this)
.load(largeSizeUrl)
.thumbnail(thumbnailRequest)
.apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.AUTOMATIC))
.into(new CustomTarget<Drawable>() {
@Override
public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
// Save downloaded bitmap into local file
imageView.setImageDrawable(resource);
if (resource instanceof BitmapDrawable) {
mBitmaps.put(position, ((BitmapDrawable)resource).getBitmap());
} else if (resource instanceof GifDrawable) {
mBitmaps.put(position, ((GifDrawable) resource).getFirstFrame());
}
}
@Override
public void onLoadCleared(@Nullable Drawable placeholder) {
}
@Override
public void onLoadFailed(@Nullable Drawable errorDrawable) {
// Failed to load observation photo
try {
JSONObject eventParams = new JSONObject();
eventParams.put(AnalyticsClient.EVENT_PARAM_SIZE, AnalyticsClient.EVENT_PARAM_VALUE_MEDIUM);
AnalyticsClient.getInstance().logEvent(AnalyticsClient.EVENT_NAME_OBS_PHOTO_FAILED_TO_LOAD, eventParams);
} catch (JSONException e) {
Logger.tag(TAG).error(e);
}
}
});
} else {
// Offline photo
int newHeight = mPhotosViewPager.getMeasuredHeight();
int newWidth = mPhotosViewPager.getMeasuredWidth();
Bitmap bitmapImage = null;
try {
BitmapFactory.Options options = new BitmapFactory.Options();
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
// This decreases in-memory byte-storage per pixel
options.inPreferredConfig = Bitmap.Config.ALPHA_8;
bitmapImage = BitmapFactory.decodeFile(photoFilename, options);
bitmapImage = ImageUtils.rotateAccordingToOrientation(bitmapImage, photoFilename);
imageView.setImageBitmap(bitmapImage);
mBitmaps.put(position, bitmapImage);
} catch (Exception e) {
Logger.tag(TAG).error(e);
}
}
((ViewPager)container).addView(imageView, 0);
new Zoomy.Builder(ObservationViewerActivity.this)
.target(imageView)
.zoomListener(new ZoomListener() {
@Override
public void onViewBeforeStartedZooming(View view) {
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setImageBitmap(mBitmaps.get(position));
}
@Override
public void onViewStartedZooming(View view) {
}
@Override
public void onViewEndedZooming(View view) {
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
}
})
.tapListener(new TapListener() {
@Override
public void onTap(View v) {
Intent intent = new Intent(ObservationViewerActivity.this, ObservationPhotosViewer.class);
intent.putExtra(ObservationPhotosViewer.CURRENT_PHOTO_INDEX, position);
if (!mReadOnly) {
intent.putExtra(ObservationPhotosViewer.OBSERVATION_ID, mObservation.id);
intent.putExtra(ObservationPhotosViewer.OBSERVATION_ID_INTERNAL, mObservation._id);
intent.putExtra(ObservationPhotosViewer.OBSERVATION_UUID, mObservation.uuid);
intent.putExtra(ObservationPhotosViewer.IS_NEW_OBSERVATION, true);
intent.putExtra(ObservationPhotosViewer.READ_ONLY, false);
startActivityForResult(intent, OBSERVATION_PHOTOS_REQUEST_CODE);
} else {
try {
JSONObject obs = ObservationUtils.getMinimalObservation(new JSONObject(mObsJson));
intent.putExtra(ObservationPhotosViewer.OBSERVATION, obs.toString());
startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
})
.register();
return imageView;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((View) object);
}
public void destroy() {
for (SoundPlayer player : mPlayers) {
if (player != null) {
player.destroy();
}
}
}
public void pause() {
for (SoundPlayer player : mPlayers) {
if (player != null) {
player.pause();
}
}
}
@Override
public void onPlay(SoundPlayer player) {
// Pause all other players
for (SoundPlayer p : mPlayers) {
if ((p != null) && (!p.equals(player))) {
p.pause();
}
}
}
@Override
public void onPause(SoundPlayer player) {
}
}
@Override
protected void onResume() {
super.onResume();
loadObservationIntoUI();
refreshDataQuality();
refreshProjectList();
setupMap();
resizeActivityList();
resizeFavList();
refreshAttributes();
mAttributesReceiver = new AttributesReceiver();
IntentFilter filter = new IntentFilter(INaturalistService.GET_ATTRIBUTES_FOR_TAXON_RESULT);
BaseFragmentActivity.safeRegisterReceiver(mAttributesReceiver, filter, ObservationViewerActivity.this);
mChangeAttributesReceiver = new ChangeAttributesReceiver();
IntentFilter filter2 = new IntentFilter(INaturalistService.DELETE_ANNOTATION_RESULT);
filter2.addAction(INaturalistService.AGREE_ANNOTATION_RESULT);
filter2.addAction(INaturalistService.DISAGREE_ANNOTATION_RESULT);
filter2.addAction(INaturalistService.DELETE_ANNOTATION_VOTE_RESULT);
filter2.addAction(INaturalistService.SET_ANNOTATION_VALUE_RESULT);
BaseFragmentActivity.safeRegisterReceiver(mChangeAttributesReceiver, filter2, ObservationViewerActivity.this);
mDownloadObservationReceiver = new DownloadObservationReceiver();
IntentFilter filter3 = new IntentFilter(INaturalistService.ACTION_GET_AND_SAVE_OBSERVATION_RESULT);
BaseFragmentActivity.safeRegisterReceiver(mDownloadObservationReceiver, filter3, this);
mObservationSubscriptionsReceiver = new ObservationSubscriptionsReceiver();
IntentFilter filter4 = new IntentFilter(INaturalistService.ACTION_GET_OBSERVATION_SUBSCRIPTIONS_RESULT);
BaseFragmentActivity.safeRegisterReceiver(mObservationSubscriptionsReceiver, filter4, this);
mObservationFollowReceiver = new ObservationFollowReceiver();
IntentFilter filter5 = new IntentFilter(INaturalistService.ACTION_FOLLOW_OBSERVATION_RESULT);
BaseFragmentActivity.safeRegisterReceiver(mObservationFollowReceiver, filter5, this);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bridge.restoreInstanceState(this, savedInstanceState);
ActionBar actionBar = getSupportActionBar();
actionBar.setLogo(R.drawable.ic_arrow_back);
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle(R.string.observation);
mApp = (INaturalistApp) getApplicationContext();
mApp.applyLocaleSettings(getBaseContext());
setContentView(R.layout.observation_viewer);
mHelper = new ActivityHelper(this);
mMetadataObservationID = (TextView) findViewById(R.id.observation_id);
mMetadataObservationIDRow = (ViewGroup) findViewById(R.id.metadata_id_row);
mMetadataObservationUUID = (TextView) findViewById(R.id.observation_uuid);
mMetadataObservationURL = (TextView) findViewById(R.id.observation_url);
mMetadataObservationURLRow = (ViewGroup) findViewById(R.id.metadata_url_row);
reloadObservation(savedInstanceState, false);
mAnnotationSection = (ViewGroup) findViewById(R.id.annotations_section);
mAnnotationsList = (ListView) findViewById(R.id.annotations_list);
mLoadingAnnotations = (ProgressBar) findViewById(R.id.loading_annotations);
mAnnotationsContent = (ViewGroup) findViewById(R.id.annotations_content);
mAddCommentBackground = (View) findViewById(R.id.add_comment_background);
mAddCommentContainer = (ViewGroup) findViewById(R.id.add_comment_container);
mAddCommentDone = findViewById(R.id.add_comment_done);
mAddCommentText = (EditText) findViewById(R.id.add_comment_text);
mCommentMentions = new MentionsAutoComplete(ObservationViewerActivity.this, mAddCommentText);
mScrollView = (ScrollView) findViewById(R.id.scroll_view);
mUserName = (TextView) findViewById(R.id.user_name);
mObservedOn = (TextView) findViewById(R.id.observed_on);
mUserPic = (ImageView) findViewById(R.id.user_pic);
mPhotosViewPager = (ViewPager) findViewById(R.id.photos);
mIndicator = (CirclePageIndicator)findViewById(R.id.photos_indicator);
mSharePhoto = findViewById(R.id.share_photo);
mIdPic = (ImageView)findViewById(R.id.id_icon);
mIdName = (TextView) findViewById(R.id.id_name);
mTaxonicName = (TextView) findViewById(R.id.id_sub_name);
mIdRow = (ViewGroup) findViewById(R.id.id_row);
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.location_map)).getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
setupMap();
}
});
mLocationMapContainer = (ViewGroup) findViewById(R.id.location_map_container);
mUnknownLocationContainer = (ViewGroup) findViewById(R.id.unknown_location_container);
mUnknownLocationIcon = (ImageView) findViewById(R.id.unknown_location);
mLocationText = (TextView) findViewById(R.id.location_text);
mLocationPrivate = (ImageView) findViewById(R.id.location_private);
mCasualGradeText = (TextView) findViewById(R.id.casual_grade_text);
mCasualGradeIcon = (ImageView) findViewById(R.id.casual_grade_icon);
mNeedsIdLine = (View) findViewById(R.id.needs_id_line);
mResearchGradeLine = (View) findViewById(R.id.research_grade_line);
mNeedsIdText = (TextView) findViewById(R.id.needs_id_text);
mNeedsIdIcon = (ImageView) findViewById(R.id.needs_id_icon);
mResearchGradeText = (TextView) findViewById(R.id.research_grade_text);
mResearchGradeIcon = (ImageView) findViewById(R.id.research_grade_icon);
mTipText = (TextView) findViewById(R.id.tip_text);
mDataQualityReason = (ViewGroup) findViewById(R.id.data_quality_reason);
mDataQualityGraph = (ViewGroup) findViewById(R.id.data_quality_graph);
mIncludedInProjects = (TextView) findViewById(R.id.included_in_projects);
mIncludedInProjectsContainer = (ViewGroup) findViewById(R.id.included_in_projects_container);
mActivityTabContainer = (ViewGroup) findViewById(R.id.activity_tab_content);
mInfoTabContainer = (ViewGroup) findViewById(R.id.info_tab_content);
mLoadingActivity = (ProgressBar) findViewById(R.id.loading_activity);
mCommentsIdsList = (ListView) findViewById(R.id.comment_id_list);
mActivityButtons = (ViewGroup) findViewById(R.id.activity_buttons);
mAddComment = (ViewGroup) findViewById(R.id.add_comment);
mAddId = (ViewGroup) findViewById(R.id.add_id);
mFavoritesTabContainer = (ViewGroup) findViewById(R.id.favorites_tab_content);
mLoadingFavs = (ProgressBar) findViewById(R.id.loading_favorites);
mFavoritesList = (ListView) findViewById(R.id.favorites_list);
mAddFavorite = (ViewGroup) findViewById(R.id.add_favorite);
mRemoveFavorite = (ViewGroup) findViewById(R.id.remove_favorite);
mNoFavsMessage = (TextView) findViewById(R.id.no_favs);
mNoActivityMessage = (TextView) findViewById(R.id.no_activity);
mNotesContainer = (ViewGroup) findViewById(R.id.notes_container);
mNotes = (TextView) findViewById(R.id.notes);
mLoginToAddCommentId = (TextView) findViewById(R.id.login_to_add_comment_id);
mActivitySignUp = (Button) findViewById(R.id.activity_sign_up);
mActivityLogin = (Button) findViewById(R.id.activity_login);
mActivityLoginSignUpButtons = (ViewGroup) findViewById(R.id.activity_login_signup);
mLoginToAddFave = (TextView) findViewById(R.id.login_to_add_fave);
mFavesSignUp = (Button) findViewById(R.id.faves_sign_up);
mFavesLogin = (Button) findViewById(R.id.faves_login);
mFavesLoginSignUpButtons = (ViewGroup) findViewById(R.id.faves_login_signup);
mSyncToAddCommentsIds = (TextView) findViewById(R.id.sync_to_add_comments_ids);
mSyncToAddFave = (TextView) findViewById(R.id.sync_to_add_fave);
mNoPhotosContainer = (ViewGroup) findViewById(R.id.no_photos);
mLocationLabelContainer = (ViewGroup) findViewById(R.id.location_label_container);
mIdPicBig = (ImageView) findViewById(R.id.id_icon_big);
mIdArrow = (ImageView) findViewById(R.id.id_arrow);
mPhotosContainer = (ViewGroup) findViewById(R.id.photos_container);
mLoadingPhotos = (ProgressBar) findViewById(R.id.loading_photos);
mLoadingMap = (ProgressBar) findViewById(R.id.loading_map);
mTaxonInactive = (ViewGroup) findViewById(R.id.taxon_inactive);
mMetadataObservationURL.setOnClickListener(v -> {
String inatNetwork = mApp.getInaturalistNetworkMember();
String inatHost = mApp.getStringResourceByName("inat_host_" + inatNetwork);
String obsUrl = inatHost + "/observations/" + mObservation.id;
mHelper.openUrlInBrowser(obsUrl);
});
WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mPhotosContainer.getLayoutParams();
params.height = (int) (display.getHeight() * 0.37);
mPhotosContainer.setLayoutParams(params);
View.OnClickListener onLogin = new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(ObservationViewerActivity.this, OnboardingActivity.class);
intent.putExtra(OnboardingActivity.LOGIN, true);
startActivityForResult(intent, REQUEST_CODE_LOGIN);
}
};
View.OnClickListener onSignUp = new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivityForResult(new Intent(ObservationViewerActivity.this, OnboardingActivity.class), REQUEST_CODE_LOGIN);
}
};
mActivityLogin.setOnClickListener(onLogin);
mActivitySignUp.setOnClickListener(onSignUp);
mFavesLogin.setOnClickListener(onLogin);
mFavesSignUp.setOnClickListener(onSignUp);
mLocationPrivate.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
mHelper.alert(R.string.geoprivacy, R.string.geoprivacy_explanation);
}
});
setupTabs();
refreshActivity();
refreshFavorites();
reloadPhotos();
getCommentIdList();
refreshDataQuality();
refreshAttributes();
refreshFollowStatus();
// Mark observation updates as viewed
if (mObservation != null && mObservation._synced_at != null) {
Intent serviceIntent = new Intent(INaturalistService.ACTION_VIEWED_UPDATE, null, this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.OBSERVATION_ID, mObservation.id);
ContextCompat.startForegroundService(this, serviceIntent);
}
}
private void reloadObservation(Bundle savedInstanceState, boolean forceReload) {
Intent intent = getIntent();
if (savedInstanceState == null) {
// Do some setup based on the action being performed.
Uri uri = intent.getData();
if ((uri != null) && (uri.getScheme().equals("https"))) {
// User clicked on an observation link (e.g. https://www.inaturalist.org/observations/1234)
String path = uri.getPath();
Logger.tag(TAG).info("Launched from external URL: " + uri);
if (path.toLowerCase().startsWith("/observations/")) {
Pattern pattern = Pattern.compile("/observations/([0-9]+)");
Matcher matcher = pattern.matcher(path);
if (matcher.find()) {
int obsId = Integer.valueOf(matcher.group(1));
mReadOnly = true;
mShowComments = false;
mScrollToCommentsBottom = false;
mReloadObs = true;
mObsJson = String.format(Locale.ENGLISH, "{ \"id\": %d }", obsId);
mObservation = new Observation(new BetterJSONObject(mObsJson));
} else {
Logger.tag(TAG).error("Invalid URL");
finish();
return;
}
} else {
Logger.tag(TAG).error("Invalid URL");
finish();
return;
}
} else {
mShowComments = intent.getBooleanExtra(SHOW_COMMENTS, false);
mScrollToCommentsBottom = intent.getBooleanExtra(SCROLL_TO_COMMENTS_BOTTOM, false);
if (uri == null) {
String obsJson = intent.getStringExtra("observation");
mReadOnly = intent.getBooleanExtra("read_only", false);
mReloadObs = intent.getBooleanExtra("reload", false);
mObsJson = obsJson;
if (obsJson == null) {
Logger.tag(TAG).error("Null URI from intent.getData");
finish();
return;
}
mObservation = new Observation(new BetterJSONObject(obsJson));
if (mReadOnly && mObservation.id != null && mObservation.user_login != null && mApp.loggedIn()) {
// See if this read-only observation is in fact our own observation (e.g. viewed from explore screen)
if (mObservation.user_login.toLowerCase().equals(mApp.currentUserLogin().toLowerCase())) {
// Our own observation
Cursor c = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "id = ?", new String[]{String.valueOf(mObservation.id)}, Observation.DEFAULT_SORT_ORDER);
if (c.getCount() > 0) {
// Observation available locally in the DB - just show/edit it
mReadOnly = false;
c.moveToFirst();
mObservation = new Observation(c);
mReloadObs = false;
uri = mObservation.getUri();
intent.setData(uri);
} else {
// Observation not downloaded yet - download and save it
Intent serviceIntent = new Intent(INaturalistService.ACTION_GET_AND_SAVE_OBSERVATION, null, this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.OBSERVATION_ID, mObservation.id);
ContextCompat.startForegroundService(this, serviceIntent);
mReadOnly = false;
mReloadObs = true;
uri = ContentUris.withAppendedId(Observation.CONTENT_URI, mObservation.id);
}
c.close();
}
}
}
mUri = uri;
}
} else {
String obsUri = savedInstanceState.getString("mUri");
if (obsUri != null) {
mUri = Uri.parse(obsUri);
} else {
mUri = intent.getData();
}
}
if (mCursor != null) {
if (!mCursor.isClosed()) mCursor.close();
mCursor = null;
}
if ((!mReadOnly) && (mUri != null)) mCursor = getContentResolver().query(mUri, Observation.PROJECTION, null, null, null);
if ((mObservation == null) || (forceReload)) {
if (!mReadOnly) {
if (mCursor == null || mCursor.getCount() == 0) {
Logger.tag(TAG).error("Cursor count is zero - finishing activity: " + mCursor);
finish();
return;
}
mObservation = new Observation(mCursor);
}
}
if ((mObservation != null) && (mObsJson == null)) {
mObservationReceiver = new ObservationReceiver();
IntentFilter filter = new IntentFilter(INaturalistService.ACTION_OBSERVATION_RESULT);
Logger.tag(TAG).info("Registering ACTION_OBSERVATION_RESULT");
BaseFragmentActivity.safeRegisterReceiver(mObservationReceiver, filter, this);
mLoadObsJson = true;
Intent serviceIntent = new Intent(INaturalistService.ACTION_GET_OBSERVATION, null, this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.OBSERVATION_ID, mObservation.id);
serviceIntent.putExtra(INaturalistService.GET_PROJECTS, true);
ContextCompat.startForegroundService(this, serviceIntent);
}
if (mObservation != null) {
JSONObject json = null;
try {
if (mObsJson != null) json = new JSONObject(mObsJson);
} catch (JSONException e) {
e.printStackTrace();
}
mMetadataObservationUUID.setText((mObservation.uuid != null) || (json == null) ? mObservation.uuid : json.optString("uuid"));
if (mObservation.id != null) {
mMetadataObservationIDRow.setVisibility(View.VISIBLE);
mMetadataObservationID.setText(String.valueOf(mObservation.id));
mMetadataObservationURLRow.setVisibility(View.VISIBLE);
String inatNetwork = mApp.getInaturalistNetworkMember();
String inatHost = mApp.getStringResourceByName("inat_host_" + inatNetwork);
String obsUrl = inatHost + "/observations/" + mObservation.id;
mMetadataObservationURL.setText(obsUrl);
} else {
mMetadataObservationIDRow.setVisibility(View.GONE);
mMetadataObservationURLRow.setVisibility(View.GONE);
}
}
}
@Override
public void onDestroy() {
if ((mCursor != null) && (!mCursor.isClosed())) mCursor.close();
super.onDestroy();
}
private int getFavoritedByUsername(String username) {
for (int i = 0; i < mFavorites.size(); i++) {
BetterJSONObject currentFav = mFavorites.get(i);
BetterJSONObject user = new BetterJSONObject(currentFav.getJSONObject("user"));
if (user.getString("login").equals(username)) {
// Current user has favorited this observation
return i;
}
}
return -1;
}
private void refreshFavorites() {
SharedPreferences pref = getSharedPreferences("iNaturalistPreferences", MODE_PRIVATE);
final String username = pref.getString("username", null);
TabWidget tabWidget = mTabHost.getTabWidget();
if ((mFavorites == null) || (mFavorites.size() == 0)) {
((TextView) tabWidget.getChildAt(2).findViewById(R.id.count)).setVisibility(View.GONE);
} else {
((TextView) tabWidget.getChildAt(2).findViewById(R.id.count)).setVisibility(View.VISIBLE);
((TextView) tabWidget.getChildAt(2).findViewById(R.id.count)).setText(String.valueOf(mFavorites.size()));
}
if (username == null) {
// Not logged in
mAddFavorite.setVisibility(View.GONE);
mLoginToAddFave.setVisibility(View.VISIBLE);
mFavesLoginSignUpButtons.setVisibility(View.VISIBLE);
mLoadingFavs.setVisibility(View.GONE);
mFavoritesList.setVisibility(View.GONE);
mNoFavsMessage.setVisibility(View.GONE);
mSyncToAddFave.setVisibility(View.GONE);
return;
}
if ((mObservation == null) || (mObservation.id == null)) {
// Observation not synced
mSyncToAddFave.setVisibility(View.VISIBLE);
mLoginToAddFave.setVisibility(View.GONE);
mFavesLoginSignUpButtons.setVisibility(View.GONE);
mLoadingFavs.setVisibility(View.GONE);
mFavoritesList.setVisibility(View.GONE);
mAddFavorite.setVisibility(View.GONE);
mRemoveFavorite.setVisibility(View.GONE);
mNoFavsMessage.setVisibility(View.GONE);
return;
}
mSyncToAddFave.setVisibility(View.GONE);
mLoginToAddFave.setVisibility(View.GONE);
mFavesLoginSignUpButtons.setVisibility(View.GONE);
if (mFavorites == null) {
// Still loading
mLoadingFavs.setVisibility(View.VISIBLE);
mFavoritesList.setVisibility(View.GONE);
mAddFavorite.setVisibility(View.GONE);
mRemoveFavorite.setVisibility(View.GONE);
mNoFavsMessage.setVisibility(View.GONE);
return;
}
mLoadingFavs.setVisibility(View.GONE);
mFavoritesList.setVisibility(View.VISIBLE);
if (mFavorites.size() == 0) {
mNoFavsMessage.setVisibility(View.VISIBLE);
} else {
mNoFavsMessage.setVisibility(View.GONE);
}
mFavIndex = getFavoritedByUsername(username);
if (mFavIndex > -1) {
// User has favorited the observation
mAddFavorite.setVisibility(View.GONE);
mRemoveFavorite.setVisibility(View.VISIBLE);
} else {
mAddFavorite.setVisibility(View.VISIBLE);
mRemoveFavorite.setVisibility(View.GONE);
}
mFavoritesAdapter = new FavoritesAdapter(this, mFavorites);
mFavoritesList.setAdapter(mFavoritesAdapter);
mRemoveFavorite.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
AnalyticsClient.getInstance().logEvent(AnalyticsClient.EVENT_NAME_OBS_UNFAVE);
Intent serviceIntent = new Intent(INaturalistService.ACTION_REMOVE_FAVORITE, null, ObservationViewerActivity.this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.OBSERVATION_ID, mObservation.id);
ContextCompat.startForegroundService(ObservationViewerActivity.this, serviceIntent);
mFavIndex = getFavoritedByUsername(username);
if (mFavIndex > -1) mFavorites.remove(mFavIndex);
mFavoritesAdapter.notifyDataSetChanged();
mAddFavorite.setVisibility(View.VISIBLE);
mRemoveFavorite.setVisibility(View.GONE);
if (mFavorites.size() == 0) {
mNoFavsMessage.setVisibility(View.VISIBLE);
} else {
mNoFavsMessage.setVisibility(View.GONE);
}
}
});
mAddFavorite.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
AnalyticsClient.getInstance().logEvent(AnalyticsClient.EVENT_NAME_OBS_FAVE);
Intent serviceIntent = new Intent(INaturalistService.ACTION_ADD_FAVORITE, null, ObservationViewerActivity.this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.OBSERVATION_ID, mObservation.id);
ContextCompat.startForegroundService(ObservationViewerActivity.this, serviceIntent);
SharedPreferences pref = getSharedPreferences("iNaturalistPreferences", MODE_PRIVATE);
String username = pref.getString("username", null);
String userIconUrl = pref.getString("user_icon_url", null);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.US);
String dateStr = dateFormat.format(new Date());
BetterJSONObject newFav = new BetterJSONObject(String.format(
"{ \"user\": { \"login\": \"%s\", \"user_icon_url\": \"%s\" }, \"created_at\": \"%s\" }",
username, userIconUrl, dateStr));
mFavorites.add(newFav);
mFavoritesAdapter.notifyDataSetChanged();
mRemoveFavorite.setVisibility(View.VISIBLE);
mAddFavorite.setVisibility(View.GONE);
if (mFavorites.size() == 0) {
mNoFavsMessage.setVisibility(View.VISIBLE);
} else {
mNoFavsMessage.setVisibility(View.GONE);
}
}
});
}
private void refreshActivity() {
SharedPreferences pref = getSharedPreferences("iNaturalistPreferences", MODE_PRIVATE);
String username = pref.getString("username", null);
mLoadingPhotos.setVisibility(View.GONE);
if (username == null) {
// Not logged in
mActivityButtons.setVisibility(View.GONE);
mLoginToAddCommentId.setVisibility(View.VISIBLE);
mActivityLoginSignUpButtons.setVisibility(View.VISIBLE);
mLoadingActivity.setVisibility(View.GONE);
mCommentsIdsList.setVisibility(View.GONE);
mNoActivityMessage.setVisibility(View.GONE);
mSyncToAddCommentsIds.setVisibility(View.GONE);
return;
}
if (mObservation == null) return;
if (mObservation.id == null) {
// Observation not synced
mSyncToAddCommentsIds.setVisibility(View.VISIBLE);
mLoginToAddCommentId.setVisibility(View.GONE);
mActivityLoginSignUpButtons.setVisibility(View.GONE);
return;
}
// Update observation comment/id count for signed in users observations
mObservation.comments_count = mObservation.last_comments_count = mCommentCount;
mObservation.identifications_count = mObservation.last_identifications_count = mIdCount;
if (mObservation.getUri() != null) {
ContentValues cv = new ContentValues();
cv.put(Observation.COMMENTS_COUNT, mObservation.comments_count);
cv.put(Observation.LAST_COMMENTS_COUNT, mObservation.last_comments_count);
cv.put(Observation.IDENTIFICATIONS_COUNT, mObservation.identifications_count);
cv.put(Observation.LAST_IDENTIFICATIONS_COUNT, mObservation.last_identifications_count);
if ((mObservation._synced_at != null) && (mObservation.id != null)) {
if ((mObservation._updated_at == null) || (mObservation._updated_at.before(mObservation._synced_at)) || (mObservation._updated_at.equals(mObservation._synced_at))) {
cv.put(Observation._SYNCED_AT, System.currentTimeMillis()); // No need to sync
}
}
getContentResolver().update(mObservation.getUri(), cv, null, null);
Logger.tag(TAG).debug("ObservationViewerActivity - refreshActivity - update obs: " + mObservation.id + ":" + mObservation.preferred_common_name + ":" + mObservation.taxon_id);
}
mLoginToAddCommentId.setVisibility(View.GONE);
mActivityLoginSignUpButtons.setVisibility(View.GONE);
mSyncToAddCommentsIds.setVisibility(View.GONE);
if (mCommentsIds == null) {
// Still loading
mLoadingActivity.setVisibility(View.VISIBLE);
mCommentsIdsList.setVisibility(View.GONE);
mActivityButtons.setVisibility(View.GONE);
mNoActivityMessage.setVisibility(View.GONE);
return;
}
mLoadingActivity.setVisibility(View.GONE);
mCommentsIdsList.setVisibility(View.VISIBLE);
mActivityButtons.setVisibility(View.VISIBLE);
if (mCommentsIds.size() == 0) {
mNoActivityMessage.setVisibility(View.VISIBLE);
} else {
mNoActivityMessage.setVisibility(View.GONE);
}
if (mScrollToCommentsBottom) {
mScrollView.post(new Runnable() {
@Override
public void run() {
mScrollView.fullScroll(ScrollView.FOCUS_DOWN);
}
});
}
mAdapter = new CommentsIdsAdapter(this, mObsJson != null ? new BetterJSONObject(mObsJson) : new BetterJSONObject(mObservation.toJSONObject()), mCommentsIds, mObservation.taxon_id == null ? 0 : mObservation.taxon_id , new CommentsIdsAdapter.OnIDAdded() {
@Override
public void onIdentificationAdded(BetterJSONObject taxon) {
try {
// After calling the added ID API - we'll refresh the comment/ID list
IntentFilter filter = new IntentFilter(INaturalistService.ACTION_OBSERVATION_RESULT);
BaseFragmentActivity.safeRegisterReceiver(mObservationReceiver, filter, ObservationViewerActivity.this);
Intent serviceIntent = new Intent(INaturalistService.ACTION_AGREE_ID, null, ObservationViewerActivity.this, INaturalistService.class);
mReloadTaxon = true;
serviceIntent.putExtra(INaturalistService.OBSERVATION_ID, mObservation.id);
serviceIntent.putExtra(INaturalistService.TAXON_ID, taxon.getJSONObject("taxon").getInt("id"));
serviceIntent.putExtra(INaturalistService.FROM_VISION, false);
ContextCompat.startForegroundService(ObservationViewerActivity.this, serviceIntent);
try {
JSONObject eventParams = new JSONObject();
eventParams.put(AnalyticsClient.EVENT_PARAM_VIA, AnalyticsClient.EVENT_VALUE_VIEW_OBS_AGREE);
eventParams.put(AnalyticsClient.EVENT_PARAM_FROM_VISION_SUGGESTION, false);
AnalyticsClient.getInstance().logEvent(AnalyticsClient.EVENT_NAME_OBS_ADD_ID, eventParams);
} catch (JSONException e) {
Logger.tag(TAG).error(e);
}
} catch (JSONException e) {
Logger.tag(TAG).error(e);
}
}
@Override
public void onIdentificationRemoved(BetterJSONObject taxon) {
// After calling the remove API - we'll refresh the comment/ID list
IntentFilter filter = new IntentFilter(INaturalistService.ACTION_OBSERVATION_RESULT);
BaseFragmentActivity.safeRegisterReceiver(mObservationReceiver, filter, ObservationViewerActivity.this);
Intent serviceIntent = new Intent(INaturalistService.ACTION_REMOVE_ID, null, ObservationViewerActivity.this, INaturalistService.class);
mReloadTaxon = true;
serviceIntent.putExtra(INaturalistService.IDENTIFICATION_ID, taxon.getInt("id"));
serviceIntent.putExtra(INaturalistService.OBSERVATION_ID, mObservation.id);
ContextCompat.startForegroundService(ObservationViewerActivity.this, serviceIntent);
}
@Override
public void onIdentificationUpdated(final BetterJSONObject id) {
// Set up the input
final EditText input = new EditText(ObservationViewerActivity.this);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
input.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT));
input.setText(id.getString("body"));
input.setSelection(input.getText().length());
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
input.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(input, InputMethodManager.SHOW_IMPLICIT);
}
}, 100);
mHelper.confirm(R.string.update_id_description, input,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String body = input.getText().toString();
// After calling the update API - we'll refresh the comment/ID list
IntentFilter filter = new IntentFilter(INaturalistService.ACTION_OBSERVATION_RESULT);
BaseFragmentActivity.safeRegisterReceiver(mObservationReceiver, filter, ObservationViewerActivity.this);
Intent serviceIntent = new Intent(INaturalistService.ACTION_UPDATE_ID, null, ObservationViewerActivity.this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.IDENTIFICATION_ID, id.getInt("id"));
serviceIntent.putExtra(INaturalistService.OBSERVATION_ID, mObservation.id);
serviceIntent.putExtra(INaturalistService.IDENTIFICATION_BODY, body);
serviceIntent.putExtra(INaturalistService.TAXON_ID, id.getInt("taxon_id"));
ContextCompat.startForegroundService(ObservationViewerActivity.this, serviceIntent);
}
},
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
}
@Override
public void onIdentificationRestored(BetterJSONObject id) {
// After calling the restore ID API - we'll refresh the comment/ID list
IntentFilter filter = new IntentFilter(INaturalistService.ACTION_OBSERVATION_RESULT);
BaseFragmentActivity.safeRegisterReceiver(mObservationReceiver, filter, ObservationViewerActivity.this);
Intent serviceIntent = new Intent(INaturalistService.ACTION_RESTORE_ID, null, ObservationViewerActivity.this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.IDENTIFICATION_ID, id.getInt("id"));
serviceIntent.putExtra(INaturalistService.OBSERVATION_ID, mObservation.id);
ContextCompat.startForegroundService(ObservationViewerActivity.this, serviceIntent);
}
@Override
public void onCommentRemoved(BetterJSONObject comment) {
// After calling the remove API - we'll refresh the comment/ID list
IntentFilter filter = new IntentFilter(INaturalistService.ACTION_OBSERVATION_RESULT);
BaseFragmentActivity.safeRegisterReceiver(mObservationReceiver, filter, ObservationViewerActivity.this);
Intent serviceIntent = new Intent(INaturalistService.ACTION_DELETE_COMMENT, null, ObservationViewerActivity.this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.COMMENT_ID, comment.getInt("id"));
serviceIntent.putExtra(INaturalistService.OBSERVATION_ID, mObservation.id);
ContextCompat.startForegroundService(ObservationViewerActivity.this, serviceIntent);
}
@Override
public void onCommentUpdated(final BetterJSONObject comment) {
// Set up the input
final EditText input = new EditText(ObservationViewerActivity.this);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
input.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT));
input.setText(comment.getString("body"));
input.setSelection(input.getText().length());
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
input.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(input, InputMethodManager.SHOW_IMPLICIT);
}
}, 100);
mHelper.confirm(R.string.update_comment, input,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String commentBody = input.getText().toString();
// After calling the update API - we'll refresh the comment/ID list
IntentFilter filter = new IntentFilter(INaturalistService.ACTION_OBSERVATION_RESULT);
BaseFragmentActivity.safeRegisterReceiver(mObservationReceiver, filter, ObservationViewerActivity.this);
Intent serviceIntent = new Intent(INaturalistService.ACTION_UPDATE_COMMENT, null, ObservationViewerActivity.this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.COMMENT_ID, comment.getInt("id"));
serviceIntent.putExtra(INaturalistService.OBSERVATION_ID, mObservation.id);
serviceIntent.putExtra(INaturalistService.COMMENT_BODY, commentBody);
ContextCompat.startForegroundService(ObservationViewerActivity.this, serviceIntent);
}
},
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
}
}, mReadOnly);
mCommentsIdsList.setAdapter(mAdapter);
mAddId.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(ObservationViewerActivity.this, IdentificationActivity.class);
intent.putExtra(IdentificationActivity.SUGGEST_ID, true);
intent.putExtra(IdentificationActivity.OBSERVATION_ID, mObservation.id);
intent.putExtra(IdentificationActivity.OBSERVATION_ID_INTERNAL, mObservation._id);
intent.putExtra(IdentificationActivity.OBSERVATION_UUID, mObservation.uuid);
intent.putExtra(IdentificationActivity.OBSERVED_ON, mObservation.observed_on);
intent.putExtra(IdentificationActivity.LONGITUDE, mObservation.longitude);
intent.putExtra(IdentificationActivity.LATITUDE, mObservation.latitude);
if (mObservation._id != null) {
if (((PhotosViewPagerAdapter)mPhotosViewPager.getAdapter()).getPhotoCount() > 0) {
Cursor imageCursor = ((PhotosViewPagerAdapter) mPhotosViewPager.getAdapter()).getCursor();
int pos = imageCursor.getPosition();
imageCursor.moveToFirst();
intent.putExtra(IdentificationActivity.OBS_PHOTO_FILENAME,
imageCursor.getString(imageCursor.getColumnIndex(ObservationPhoto.PHOTO_FILENAME)));
intent.putExtra(IdentificationActivity.OBS_PHOTO_URL,
imageCursor.getString(imageCursor.getColumnIndex(ObservationPhoto.PHOTO_URL)));
imageCursor.move(pos);
}
} else {
if ((mObservation.photos != null) && (mObservation.photos.size() > 0)) {
intent.putExtra(IdentificationActivity.OBS_PHOTO_FILENAME, mObservation.photos.get(0).photo_filename);
intent.putExtra(IdentificationActivity.OBS_PHOTO_URL, mObservation.photos.get(0).photo_url);
}
}
intent.putExtra(IdentificationActivity.OBSERVATION, mObsJson);
startActivityForResult(intent, NEW_ID_REQUEST_CODE);
}
});
mAddComment.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
mAddCommentBackground.setVisibility(View.VISIBLE);
mAddCommentContainer.setVisibility(View.VISIBLE);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
mAddCommentText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(mAddCommentText, InputMethodManager.SHOW_IMPLICIT);
}
}, 100);
mAddCommentText.setText("");
SharedPreferences pref = mApp.getPrefs();
String username = pref.getString("username", null);
String userIconUrl = pref.getString("user_icon_url", null);
mAddCommentDone.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String comment = mAddCommentText.getText().toString();
// Add the comment
Intent serviceIntent = new Intent(INaturalistService.ACTION_ADD_COMMENT, null, ObservationViewerActivity.this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.OBSERVATION_ID, mObservation.id);
serviceIntent.putExtra(INaturalistService.COMMENT_BODY, comment);
ContextCompat.startForegroundService(ObservationViewerActivity.this, serviceIntent);
mCommentMentions.dismiss();
mCommentsIds = null;
refreshActivity();
// Refresh the comment/id list
IntentFilter filter = new IntentFilter(INaturalistService.ACTION_OBSERVATION_RESULT);
BaseFragmentActivity.safeRegisterReceiver(mObservationReceiver, filter, ObservationViewerActivity.this);
mAddCommentContainer.setVisibility(View.GONE);
mAddCommentBackground.setVisibility(View.GONE);
// Hide keyboard
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mAddCommentText.getWindowToken(), 0);
}
});
mAddCommentBackground.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
discardAddComment();
}
});
}
});
}
private void discardAddComment() {
mHelper.confirm((View) null, getString(R.string.discard_comment), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mAddCommentContainer.setVisibility(View.GONE);
mAddCommentBackground.setVisibility(View.GONE);
dialog.dismiss();
mCommentMentions.dismiss();
// Hide keyboard
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (getCurrentFocus() != null) imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
}, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}, R.string.yes, R.string.no);
}
private void setupMap() {
if (mMap == null) return;
if (mObservation == null) return;
mMap.setMyLocationEnabled(false);
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.getUiSettings().setAllGesturesEnabled(false);
mMap.getUiSettings().setZoomControlsEnabled(false);
Double lat, lon;
Integer acc;
lat = mObservation.private_latitude == null ? mObservation.latitude : mObservation.private_latitude;
lon = mObservation.private_longitude == null ? mObservation.longitude : mObservation.private_longitude;
acc = mObservation.positional_accuracy;
if (!mLoadingObservation) {
mLoadingMap.setVisibility(View.GONE);
mLocationLabelContainer.setVisibility(View.VISIBLE);
}
if (lat != null && lon != null) {
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng latLng) {
Intent intent = new Intent(ObservationViewerActivity.this, LocationDetailsActivity.class);
intent.putExtra(LocationDetailsActivity.OBSERVATION, mObservation);
intent.putExtra(LocationDetailsActivity.OBSERVATION_JSON, mObsJson);
intent.putExtra(LocationDetailsActivity.READ_ONLY, true);
startActivity(intent);
}
});
// Add the marker
mMap.clear();
mHelper.addMapPosition(mMap, mObservation, mObsJson != null ? new BetterJSONObject(mObsJson) : null);
mLocationMapContainer.setVisibility(View.VISIBLE);
mUnknownLocationIcon.setVisibility(View.GONE);
if (((mObservation.place_guess == null) || (mObservation.place_guess.length() == 0)) &&
((mObservation.private_place_guess == null) || (mObservation.private_place_guess.length() == 0))) {
// No place guess - show coordinates instead
if (acc == null) {
mLocationText.setText(String.format(getString(R.string.location_coords_no_acc),
String.format("%.3f...", lat),
String.format("%.3f...", lon)));
} else {
mLocationText.setText(String.format(getString(R.string.location_coords),
String.format("%.3f...", lat),
String.format("%.3f...", lon),
acc > 999 ? ">1 km" : String.format("%dm", (int) acc)));
}
} else{
mLocationText.setText((mObservation.private_place_guess != null) && (mObservation.private_place_guess.length() > 0) ?
mObservation.private_place_guess : mObservation.place_guess);
}
mLocationText.setGravity(View.TEXT_ALIGNMENT_TEXT_END);
String geoprivacyField = mObservation.geoprivacy == null ? mObservation.taxon_geoprivacy : mObservation.geoprivacy;
if ((geoprivacyField == null) || (geoprivacyField.equals("open"))) {
mLocationPrivate.setVisibility(View.GONE);
} else if (geoprivacyField.equals("private")) {
mLocationPrivate.setVisibility(View.VISIBLE);
mLocationPrivate.setImageResource(R.drawable.ic_visibility_off_black_24dp);
} else if (geoprivacyField.equals("obscured")) {
mLocationPrivate.setVisibility(View.VISIBLE);
mLocationPrivate.setImageResource(R.drawable.ic_filter_tilt_shift_black_24dp);
}
mUnknownLocationContainer.setVisibility(View.GONE);
} else {
// Unknown place
mLocationMapContainer.setVisibility(View.GONE);
mUnknownLocationIcon.setVisibility(View.VISIBLE);
mLocationText.setText(R.string.unable_to_acquire_location);
mLocationText.setGravity(View.TEXT_ALIGNMENT_CENTER);
mLocationPrivate.setVisibility(View.GONE);
if (!mLoadingObservation) mUnknownLocationContainer.setVisibility(View.VISIBLE);
}
}
private View createTabContent(int tabIconResource, int contentDescriptionResource) {
View view = LayoutInflater.from(this).inflate(R.layout.observation_viewer_tab, null);
TextView countText = (TextView) view.findViewById(R.id.count);
ImageView tabIcon = (ImageView) view.findViewById(R.id.tab_icon);
tabIcon.setContentDescription(getString(contentDescriptionResource));
tabIcon.setImageResource(tabIconResource);
return view;
}
private void setupTabs() {
mTabHost.setup();
addTab(mTabHost, mTabHost.newTabSpec(VIEW_TYPE_INFO).setIndicator(createTabContent(R.drawable.ic_info_black_48dp, R.string.details)));
addTab(mTabHost, mTabHost.newTabSpec(VIEW_TYPE_COMMENTS_IDS).setIndicator(createTabContent(R.drawable.ic_forum_black_48dp, R.string.comments_ids_title)));
addTab(mTabHost, mTabHost.newTabSpec(VIEW_TYPE_FAVS).setIndicator(createTabContent(R.drawable.ic_star_black_48dp, R.string.faves)));
mTabHost.getTabWidget().setDividerDrawable(null);
if ((mActiveTab == null) && (mShowComments)) {
mTabHost.setCurrentTab(1);
refreshTabs(VIEW_TYPE_COMMENTS_IDS);
} else {
if (mActiveTab == null) {
mTabHost.setCurrentTab(0);
refreshTabs(VIEW_TYPE_INFO);
} else {
int i = 0;
if (mActiveTab.equals(VIEW_TYPE_INFO)) i = 0;
if (mActiveTab.equals(VIEW_TYPE_COMMENTS_IDS)) i = 1;
if (mActiveTab.equals(VIEW_TYPE_FAVS)) i = 2;
mTabHost.setCurrentTab(i);
refreshTabs(mActiveTab);
}
}
mTabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
@Override
public void onTabChanged(String tag) {
refreshTabs(tag);
}
});
}
private void refreshTabs(String tag) {
mActiveTab = tag;
mInfoTabContainer.setVisibility(View.GONE);
mActivityTabContainer.setVisibility(View.GONE);
mFavoritesTabContainer.setVisibility(View.GONE);
TabWidget tabWidget = mTabHost.getTabWidget();
tabWidget.getChildAt(0).findViewById(R.id.bottom_line).setVisibility(View.GONE);
tabWidget.getChildAt(1).findViewById(R.id.bottom_line).setVisibility(View.GONE);
tabWidget.getChildAt(2).findViewById(R.id.bottom_line).setVisibility(View.GONE);
((ImageView)tabWidget.getChildAt(0).findViewById(R.id.tab_icon)).setColorFilter(Color.parseColor("#757575"));
((ImageView)tabWidget.getChildAt(1).findViewById(R.id.tab_icon)).setColorFilter(Color.parseColor("#757575"));
((ImageView)tabWidget.getChildAt(2).findViewById(R.id.tab_icon)).setColorFilter(Color.parseColor("#757575"));
((TextView)tabWidget.getChildAt(2).findViewById(R.id.count)).setTextColor(Color.parseColor("#757575"));
int i = 0;
if (tag.equals(VIEW_TYPE_INFO)) {
mInfoTabContainer.setVisibility(View.VISIBLE);
i = 0;
} else if (tag.equals(VIEW_TYPE_COMMENTS_IDS)) {
mActivityTabContainer.setVisibility(View.VISIBLE);
i = 1;
} else if (tag.equals(VIEW_TYPE_FAVS)) {
mFavoritesTabContainer.setVisibility(View.VISIBLE);
((TextView)tabWidget.getChildAt(2).findViewById(R.id.count)).setTextColor(getResources().getColor(R.color.inatapptheme_color));
i = 2;
}
tabWidget.getChildAt(i).findViewById(R.id.bottom_line).setVisibility(View.VISIBLE);
((ImageView)tabWidget.getChildAt(i).findViewById(R.id.tab_icon)).setColorFilter(getResources().getColor(R.color.inatapptheme_color));
}
private void addTab(TabHost tabHost, TabHost.TabSpec tabSpec) {
tabSpec.setContent(new MyTabFactory(this));
tabHost.addTab(tabSpec);
}
private void getCommentIdList() {
if ((mObservation != null) && (mObservation.id != null) && (mCommentsIds == null)) {
BaseFragmentActivity.safeUnregisterReceiver(mObservationReceiver, this);
mObservationReceiver = new ObservationReceiver();
IntentFilter filter = new IntentFilter(INaturalistService.ACTION_OBSERVATION_RESULT);
Logger.tag(TAG).info("Registering ACTION_OBSERVATION_RESULT");
BaseFragmentActivity.safeRegisterReceiver(mObservationReceiver, filter, this);
Intent serviceIntent = new Intent(INaturalistService.ACTION_GET_OBSERVATION, null, this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.OBSERVATION_ID, mObservation.id);
serviceIntent.putExtra(INaturalistService.GET_PROJECTS, false);
ContextCompat.startForegroundService(this, serviceIntent);
if (mReadOnly) {
// Show loading progress bars for the photo and map
mLoadingObservation = true;
mLoadingPhotos.setVisibility(View.VISIBLE);
mNoPhotosContainer.setVisibility(View.GONE);
mLoadingMap.setVisibility(View.VISIBLE);
mUnknownLocationContainer.setVisibility(View.GONE);
mLocationLabelContainer.setVisibility(View.GONE);
}
}
}
private void refreshDataQuality() {
int dataQuality = DATA_QUALITY_CASUAL_GRADE;
int reasonText = 0;
if (mObservation == null) {
return;
}
Logger.tag(TAG).debug("refreshDataQuality: " + mObservation.id);
if (((mObservation.latitude == null) && (mObservation.longitude == null)) && ((mObservation.private_latitude == null) && (mObservation.private_longitude == null))) {
// No place
dataQuality = DATA_QUALITY_CASUAL_GRADE;
reasonText = R.string.casual_grade_add_location;
} else if (mObservation.observed_on == null) {
// No observed on date
dataQuality = DATA_QUALITY_CASUAL_GRADE;
reasonText = R.string.casual_grade_add_date;
} else if (((PhotosViewPagerAdapter)mPhotosViewPager.getAdapter()).getCount() == 0) {
// No photos
dataQuality = DATA_QUALITY_CASUAL_GRADE;
reasonText = R.string.casual_grade_add_photo;
} else if ((mObservation.captive != null && mObservation.captive) || mFlagAsCaptive) {
// Captive
dataQuality = DATA_QUALITY_CASUAL_GRADE;
reasonText = R.string.casual_grade_captive;
} else if (mIdCount <= 1) {
dataQuality = DATA_QUALITY_NEEDS_ID;
reasonText = R.string.needs_id_more_ids;
} else {
dataQuality = DATA_QUALITY_RESEARCH_GRADE;
}
Logger.tag(TAG).debug("refreshDataQuality 2: " + dataQuality + ":" + (reasonText != 0 ? getString(reasonText) : "N/A"));
if (mObservation.quality_grade != null) {
int observedDataQuality = -1;
if (mObservation.quality_grade.equals(QUALITY_GRADE_CASUAL_GRADE)) {
observedDataQuality = DATA_QUALITY_CASUAL_GRADE;
} else if (mObservation.quality_grade.equals(QUALITY_GRADE_NEEDS_ID)) {
observedDataQuality = DATA_QUALITY_NEEDS_ID;
} else if (mObservation.quality_grade.equals(QUALITY_GRADE_RESEARCH)) {
observedDataQuality = DATA_QUALITY_RESEARCH_GRADE;
}
if ((observedDataQuality != dataQuality) && (observedDataQuality != -1)) {
// This observation was synced and got a different data quality score - prefer
// to use what the server deducted through analysis / more advanced algorithm
dataQuality = observedDataQuality;
// Remove the reasoning
reasonText = 0;
}
Logger.tag(TAG).debug("refreshDataQuality 3: " + dataQuality);
}
Logger.tag(TAG).debug("refreshDataQuality 4: " + mObservation.quality_grade + ":" + mIdCount + ":" + mObservation.captive + ":" + mFlagAsCaptive + ":" +
((PhotosViewPagerAdapter)mPhotosViewPager.getAdapter()).getCount() + ":" + mObservation.observed_on + ":" + mObservation.latitude + ":" + mObservation.private_latitude +
":" + mObservation.longitude + ":" + mObservation.private_longitude);
// TODO - "Observation is casual grade because the community voted that they cannot identify it from the photo."
// TODO - "Observation needs finer identifications from the community to become "Research Grade" status.
int gray = Color.parseColor("#CBCBCB");
int green = Color.parseColor("#8DBA30");
if (dataQuality == DATA_QUALITY_CASUAL_GRADE) {
mNeedsIdLine.setBackgroundColor(gray);
mResearchGradeLine.setBackgroundColor(gray);
mNeedsIdText.setTextColor(gray);
mResearchGradeText.setTextColor(gray);
mNeedsIdIcon.setBackgroundResource(R.drawable.circular_border_thick_gray);
mResearchGradeIcon.setBackgroundResource(R.drawable.circular_border_thick_gray);
mNeedsIdIcon.setImageResource(R.drawable.transparent);
mResearchGradeIcon.setImageResource(R.drawable.transparent);
} else if (dataQuality == DATA_QUALITY_NEEDS_ID) {
mNeedsIdLine.setBackgroundColor(green);
mResearchGradeLine.setBackgroundColor(green);
mNeedsIdText.setTextColor(green);
mNeedsIdIcon.setBackgroundResource(R.drawable.circular_border_thick_green);
mNeedsIdIcon.setImageResource(R.drawable.ic_done_black_24dp);
mResearchGradeLine.setBackgroundColor(gray);
mResearchGradeText.setTextColor(gray);
mResearchGradeIcon.setBackgroundResource(R.drawable.circular_border_thick_gray);
mResearchGradeIcon.setImageResource(R.drawable.transparent);
} else {
mNeedsIdLine.setBackgroundColor(green);
mResearchGradeLine.setBackgroundColor(green);
mNeedsIdText.setTextColor(green);
mNeedsIdIcon.setBackgroundResource(R.drawable.circular_border_thick_green);
mNeedsIdIcon.setImageResource(R.drawable.ic_done_black_24dp);
mResearchGradeLine.setBackgroundColor(green);
mResearchGradeText.setTextColor(green);
mResearchGradeIcon.setBackgroundResource(R.drawable.circular_border_thick_green);
mResearchGradeIcon.setImageResource(R.drawable.ic_done_black_24dp);
}
if ((reasonText != 0) && (!mReadOnly)) {
mTipText.setText(Html.fromHtml(getString(reasonText)));
mDataQualityReason.setVisibility(View.VISIBLE);
} else {
mDataQualityReason.setVisibility(View.GONE);
}
OnClickListener showDataQualityAssessment = new OnClickListener() {
@Override
public void onClick(View view) {
if (!isNetworkAvailable()) {
Toast.makeText(getApplicationContext(), R.string.not_connected, Toast.LENGTH_LONG).show();
return;
}
if (mObsJson != null) {
try {
Intent intent = new Intent(ObservationViewerActivity.this, DataQualityAssessment.class);
intent.putExtra(DataQualityAssessment.OBSERVATION, new BetterJSONObject(getMinimalObservation(new JSONObject(mObsJson))));
startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
};
mDataQualityReason.setOnClickListener(showDataQualityAssessment);
mDataQualityGraph.setOnClickListener(showDataQualityAssessment);
}
private void loadObservationIntoUI() {
String userIconUrl = null;
if (mReadOnly) {
if (mObsJson == null) {
finish();
return;
}
BetterJSONObject obs = new BetterJSONObject(mObsJson);
JSONObject userObj = obs.getJSONObject("user");
if (userObj != null) {
userIconUrl = userObj.has("user_icon_url") && !userObj.isNull("user_icon_url") ? userObj.optString("user_icon_url", null) : null;
if (userIconUrl == null) {
userIconUrl = userObj.has("icon_url") && !userObj.isNull("icon_url") ? userObj.optString("icon_url", null) : null;
}
mUserName.setText(userObj.optString("login"));
mUserPic.setVisibility(View.VISIBLE);
mUserName.setVisibility(View.VISIBLE);
}
} else {
SharedPreferences pref = getSharedPreferences("iNaturalistPreferences", MODE_PRIVATE);
String username = pref.getString("username", null);
userIconUrl = pref.getString("user_icon_url", null);
mUserName.setText(username);
// Display the errors for the observation, if any
TextView errorsDescription = (TextView) findViewById(R.id.errors);
if (mObservation.id != null) {
JSONArray errors = mApp.getErrorsForObservation(mObservation.id != null ? mObservation.id : mObservation._id);
if (errors.length() == 0) {
errorsDescription.setVisibility(View.GONE);
} else {
errorsDescription.setVisibility(View.VISIBLE);
StringBuilder errorsHtml = new StringBuilder();
try {
for (int i = 0; i < errors.length(); i++) {
errorsHtml.append("• ");
errorsHtml.append(errors.getString(i));
if (i < errors.length() - 1)
errorsHtml.append("<br/>");
}
} catch (JSONException e) {
Logger.tag(TAG).error(e);
}
errorsDescription.setText(Html.fromHtml(errorsHtml.toString()));
}
} else {
errorsDescription.setVisibility(View.GONE);
}
}
if ((userIconUrl != null) && (userIconUrl.length() > 0)) {
String extension = userIconUrl.substring(userIconUrl.lastIndexOf(".") + 1);
userIconUrl = userIconUrl.substring(0, userIconUrl.lastIndexOf('/') + 1) + "medium." + extension;
}
if ((userIconUrl != null) && (userIconUrl.length() > 0)) {
UrlImageViewHelper.setUrlDrawable(mUserPic, userIconUrl, R.drawable.ic_account_circle_black_24dp, new UrlImageViewCallback() {
@Override
public void onLoaded(ImageView imageView, Bitmap loadedBitmap, String url, boolean loadedFromCache) { }
@Override
public Bitmap onPreSetBitmap(ImageView imageView, Bitmap loadedBitmap, String url, boolean loadedFromCache) {
// Return a circular version of the profile picture
Bitmap centerCrop = ImageUtils.centerCropBitmap(loadedBitmap);
return ImageUtils.getCircleBitmap(centerCrop);
}
});
} else {
mUserPic.setImageResource(R.drawable.ic_account_circle_black_24dp);
}
if (mReadOnly) {
if (mObsJson == null) return;
BetterJSONObject obs = new BetterJSONObject(mObsJson);
final JSONObject userObj = obs.getJSONObject("user");
OnClickListener showUser = new OnClickListener() {
@Override
public void onClick(View view) {
if (userObj == null) return;
Intent intent = new Intent(ObservationViewerActivity.this, UserProfile.class);
intent.putExtra("user", new BetterJSONObject(userObj));
startActivity(intent);
}
};
mUserName.setOnClickListener(showUser);
mUserPic.setOnClickListener(showUser);
}
mObservedOn.setText(formatObservedOn(mObservation.observed_on, mObservation.time_observed_at));
if (mPhotosAdapter.getCount() <= 1) {
mIndicator.setVisibility(View.GONE);
mNoPhotosContainer.setVisibility(View.GONE);
if (mPhotosAdapter.getCount() == 0) {
// No photos at all
mNoPhotosContainer.setVisibility(View.VISIBLE);
mIdPicBig.setImageResource(TaxonUtils.observationIcon(mObservation.toJSONObject()));
}
} else {
mIndicator.setVisibility(View.VISIBLE);
mNoPhotosContainer.setVisibility(View.GONE);
}
mSharePhoto.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
final DialogInterface.OnClickListener onClick = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String inatNetwork = mApp.getInaturalistNetworkMember();
String inatHost = mApp.getStringResourceByName("inat_host_" + inatNetwork);
String obsUrl = inatHost + "/observations/" + mObservation.id;
switch (which) {
case R.id.share:
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, obsUrl);
Intent chooserIntent = Intent.createChooser(shareIntent, getString(R.string.share));
startActivityForResult(chooserIntent, SHARE_REQUEST_CODE);
AnalyticsClient.getInstance().logEvent(AnalyticsClient.EVENT_NAME_OBS_SHARE_STARTED);
break;
case R.id.view_on_inat:
mHelper.openUrlInBrowser(obsUrl);
break;
case R.id.share_location:
String locationLabel;
if (mTaxon == null) {
// No taxon set - don't display the label
locationLabel = "";
} else if (mApp.getShowScientificNameFirst()) {
// Show scientific name
locationLabel = mTaxon.optString("name", "");;
} else {
locationLabel = TaxonUtils.getTaxonName(ObservationViewerActivity.this, mTaxon);
}
double latitude = (mObservation.geoprivacy == null) || (mObservation.geoprivacy.equals("open")) ? mObservation.latitude : mObservation.private_latitude;
double longitude = (mObservation.geoprivacy == null) || (mObservation.geoprivacy.equals("open")) ? mObservation.longitude : mObservation.private_longitude;
String uri = String.format(Locale.ENGLISH, "geo:0,0?q=%f,%f(%s)", latitude, longitude, locationLabel);
Intent mapIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(mapIntent);
break;
}
}
};
PopupMenu popup = new PopupMenu(ObservationViewerActivity.this, mSharePhoto);
popup.getMenuInflater().inflate(R.menu.share_photo_menu, popup.getMenu());
if ((mObservation.latitude == null) || (mObservation.longitude == null)) {
// No latitude/longitude - Hide "Share Location" menu option
popup.getMenu().getItem(1).setVisible(false);
} else {
if ((mObservation.geoprivacy != null) && (!mObservation.geoprivacy.equals("open"))) {
popup.getMenu().getItem(1).setTitle(R.string.share_hidden_location);
}
}
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(android.view.MenuItem menuItem) {
onClick.onClick(null, menuItem.getItemId());
return true;
}
});
popup.show();
}
});
OnClickListener listener = new OnClickListener() {
@Override
public void onClick(View view) {
if (mTaxon == null) {
// No taxon - don't show the taxon details page
return;
}
Intent intent = new Intent(ObservationViewerActivity.this, TaxonActivity.class);
intent.putExtra(TaxonActivity.TAXON, new BetterJSONObject(mTaxon));
intent.putExtra(TaxonActivity.OBSERVATION, mObsJson != null ? new BetterJSONObject(mObsJson) : new BetterJSONObject(mObservation.toJSONObject()));
startActivity(intent);
}
};
mIdRow.setOnClickListener(listener);
mIdName.setOnClickListener(listener);
mTaxonicName.setOnClickListener(listener);
mIdPic.setImageResource(TaxonUtils.observationIcon(mObservation.toJSONObject()));
if (mObservation.preferred_common_name != null && mObservation.preferred_common_name.length() > 0) {
mIdName.setText(mObservation.preferred_common_name);
mTaxonicName.setText(mObservation.preferred_common_name);
} else {
mIdName.setText(mObservation.species_guess);
mTaxonicName.setText(mObservation.species_guess);
}
if (mObservation.id == null) {
mSharePhoto.setVisibility(View.GONE);
}
if ((mObservation.taxon_id == null) && (mObservation.species_guess == null)) {
mIdName.setText(R.string.unknown_species);
mIdArrow.setVisibility(View.GONE);
} else if (mObservation.taxon_id != null) {
mIdArrow.setVisibility(View.VISIBLE);
if ((mTaxonScientificName == null) || (mTaxonIdName == null) || (mTaxonImage == null)) {
downloadObsTaxonAndUpdate();
} else {
UrlImageViewHelper.setUrlDrawable(mIdPic, mTaxonImage);
if (mTaxon == null) {
if ((mTaxonIdName == null) || (mTaxonIdName.length() == 0)) {
mIdName.setText(mTaxonScientificName);
mTaxonicName.setText(mTaxonScientificName);
} else {
mTaxonicName.setVisibility(View.VISIBLE);
if (mApp.getShowScientificNameFirst()) {
// Show scientific name first, before common name
TaxonUtils.setTaxonScientificName(mApp, mIdName, mTaxonScientificName, mTaxonRankLevel, mTaxonRank);
mTaxonicName.setText(mTaxonIdName);
} else {
TaxonUtils.setTaxonScientificName(mApp, mTaxonicName, mTaxonScientificName, mTaxonRankLevel, mTaxonRank);
mIdName.setText(mTaxonIdName);
}
}
} else {
if (mApp.getShowScientificNameFirst()) {
// Show scientific name first, before common name
TaxonUtils.setTaxonScientificName(mApp, mIdName, mTaxon);
mTaxonicName.setText(TaxonUtils.getTaxonName(this, mTaxon));
} else {
TaxonUtils.setTaxonScientificName(mApp, mTaxonicName, mTaxon);
mIdName.setText(TaxonUtils.getTaxonName(this, mTaxon));
}
}
}
}
mTaxonInactive.setVisibility(mTaxon == null || mTaxon.optBoolean("is_active", true) ? View.GONE : View.VISIBLE);
mTaxonInactive.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String inatNetwork = mApp.getInaturalistNetworkMember();
String inatHost = mApp.getStringResourceByName("inat_host_" + inatNetwork);
String taxonUrl = String.format(Locale.ENGLISH, "%s/taxon_changes?taxon_id=%d&locale=%s", inatHost, mTaxon.optInt("id"), mApp.getLanguageCodeForAPI());
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(taxonUrl));
startActivity(i);
}
});
if (!mReadOnly && (mProjects == null)) {
// Get IDs of project-observations
int obsId = (mObservation.id == null ? mObservation._id : mObservation.id);
Cursor c = getContentResolver().query(ProjectObservation.CONTENT_URI, ProjectObservation.PROJECTION,
"(observation_id = " + obsId + ") AND ((is_deleted = 0) OR (is_deleted is NULL))",
null, ProjectObservation.DEFAULT_SORT_ORDER);
mProjectIds = new ArrayList<Integer>();
while (c.isAfterLast() == false) {
ProjectObservation projectObservation = new ProjectObservation(c);
mProjectIds.add(projectObservation.project_id);
c.moveToNext();
}
c.close();
mProjects = new ArrayList<BetterJSONObject>();
for (int projectId : mProjectIds) {
c = getContentResolver().query(Project.CONTENT_URI, Project.PROJECTION,
"(id = " + projectId + ")", null, Project.DEFAULT_SORT_ORDER);
if (c.getCount() > 0) {
Project project = new Project(c);
BetterJSONObject projectJson = new BetterJSONObject();
projectJson.put("project", project.toJSONObject());
mProjects.add(projectJson);
}
c.close();
}
}
refreshProjectList();
mIncludedInProjectsContainer.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(ObservationViewerActivity.this, ObservationProjectsViewer.class);
intent.putExtra(ObservationProjectsViewer.PROJECTS, mProjects);
startActivity(intent);
}
});
if ((mObservation.description != null) && (mObservation.description.trim().length() > 0)) {
mNotesContainer.setVisibility(View.VISIBLE);
HtmlUtils.fromHtml(mNotes, mObservation.description);
} else {
mNotesContainer.setVisibility(View.GONE);
}
}
private JSONObject downloadTaxon(int taxonId) {
final String idUrl = INaturalistService.API_HOST + "/taxa/" + taxonId + "?locale=" + mApp.getLanguageCodeForAPI();
JSONObject results = downloadJson(idUrl);
if (results == null) return null;
return results.optJSONArray("results").optJSONObject(0);
}
private void downloadObsTaxonAndUpdate() {
// Download the taxon URL
new Thread(new Runnable() {
@Override
public void run() {
final JSONObject taxon = downloadTaxon(mObservation.taxon_id);
if (taxon == null) return;
mTaxon = taxon;
if (taxon != null) {
try {
JSONObject defaultPhoto = taxon.getJSONObject("default_photo");
final String imageUrl = defaultPhoto.getString("square_url");
runOnUiThread(new Runnable() {
@Override
public void run() {
mTaxonImage = imageUrl;
UrlImageViewHelper.setUrlDrawable(mIdPic, mTaxonImage);
mTaxonIdName = TaxonUtils.getTaxonName(ObservationViewerActivity.this, mTaxon);
mTaxonScientificName = TaxonUtils.getTaxonScientificName(mApp, taxon);
mTaxonRankLevel = taxon.optInt("rank_level", 0);
mTaxonRank = taxon.optString("rank");
if (mApp.getShowScientificNameFirst()) {
// Show scientific name first, before common name
mTaxonicName.setText(mTaxonIdName);
TaxonUtils.setTaxonScientificName(mApp, mIdName, taxon);
} else {
mIdName.setText(mTaxonIdName);
TaxonUtils.setTaxonScientificName(mApp, mTaxonicName, taxon);
}
mTaxonicName.setVisibility(View.VISIBLE);
}
});
} catch (JSONException e) {
Logger.tag(TAG).error(e);
}
}
}
}).start();
}
private JSONObject downloadJson(String uri) {
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
try {
URL url = new URL(uri);
conn = (HttpURLConnection) url.openConnection();
String jwtToken = mApp.getJWTToken();
if (mApp.loggedIn() && (jwtToken != null)) conn.setRequestProperty ("Authorization", jwtToken);
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Load the results into a StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
} catch (MalformedURLException e) {
return null;
} catch (IOException e) {
return null;
} finally {
if (conn != null) {
conn.disconnect();
}
}
try {
return new JSONObject(jsonResults.toString());
} catch (JSONException e) {
return null;
}
}
private String formatObservedOn(Timestamp date, Timestamp time) {
StringBuilder format = new StringBuilder();
if (date != null) {
// Format the date part
Calendar today = Calendar.getInstance();
today.setTime(new Date());
Calendar calDate = Calendar.getInstance();
calDate.setTimeInMillis(date.getTime());
String dateFormatString;
if (today.get(Calendar.YEAR) > calDate.get(Calendar.YEAR)) {
// Previous year(s)
dateFormatString = getString(R.string.date_short);
} else {
// Current year
dateFormatString = getString(R.string.date_short_this_year);
}
SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormatString);
format.append(dateFormat.format(date));
}
if (time != null) {
// Format the time part
if (date != null) {
format.append(" • ");
}
String timeFormatString;
if (DateFormat.is24HourFormat(getApplicationContext())) {
timeFormatString = getString(R.string.time_short_24_hour);
} else {
timeFormatString = getString(R.string.time_short_12_hour);
}
SimpleDateFormat timeFormat = new SimpleDateFormat(timeFormatString);
format.append(timeFormat.format(time));
}
return format.toString();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent;
switch (item.getItemId()) {
case android.R.id.home:
prepareToExit();
return true;
case R.id.edit_observation:
intent = new Intent(Intent.ACTION_EDIT, mUri, this, ObservationEditor.class);
if (mTaxon != null) mApp.setServiceResult(ObservationEditor.TAXON, mTaxon.toString());
if (mObsJson != null) intent.putExtra(ObservationEditor.OBSERVATION_JSON, mObsJson);
startActivityForResult(intent, REQUEST_CODE_EDIT_OBSERVATION);
return true;
case R.id.flag_captive:
mFlagAsCaptive = !mFlagAsCaptive;
refreshDataQuality();
refreshMenu();
return true;
case R.id.follow_observation:
Intent serviceIntent = new Intent(INaturalistService.ACTION_FOLLOW_OBSERVATION, null, ObservationViewerActivity.this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.OBSERVATION_ID, mObservation.id);
ContextCompat.startForegroundService(ObservationViewerActivity.this, serviceIntent);
mFollowingObservation = true;
refreshMenu();
return true;
case R.id.duplicate:
intent = new Intent(Intent.ACTION_EDIT, mUri, this, ObservationEditor.class);
if (mObsJson != null) intent.putExtra(ObservationEditor.OBSERVATION_JSON, mObsJson);
intent.putExtra(ObservationEditor.DUPLICATE, true);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onBackPressed() {
if (mAddCommentContainer.getVisibility() == View.VISIBLE) {
// Currently showing the add comment dialog
discardAddComment();
} else {
prepareToExit();
}
}
private void prepareToExit() {
if (!mFlagAsCaptive) {
finish();
return;
}
// Ask the user if he really wants to mark observation as captive
mHelper.confirm(getString(R.string.flag_as_captive), getString(R.string.are_you_sure_you_want_to_flag_as_captive),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (!mReadOnly) {
// Local observation - just update the local DB instance
ContentValues cv = mObservation.getContentValues();
cv.put(Observation.CAPTIVE, true);
int count = getContentResolver().update(mObservation.getUri(), cv, null, null);
finish();
return;
}
// Flag as captive
Intent serviceIntent = new Intent(INaturalistService.ACTION_FLAG_OBSERVATION_AS_CAPTIVE, null, ObservationViewerActivity.this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.OBSERVATION_ID, mObservation.id);
ContextCompat.startForegroundService(ObservationViewerActivity.this, serviceIntent);
Toast.makeText(getApplicationContext(), R.string.observation_flagged_as_captive, Toast.LENGTH_LONG).show();
setResult(RESULT_FLAGGED_AS_CAPTIVE);
finish();
}
},
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
}, R.string.yes, R.string.no);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.observation_viewer_menu, menu);
mMenu = menu;
refreshMenu();
return true;
}
private void refreshMenu() {
if (mMenu == null) return;
MenuItem flagCaptive = mMenu.findItem(R.id.flag_captive);
MenuItem duplicate = mMenu.findItem(R.id.duplicate);
MenuItem edit = mMenu.findItem(R.id.edit_observation);
MenuItem follow = mMenu.findItem(R.id.follow_observation);
if (mReadOnly) {
edit.setVisible(false);
duplicate.setVisible(false);
} else {
edit.setVisible(true);
duplicate.setVisible(true);
}
flagCaptive.setChecked(mFlagAsCaptive);
if (mObservationSubscriptions == null) {
follow.setEnabled(false);
follow.setTitle(R.string.follow_this_observation);
} else {
follow.setEnabled(!mFollowingObservation);
follow.setTitle(isFollowingObservation() ?
R.string.unfollow_this_observation : R.string.follow_this_observation);
}
}
private boolean isFollowingObservation() {
if ((mObservationSubscriptions == null) || (mObservationSubscriptions.length() == 0)) {
return false;
}
for (int i = 0; i < mObservationSubscriptions.length(); i++) {
JSONObject subscription = mObservationSubscriptions.optJSONObject(i);
if ((subscription.optString("resource_type", "").equals("Observation")) && (subscription.optInt("resource_id", -1) == mObservation.id)) {
return true;
}
}
return false;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
return true;
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Bridge.saveInstanceState(this, outState);
}
private class ChangeAttributesReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Logger.tag(TAG).error("ChangeAttributesReceiver");
// Re-download the observation JSON so we'll refresh the annotations
mObservationReceiver = new ObservationReceiver();
IntentFilter filter = new IntentFilter(INaturalistService.ACTION_OBSERVATION_RESULT);
Logger.tag(TAG).info("Registering ACTION_OBSERVATION_RESULT");
BaseFragmentActivity.safeRegisterReceiver(mObservationReceiver, filter, ObservationViewerActivity.this);
mLoadObsJson = true;
Intent serviceIntent = new Intent(INaturalistService.ACTION_GET_OBSERVATION, null, ObservationViewerActivity.this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.OBSERVATION_ID, mObservation.id);
serviceIntent.putExtra(INaturalistService.GET_PROJECTS, false);
ContextCompat.startForegroundService(ObservationViewerActivity.this, serviceIntent);
}
}
private void refreshFollowStatus() {
if (mObservation == null) return;
Intent serviceIntent = new Intent(INaturalistService.ACTION_GET_OBSERVATION_SUBSCRIPTIONS, null, ObservationViewerActivity.this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.OBSERVATION_ID, mObservation.id);
ContextCompat.startForegroundService(ObservationViewerActivity.this, serviceIntent);
mObservationSubscriptions = null;
mFollowingObservation = false;
refreshMenu();
}
private class AttributesReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Logger.tag(TAG).info("AttributesReceiver");
BetterJSONObject resultsObj = (BetterJSONObject) mApp.getServiceResult(INaturalistService.GET_ATTRIBUTES_FOR_TAXON_RESULT);
if (resultsObj == null) {
mAttributes = new SerializableJSONArray();
refreshAttributes();
return;
}
mAttributes = resultsObj.getJSONArray("results");
refreshAttributes();
}
}
private class ObservationFollowReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Logger.tag(TAG).error("ObservationFollowReceiver - result - " + mObservationSubscriptions);
boolean success = intent.getBooleanExtra(INaturalistService.SUCCESS, false);
if (!success) {
mFollowingObservation = false;
Toast.makeText(getApplicationContext(), getString(
isFollowingObservation() ?
R.string.could_not_unfollow_observation : R.string.could_not_follow_observation
), Toast.LENGTH_LONG).show();
refreshMenu();
return;
}
mFollowingObservation = false;
if (!isFollowingObservation()) {
mObservationSubscriptions = new JSONArray();
try {
JSONObject item = new JSONObject();
item.put("resource_type", "Observation");
item.put("resource_id", mObservation.id);
mObservationSubscriptions.put(item);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
mObservationSubscriptions = new JSONArray();
}
refreshMenu();
}
}
private class ObservationSubscriptionsReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Logger.tag(TAG).error("ObservationSubscriptionsReceiver - result");
boolean isSharedOnApp = intent.getBooleanExtra(INaturalistService.IS_SHARED_ON_APP, false);
SerializableJSONArray subscriptions;
if (isSharedOnApp) {
subscriptions = (SerializableJSONArray) mApp.getServiceResult(INaturalistService.ACTION_GET_OBSERVATION_SUBSCRIPTIONS_RESULT);
} else {
subscriptions = (SerializableJSONArray) intent.getSerializableExtra(INaturalistService.RESULTS);
}
if ((subscriptions == null) || (subscriptions.getJSONArray() == null)) {
mObservationSubscriptions = null;
refreshMenu();
return;
}
JSONArray results = subscriptions.getJSONArray();
mObservationSubscriptions = results;
refreshMenu();
}
}
private class DownloadObservationReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Logger.tag(TAG).error("DownloadObservationReceiver - OBSERVATION_RESULT");
BaseFragmentActivity.safeUnregisterReceiver(mDownloadObservationReceiver, ObservationViewerActivity.this);
boolean isSharedOnApp = intent.getBooleanExtra(INaturalistService.IS_SHARED_ON_APP, false);
Observation observation;
if (isSharedOnApp) {
observation = (Observation) mApp.getServiceResult(INaturalistService.ACTION_OBSERVATION_RESULT);
} else {
observation = (Observation) intent.getSerializableExtra(INaturalistService.OBSERVATION_RESULT);
}
if (mObservation == null) {
reloadObservation(null, false);
mObsJson = null;
}
if (observation == null) {
// Couldn't retrieve observation details (probably deleted)
mCommentsIds = new ArrayList<BetterJSONObject>();
mFavorites = new ArrayList<BetterJSONObject>();
refreshActivity();
refreshFavorites();
return;
}
if (!observation.id.equals(mObservation.id)) {
Logger.tag(TAG).error(String.format("DownloadObservationReceiver: Got old observation result for id %d, while current observation is %d", observation.id, mObservation.id));
return;
}
JSONArray projects = observation.projects.getJSONArray();
JSONArray comments = observation.comments.getJSONArray();
JSONArray ids = observation.identifications.getJSONArray();
JSONArray favs = observation.favorites.getJSONArray();
ArrayList<BetterJSONObject> results = new ArrayList<BetterJSONObject>();
ArrayList<BetterJSONObject> favResults = new ArrayList<BetterJSONObject>();
ArrayList<BetterJSONObject> projectResults = new ArrayList<BetterJSONObject>();
// #560 - refresh data quality grade
mObservation.captive = observation.captive;
mObservation.quality_grade = observation.quality_grade;
mIdCount = 0;
mCommentCount = 0;
try {
for (int i = 0; i < projects.length(); i++) {
BetterJSONObject project = new BetterJSONObject(projects.getJSONObject(i));
projectResults.add(project);
}
for (int i = 0; i < comments.length(); i++) {
BetterJSONObject comment = new BetterJSONObject(comments.getJSONObject(i));
comment.put("type", "comment");
results.add(comment);
mCommentCount++;
}
for (int i = 0; i < ids.length(); i++) {
BetterJSONObject id = new BetterJSONObject(ids.getJSONObject(i));
id.put("type", "identification");
results.add(id);
mIdCount++;
}
for (int i = 0; i < favs.length(); i++) {
BetterJSONObject fav = new BetterJSONObject(favs.getJSONObject(i));
favResults.add(fav);
}
} catch (JSONException e) {
Logger.tag(TAG).error(e);
}
Comparator<BetterJSONObject> comp = new Comparator<BetterJSONObject>() {
@Override
public int compare(BetterJSONObject lhs, BetterJSONObject rhs) {
Timestamp date1 = lhs.getTimestamp("created_at");
Timestamp date2 = rhs.getTimestamp("created_at");
return date1.compareTo(date2);
}
};
Collections.sort(results, comp);
Collections.sort(favResults, comp);
mCommentsIds = results;
mFavorites = favResults;
mProjects = projectResults;
if (mReloadObs) {
// Reload entire observation details (not just the comments/favs)
mObservation = observation;
if (!mReadOnly) {
mUri = mObservation.getUri();
getIntent().setData(mUri);
}
}
if (mReloadObs || mLoadObsJson) {
if (isSharedOnApp) {
mObsJson = (String) mApp.getServiceResult(INaturalistService.OBSERVATION_JSON_RESULT);
} else {
mObsJson = intent.getStringExtra(INaturalistService.OBSERVATION_JSON_RESULT);
}
if (mTaxonJson == null) {
new Thread(new Runnable() {
@Override
public void run() {
downloadCommunityTaxon(false);
}
}).start();
}
}
mLoadObsJson = false;
if (mReloadTaxon) {
// Reload just the taxon part, if changed
if (((mObservation.taxon_id == null) && (observation.taxon_id != null)) ||
((mObservation.taxon_id != null) && (observation.taxon_id == null)) ||
(mObservation.taxon_id != observation.taxon_id)) {
Logger.tag(TAG).debug("ObservationViewerActivity - ObservationReceiver: Updated taxon: " + mObservation.id + ":" + mObservation.preferred_common_name + ":" + mObservation.taxon_id);
Logger.tag(TAG).debug("ObservationViewerActivity - ObservationReceiver: Updated taxon (new): " + observation.id + ":" + observation.preferred_common_name + ":" + observation.taxon_id);
mObservation.species_guess = observation.species_guess;
mObservation.taxon_id = observation.taxon_id;
mObservation.preferred_common_name = observation.preferred_common_name;
mObservation.iconic_taxon_name = observation.iconic_taxon_name;
mTaxonScientificName = null;
mTaxonIdName = null;
mTaxonImage = null;
}
mReloadTaxon = false;
if (!mReadOnly) {
// Update observation's taxon in DB
ContentValues cv = mObservation.getContentValues();
getContentResolver().update(mUri, cv, null, null);
Logger.tag(TAG).debug("ObservationViewerActivity - ObservationReceiver - update obs: " + mObservation.id + ":" + mObservation.preferred_common_name + ":" + mObservation.taxon_id);
}
}
reloadPhotos();
loadObservationIntoUI();
setupMap();
refreshActivity();
refreshFavorites();
resizeActivityList();
resizeFavList();
refreshProjectList();
refreshDataQuality();
refreshAttributes();
}
}
private class ObservationReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Logger.tag(TAG).error("ObservationReceiver - OBSERVATION_RESULT");
BaseFragmentActivity.safeUnregisterReceiver(mObservationReceiver, ObservationViewerActivity.this);
mLoadingObservation = false;
boolean isSharedOnApp = intent.getBooleanExtra(INaturalistService.IS_SHARED_ON_APP, false);
Observation observation;
if (isSharedOnApp) {
observation = (Observation) mApp.getServiceResult(INaturalistService.ACTION_OBSERVATION_RESULT);
} else {
observation = (Observation) intent.getSerializableExtra(INaturalistService.OBSERVATION_RESULT);
}
if (mObservation == null) {
reloadObservation(null, false);
mObsJson = null;
}
if (observation == null) {
// Couldn't retrieve observation details (probably deleted)
mCommentsIds = new ArrayList<BetterJSONObject>();
mFavorites = new ArrayList<BetterJSONObject>();
refreshActivity();
refreshFavorites();
return;
}
if (!observation.id.equals(mObservation.id)) {
Logger.tag(TAG).error(String.format("ObservationReceiver: Got old observation result for id %d, while current observation is %d", observation.id, mObservation.id));
return;
}
JSONArray projects = observation.projects.getJSONArray();
JSONArray comments = observation.comments.getJSONArray();
JSONArray ids = observation.identifications.getJSONArray();
JSONArray favs = observation.favorites.getJSONArray();
ArrayList<BetterJSONObject> results = new ArrayList<BetterJSONObject>();
ArrayList<BetterJSONObject> favResults = new ArrayList<BetterJSONObject>();
ArrayList<BetterJSONObject> projectResults = new ArrayList<BetterJSONObject>();
// #560 - refresh data quality grade
mObservation.captive = observation.captive;
mObservation.quality_grade = observation.quality_grade;
mIdCount = 0;
mCommentCount = 0;
try {
for (int i = 0; i < projects.length(); i++) {
BetterJSONObject project = new BetterJSONObject(projects.getJSONObject(i));
projectResults.add(project);
}
for (int i = 0; i < comments.length(); i++) {
BetterJSONObject comment = new BetterJSONObject(comments.getJSONObject(i));
comment.put("type", "comment");
results.add(comment);
mCommentCount++;
}
for (int i = 0; i < ids.length(); i++) {
BetterJSONObject id = new BetterJSONObject(ids.getJSONObject(i));
id.put("type", "identification");
results.add(id);
mIdCount++;
}
for (int i = 0; i < favs.length(); i++) {
BetterJSONObject fav = new BetterJSONObject(favs.getJSONObject(i));
favResults.add(fav);
}
} catch (JSONException e) {
Logger.tag(TAG).error(e);
}
Comparator<BetterJSONObject> comp = new Comparator<BetterJSONObject>() {
@Override
public int compare(BetterJSONObject lhs, BetterJSONObject rhs) {
Timestamp date1 = lhs.getTimestamp("created_at");
Timestamp date2 = rhs.getTimestamp("created_at");
return date1.compareTo(date2);
}
};
Collections.sort(results, comp);
Collections.sort(favResults, comp);
mCommentsIds = results;
mFavorites = favResults;
mProjects = projectResults;
if (mReloadObs) {
// Reload entire observation details (not just the comments/favs)
mObservation = observation;
}
if (mReloadObs || mLoadObsJson) {
if (isSharedOnApp) {
mObsJson = (String) mApp.getServiceResult(INaturalistService.OBSERVATION_JSON_RESULT);
} else {
mObsJson = intent.getStringExtra(INaturalistService.OBSERVATION_JSON_RESULT);
}
if (mTaxonJson == null) {
new Thread(new Runnable() {
@Override
public void run() {
downloadCommunityTaxon(false);
}
}).start();
}
}
mLoadObsJson = false;
if (mReloadTaxon) {
// Reload just the taxon part, if changed
if (((mObservation.taxon_id == null) && (observation.taxon_id != null)) ||
((mObservation.taxon_id != null) && (observation.taxon_id == null)) ||
(mObservation.taxon_id != observation.taxon_id)) {
Logger.tag(TAG).debug("ObservationViewerActivity - ObservationReceiver: Updated taxon: " + mObservation.id + ":" + mObservation.preferred_common_name + ":" + mObservation.taxon_id);
Logger.tag(TAG).debug("ObservationViewerActivity - ObservationReceiver: Updated taxon (new): " + observation.id + ":" + observation.preferred_common_name + ":" + observation.taxon_id);
mObservation.species_guess = observation.species_guess;
mObservation.taxon_id = observation.taxon_id;
mObservation.preferred_common_name = observation.preferred_common_name;
mObservation.iconic_taxon_name = observation.iconic_taxon_name;
mTaxonScientificName = null;
mTaxonIdName = null;
mTaxonImage = null;
}
mReloadTaxon = false;
if (!mReadOnly) {
// Update observation's taxon in DB
ContentValues cv = mObservation.getContentValues();
getContentResolver().update(mUri, cv, null, null);
Logger.tag(TAG).debug("ObservationViewerActivity - ObservationReceiver - update obs: " + mObservation.id + ":" + mObservation.preferred_common_name + ":" + mObservation.taxon_id);
}
// Get latest annotations since community taxon might have changed
new Thread(new Runnable() {
@Override
public void run() {
downloadCommunityTaxon(true);
}
}).start();
}
if (mReloadObs && mReadOnly && mObservation.id != null && mApp.loggedIn()) {
// See if this read-only observation is in fact our own observation (e.g. viewed from explore screen)
if (mObservation.user_login.toLowerCase().equals(mApp.currentUserLogin().toLowerCase())) {
// Our own observation
Cursor c = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "id = ?", new String[]{String.valueOf(mObservation.id)}, Observation.DEFAULT_SORT_ORDER);
if (c.getCount() > 0) {
// Observation available locally in the DB - just show/edit it
mReadOnly = false;
c.moveToFirst();
mObservation = new Observation(c);
mReloadObs = false;
mUri = mObservation.getUri();
getIntent().setData(mUri);
} else {
// Observation not downloaded yet - download and save it
Intent serviceIntent = new Intent(INaturalistService.ACTION_GET_AND_SAVE_OBSERVATION, null, ObservationViewerActivity.this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.OBSERVATION_ID, mObservation.id);
ContextCompat.startForegroundService(ObservationViewerActivity.this, serviceIntent);
mReadOnly = false;
mReloadObs = true;
}
c.close();
refreshMenu();
}
}
reloadPhotos();
loadObservationIntoUI();
setupMap();
refreshActivity();
refreshFavorites();
resizeActivityList();
resizeFavList();
refreshProjectList();
refreshDataQuality();
refreshAttributes();
}
}
private void downloadCommunityTaxon(boolean downloadFromOriginalObservation) {
JSONObject observation;
try {
observation = new JSONObject(mObsJson);
} catch (JSONException e) {
Logger.tag(TAG).error(e);
return;
}
int taxonId = -1;
// Use current taxon
if (observation.has("taxon")) {
JSONObject taxon = observation.optJSONObject("taxon");
if (taxon != null) {
taxonId = taxon.optInt("id");
}
}
if (taxonId == -1) {
// No taxon - get the generic attributes (no taxon)
Intent serviceIntent = new Intent(INaturalistService.ACTION_GET_ATTRIBUTES_FOR_TAXON, null, ObservationViewerActivity.this, INaturalistService.class);
ContextCompat.startForegroundService(this, serviceIntent);
return;
}
if (downloadFromOriginalObservation) {
if (mObservation == null) return;
taxonId = mObservation.taxon_id;
}
JSONObject taxon = downloadTaxon(taxonId);
if (taxon == null) {
mAttributes = new SerializableJSONArray();
runOnUiThread(new Runnable() {
@Override
public void run() {
refreshAttributes();
}
});
return;
}
mTaxonJson = taxon.toString();
// Now that we have full taxon details, we can retrieve the annotations/attributes for that taxon
Intent serviceIntent = new Intent(INaturalistService.ACTION_GET_ATTRIBUTES_FOR_TAXON, null, ObservationViewerActivity.this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.TAXON_ID, taxon.optInt("id"));
serviceIntent.putExtra(INaturalistService.ANCESTORS, new SerializableJSONArray(taxon.optJSONArray("ancestor_ids")));
ContextCompat.startForegroundService(this, serviceIntent);
}
private void reloadPhotos() {
mLoadingPhotos.setVisibility(View.GONE);
mPhotosAdapter = new PhotosViewPagerAdapter();
mPhotosViewPager.setAdapter(mPhotosAdapter);
mIndicator.setViewPager(mPhotosViewPager);
}
private void refreshAttributes() {
if ((mObservation != null) && (mObservation.id == null)) {
// Don't show attributes for non-synced observations
mAnnotationSection.setVisibility(View.GONE);
return;
}
if (mAttributes == null) {
mAnnotationSection.setVisibility(View.VISIBLE);
mLoadingAnnotations.setVisibility(View.VISIBLE);
mAnnotationsContent.setVisibility(View.GONE);
return;
} else if (mAttributes.getJSONArray().length() == 0) {
mAnnotationSection.setVisibility(View.GONE);
return;
}
mAnnotationsContent.setVisibility(View.VISIBLE);
mAnnotationSection.setVisibility(View.VISIBLE);
mLoadingAnnotations.setVisibility(View.GONE);
JSONArray obsAnnotations = null;
if (mObsJson != null) {
try {
JSONObject obs = new JSONObject(mObsJson);
obsAnnotations = obs.getJSONArray("annotations");
} catch (JSONException e) {
Logger.tag(TAG).error(e);
}
}
try {
mAnnotationsList.setAdapter(new AnnotationsAdapter(this, this, mObservation.toJSONObject(), mTaxonJson != null ? new JSONObject(mTaxonJson) : null, mAttributes.getJSONArray(), obsAnnotations));
} catch (JSONException e) {
Logger.tag(TAG).error(e);
}
ActivityHelper.resizeList(mAnnotationsList);
if (mAnnotationsList.getAdapter().getCount() == 0) {
// No visible annotation - hide the entire section
mAnnotationSection.setVisibility(View.GONE);
}
}
private void resizeFavList() {
final Handler handler = new Handler();
if ((mFavoritesTabContainer.getVisibility() == View.VISIBLE) && (mFavoritesList.getVisibility() == View.VISIBLE) && (mFavoritesList.getWidth() == 0)) {
// UI not initialized yet - try later
handler.postDelayed(new Runnable() {
@Override
public void run() {
resizeFavList();
}
}, 100);
return;
}
handler.postDelayed(new Runnable() {
@Override
public void run() {
setListViewHeightBasedOnItems(mFavoritesList);
}
}, 100);
}
private void resizeActivityList() {
final Handler handler = new Handler();
if ((mCommentsIdsList.getVisibility() == View.VISIBLE) && (mActivityTabContainer.getVisibility() == View.VISIBLE) && (mCommentsIdsList.getWidth() == 0)) {
// UI not initialized yet - try later
handler.postDelayed(new Runnable() {
@Override
public void run() {
resizeActivityList();
}
}, 100);
return;
}
mCommentsIdsList.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView absListView, int i) {
}
@Override
public void onScroll(AbsListView absListView, int i, int i1, int i2) {
int height = setListViewHeightBasedOnItems(mCommentsIdsList);
View background = findViewById(R.id.comment_id_list_background);
ViewGroup.LayoutParams params = background.getLayoutParams();
if (params.height != height) {
params.height = height;
background.requestLayout();
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Logger.tag(TAG).debug("onActivityResult - " + requestCode + ":" + resultCode);
if (requestCode == SHARE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// TODO - RESULT_OK is never returned + need to add "destination" param (what type of share was performed)
AnalyticsClient.getInstance().logEvent(AnalyticsClient.EVENT_NAME_OBS_SHARE_FINISHED);
} else {
AnalyticsClient.getInstance().logEvent(AnalyticsClient.EVENT_NAME_OBS_SHARE_CANCELLED);
}
} else if (requestCode == REQUEST_CODE_EDIT_OBSERVATION) {
Logger.tag(TAG).debug("onActivityResult - EDIT_OBS: " + requestCode + ":" + resultCode);
if ((resultCode == ObservationEditor.RESULT_DELETED) || (resultCode == ObservationEditor.RESULT_RETURN_TO_OBSERVATION_LIST)) {
// User deleted the observation (or did a batch-edit)
Logger.tag(TAG).debug("onActivityResult - EDIT_OBS: Finish");
setResult(RESULT_OBSERVATION_CHANGED);
finish();
return;
} else if (resultCode == ObservationEditor.RESULT_REFRESH_OBS) {
// User made changes to observation - refresh the view
reloadObservation(null, true);
reloadPhotos();
loadObservationIntoUI();
getCommentIdList();
setupMap();
refreshActivity();
refreshFavorites();
resizeActivityList();
resizeFavList();
refreshProjectList();
refreshDataQuality();
refreshAttributes();
setResult(RESULT_OBSERVATION_CHANGED);
}
} if (requestCode == NEW_ID_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// Add the ID
final Integer taxonId = data.getIntExtra(IdentificationActivity.TAXON_ID, 0);
String taxonName = data.getStringExtra(IdentificationActivity.TAXON_NAME);
String speciesGuess = data.getStringExtra(IdentificationActivity.SPECIES_GUESS);
final String idRemarks = data.getStringExtra(IdentificationActivity.ID_REMARKS);
final boolean fromSuggestion = data.getBooleanExtra(IdentificationActivity.FROM_SUGGESTION, false);
checkForTaxonDisagreement(taxonId, taxonName, speciesGuess, new onDisagreement() {
@Override
public void onDisagreement(boolean disagreement) {
Intent serviceIntent = new Intent(INaturalistService.ACTION_ADD_IDENTIFICATION, null, ObservationViewerActivity.this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.OBSERVATION_ID, mObservation.id);
serviceIntent.putExtra(INaturalistService.TAXON_ID, taxonId);
serviceIntent.putExtra(INaturalistService.IDENTIFICATION_BODY, idRemarks);
serviceIntent.putExtra(INaturalistService.DISAGREEMENT, disagreement);
serviceIntent.putExtra(INaturalistService.FROM_VISION, fromSuggestion);
ContextCompat.startForegroundService(ObservationViewerActivity.this, serviceIntent);
try {
JSONObject eventParams = new JSONObject();
eventParams.put(AnalyticsClient.EVENT_PARAM_VIA, AnalyticsClient.EVENT_VALUE_VIEW_OBS_ADD);
eventParams.put(AnalyticsClient.EVENT_PARAM_FROM_VISION_SUGGESTION, fromSuggestion);
AnalyticsClient.getInstance().logEvent(AnalyticsClient.EVENT_NAME_OBS_ADD_ID, eventParams);
} catch (JSONException e) {
Logger.tag(TAG).error(e);
}
// Show a loading progress until the new comments/IDs are loaded
mCommentsIds = null;
refreshActivity();
// Refresh the comment/id list
mReloadTaxon = true;
IntentFilter filter = new IntentFilter(INaturalistService.ACTION_OBSERVATION_RESULT);
BaseFragmentActivity.safeRegisterReceiver(mObservationReceiver, filter, ObservationViewerActivity.this);
}
});
}
} else if ((requestCode == REQUEST_CODE_LOGIN) && (resultCode == Activity.RESULT_OK)) {
// Show a loading progress until the new comments/IDs are loaded
mCommentsIds = null;
mFavorites = null;
refreshActivity();
refreshFavorites();
// Refresh the comment/id list
IntentFilter filter = new IntentFilter(INaturalistService.ACTION_OBSERVATION_RESULT);
BaseFragmentActivity.safeRegisterReceiver(mObservationReceiver, filter, this);
Intent serviceIntent2 = new Intent(INaturalistService.ACTION_GET_OBSERVATION, null, this, INaturalistService.class);
serviceIntent2.putExtra(INaturalistService.OBSERVATION_ID, mObservation.id);
serviceIntent2.putExtra(INaturalistService.GET_PROJECTS, false);
ContextCompat.startForegroundService(this, serviceIntent2);
} else if (requestCode == OBSERVATION_PHOTOS_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
Integer setFirstPhotoIndex = data.getIntExtra(ObservationPhotosViewer.SET_DEFAULT_PHOTO_INDEX, -1);
Integer deletePhotoIndex = data.getIntExtra(ObservationPhotosViewer.DELETE_PHOTO_INDEX, -1);
Integer duplicatePhotoIndex = data.getIntExtra(ObservationPhotosViewer.DUPLICATE_PHOTO_INDEX, -1);
if (data.hasExtra(ObservationPhotosViewer.REPLACED_PHOTOS)) {
// Photos the user has edited
String rawReplacedPhotos = data.getStringExtra(ObservationPhotosViewer.REPLACED_PHOTOS);
rawReplacedPhotos = rawReplacedPhotos.substring(1, rawReplacedPhotos.length() - 1);
String parts[] = rawReplacedPhotos.split(",");
List<Pair<Uri, Long>> replacedPhotos = new ArrayList<>();
for (String value : parts) {
value = value.trim();
String[] innerParts = value.substring(5, value.length() - 1).split(" ", 2);
replacedPhotos.add(new Pair<Uri, Long>(Uri.parse(innerParts[0]), Long.valueOf(innerParts[1])));
}
for (Pair<Uri, Long> replacedPhoto : replacedPhotos) {
int index = replacedPhoto.second.intValue();
Uri photoUri = replacedPhoto.first;
// Delete old photo
Logger.tag(TAG).debug(String.format(Locale.ENGLISH, "Replacing/deleting previous photo at index: %d: %s", index, photoUri));
deletePhoto(index, false);
// Add new photo instead
Uri createdUri = createObservationPhotoForPhoto(photoUri, index, false);
}
reloadPhotos();
}
if (setFirstPhotoIndex > -1) {
// Set photo as first
if (setFirstPhotoIndex < mPhotosAdapter.getPhotoCount()) {
mPhotosAdapter.setAsFirstPhoto(setFirstPhotoIndex);
}
AnalyticsClient.getInstance().logEvent(AnalyticsClient.EVENT_NAME_OBS_NEW_DEFAULT_PHOTO);
} else if (deletePhotoIndex > -1) {
// Delete photo
deletePhoto(deletePhotoIndex, true);
AnalyticsClient.getInstance().logEvent(AnalyticsClient.EVENT_NAME_OBS_DELETE_PHOTO);
} else if (duplicatePhotoIndex > -1) {
// Duplicate photo
duplicatePhoto(duplicatePhotoIndex);
}
}
}
}
private interface onDisagreement {
void onDisagreement(boolean disagreement);
}
private void checkForTaxonDisagreement(int taxonId, String name, String scientificName, final onDisagreement cb) {
if ((mTaxonJson == null) || (mObsJson == null)) {
// We don't have the JSON structures for the observation and the taxon - cannot check for possible disagreement
cb.onDisagreement(false);
return;
}
BetterJSONObject taxon = new BetterJSONObject(mTaxonJson);
int communityTaxonId = taxon.getInt("id");
JSONArray ancestors = taxon.getJSONArray("ancestor_ids").getJSONArray();
// See if the current ID taxon is an ancestor of the current observation taxon / community taxon
boolean disagreement = false;
for (int i = 0; i < ancestors.length(); i++) {
int currentTaxonId = ancestors.optInt(i);
if (currentTaxonId == taxonId) {
disagreement = true;
break;
}
}
if ((!disagreement) || (communityTaxonId == taxonId)) {
// No disagreement here
cb.onDisagreement(false);
return;
}
// Show disagreement dialog
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ViewGroup dialogContent = (ViewGroup) inflater.inflate(R.layout.explicit_disagreement, null, false);
TextView questionText = (TextView) dialogContent.findViewById(R.id.question);
final RadioButton disagreementRadioButton = (RadioButton) dialogContent.findViewById(R.id.disagreement);
final RadioButton noDisagreemenRadioButton = (RadioButton) dialogContent.findViewById(R.id.no_disagreement);
String taxonName = String.format("%s (%s)", name, scientificName);
String communityTaxonName = String.format("%s (%s)", TaxonUtils.getTaxonName(this, taxon.getJSONObject()), TaxonUtils.getTaxonScientificName(mApp, taxon.getJSONObject()));
questionText.setText(Html.fromHtml(String.format(getString(R.string.do_you_think_this_could_be), communityTaxonName)));
noDisagreemenRadioButton.setText(Html.fromHtml(String.format(getString(R.string.i_dont_know_but), taxonName)));
disagreementRadioButton.setText(Html.fromHtml(String.format(getString(R.string.no_but_it_is_a_member_of_taxon), taxonName)));
mHelper.confirm(getString(R.string.potential_disagreement), dialogContent, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
boolean isDisagreement = disagreementRadioButton.isChecked();
cb.onDisagreement(isDisagreement);
}
}, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Canceled dialog - nothing to do here
}
}, R.string.submit, R.string.cancel);
}
private void refreshProjectList() {
if ((mProjects != null) && (mProjects.size() > 0)) {
mIncludedInProjectsContainer.setVisibility(View.VISIBLE);
int count = mProjects.size();
mIncludedInProjects.setText(getResources().getQuantityString(R.plurals.included_in_projects, count, count));
} else {
mIncludedInProjectsContainer.setVisibility(View.GONE);
}
}
/**
* Sets ListView height dynamically based on the height of the items.
*
* @param listView to be resized
*/
public int setListViewHeightBasedOnItems(final ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter != null) {
int numberOfItems = listAdapter.getCount();
// Get total height of all items.
int totalItemsHeight = 0;
for (int itemPos = 0; itemPos < numberOfItems; itemPos++) {
View item = listAdapter.getView(itemPos, null, listView);
item.measure(MeasureSpec.makeMeasureSpec(listView.getWidth(), MeasureSpec.AT_MOST), MeasureSpec.UNSPECIFIED);
totalItemsHeight += item.getMeasuredHeight();
}
// Get total height of all item dividers.
int totalDividersHeight = listView.getDividerHeight() *
(numberOfItems - 1);
// Set list height.
ViewGroup.LayoutParams params = listView.getLayoutParams();
int paddingHeight = (int) getResources().getDimension(R.dimen.actionbar_height);
int newHeight = totalItemsHeight + totalDividersHeight;
if (params.height != newHeight) {
params.height = totalItemsHeight + totalDividersHeight;
listView.setLayoutParams(params);
listView.requestLayout();
}
return params.height;
} else {
return 0;
}
}
@Override
protected void onPause() {
super.onPause();
BaseFragmentActivity.safeUnregisterReceiver(mObservationReceiver, this);
BaseFragmentActivity.safeUnregisterReceiver(mAttributesReceiver, this);
BaseFragmentActivity.safeUnregisterReceiver(mChangeAttributesReceiver, this);
BaseFragmentActivity.safeUnregisterReceiver(mDownloadObservationReceiver, this);
BaseFragmentActivity.safeUnregisterReceiver(mObservationSubscriptionsReceiver, this);
BaseFragmentActivity.safeUnregisterReceiver(mObservationFollowReceiver, this);
if (mPhotosAdapter != null) {
mPhotosAdapter.pause();
}
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
private void deletePhoto(int position, boolean refreshPositions) {
PhotosViewPagerAdapter adapter = mPhotosAdapter;
if (position >= adapter.getPhotoCount()) {
return;
}
Cursor cursor = adapter.getCursor();
cursor.moveToPosition(position);
ObservationPhoto op = new ObservationPhoto(cursor);
// Mark photo as deleted
Logger.tag(TAG).debug(String.format("Marking photo for deletion: %s", op.toString()));
ContentValues cv = new ContentValues();
cv.put(ObservationPhoto.IS_DELETED, 1);
int updateCount = getContentResolver().update(op.getUri(), cv, null, null);
reloadPhotos();
if (refreshPositions) {
// Refresh the positions of all other photos
adapter = mPhotosAdapter;
adapter.refreshPhotoPositions(null, false);
}
}
private void duplicatePhoto(int position) {
PhotosViewPagerAdapter adapter = mPhotosAdapter;
if (position >= adapter.getPhotoCount()) {
return;
}
Cursor cursor = adapter.getCursor();
cursor.moveToPosition(position);
ObservationPhoto op = new ObservationPhoto(cursor);
// Add a duplicate of this photo (in a position ahead of this one)
// Copy file
String photoUrl = op.photo_url;
String photoFileName = op.photo_filename;
final File destFile = new File(getFilesDir(), UUID.randomUUID().toString() + ".jpeg");
Logger.tag(TAG).info("Duplicate: " + op + ":" + photoFileName + ":" + photoUrl);
if (photoFileName != null) {
// Local file - copy it
try {
FileUtils.copyFile(new File(photoFileName), destFile);
addDuplicatedPhoto(op, destFile);
} catch (IOException e) {
Logger.tag(TAG).error(e);
Toast.makeText(getApplicationContext(), getString(R.string.couldnt_duplicate_photo), Toast.LENGTH_SHORT).show();
return;
}
} else {
// Online only - need to download it and then copy
Glide.with(this)
.asBitmap()
.load(photoUrl)
.apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.AUTOMATIC))
.into(new CustomTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
// Save downloaded bitmap into local file
try {
OutputStream outStream = new FileOutputStream(destFile);
resource.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.close();
addDuplicatedPhoto(op, destFile);
} catch (Exception e) {
Logger.tag(TAG).error(e);
Toast.makeText(getApplicationContext(), getString(R.string.couldnt_duplicate_photo), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onLoadCleared(@Nullable Drawable placeholder) {
}
@Override
public void onLoadFailed(@Nullable Drawable errorDrawable) {
Logger.tag(TAG).error("onLoadedFailed");
Toast.makeText(getApplicationContext(), getString(R.string.couldnt_duplicate_photo), Toast.LENGTH_SHORT).show();
}
});
}
}
private void addDuplicatedPhoto(ObservationPhoto originalPhoto, File duplicatedPhotoFile) {
// Create new photo observation with the duplicated photo file
Uri createdUri = createObservationPhotoForPhoto(Uri.fromFile(duplicatedPhotoFile), originalPhoto.position, true);
if (createdUri == null) {
Logger.tag(TAG).error("addDuplicatedPhoto - couldn't create duplicate OP");
Toast.makeText(getApplicationContext(), getString(R.string.couldnt_duplicate_photo), Toast.LENGTH_SHORT).show();
return;
}
reloadPhotos();
// Refresh the positions of all other photos
mPhotosAdapter.refreshPhotoPositions(originalPhoto.position, false);
}
private Uri createObservationPhotoForPhoto(Uri photoUri, int position, boolean isDuplicated) {
String path = FileUtils.getPath(this, photoUri);
String extension = FileUtils.getExtension(this, photoUri);
if ((extension == null) && (path != null)) {
int i = path.lastIndexOf('.');
if (i >= 0) {
extension = path.substring(i + 1).toLowerCase();
}
}
if ((extension == null) || (
(!extension.toLowerCase().equals("jpg")) &&
(!extension.toLowerCase().equals("jpeg")) &&
(!extension.toLowerCase().equals("png"))
)) {
return null;
}
// Resize photo to 2048x2048 max
String resizedPhoto = ImageUtils.resizeImage(this, path, photoUri, 2048);
if (resizedPhoto == null) {
return null;
}
ObservationPhoto op = new ObservationPhoto();
op.uuid = UUID.randomUUID().toString();
ContentValues cv = op.getContentValues();
cv.put(ObservationPhoto._OBSERVATION_ID, mObservation._id);
cv.put(ObservationPhoto.OBSERVATION_ID, mObservation.id);
cv.put(ObservationPhoto.PHOTO_FILENAME, resizedPhoto);
cv.put(ObservationPhoto.ORIGINAL_PHOTO_FILENAME, (String)null);
cv.put(ObservationPhoto.POSITION, position);
cv.put(ObservationPhoto.OBSERVATION_UUID, mObservation.uuid);
return getContentResolver().insert(ObservationPhoto.CONTENT_URI, cv);
}
// Returns a minimal version of an observation JSON (used to lower memory usage)
private JSONObject getMinimalObservation(JSONObject observation) {
JSONObject minimaldObs = new JSONObject();
try {
minimaldObs.put("id", observation.optInt("id"));
if (observation.has("votes") && !observation.isNull("votes")) minimaldObs.put("votes", observation.optJSONArray("votes"));
if (observation.has("observed_on") && !observation.isNull("observed_on")) minimaldObs.put("observed_on", observation.optString("observed_on"));
if (observation.has("location") && !observation.isNull("location")) minimaldObs.put("location", observation.optString("location"));
if (observation.has("photos") && !observation.isNull("photos")) {
minimaldObs.put("photo_count", observation.optJSONArray("photos").length());
} else {
minimaldObs.put("photo_count", 0);
}
if (observation.has("identifications") && !observation.isNull("identifications")) {
minimaldObs.put("identification_count", observation.optJSONArray("identifications").length());
} else {
minimaldObs.put("identification_count", 0);
}
if (observation.has("community_taxon") && !observation.isNull("community_taxon")) minimaldObs.put("community_taxon", observation.optJSONObject("community_taxon"));
} catch (JSONException e) {
Logger.tag(TAG).error(e);
return null;
}
return minimaldObs;
}
}
|
iNaturalist/src/main/java/org/inaturalist/android/ObservationViewerActivity.java
|
package org.inaturalist.android;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import android.text.Html;
import android.text.InputType;
import android.text.format.DateFormat;
import android.util.Log;
import android.util.Pair;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.ScrollView;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;
import android.widget.Toast;
import com.ablanco.zoomy.TapListener;
import com.ablanco.zoomy.ZoomListener;
import com.ablanco.zoomy.Zoomy;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.RequestManager;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.gif.GifDrawable;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.cocosw.bottomsheet.BottomSheet;
import com.evernote.android.state.State;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.koushikdutta.urlimageviewhelper.UrlImageViewCallback;
import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper;
import com.livefront.bridge.Bridge;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import com.viewpagerindicator.CirclePageIndicator;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.tinylog.Logger;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ObservationViewerActivity extends AppCompatActivity implements AnnotationsAdapter.OnAnnotationActions {
private static final int NEW_ID_REQUEST_CODE = 0x101;
private static final int REQUEST_CODE_LOGIN = 0x102;
private static final int REQUEST_CODE_EDIT_OBSERVATION = 0x103;
private static final int SHARE_REQUEST_CODE = 0x104;
private static final int OBSERVATION_PHOTOS_REQUEST_CODE = 0x105;
public static final int RESULT_FLAGGED_AS_CAPTIVE = 0x300;
public static final int RESULT_OBSERVATION_CHANGED = 0x301;
private static String TAG = "ObservationViewerActivity";
public final static String SHOW_COMMENTS = "show_comments";
public final static String SCROLL_TO_COMMENTS_BOTTOM = "scroll_to_comments_bottom";
private static int DATA_QUALITY_CASUAL_GRADE = 0;
private static int DATA_QUALITY_NEEDS_ID = 1;
private static int DATA_QUALITY_RESEARCH_GRADE = 2;
private static String QUALITY_GRADE_RESEARCH = "research";
private static String QUALITY_GRADE_NEEDS_ID = "needs_id";
private static String QUALITY_GRADE_CASUAL_GRADE = "casual";
private INaturalistApp mApp;
private ActivityHelper mHelper;
@State(AndroidStateBundlers.SerializableBundler.class) public Observation mObservation;
@State public boolean mFlagAsCaptive;
private Uri mUri;
private Cursor mCursor;
private TextView mUserName;
private ImageView mUserPic;
private TextView mObservedOn;
private ViewPager mPhotosViewPager;
private CirclePageIndicator mIndicator;
private ImageView mSharePhoto;
private ImageView mIdPic;
private TextView mIdName;
private TextView mTaxonicName;
private ViewGroup mIdRow;
@State(AndroidStateBundlers.JSONObjectBundler.class) public JSONObject mTaxon;
private TabHost mTabHost;
private final static String VIEW_TYPE_INFO = "info";
private final static String VIEW_TYPE_COMMENTS_IDS = "comments_ids";
private final static String VIEW_TYPE_FAVS = "favs";
private GoogleMap mMap;
private ViewGroup mLocationMapContainer;
private ImageView mUnknownLocationIcon;
private TextView mLocationText;
private ImageView mLocationPrivate;
private TextView mCasualGradeText;
private ImageView mCasualGradeIcon;
private View mNeedsIdLine;
private View mResearchGradeLine;
private TextView mNeedsIdText;
private ImageView mNeedsIdIcon;
private TextView mResearchGradeText;
private ImageView mResearchGradeIcon;
private TextView mTipText;
private ViewGroup mDataQualityReason;
private ViewGroup mDataQualityGraph;
private TextView mIncludedInProjects;
private ViewGroup mIncludedInProjectsContainer;
private ProgressBar mLoadingPhotos;
private ProgressBar mLoadingMap;
private ObservationReceiver mObservationReceiver;
@State(AndroidStateBundlers.BetterJSONListBundler.class) public ArrayList<BetterJSONObject> mFavorites = null;
@State(AndroidStateBundlers.BetterJSONListBundler.class) public ArrayList<BetterJSONObject> mCommentsIds = null;
@State public int mIdCount = 0;
private ArrayList<Integer> mProjectIds;
private ViewGroup mActivityTabContainer;
private ViewGroup mInfoTabContainer;
private ListView mCommentsIdsList;
private ProgressBar mLoadingActivity;
private CommentsIdsAdapter mAdapter;
private ViewGroup mAddId;
private ViewGroup mActivityButtons;
private ViewGroup mAddComment;
private ViewGroup mFavoritesTabContainer;
private ProgressBar mLoadingFavs;
private ListView mFavoritesList;
private ViewGroup mAddFavorite;
private FavoritesAdapter mFavoritesAdapter;
private ViewGroup mRemoveFavorite;
private int mFavIndex;
private TextView mNoFavsMessage;
private TextView mNoActivityMessage;
private ViewGroup mNotesContainer;
private TextView mNotes;
private TextView mLoginToAddCommentId;
private Button mActivitySignUp;
private Button mActivityLogin;
private ViewGroup mActivityLoginSignUpButtons;
private TextView mLoginToAddFave;
private Button mFavesSignUp;
private Button mFavesLogin;
private ViewGroup mFavesLoginSignUpButtons;
private TextView mSyncToAddCommentsIds;
private TextView mSyncToAddFave;
private ImageView mIdPicBig;
private ViewGroup mNoPhotosContainer;
private ViewGroup mLocationLabelContainer;
private PhotosViewPagerAdapter mPhotosAdapter = null;
@State(AndroidStateBundlers.BetterJSONListBundler.class) public ArrayList<BetterJSONObject> mProjects;
private ImageView mIdArrow;
private ViewGroup mUnknownLocationContainer;
@State public boolean mReadOnly;
private boolean mLoadingObservation;
@State public String mObsJson;
@State public String mTaxonJson;
private boolean mShowComments;
@State public int mCommentCount;
@State public String mTaxonImage;
@State public String mTaxonIdName;
@State public String mTaxonScientificName;
@State public int mTaxonRankLevel;
@State public String mTaxonRank;
@State public String mActiveTab;
private boolean mReloadObs;
private boolean mLoadObsJson = false;
private ViewGroup mPhotosContainer;
@State public boolean mReloadTaxon;
private boolean mScrollToCommentsBottom;
private ScrollView mScrollView;
private ViewGroup mTaxonInactive;
private View mAddCommentBackground;
private ViewGroup mAddCommentContainer;
private EditText mAddCommentText;
private View mAddCommentDone;
private MentionsAutoComplete mCommentMentions;
private AttributesReceiver mAttributesReceiver;
private ChangeAttributesReceiver mChangeAttributesReceiver;
@State public SerializableJSONArray mAttributes;
private ViewGroup mAnnotationSection;
private ListView mAnnotationsList;
private ProgressBar mLoadingAnnotations;
private ViewGroup mAnnotationsContent;
private DownloadObservationReceiver mDownloadObservationReceiver;
private ObservationSubscriptionsReceiver mObservationSubscriptionsReceiver;
private ObservationFollowReceiver mObservationFollowReceiver;
private Menu mMenu;
@State(AndroidStateBundlers.JSONArrayBundler.class) public JSONArray mObservationSubscriptions = null;
@State public boolean mFollowingObservation = false;
private TextView mMetadataObservationID;
private ViewGroup mMetadataObservationIDRow;
private TextView mMetadataObservationUUID;
private TextView mMetadataObservationURL;
private ViewGroup mMetadataObservationURLRow;
@Override
protected void onStart() {
super.onStart();
}
@Override
protected void onStop() {
super.onStop();
}
@Override
public void onAnnotationCollapsedExpanded() {
// Annotation has been expanded / collapsed - resize the list to show it
(new Handler()).postDelayed(new Runnable() {
@Override
public void run() {
ActivityHelper.setListViewHeightBasedOnItems(mAnnotationsList);
mAnnotationsList.requestLayout();
}
}, 50);
}
@Override
public void onDeleteAnnotationValue(String uuid) {
Intent serviceIntent = new Intent(INaturalistService.ACTION_DELETE_ANNOTATION, null, ObservationViewerActivity.this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.UUID, uuid);
ContextCompat.startForegroundService(this, serviceIntent);
}
@Override
public void onAnnotationAgree(String uuid) {
Intent serviceIntent = new Intent(INaturalistService.ACTION_AGREE_ANNOTATION, null, ObservationViewerActivity.this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.UUID, uuid);
ContextCompat.startForegroundService(this, serviceIntent);
}
@Override
public void onAnnotationDisagree(String uuid) {
Intent serviceIntent = new Intent(INaturalistService.ACTION_DISAGREE_ANNOTATION, null, ObservationViewerActivity.this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.UUID, uuid);
ContextCompat.startForegroundService(this, serviceIntent);
}
@Override
public void onAnnotationVoteDelete(String uuid) {
Intent serviceIntent = new Intent(INaturalistService.ACTION_DELETE_ANNOTATION_VOTE, null, ObservationViewerActivity.this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.UUID, uuid);
ContextCompat.startForegroundService(this, serviceIntent);
}
@Override
public void onSetAnnotationValue(int annotationId, int valueId) {
Intent serviceIntent = new Intent(INaturalistService.ACTION_SET_ANNOTATION_VALUE, null, ObservationViewerActivity.this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.ATTRIBUTE_ID, annotationId);
serviceIntent.putExtra(INaturalistService.VALUE_ID, valueId);
serviceIntent.putExtra(INaturalistService.OBSERVATION_ID, mObservation.id);
ContextCompat.startForegroundService(this, serviceIntent);
}
private class PhotosViewPagerAdapter extends PagerAdapter implements SoundPlayer.OnPlayerStatusChange {
private Cursor mImageCursor = null;
private Cursor mSoundCursor = null;
private List<SoundPlayer> mPlayers = new ArrayList<>();
private HashMap<Integer, Bitmap> mBitmaps = new HashMap<>();
public void refreshPhotoPositions(Integer position, boolean doNotUpdate) {
int currentPosition = position == null ? 0 : 1;
int count = mImageCursor.getCount();
if (count == 0) return;
mImageCursor.moveToPosition(0);
do {
if ((position == null) || (mImageCursor.getPosition() != position.intValue())) {
ObservationPhoto currentOp = new ObservationPhoto(mImageCursor);
currentOp.position = currentPosition;
ContentValues cv = currentOp.getContentValues();
if (doNotUpdate && currentOp._synced_at != null) {
cv.put(ObservationPhoto._SYNCED_AT, currentOp._synced_at.getTime());
}
if (currentOp.photo_filename != null) {
getContentResolver().update(ObservationPhoto.CONTENT_URI, cv, "photo_filename = '" + currentOp.photo_filename + "'", null);
} else {
getContentResolver().update(ObservationPhoto.CONTENT_URI, cv, "photo_url = '" + currentOp.photo_url + "'", null);
}
currentPosition++;
}
} while (mImageCursor.moveToNext());
}
public PhotosViewPagerAdapter() {
if (!mReadOnly && mObservation != null && mObservation.uuid != null) {
mImageCursor = getContentResolver().query(ObservationPhoto.CONTENT_URI,
ObservationPhoto.PROJECTION,
"(observation_uuid=?) and ((is_deleted = 0) OR (is_deleted IS NULL))",
new String[]{mObservation.uuid},
ObservationPhoto.DEFAULT_SORT_ORDER);
mSoundCursor = getContentResolver().query(ObservationSound.CONTENT_URI,
ObservationSound.PROJECTION,
"(observation_uuid=?) and ((is_deleted = 0) OR (is_deleted IS NULL))",
new String[]{mObservation.uuid},
ObservationSound.DEFAULT_SORT_ORDER);
mImageCursor.moveToFirst();
}
}
public Cursor getCursor() {
return mImageCursor;
}
@Override
public int getCount() {
return mReadOnly ?
(mObservation.photos.size() + mObservation.sounds.size()) :
(mImageCursor != null ? mImageCursor.getCount() : 0) +
(mSoundCursor != null ? mSoundCursor.getCount() : 0);
}
public int getPhotoCount() {
return mReadOnly ? mObservation.photos.size() : mImageCursor.getCount();
}
public void setAsFirstPhoto(int position) {
// Set current photo to be positioned first
mImageCursor.moveToPosition(position);
ObservationPhoto op = new ObservationPhoto(mImageCursor);
op.position = 0;
if (op.photo_filename != null) {
getContentResolver().update(ObservationPhoto.CONTENT_URI, op.getContentValues(), "photo_filename = '" + op.photo_filename + "'", null);
} else {
getContentResolver().update(ObservationPhoto.CONTENT_URI, op.getContentValues(), "photo_url = '" + op.photo_url + "'", null);
}
// Update the rest of the photos to be positioned afterwards
refreshPhotoPositions(position, false);
reloadPhotos();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public Object instantiateItem(ViewGroup container, final int position) {
ImageView imageView = new ImageView(ObservationViewerActivity.this);
imageView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
int imageId = 0;
String photoFilename = null;
String imageUrl = null;
ObservationSound sound = null;
if (!mReadOnly) {
if (position >= mImageCursor.getCount()) {
// Sound
mSoundCursor.moveToPosition(position - mImageCursor.getCount());
sound = new ObservationSound(mSoundCursor);
Logger.tag(TAG).info("Observation: " + mObservation);
Logger.tag(TAG).info("Sound: " + sound);
} else {
// Photo
mImageCursor.moveToPosition(position);
imageUrl = mImageCursor.getString(mImageCursor.getColumnIndexOrThrow(ObservationPhoto.PHOTO_URL));
photoFilename = mImageCursor.getString(mImageCursor.getColumnIndexOrThrow(ObservationPhoto.PHOTO_FILENAME));
}
} else {
if (position >= mObservation.photos.size()) {
// Show sound
sound = mObservation.sounds.get(position - mObservation.photos.size());
} else {
imageUrl = mObservation.photos.get(position).photo_url;
}
}
if (sound != null) {
// Sound - show a sound player interface
SoundPlayer player = new SoundPlayer(ObservationViewerActivity.this, container, sound, this);
View view = player.getView();
((ViewPager)container).addView(view, 0);
view.setTag(player);
mPlayers.add(player);
return view;
}
if (imageUrl != null) {
// Online photo
imageView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
String extension = imageUrl.substring(imageUrl.lastIndexOf('.'));
String thumbnailUrl, largeSizeUrl;
// Deduce the original-sized URL
if (imageUrl.substring(0, imageUrl.lastIndexOf('/')).endsWith("assets")) {
// It's an assets default URL - e.g. https://www.inaturalist.org/assets/copyright-infringement-square.png
largeSizeUrl = imageUrl.substring(0, imageUrl.lastIndexOf('-') + 1) + "original" + extension;
thumbnailUrl = imageUrl.substring(0, imageUrl.lastIndexOf('-') + 1) + "small" + extension;
} else {
// "Regular" observation photo
largeSizeUrl = imageUrl.substring(0, imageUrl.lastIndexOf('/') + 1) + "original" + extension;
thumbnailUrl = imageUrl.substring(0, imageUrl.lastIndexOf('/') + 1) + "small" + extension;
}
RequestBuilder thumbnailRequest = Glide.with(ObservationViewerActivity.this)
.load(thumbnailUrl);
Glide.with(ObservationViewerActivity.this)
.load(largeSizeUrl)
.thumbnail(thumbnailRequest)
.apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.AUTOMATIC))
.into(new CustomTarget<Drawable>() {
@Override
public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
// Save downloaded bitmap into local file
imageView.setImageDrawable(resource);
if (resource instanceof BitmapDrawable) {
mBitmaps.put(position, ((BitmapDrawable)resource).getBitmap());
} else if (resource instanceof GifDrawable) {
mBitmaps.put(position, ((GifDrawable) resource).getFirstFrame());
}
}
@Override
public void onLoadCleared(@Nullable Drawable placeholder) {
}
@Override
public void onLoadFailed(@Nullable Drawable errorDrawable) {
// Failed to load observation photo
try {
JSONObject eventParams = new JSONObject();
eventParams.put(AnalyticsClient.EVENT_PARAM_SIZE, AnalyticsClient.EVENT_PARAM_VALUE_MEDIUM);
AnalyticsClient.getInstance().logEvent(AnalyticsClient.EVENT_NAME_OBS_PHOTO_FAILED_TO_LOAD, eventParams);
} catch (JSONException e) {
Logger.tag(TAG).error(e);
}
}
});
} else {
// Offline photo
int newHeight = mPhotosViewPager.getMeasuredHeight();
int newWidth = mPhotosViewPager.getMeasuredWidth();
Bitmap bitmapImage = null;
try {
BitmapFactory.Options options = new BitmapFactory.Options();
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
// This decreases in-memory byte-storage per pixel
options.inPreferredConfig = Bitmap.Config.ALPHA_8;
bitmapImage = BitmapFactory.decodeFile(photoFilename, options);
bitmapImage = ImageUtils.rotateAccordingToOrientation(bitmapImage, photoFilename);
imageView.setImageBitmap(bitmapImage);
mBitmaps.put(position, bitmapImage);
} catch (Exception e) {
Logger.tag(TAG).error(e);
}
}
((ViewPager)container).addView(imageView, 0);
new Zoomy.Builder(ObservationViewerActivity.this)
.target(imageView)
.zoomListener(new ZoomListener() {
@Override
public void onViewBeforeStartedZooming(View view) {
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setImageBitmap(mBitmaps.get(position));
}
@Override
public void onViewStartedZooming(View view) {
}
@Override
public void onViewEndedZooming(View view) {
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
}
})
.tapListener(new TapListener() {
@Override
public void onTap(View v) {
Intent intent = new Intent(ObservationViewerActivity.this, ObservationPhotosViewer.class);
intent.putExtra(ObservationPhotosViewer.CURRENT_PHOTO_INDEX, position);
if (!mReadOnly) {
intent.putExtra(ObservationPhotosViewer.OBSERVATION_ID, mObservation.id);
intent.putExtra(ObservationPhotosViewer.OBSERVATION_ID_INTERNAL, mObservation._id);
intent.putExtra(ObservationPhotosViewer.OBSERVATION_UUID, mObservation.uuid);
intent.putExtra(ObservationPhotosViewer.IS_NEW_OBSERVATION, true);
intent.putExtra(ObservationPhotosViewer.READ_ONLY, false);
startActivityForResult(intent, OBSERVATION_PHOTOS_REQUEST_CODE);
} else {
try {
JSONObject obs = ObservationUtils.getMinimalObservation(new JSONObject(mObsJson));
intent.putExtra(ObservationPhotosViewer.OBSERVATION, obs.toString());
startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
})
.register();
return imageView;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((View) object);
}
public void destroy() {
for (SoundPlayer player : mPlayers) {
if (player != null) {
player.destroy();
}
}
}
public void pause() {
for (SoundPlayer player : mPlayers) {
if (player != null) {
player.pause();
}
}
}
@Override
public void onPlay(SoundPlayer player) {
// Pause all other players
for (SoundPlayer p : mPlayers) {
if ((p != null) && (!p.equals(player))) {
p.pause();
}
}
}
@Override
public void onPause(SoundPlayer player) {
}
}
@Override
protected void onResume() {
super.onResume();
loadObservationIntoUI();
refreshDataQuality();
refreshProjectList();
setupMap();
resizeActivityList();
resizeFavList();
refreshAttributes();
mAttributesReceiver = new AttributesReceiver();
IntentFilter filter = new IntentFilter(INaturalistService.GET_ATTRIBUTES_FOR_TAXON_RESULT);
BaseFragmentActivity.safeRegisterReceiver(mAttributesReceiver, filter, ObservationViewerActivity.this);
mChangeAttributesReceiver = new ChangeAttributesReceiver();
IntentFilter filter2 = new IntentFilter(INaturalistService.DELETE_ANNOTATION_RESULT);
filter2.addAction(INaturalistService.AGREE_ANNOTATION_RESULT);
filter2.addAction(INaturalistService.DISAGREE_ANNOTATION_RESULT);
filter2.addAction(INaturalistService.DELETE_ANNOTATION_VOTE_RESULT);
filter2.addAction(INaturalistService.SET_ANNOTATION_VALUE_RESULT);
BaseFragmentActivity.safeRegisterReceiver(mChangeAttributesReceiver, filter2, ObservationViewerActivity.this);
mDownloadObservationReceiver = new DownloadObservationReceiver();
IntentFilter filter3 = new IntentFilter(INaturalistService.ACTION_GET_AND_SAVE_OBSERVATION_RESULT);
BaseFragmentActivity.safeRegisterReceiver(mDownloadObservationReceiver, filter3, this);
mObservationSubscriptionsReceiver = new ObservationSubscriptionsReceiver();
IntentFilter filter4 = new IntentFilter(INaturalistService.ACTION_GET_OBSERVATION_SUBSCRIPTIONS_RESULT);
BaseFragmentActivity.safeRegisterReceiver(mObservationSubscriptionsReceiver, filter4, this);
mObservationFollowReceiver = new ObservationFollowReceiver();
IntentFilter filter5 = new IntentFilter(INaturalistService.ACTION_FOLLOW_OBSERVATION_RESULT);
BaseFragmentActivity.safeRegisterReceiver(mObservationFollowReceiver, filter5, this);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bridge.restoreInstanceState(this, savedInstanceState);
ActionBar actionBar = getSupportActionBar();
actionBar.setLogo(R.drawable.ic_arrow_back);
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle(R.string.observation);
mApp = (INaturalistApp) getApplicationContext();
mApp.applyLocaleSettings(getBaseContext());
setContentView(R.layout.observation_viewer);
mHelper = new ActivityHelper(this);
mMetadataObservationID = (TextView) findViewById(R.id.observation_id);
mMetadataObservationIDRow = (ViewGroup) findViewById(R.id.metadata_id_row);
mMetadataObservationUUID = (TextView) findViewById(R.id.observation_uuid);
mMetadataObservationURL = (TextView) findViewById(R.id.observation_url);
mMetadataObservationURLRow = (ViewGroup) findViewById(R.id.metadata_url_row);
reloadObservation(savedInstanceState, false);
mAnnotationSection = (ViewGroup) findViewById(R.id.annotations_section);
mAnnotationsList = (ListView) findViewById(R.id.annotations_list);
mLoadingAnnotations = (ProgressBar) findViewById(R.id.loading_annotations);
mAnnotationsContent = (ViewGroup) findViewById(R.id.annotations_content);
mAddCommentBackground = (View) findViewById(R.id.add_comment_background);
mAddCommentContainer = (ViewGroup) findViewById(R.id.add_comment_container);
mAddCommentDone = findViewById(R.id.add_comment_done);
mAddCommentText = (EditText) findViewById(R.id.add_comment_text);
mCommentMentions = new MentionsAutoComplete(ObservationViewerActivity.this, mAddCommentText);
mScrollView = (ScrollView) findViewById(R.id.scroll_view);
mUserName = (TextView) findViewById(R.id.user_name);
mObservedOn = (TextView) findViewById(R.id.observed_on);
mUserPic = (ImageView) findViewById(R.id.user_pic);
mPhotosViewPager = (ViewPager) findViewById(R.id.photos);
mIndicator = (CirclePageIndicator)findViewById(R.id.photos_indicator);
mSharePhoto = findViewById(R.id.share_photo);
mIdPic = (ImageView)findViewById(R.id.id_icon);
mIdName = (TextView) findViewById(R.id.id_name);
mTaxonicName = (TextView) findViewById(R.id.id_sub_name);
mIdRow = (ViewGroup) findViewById(R.id.id_row);
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.location_map)).getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
setupMap();
}
});
mLocationMapContainer = (ViewGroup) findViewById(R.id.location_map_container);
mUnknownLocationContainer = (ViewGroup) findViewById(R.id.unknown_location_container);
mUnknownLocationIcon = (ImageView) findViewById(R.id.unknown_location);
mLocationText = (TextView) findViewById(R.id.location_text);
mLocationPrivate = (ImageView) findViewById(R.id.location_private);
mCasualGradeText = (TextView) findViewById(R.id.casual_grade_text);
mCasualGradeIcon = (ImageView) findViewById(R.id.casual_grade_icon);
mNeedsIdLine = (View) findViewById(R.id.needs_id_line);
mResearchGradeLine = (View) findViewById(R.id.research_grade_line);
mNeedsIdText = (TextView) findViewById(R.id.needs_id_text);
mNeedsIdIcon = (ImageView) findViewById(R.id.needs_id_icon);
mResearchGradeText = (TextView) findViewById(R.id.research_grade_text);
mResearchGradeIcon = (ImageView) findViewById(R.id.research_grade_icon);
mTipText = (TextView) findViewById(R.id.tip_text);
mDataQualityReason = (ViewGroup) findViewById(R.id.data_quality_reason);
mDataQualityGraph = (ViewGroup) findViewById(R.id.data_quality_graph);
mIncludedInProjects = (TextView) findViewById(R.id.included_in_projects);
mIncludedInProjectsContainer = (ViewGroup) findViewById(R.id.included_in_projects_container);
mActivityTabContainer = (ViewGroup) findViewById(R.id.activity_tab_content);
mInfoTabContainer = (ViewGroup) findViewById(R.id.info_tab_content);
mLoadingActivity = (ProgressBar) findViewById(R.id.loading_activity);
mCommentsIdsList = (ListView) findViewById(R.id.comment_id_list);
mActivityButtons = (ViewGroup) findViewById(R.id.activity_buttons);
mAddComment = (ViewGroup) findViewById(R.id.add_comment);
mAddId = (ViewGroup) findViewById(R.id.add_id);
mFavoritesTabContainer = (ViewGroup) findViewById(R.id.favorites_tab_content);
mLoadingFavs = (ProgressBar) findViewById(R.id.loading_favorites);
mFavoritesList = (ListView) findViewById(R.id.favorites_list);
mAddFavorite = (ViewGroup) findViewById(R.id.add_favorite);
mRemoveFavorite = (ViewGroup) findViewById(R.id.remove_favorite);
mNoFavsMessage = (TextView) findViewById(R.id.no_favs);
mNoActivityMessage = (TextView) findViewById(R.id.no_activity);
mNotesContainer = (ViewGroup) findViewById(R.id.notes_container);
mNotes = (TextView) findViewById(R.id.notes);
mLoginToAddCommentId = (TextView) findViewById(R.id.login_to_add_comment_id);
mActivitySignUp = (Button) findViewById(R.id.activity_sign_up);
mActivityLogin = (Button) findViewById(R.id.activity_login);
mActivityLoginSignUpButtons = (ViewGroup) findViewById(R.id.activity_login_signup);
mLoginToAddFave = (TextView) findViewById(R.id.login_to_add_fave);
mFavesSignUp = (Button) findViewById(R.id.faves_sign_up);
mFavesLogin = (Button) findViewById(R.id.faves_login);
mFavesLoginSignUpButtons = (ViewGroup) findViewById(R.id.faves_login_signup);
mSyncToAddCommentsIds = (TextView) findViewById(R.id.sync_to_add_comments_ids);
mSyncToAddFave = (TextView) findViewById(R.id.sync_to_add_fave);
mNoPhotosContainer = (ViewGroup) findViewById(R.id.no_photos);
mLocationLabelContainer = (ViewGroup) findViewById(R.id.location_label_container);
mIdPicBig = (ImageView) findViewById(R.id.id_icon_big);
mIdArrow = (ImageView) findViewById(R.id.id_arrow);
mPhotosContainer = (ViewGroup) findViewById(R.id.photos_container);
mLoadingPhotos = (ProgressBar) findViewById(R.id.loading_photos);
mLoadingMap = (ProgressBar) findViewById(R.id.loading_map);
mTaxonInactive = (ViewGroup) findViewById(R.id.taxon_inactive);
mMetadataObservationURL.setOnClickListener(v -> {
String inatNetwork = mApp.getInaturalistNetworkMember();
String inatHost = mApp.getStringResourceByName("inat_host_" + inatNetwork);
String obsUrl = inatHost + "/observations/" + mObservation.id;
mHelper.openUrlInBrowser(obsUrl);
});
WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mPhotosContainer.getLayoutParams();
params.height = (int) (display.getHeight() * 0.37);
mPhotosContainer.setLayoutParams(params);
View.OnClickListener onLogin = new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(ObservationViewerActivity.this, OnboardingActivity.class);
intent.putExtra(OnboardingActivity.LOGIN, true);
startActivityForResult(intent, REQUEST_CODE_LOGIN);
}
};
View.OnClickListener onSignUp = new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivityForResult(new Intent(ObservationViewerActivity.this, OnboardingActivity.class), REQUEST_CODE_LOGIN);
}
};
mActivityLogin.setOnClickListener(onLogin);
mActivitySignUp.setOnClickListener(onSignUp);
mFavesLogin.setOnClickListener(onLogin);
mFavesSignUp.setOnClickListener(onSignUp);
mLocationPrivate.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
mHelper.alert(R.string.geoprivacy, R.string.geoprivacy_explanation);
}
});
setupTabs();
refreshActivity();
refreshFavorites();
reloadPhotos();
getCommentIdList();
refreshDataQuality();
refreshAttributes();
refreshFollowStatus();
// Mark observation updates as viewed
if (mObservation != null && mObservation._synced_at != null) {
Intent serviceIntent = new Intent(INaturalistService.ACTION_VIEWED_UPDATE, null, this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.OBSERVATION_ID, mObservation.id);
ContextCompat.startForegroundService(this, serviceIntent);
}
}
private void reloadObservation(Bundle savedInstanceState, boolean forceReload) {
Intent intent = getIntent();
if (savedInstanceState == null) {
// Do some setup based on the action being performed.
Uri uri = intent.getData();
if ((uri != null) && (uri.getScheme().equals("https"))) {
// User clicked on an observation link (e.g. https://www.inaturalist.org/observations/1234)
String path = uri.getPath();
Logger.tag(TAG).info("Launched from external URL: " + uri);
if (path.toLowerCase().startsWith("/observations/")) {
Pattern pattern = Pattern.compile("/observations/([0-9]+)");
Matcher matcher = pattern.matcher(path);
if (matcher.find()) {
int obsId = Integer.valueOf(matcher.group(1));
mReadOnly = true;
mShowComments = false;
mScrollToCommentsBottom = false;
mReloadObs = true;
mObsJson = String.format(Locale.ENGLISH, "{ \"id\": %d }", obsId);
mObservation = new Observation(new BetterJSONObject(mObsJson));
} else {
Logger.tag(TAG).error("Invalid URL");
finish();
return;
}
} else {
Logger.tag(TAG).error("Invalid URL");
finish();
return;
}
} else {
mShowComments = intent.getBooleanExtra(SHOW_COMMENTS, false);
mScrollToCommentsBottom = intent.getBooleanExtra(SCROLL_TO_COMMENTS_BOTTOM, false);
if (uri == null) {
String obsJson = intent.getStringExtra("observation");
mReadOnly = intent.getBooleanExtra("read_only", false);
mReloadObs = intent.getBooleanExtra("reload", false);
mObsJson = obsJson;
if (obsJson == null) {
Logger.tag(TAG).error("Null URI from intent.getData");
finish();
return;
}
mObservation = new Observation(new BetterJSONObject(obsJson));
if (mReadOnly && mObservation.id != null && mObservation.user_login != null && mApp.loggedIn()) {
// See if this read-only observation is in fact our own observation (e.g. viewed from explore screen)
if (mObservation.user_login.toLowerCase().equals(mApp.currentUserLogin().toLowerCase())) {
// Our own observation
Cursor c = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "id = ?", new String[]{String.valueOf(mObservation.id)}, Observation.DEFAULT_SORT_ORDER);
if (c.getCount() > 0) {
// Observation available locally in the DB - just show/edit it
mReadOnly = false;
c.moveToFirst();
mObservation = new Observation(c);
mReloadObs = false;
uri = mObservation.getUri();
intent.setData(uri);
} else {
// Observation not downloaded yet - download and save it
Intent serviceIntent = new Intent(INaturalistService.ACTION_GET_AND_SAVE_OBSERVATION, null, this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.OBSERVATION_ID, mObservation.id);
ContextCompat.startForegroundService(this, serviceIntent);
mReadOnly = false;
mReloadObs = true;
uri = ContentUris.withAppendedId(Observation.CONTENT_URI, mObservation.id);
}
c.close();
}
}
}
mUri = uri;
}
} else {
String obsUri = savedInstanceState.getString("mUri");
if (obsUri != null) {
mUri = Uri.parse(obsUri);
} else {
mUri = intent.getData();
}
}
if (mCursor != null) {
if (!mCursor.isClosed()) mCursor.close();
mCursor = null;
}
if ((!mReadOnly) && (mUri != null)) mCursor = getContentResolver().query(mUri, Observation.PROJECTION, null, null, null);
if ((mObservation == null) || (forceReload)) {
if (!mReadOnly) {
if (mCursor == null || mCursor.getCount() == 0) {
Logger.tag(TAG).error("Cursor count is zero - finishing activity: " + mCursor);
finish();
return;
}
mObservation = new Observation(mCursor);
}
}
if ((mObservation != null) && (mObsJson == null)) {
mObservationReceiver = new ObservationReceiver();
IntentFilter filter = new IntentFilter(INaturalistService.ACTION_OBSERVATION_RESULT);
Logger.tag(TAG).info("Registering ACTION_OBSERVATION_RESULT");
BaseFragmentActivity.safeRegisterReceiver(mObservationReceiver, filter, this);
mLoadObsJson = true;
Intent serviceIntent = new Intent(INaturalistService.ACTION_GET_OBSERVATION, null, this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.OBSERVATION_ID, mObservation.id);
serviceIntent.putExtra(INaturalistService.GET_PROJECTS, true);
ContextCompat.startForegroundService(this, serviceIntent);
}
if (mObservation != null) {
JSONObject json = null;
try {
if (mObsJson != null) json = new JSONObject(mObsJson);
} catch (JSONException e) {
e.printStackTrace();
}
mMetadataObservationUUID.setText((mObservation.uuid != null) || (json == null) ? mObservation.uuid : json.optString("uuid"));
if (mObservation.id != null) {
mMetadataObservationIDRow.setVisibility(View.VISIBLE);
mMetadataObservationID.setText(String.valueOf(mObservation.id));
mMetadataObservationURLRow.setVisibility(View.VISIBLE);
String inatNetwork = mApp.getInaturalistNetworkMember();
String inatHost = mApp.getStringResourceByName("inat_host_" + inatNetwork);
String obsUrl = inatHost + "/observations/" + mObservation.id;
mMetadataObservationURL.setText(obsUrl);
} else {
mMetadataObservationIDRow.setVisibility(View.GONE);
mMetadataObservationURLRow.setVisibility(View.GONE);
}
}
}
@Override
public void onDestroy() {
if ((mCursor != null) && (!mCursor.isClosed())) mCursor.close();
super.onDestroy();
}
private int getFavoritedByUsername(String username) {
for (int i = 0; i < mFavorites.size(); i++) {
BetterJSONObject currentFav = mFavorites.get(i);
BetterJSONObject user = new BetterJSONObject(currentFav.getJSONObject("user"));
if (user.getString("login").equals(username)) {
// Current user has favorited this observation
return i;
}
}
return -1;
}
private void refreshFavorites() {
SharedPreferences pref = getSharedPreferences("iNaturalistPreferences", MODE_PRIVATE);
final String username = pref.getString("username", null);
TabWidget tabWidget = mTabHost.getTabWidget();
if ((mFavorites == null) || (mFavorites.size() == 0)) {
((TextView) tabWidget.getChildAt(2).findViewById(R.id.count)).setVisibility(View.GONE);
} else {
((TextView) tabWidget.getChildAt(2).findViewById(R.id.count)).setVisibility(View.VISIBLE);
((TextView) tabWidget.getChildAt(2).findViewById(R.id.count)).setText(String.valueOf(mFavorites.size()));
}
if (username == null) {
// Not logged in
mAddFavorite.setVisibility(View.GONE);
mLoginToAddFave.setVisibility(View.VISIBLE);
mFavesLoginSignUpButtons.setVisibility(View.VISIBLE);
mLoadingFavs.setVisibility(View.GONE);
mFavoritesList.setVisibility(View.GONE);
mNoFavsMessage.setVisibility(View.GONE);
mSyncToAddFave.setVisibility(View.GONE);
return;
}
if ((mObservation == null) || (mObservation.id == null)) {
// Observation not synced
mSyncToAddFave.setVisibility(View.VISIBLE);
mLoginToAddFave.setVisibility(View.GONE);
mFavesLoginSignUpButtons.setVisibility(View.GONE);
mLoadingFavs.setVisibility(View.GONE);
mFavoritesList.setVisibility(View.GONE);
mAddFavorite.setVisibility(View.GONE);
mRemoveFavorite.setVisibility(View.GONE);
mNoFavsMessage.setVisibility(View.GONE);
return;
}
mSyncToAddFave.setVisibility(View.GONE);
mLoginToAddFave.setVisibility(View.GONE);
mFavesLoginSignUpButtons.setVisibility(View.GONE);
if (mFavorites == null) {
// Still loading
mLoadingFavs.setVisibility(View.VISIBLE);
mFavoritesList.setVisibility(View.GONE);
mAddFavorite.setVisibility(View.GONE);
mRemoveFavorite.setVisibility(View.GONE);
mNoFavsMessage.setVisibility(View.GONE);
return;
}
mLoadingFavs.setVisibility(View.GONE);
mFavoritesList.setVisibility(View.VISIBLE);
if (mFavorites.size() == 0) {
mNoFavsMessage.setVisibility(View.VISIBLE);
} else {
mNoFavsMessage.setVisibility(View.GONE);
}
mFavIndex = getFavoritedByUsername(username);
if (mFavIndex > -1) {
// User has favorited the observation
mAddFavorite.setVisibility(View.GONE);
mRemoveFavorite.setVisibility(View.VISIBLE);
} else {
mAddFavorite.setVisibility(View.VISIBLE);
mRemoveFavorite.setVisibility(View.GONE);
}
mFavoritesAdapter = new FavoritesAdapter(this, mFavorites);
mFavoritesList.setAdapter(mFavoritesAdapter);
mRemoveFavorite.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
AnalyticsClient.getInstance().logEvent(AnalyticsClient.EVENT_NAME_OBS_UNFAVE);
Intent serviceIntent = new Intent(INaturalistService.ACTION_REMOVE_FAVORITE, null, ObservationViewerActivity.this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.OBSERVATION_ID, mObservation.id);
ContextCompat.startForegroundService(ObservationViewerActivity.this, serviceIntent);
mFavIndex = getFavoritedByUsername(username);
if (mFavIndex > -1) mFavorites.remove(mFavIndex);
mFavoritesAdapter.notifyDataSetChanged();
mAddFavorite.setVisibility(View.VISIBLE);
mRemoveFavorite.setVisibility(View.GONE);
if (mFavorites.size() == 0) {
mNoFavsMessage.setVisibility(View.VISIBLE);
} else {
mNoFavsMessage.setVisibility(View.GONE);
}
}
});
mAddFavorite.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
AnalyticsClient.getInstance().logEvent(AnalyticsClient.EVENT_NAME_OBS_FAVE);
Intent serviceIntent = new Intent(INaturalistService.ACTION_ADD_FAVORITE, null, ObservationViewerActivity.this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.OBSERVATION_ID, mObservation.id);
ContextCompat.startForegroundService(ObservationViewerActivity.this, serviceIntent);
SharedPreferences pref = getSharedPreferences("iNaturalistPreferences", MODE_PRIVATE);
String username = pref.getString("username", null);
String userIconUrl = pref.getString("user_icon_url", null);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.US);
String dateStr = dateFormat.format(new Date());
BetterJSONObject newFav = new BetterJSONObject(String.format(
"{ \"user\": { \"login\": \"%s\", \"user_icon_url\": \"%s\" }, \"created_at\": \"%s\" }",
username, userIconUrl, dateStr));
mFavorites.add(newFav);
mFavoritesAdapter.notifyDataSetChanged();
mRemoveFavorite.setVisibility(View.VISIBLE);
mAddFavorite.setVisibility(View.GONE);
if (mFavorites.size() == 0) {
mNoFavsMessage.setVisibility(View.VISIBLE);
} else {
mNoFavsMessage.setVisibility(View.GONE);
}
}
});
}
private void refreshActivity() {
SharedPreferences pref = getSharedPreferences("iNaturalistPreferences", MODE_PRIVATE);
String username = pref.getString("username", null);
mLoadingPhotos.setVisibility(View.GONE);
if (username == null) {
// Not logged in
mActivityButtons.setVisibility(View.GONE);
mLoginToAddCommentId.setVisibility(View.VISIBLE);
mActivityLoginSignUpButtons.setVisibility(View.VISIBLE);
mLoadingActivity.setVisibility(View.GONE);
mCommentsIdsList.setVisibility(View.GONE);
mNoActivityMessage.setVisibility(View.GONE);
mSyncToAddCommentsIds.setVisibility(View.GONE);
return;
}
if (mObservation == null) return;
if (mObservation.id == null) {
// Observation not synced
mSyncToAddCommentsIds.setVisibility(View.VISIBLE);
mLoginToAddCommentId.setVisibility(View.GONE);
mActivityLoginSignUpButtons.setVisibility(View.GONE);
return;
}
// Update observation comment/id count for signed in users observations
mObservation.comments_count = mObservation.last_comments_count = mCommentCount;
mObservation.identifications_count = mObservation.last_identifications_count = mIdCount;
if (mObservation.getUri() != null) {
ContentValues cv = new ContentValues();
cv.put(Observation.COMMENTS_COUNT, mObservation.comments_count);
cv.put(Observation.LAST_COMMENTS_COUNT, mObservation.last_comments_count);
cv.put(Observation.IDENTIFICATIONS_COUNT, mObservation.identifications_count);
cv.put(Observation.LAST_IDENTIFICATIONS_COUNT, mObservation.last_identifications_count);
if ((mObservation._synced_at != null) && (mObservation.id != null)) {
if ((mObservation._updated_at == null) || (mObservation._updated_at.before(mObservation._synced_at)) || (mObservation._updated_at.equals(mObservation._synced_at))) {
cv.put(Observation._SYNCED_AT, System.currentTimeMillis()); // No need to sync
}
}
getContentResolver().update(mObservation.getUri(), cv, null, null);
Logger.tag(TAG).debug("ObservationViewerActivity - refreshActivity - update obs: " + mObservation.id + ":" + mObservation.preferred_common_name + ":" + mObservation.taxon_id);
}
mLoginToAddCommentId.setVisibility(View.GONE);
mActivityLoginSignUpButtons.setVisibility(View.GONE);
mSyncToAddCommentsIds.setVisibility(View.GONE);
if (mCommentsIds == null) {
// Still loading
mLoadingActivity.setVisibility(View.VISIBLE);
mCommentsIdsList.setVisibility(View.GONE);
mActivityButtons.setVisibility(View.GONE);
mNoActivityMessage.setVisibility(View.GONE);
return;
}
mLoadingActivity.setVisibility(View.GONE);
mCommentsIdsList.setVisibility(View.VISIBLE);
mActivityButtons.setVisibility(View.VISIBLE);
if (mCommentsIds.size() == 0) {
mNoActivityMessage.setVisibility(View.VISIBLE);
} else {
mNoActivityMessage.setVisibility(View.GONE);
}
if (mScrollToCommentsBottom) {
mScrollView.post(new Runnable() {
@Override
public void run() {
mScrollView.fullScroll(ScrollView.FOCUS_DOWN);
}
});
}
mAdapter = new CommentsIdsAdapter(this, mObsJson != null ? new BetterJSONObject(mObsJson) : new BetterJSONObject(mObservation.toJSONObject()), mCommentsIds, mObservation.taxon_id == null ? 0 : mObservation.taxon_id , new CommentsIdsAdapter.OnIDAdded() {
@Override
public void onIdentificationAdded(BetterJSONObject taxon) {
try {
// After calling the added ID API - we'll refresh the comment/ID list
IntentFilter filter = new IntentFilter(INaturalistService.ACTION_OBSERVATION_RESULT);
BaseFragmentActivity.safeRegisterReceiver(mObservationReceiver, filter, ObservationViewerActivity.this);
Intent serviceIntent = new Intent(INaturalistService.ACTION_AGREE_ID, null, ObservationViewerActivity.this, INaturalistService.class);
mReloadTaxon = true;
serviceIntent.putExtra(INaturalistService.OBSERVATION_ID, mObservation.id);
serviceIntent.putExtra(INaturalistService.TAXON_ID, taxon.getJSONObject("taxon").getInt("id"));
serviceIntent.putExtra(INaturalistService.FROM_VISION, false);
ContextCompat.startForegroundService(ObservationViewerActivity.this, serviceIntent);
try {
JSONObject eventParams = new JSONObject();
eventParams.put(AnalyticsClient.EVENT_PARAM_VIA, AnalyticsClient.EVENT_VALUE_VIEW_OBS_AGREE);
eventParams.put(AnalyticsClient.EVENT_PARAM_FROM_VISION_SUGGESTION, false);
AnalyticsClient.getInstance().logEvent(AnalyticsClient.EVENT_NAME_OBS_ADD_ID, eventParams);
} catch (JSONException e) {
Logger.tag(TAG).error(e);
}
} catch (JSONException e) {
Logger.tag(TAG).error(e);
}
}
@Override
public void onIdentificationRemoved(BetterJSONObject taxon) {
// After calling the remove API - we'll refresh the comment/ID list
IntentFilter filter = new IntentFilter(INaturalistService.ACTION_OBSERVATION_RESULT);
BaseFragmentActivity.safeRegisterReceiver(mObservationReceiver, filter, ObservationViewerActivity.this);
Intent serviceIntent = new Intent(INaturalistService.ACTION_REMOVE_ID, null, ObservationViewerActivity.this, INaturalistService.class);
mReloadTaxon = true;
serviceIntent.putExtra(INaturalistService.IDENTIFICATION_ID, taxon.getInt("id"));
serviceIntent.putExtra(INaturalistService.OBSERVATION_ID, mObservation.id);
ContextCompat.startForegroundService(ObservationViewerActivity.this, serviceIntent);
}
@Override
public void onIdentificationUpdated(final BetterJSONObject id) {
// Set up the input
final EditText input = new EditText(ObservationViewerActivity.this);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
input.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT));
input.setText(id.getString("body"));
input.setSelection(input.getText().length());
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
input.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(input, InputMethodManager.SHOW_IMPLICIT);
}
}, 100);
mHelper.confirm(R.string.update_id_description, input,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String body = input.getText().toString();
// After calling the update API - we'll refresh the comment/ID list
IntentFilter filter = new IntentFilter(INaturalistService.ACTION_OBSERVATION_RESULT);
BaseFragmentActivity.safeRegisterReceiver(mObservationReceiver, filter, ObservationViewerActivity.this);
Intent serviceIntent = new Intent(INaturalistService.ACTION_UPDATE_ID, null, ObservationViewerActivity.this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.IDENTIFICATION_ID, id.getInt("id"));
serviceIntent.putExtra(INaturalistService.OBSERVATION_ID, mObservation.id);
serviceIntent.putExtra(INaturalistService.IDENTIFICATION_BODY, body);
serviceIntent.putExtra(INaturalistService.TAXON_ID, id.getInt("taxon_id"));
ContextCompat.startForegroundService(ObservationViewerActivity.this, serviceIntent);
}
},
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
}
@Override
public void onIdentificationRestored(BetterJSONObject id) {
// After calling the restore ID API - we'll refresh the comment/ID list
IntentFilter filter = new IntentFilter(INaturalistService.ACTION_OBSERVATION_RESULT);
BaseFragmentActivity.safeRegisterReceiver(mObservationReceiver, filter, ObservationViewerActivity.this);
Intent serviceIntent = new Intent(INaturalistService.ACTION_RESTORE_ID, null, ObservationViewerActivity.this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.IDENTIFICATION_ID, id.getInt("id"));
serviceIntent.putExtra(INaturalistService.OBSERVATION_ID, mObservation.id);
ContextCompat.startForegroundService(ObservationViewerActivity.this, serviceIntent);
}
@Override
public void onCommentRemoved(BetterJSONObject comment) {
// After calling the remove API - we'll refresh the comment/ID list
IntentFilter filter = new IntentFilter(INaturalistService.ACTION_OBSERVATION_RESULT);
BaseFragmentActivity.safeRegisterReceiver(mObservationReceiver, filter, ObservationViewerActivity.this);
Intent serviceIntent = new Intent(INaturalistService.ACTION_DELETE_COMMENT, null, ObservationViewerActivity.this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.COMMENT_ID, comment.getInt("id"));
serviceIntent.putExtra(INaturalistService.OBSERVATION_ID, mObservation.id);
ContextCompat.startForegroundService(ObservationViewerActivity.this, serviceIntent);
}
@Override
public void onCommentUpdated(final BetterJSONObject comment) {
// Set up the input
final EditText input = new EditText(ObservationViewerActivity.this);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
input.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT));
input.setText(comment.getString("body"));
input.setSelection(input.getText().length());
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
input.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(input, InputMethodManager.SHOW_IMPLICIT);
}
}, 100);
mHelper.confirm(R.string.update_comment, input,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String commentBody = input.getText().toString();
// After calling the update API - we'll refresh the comment/ID list
IntentFilter filter = new IntentFilter(INaturalistService.ACTION_OBSERVATION_RESULT);
BaseFragmentActivity.safeRegisterReceiver(mObservationReceiver, filter, ObservationViewerActivity.this);
Intent serviceIntent = new Intent(INaturalistService.ACTION_UPDATE_COMMENT, null, ObservationViewerActivity.this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.COMMENT_ID, comment.getInt("id"));
serviceIntent.putExtra(INaturalistService.OBSERVATION_ID, mObservation.id);
serviceIntent.putExtra(INaturalistService.COMMENT_BODY, commentBody);
ContextCompat.startForegroundService(ObservationViewerActivity.this, serviceIntent);
}
},
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
}
}, mReadOnly);
mCommentsIdsList.setAdapter(mAdapter);
mAddId.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(ObservationViewerActivity.this, IdentificationActivity.class);
intent.putExtra(IdentificationActivity.SUGGEST_ID, true);
intent.putExtra(IdentificationActivity.OBSERVATION_ID, mObservation.id);
intent.putExtra(IdentificationActivity.OBSERVATION_ID_INTERNAL, mObservation._id);
intent.putExtra(IdentificationActivity.OBSERVATION_UUID, mObservation.uuid);
intent.putExtra(IdentificationActivity.OBSERVED_ON, mObservation.observed_on);
intent.putExtra(IdentificationActivity.LONGITUDE, mObservation.longitude);
intent.putExtra(IdentificationActivity.LATITUDE, mObservation.latitude);
if (mObservation._id != null) {
if (((PhotosViewPagerAdapter)mPhotosViewPager.getAdapter()).getPhotoCount() > 0) {
Cursor imageCursor = ((PhotosViewPagerAdapter) mPhotosViewPager.getAdapter()).getCursor();
int pos = imageCursor.getPosition();
imageCursor.moveToFirst();
intent.putExtra(IdentificationActivity.OBS_PHOTO_FILENAME,
imageCursor.getString(imageCursor.getColumnIndex(ObservationPhoto.PHOTO_FILENAME)));
intent.putExtra(IdentificationActivity.OBS_PHOTO_URL,
imageCursor.getString(imageCursor.getColumnIndex(ObservationPhoto.PHOTO_URL)));
imageCursor.move(pos);
}
} else {
if ((mObservation.photos != null) && (mObservation.photos.size() > 0)) {
intent.putExtra(IdentificationActivity.OBS_PHOTO_FILENAME, mObservation.photos.get(0).photo_filename);
intent.putExtra(IdentificationActivity.OBS_PHOTO_URL, mObservation.photos.get(0).photo_url);
}
}
intent.putExtra(IdentificationActivity.OBSERVATION, mObsJson);
startActivityForResult(intent, NEW_ID_REQUEST_CODE);
}
});
mAddComment.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
mAddCommentBackground.setVisibility(View.VISIBLE);
mAddCommentContainer.setVisibility(View.VISIBLE);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
mAddCommentText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(mAddCommentText, InputMethodManager.SHOW_IMPLICIT);
}
}, 100);
mAddCommentText.setText("");
SharedPreferences pref = mApp.getPrefs();
String username = pref.getString("username", null);
String userIconUrl = pref.getString("user_icon_url", null);
mAddCommentDone.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String comment = mAddCommentText.getText().toString();
// Add the comment
Intent serviceIntent = new Intent(INaturalistService.ACTION_ADD_COMMENT, null, ObservationViewerActivity.this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.OBSERVATION_ID, mObservation.id);
serviceIntent.putExtra(INaturalistService.COMMENT_BODY, comment);
ContextCompat.startForegroundService(ObservationViewerActivity.this, serviceIntent);
mCommentMentions.dismiss();
mCommentsIds = null;
refreshActivity();
// Refresh the comment/id list
IntentFilter filter = new IntentFilter(INaturalistService.ACTION_OBSERVATION_RESULT);
BaseFragmentActivity.safeRegisterReceiver(mObservationReceiver, filter, ObservationViewerActivity.this);
mAddCommentContainer.setVisibility(View.GONE);
mAddCommentBackground.setVisibility(View.GONE);
// Hide keyboard
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mAddCommentText.getWindowToken(), 0);
}
});
mAddCommentBackground.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
discardAddComment();
}
});
}
});
}
private void discardAddComment() {
mHelper.confirm((View) null, getString(R.string.discard_comment), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mAddCommentContainer.setVisibility(View.GONE);
mAddCommentBackground.setVisibility(View.GONE);
dialog.dismiss();
mCommentMentions.dismiss();
// Hide keyboard
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (getCurrentFocus() != null) imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
}, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}, R.string.yes, R.string.no);
}
private void setupMap() {
if (mMap == null) return;
if (mObservation == null) return;
mMap.setMyLocationEnabled(false);
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.getUiSettings().setAllGesturesEnabled(false);
mMap.getUiSettings().setZoomControlsEnabled(false);
Double lat, lon;
Integer acc;
lat = mObservation.private_latitude == null ? mObservation.latitude : mObservation.private_latitude;
lon = mObservation.private_longitude == null ? mObservation.longitude : mObservation.private_longitude;
acc = mObservation.positional_accuracy;
if (!mLoadingObservation) {
mLoadingMap.setVisibility(View.GONE);
mLocationLabelContainer.setVisibility(View.VISIBLE);
}
if (lat != null && lon != null) {
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng latLng) {
Intent intent = new Intent(ObservationViewerActivity.this, LocationDetailsActivity.class);
intent.putExtra(LocationDetailsActivity.OBSERVATION, mObservation);
intent.putExtra(LocationDetailsActivity.OBSERVATION_JSON, mObsJson);
intent.putExtra(LocationDetailsActivity.READ_ONLY, true);
startActivity(intent);
}
});
// Add the marker
mMap.clear();
mHelper.addMapPosition(mMap, mObservation, mObsJson != null ? new BetterJSONObject(mObsJson) : null);
mLocationMapContainer.setVisibility(View.VISIBLE);
mUnknownLocationIcon.setVisibility(View.GONE);
if (((mObservation.place_guess == null) || (mObservation.place_guess.length() == 0)) &&
((mObservation.private_place_guess == null) || (mObservation.private_place_guess.length() == 0))) {
// No place guess - show coordinates instead
if (acc == null) {
mLocationText.setText(String.format(getString(R.string.location_coords_no_acc),
String.format("%.3f...", lat),
String.format("%.3f...", lon)));
} else {
mLocationText.setText(String.format(getString(R.string.location_coords),
String.format("%.3f...", lat),
String.format("%.3f...", lon),
acc > 999 ? ">1 km" : String.format("%dm", (int) acc)));
}
} else{
mLocationText.setText((mObservation.private_place_guess != null) && (mObservation.private_place_guess.length() > 0) ?
mObservation.private_place_guess : mObservation.place_guess);
}
mLocationText.setGravity(View.TEXT_ALIGNMENT_TEXT_END);
String geoprivacyField = mObservation.geoprivacy == null ? mObservation.taxon_geoprivacy : mObservation.geoprivacy;
if ((geoprivacyField == null) || (geoprivacyField.equals("open"))) {
mLocationPrivate.setVisibility(View.GONE);
} else if (geoprivacyField.equals("private")) {
mLocationPrivate.setVisibility(View.VISIBLE);
mLocationPrivate.setImageResource(R.drawable.ic_visibility_off_black_24dp);
} else if (geoprivacyField.equals("obscured")) {
mLocationPrivate.setVisibility(View.VISIBLE);
mLocationPrivate.setImageResource(R.drawable.ic_filter_tilt_shift_black_24dp);
}
mUnknownLocationContainer.setVisibility(View.GONE);
} else {
// Unknown place
mLocationMapContainer.setVisibility(View.GONE);
mUnknownLocationIcon.setVisibility(View.VISIBLE);
mLocationText.setText(R.string.unable_to_acquire_location);
mLocationText.setGravity(View.TEXT_ALIGNMENT_CENTER);
mLocationPrivate.setVisibility(View.GONE);
if (!mLoadingObservation) mUnknownLocationContainer.setVisibility(View.VISIBLE);
}
}
private View createTabContent(int tabIconResource, int contentDescriptionResource) {
View view = LayoutInflater.from(this).inflate(R.layout.observation_viewer_tab, null);
TextView countText = (TextView) view.findViewById(R.id.count);
ImageView tabIcon = (ImageView) view.findViewById(R.id.tab_icon);
tabIcon.setContentDescription(getString(contentDescriptionResource));
tabIcon.setImageResource(tabIconResource);
return view;
}
private void setupTabs() {
mTabHost.setup();
addTab(mTabHost, mTabHost.newTabSpec(VIEW_TYPE_INFO).setIndicator(createTabContent(R.drawable.ic_info_black_48dp, R.string.details)));
addTab(mTabHost, mTabHost.newTabSpec(VIEW_TYPE_COMMENTS_IDS).setIndicator(createTabContent(R.drawable.ic_forum_black_48dp, R.string.comments_ids_title)));
addTab(mTabHost, mTabHost.newTabSpec(VIEW_TYPE_FAVS).setIndicator(createTabContent(R.drawable.ic_star_black_48dp, R.string.faves)));
mTabHost.getTabWidget().setDividerDrawable(null);
if ((mActiveTab == null) && (mShowComments)) {
mTabHost.setCurrentTab(1);
refreshTabs(VIEW_TYPE_COMMENTS_IDS);
} else {
if (mActiveTab == null) {
mTabHost.setCurrentTab(0);
refreshTabs(VIEW_TYPE_INFO);
} else {
int i = 0;
if (mActiveTab.equals(VIEW_TYPE_INFO)) i = 0;
if (mActiveTab.equals(VIEW_TYPE_COMMENTS_IDS)) i = 1;
if (mActiveTab.equals(VIEW_TYPE_FAVS)) i = 2;
mTabHost.setCurrentTab(i);
refreshTabs(mActiveTab);
}
}
mTabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
@Override
public void onTabChanged(String tag) {
refreshTabs(tag);
}
});
}
private void refreshTabs(String tag) {
mActiveTab = tag;
mInfoTabContainer.setVisibility(View.GONE);
mActivityTabContainer.setVisibility(View.GONE);
mFavoritesTabContainer.setVisibility(View.GONE);
TabWidget tabWidget = mTabHost.getTabWidget();
tabWidget.getChildAt(0).findViewById(R.id.bottom_line).setVisibility(View.GONE);
tabWidget.getChildAt(1).findViewById(R.id.bottom_line).setVisibility(View.GONE);
tabWidget.getChildAt(2).findViewById(R.id.bottom_line).setVisibility(View.GONE);
((ImageView)tabWidget.getChildAt(0).findViewById(R.id.tab_icon)).setColorFilter(Color.parseColor("#757575"));
((ImageView)tabWidget.getChildAt(1).findViewById(R.id.tab_icon)).setColorFilter(Color.parseColor("#757575"));
((ImageView)tabWidget.getChildAt(2).findViewById(R.id.tab_icon)).setColorFilter(Color.parseColor("#757575"));
((TextView)tabWidget.getChildAt(2).findViewById(R.id.count)).setTextColor(Color.parseColor("#757575"));
int i = 0;
if (tag.equals(VIEW_TYPE_INFO)) {
mInfoTabContainer.setVisibility(View.VISIBLE);
i = 0;
} else if (tag.equals(VIEW_TYPE_COMMENTS_IDS)) {
mActivityTabContainer.setVisibility(View.VISIBLE);
i = 1;
} else if (tag.equals(VIEW_TYPE_FAVS)) {
mFavoritesTabContainer.setVisibility(View.VISIBLE);
((TextView)tabWidget.getChildAt(2).findViewById(R.id.count)).setTextColor(getResources().getColor(R.color.inatapptheme_color));
i = 2;
}
tabWidget.getChildAt(i).findViewById(R.id.bottom_line).setVisibility(View.VISIBLE);
((ImageView)tabWidget.getChildAt(i).findViewById(R.id.tab_icon)).setColorFilter(getResources().getColor(R.color.inatapptheme_color));
}
private void addTab(TabHost tabHost, TabHost.TabSpec tabSpec) {
tabSpec.setContent(new MyTabFactory(this));
tabHost.addTab(tabSpec);
}
private void getCommentIdList() {
if ((mObservation != null) && (mObservation.id != null) && (mCommentsIds == null)) {
BaseFragmentActivity.safeUnregisterReceiver(mObservationReceiver, this);
mObservationReceiver = new ObservationReceiver();
IntentFilter filter = new IntentFilter(INaturalistService.ACTION_OBSERVATION_RESULT);
Logger.tag(TAG).info("Registering ACTION_OBSERVATION_RESULT");
BaseFragmentActivity.safeRegisterReceiver(mObservationReceiver, filter, this);
Intent serviceIntent = new Intent(INaturalistService.ACTION_GET_OBSERVATION, null, this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.OBSERVATION_ID, mObservation.id);
serviceIntent.putExtra(INaturalistService.GET_PROJECTS, false);
ContextCompat.startForegroundService(this, serviceIntent);
if (mReadOnly) {
// Show loading progress bars for the photo and map
mLoadingObservation = true;
mLoadingPhotos.setVisibility(View.VISIBLE);
mNoPhotosContainer.setVisibility(View.GONE);
mLoadingMap.setVisibility(View.VISIBLE);
mUnknownLocationContainer.setVisibility(View.GONE);
mLocationLabelContainer.setVisibility(View.GONE);
}
}
}
private void refreshDataQuality() {
int dataQuality = DATA_QUALITY_CASUAL_GRADE;
int reasonText = 0;
if (mObservation == null) {
return;
}
Logger.tag(TAG).debug("refreshDataQuality: " + mObservation.id);
if (((mObservation.latitude == null) && (mObservation.longitude == null)) && ((mObservation.private_latitude == null) && (mObservation.private_longitude == null))) {
// No place
dataQuality = DATA_QUALITY_CASUAL_GRADE;
reasonText = R.string.casual_grade_add_location;
} else if (mObservation.observed_on == null) {
// No observed on date
dataQuality = DATA_QUALITY_CASUAL_GRADE;
reasonText = R.string.casual_grade_add_date;
} else if (((PhotosViewPagerAdapter)mPhotosViewPager.getAdapter()).getCount() == 0) {
// No photos
dataQuality = DATA_QUALITY_CASUAL_GRADE;
reasonText = R.string.casual_grade_add_photo;
} else if ((mObservation.captive != null && mObservation.captive) || mFlagAsCaptive) {
// Captive
dataQuality = DATA_QUALITY_CASUAL_GRADE;
reasonText = R.string.casual_grade_captive;
} else if (mIdCount <= 1) {
dataQuality = DATA_QUALITY_NEEDS_ID;
reasonText = R.string.needs_id_more_ids;
} else {
dataQuality = DATA_QUALITY_RESEARCH_GRADE;
}
Logger.tag(TAG).debug("refreshDataQuality 2: " + dataQuality + ":" + (reasonText != 0 ? getString(reasonText) : "N/A"));
if (mObservation.quality_grade != null) {
int observedDataQuality = -1;
if (mObservation.quality_grade.equals(QUALITY_GRADE_CASUAL_GRADE)) {
observedDataQuality = DATA_QUALITY_CASUAL_GRADE;
} else if (mObservation.quality_grade.equals(QUALITY_GRADE_NEEDS_ID)) {
observedDataQuality = DATA_QUALITY_NEEDS_ID;
} else if (mObservation.quality_grade.equals(QUALITY_GRADE_RESEARCH)) {
observedDataQuality = DATA_QUALITY_RESEARCH_GRADE;
}
if ((observedDataQuality != dataQuality) && (observedDataQuality != -1)) {
// This observation was synced and got a different data quality score - prefer
// to use what the server deducted through analysis / more advanced algorithm
dataQuality = observedDataQuality;
// Remove the reasoning
reasonText = 0;
}
Logger.tag(TAG).debug("refreshDataQuality 3: " + dataQuality);
}
Logger.tag(TAG).debug("refreshDataQuality 4: " + mObservation.quality_grade + ":" + mIdCount + ":" + mObservation.captive + ":" + mFlagAsCaptive + ":" +
((PhotosViewPagerAdapter)mPhotosViewPager.getAdapter()).getCount() + ":" + mObservation.observed_on + ":" + mObservation.latitude + ":" + mObservation.private_latitude +
":" + mObservation.longitude + ":" + mObservation.private_longitude);
// TODO - "Observation is casual grade because the community voted that they cannot identify it from the photo."
// TODO - "Observation needs finer identifications from the community to become "Research Grade" status.
int gray = Color.parseColor("#CBCBCB");
int green = Color.parseColor("#8DBA30");
if (dataQuality == DATA_QUALITY_CASUAL_GRADE) {
mNeedsIdLine.setBackgroundColor(gray);
mResearchGradeLine.setBackgroundColor(gray);
mNeedsIdText.setTextColor(gray);
mResearchGradeText.setTextColor(gray);
mNeedsIdIcon.setBackgroundResource(R.drawable.circular_border_thick_gray);
mResearchGradeIcon.setBackgroundResource(R.drawable.circular_border_thick_gray);
mNeedsIdIcon.setImageResource(R.drawable.transparent);
mResearchGradeIcon.setImageResource(R.drawable.transparent);
} else if (dataQuality == DATA_QUALITY_NEEDS_ID) {
mNeedsIdLine.setBackgroundColor(green);
mResearchGradeLine.setBackgroundColor(green);
mNeedsIdText.setTextColor(green);
mNeedsIdIcon.setBackgroundResource(R.drawable.circular_border_thick_green);
mNeedsIdIcon.setImageResource(R.drawable.ic_done_black_24dp);
mResearchGradeLine.setBackgroundColor(gray);
mResearchGradeText.setTextColor(gray);
mResearchGradeIcon.setBackgroundResource(R.drawable.circular_border_thick_gray);
mResearchGradeIcon.setImageResource(R.drawable.transparent);
} else {
mNeedsIdLine.setBackgroundColor(green);
mResearchGradeLine.setBackgroundColor(green);
mNeedsIdText.setTextColor(green);
mNeedsIdIcon.setBackgroundResource(R.drawable.circular_border_thick_green);
mNeedsIdIcon.setImageResource(R.drawable.ic_done_black_24dp);
mResearchGradeLine.setBackgroundColor(green);
mResearchGradeText.setTextColor(green);
mResearchGradeIcon.setBackgroundResource(R.drawable.circular_border_thick_green);
mResearchGradeIcon.setImageResource(R.drawable.ic_done_black_24dp);
}
if ((reasonText != 0) && (!mReadOnly)) {
mTipText.setText(Html.fromHtml(getString(reasonText)));
mDataQualityReason.setVisibility(View.VISIBLE);
} else {
mDataQualityReason.setVisibility(View.GONE);
}
OnClickListener showDataQualityAssessment = new OnClickListener() {
@Override
public void onClick(View view) {
if (!isNetworkAvailable()) {
Toast.makeText(getApplicationContext(), R.string.not_connected, Toast.LENGTH_LONG).show();
return;
}
if (mObsJson != null) {
try {
Intent intent = new Intent(ObservationViewerActivity.this, DataQualityAssessment.class);
intent.putExtra(DataQualityAssessment.OBSERVATION, new BetterJSONObject(getMinimalObservation(new JSONObject(mObsJson))));
startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
};
mDataQualityReason.setOnClickListener(showDataQualityAssessment);
mDataQualityGraph.setOnClickListener(showDataQualityAssessment);
}
private void loadObservationIntoUI() {
String userIconUrl = null;
if (mReadOnly) {
if (mObsJson == null) {
finish();
return;
}
BetterJSONObject obs = new BetterJSONObject(mObsJson);
JSONObject userObj = obs.getJSONObject("user");
if (userObj != null) {
userIconUrl = userObj.has("user_icon_url") && !userObj.isNull("user_icon_url") ? userObj.optString("user_icon_url", null) : null;
if (userIconUrl == null) {
userIconUrl = userObj.has("icon_url") && !userObj.isNull("icon_url") ? userObj.optString("icon_url", null) : null;
}
mUserName.setText(userObj.optString("login"));
mUserPic.setVisibility(View.VISIBLE);
mUserName.setVisibility(View.VISIBLE);
}
} else {
SharedPreferences pref = getSharedPreferences("iNaturalistPreferences", MODE_PRIVATE);
String username = pref.getString("username", null);
userIconUrl = pref.getString("user_icon_url", null);
mUserName.setText(username);
// Display the errors for the observation, if any
TextView errorsDescription = (TextView) findViewById(R.id.errors);
if (mObservation.id != null) {
JSONArray errors = mApp.getErrorsForObservation(mObservation.id != null ? mObservation.id : mObservation._id);
if (errors.length() == 0) {
errorsDescription.setVisibility(View.GONE);
} else {
errorsDescription.setVisibility(View.VISIBLE);
StringBuilder errorsHtml = new StringBuilder();
try {
for (int i = 0; i < errors.length(); i++) {
errorsHtml.append("• ");
errorsHtml.append(errors.getString(i));
if (i < errors.length() - 1)
errorsHtml.append("<br/>");
}
} catch (JSONException e) {
Logger.tag(TAG).error(e);
}
errorsDescription.setText(Html.fromHtml(errorsHtml.toString()));
}
} else {
errorsDescription.setVisibility(View.GONE);
}
}
if ((userIconUrl != null) && (userIconUrl.length() > 0)) {
String extension = userIconUrl.substring(userIconUrl.lastIndexOf(".") + 1);
userIconUrl = userIconUrl.substring(0, userIconUrl.lastIndexOf('/') + 1) + "medium." + extension;
}
if ((userIconUrl != null) && (userIconUrl.length() > 0)) {
UrlImageViewHelper.setUrlDrawable(mUserPic, userIconUrl, R.drawable.ic_account_circle_black_24dp, new UrlImageViewCallback() {
@Override
public void onLoaded(ImageView imageView, Bitmap loadedBitmap, String url, boolean loadedFromCache) { }
@Override
public Bitmap onPreSetBitmap(ImageView imageView, Bitmap loadedBitmap, String url, boolean loadedFromCache) {
// Return a circular version of the profile picture
Bitmap centerCrop = ImageUtils.centerCropBitmap(loadedBitmap);
return ImageUtils.getCircleBitmap(centerCrop);
}
});
} else {
mUserPic.setImageResource(R.drawable.ic_account_circle_black_24dp);
}
if (mReadOnly) {
if (mObsJson == null) return;
BetterJSONObject obs = new BetterJSONObject(mObsJson);
final JSONObject userObj = obs.getJSONObject("user");
OnClickListener showUser = new OnClickListener() {
@Override
public void onClick(View view) {
if (userObj == null) return;
Intent intent = new Intent(ObservationViewerActivity.this, UserProfile.class);
intent.putExtra("user", new BetterJSONObject(userObj));
startActivity(intent);
}
};
mUserName.setOnClickListener(showUser);
mUserPic.setOnClickListener(showUser);
}
mObservedOn.setText(formatObservedOn(mObservation.observed_on, mObservation.time_observed_at));
if (mPhotosAdapter.getCount() <= 1) {
mIndicator.setVisibility(View.GONE);
mNoPhotosContainer.setVisibility(View.GONE);
if (mPhotosAdapter.getCount() == 0) {
// No photos at all
mNoPhotosContainer.setVisibility(View.VISIBLE);
mIdPicBig.setImageResource(TaxonUtils.observationIcon(mObservation.toJSONObject()));
}
} else {
mIndicator.setVisibility(View.VISIBLE);
mNoPhotosContainer.setVisibility(View.GONE);
}
mSharePhoto.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
final DialogInterface.OnClickListener onClick = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String inatNetwork = mApp.getInaturalistNetworkMember();
String inatHost = mApp.getStringResourceByName("inat_host_" + inatNetwork);
String obsUrl = inatHost + "/observations/" + mObservation.id;
switch (which) {
case R.id.share:
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, obsUrl);
Intent chooserIntent = Intent.createChooser(shareIntent, getString(R.string.share));
startActivityForResult(chooserIntent, SHARE_REQUEST_CODE);
AnalyticsClient.getInstance().logEvent(AnalyticsClient.EVENT_NAME_OBS_SHARE_STARTED);
break;
case R.id.view_on_inat:
mHelper.openUrlInBrowser(obsUrl);
break;
case R.id.share_location:
String locationLabel;
if (mTaxon == null) {
// No taxon set - don't display the label
locationLabel = "";
} else if (mApp.getShowScientificNameFirst()) {
// Show scientific name
locationLabel = mTaxon.optString("name", "");;
} else {
locationLabel = TaxonUtils.getTaxonName(ObservationViewerActivity.this, mTaxon);
}
double latitude = (mObservation.geoprivacy == null) || (mObservation.geoprivacy.equals("open")) ? mObservation.latitude : mObservation.private_latitude;
double longitude = (mObservation.geoprivacy == null) || (mObservation.geoprivacy.equals("open")) ? mObservation.longitude : mObservation.private_longitude;
String uri = String.format(Locale.ENGLISH, "geo:0,0?q=%f,%f(%s)", latitude, longitude, locationLabel);
Intent mapIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(mapIntent);
break;
}
}
};
PopupMenu popup = new PopupMenu(ObservationViewerActivity.this, mSharePhoto);
popup.getMenuInflater().inflate(R.menu.share_photo_menu, popup.getMenu());
if ((mObservation.latitude == null) || (mObservation.longitude == null)) {
// No latitude/longitude - Hide "Share Location" menu option
popup.getMenu().getItem(1).setVisible(false);
} else {
if ((mObservation.geoprivacy != null) && (!mObservation.geoprivacy.equals("open"))) {
popup.getMenu().getItem(1).setTitle(R.string.share_hidden_location);
}
}
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(android.view.MenuItem menuItem) {
onClick.onClick(null, menuItem.getItemId());
return true;
}
});
popup.show();
}
});
OnClickListener listener = new OnClickListener() {
@Override
public void onClick(View view) {
if (mTaxon == null) {
// No taxon - don't show the taxon details page
return;
}
Intent intent = new Intent(ObservationViewerActivity.this, TaxonActivity.class);
intent.putExtra(TaxonActivity.TAXON, new BetterJSONObject(mTaxon));
intent.putExtra(TaxonActivity.OBSERVATION, mObsJson != null ? new BetterJSONObject(mObsJson) : new BetterJSONObject(mObservation.toJSONObject()));
startActivity(intent);
}
};
mIdRow.setOnClickListener(listener);
mIdName.setOnClickListener(listener);
mTaxonicName.setOnClickListener(listener);
mIdPic.setImageResource(TaxonUtils.observationIcon(mObservation.toJSONObject()));
if (mObservation.preferred_common_name != null && mObservation.preferred_common_name.length() > 0) {
mIdName.setText(mObservation.preferred_common_name);
mTaxonicName.setText(mObservation.preferred_common_name);
} else {
mIdName.setText(mObservation.species_guess);
mTaxonicName.setText(mObservation.species_guess);
}
if (mObservation.id == null) {
mSharePhoto.setVisibility(View.GONE);
}
if ((mObservation.taxon_id == null) && (mObservation.species_guess == null)) {
mIdName.setText(R.string.unknown_species);
mIdArrow.setVisibility(View.GONE);
} else if (mObservation.taxon_id != null) {
mIdArrow.setVisibility(View.VISIBLE);
if ((mTaxonScientificName == null) || (mTaxonIdName == null) || (mTaxonImage == null)) {
downloadObsTaxonAndUpdate();
} else {
UrlImageViewHelper.setUrlDrawable(mIdPic, mTaxonImage);
if (mTaxon == null) {
if ((mTaxonIdName == null) || (mTaxonIdName.length() == 0)) {
mIdName.setText(mTaxonScientificName);
mTaxonicName.setText(mTaxonScientificName);
} else {
mTaxonicName.setVisibility(View.VISIBLE);
if (mApp.getShowScientificNameFirst()) {
// Show scientific name first, before common name
TaxonUtils.setTaxonScientificName(mApp, mIdName, mTaxonScientificName, mTaxonRankLevel, mTaxonRank);
mTaxonicName.setText(mTaxonIdName);
} else {
TaxonUtils.setTaxonScientificName(mApp, mTaxonicName, mTaxonScientificName, mTaxonRankLevel, mTaxonRank);
mIdName.setText(mTaxonIdName);
}
}
} else {
if (mApp.getShowScientificNameFirst()) {
// Show scientific name first, before common name
TaxonUtils.setTaxonScientificName(mApp, mIdName, mTaxon);
mTaxonicName.setText(TaxonUtils.getTaxonName(this, mTaxon));
} else {
TaxonUtils.setTaxonScientificName(mApp, mTaxonicName, mTaxon);
mIdName.setText(TaxonUtils.getTaxonName(this, mTaxon));
}
}
}
}
mTaxonInactive.setVisibility(mTaxon == null || mTaxon.optBoolean("is_active", true) ? View.GONE : View.VISIBLE);
mTaxonInactive.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String inatNetwork = mApp.getInaturalistNetworkMember();
String inatHost = mApp.getStringResourceByName("inat_host_" + inatNetwork);
String taxonUrl = String.format(Locale.ENGLISH, "%s/taxon_changes?taxon_id=%d&locale=%s", inatHost, mTaxon.optInt("id"), mApp.getLanguageCodeForAPI());
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(taxonUrl));
startActivity(i);
}
});
if (!mReadOnly && (mProjects == null)) {
// Get IDs of project-observations
int obsId = (mObservation.id == null ? mObservation._id : mObservation.id);
Cursor c = getContentResolver().query(ProjectObservation.CONTENT_URI, ProjectObservation.PROJECTION,
"(observation_id = " + obsId + ") AND ((is_deleted = 0) OR (is_deleted is NULL))",
null, ProjectObservation.DEFAULT_SORT_ORDER);
mProjectIds = new ArrayList<Integer>();
while (c.isAfterLast() == false) {
ProjectObservation projectObservation = new ProjectObservation(c);
mProjectIds.add(projectObservation.project_id);
c.moveToNext();
}
c.close();
mProjects = new ArrayList<BetterJSONObject>();
for (int projectId : mProjectIds) {
c = getContentResolver().query(Project.CONTENT_URI, Project.PROJECTION,
"(id = " + projectId + ")", null, Project.DEFAULT_SORT_ORDER);
if (c.getCount() > 0) {
Project project = new Project(c);
BetterJSONObject projectJson = new BetterJSONObject();
projectJson.put("project", project.toJSONObject());
mProjects.add(projectJson);
}
c.close();
}
}
refreshProjectList();
mIncludedInProjectsContainer.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(ObservationViewerActivity.this, ObservationProjectsViewer.class);
intent.putExtra(ObservationProjectsViewer.PROJECTS, mProjects);
startActivity(intent);
}
});
if ((mObservation.description != null) && (mObservation.description.trim().length() > 0)) {
mNotesContainer.setVisibility(View.VISIBLE);
HtmlUtils.fromHtml(mNotes, mObservation.description);
} else {
mNotesContainer.setVisibility(View.GONE);
}
}
private JSONObject downloadTaxon(int taxonId) {
final String idUrl = INaturalistService.API_HOST + "/taxa/" + taxonId + "?locale=" + mApp.getLanguageCodeForAPI();
JSONObject results = downloadJson(idUrl);
if (results == null) return null;
return results.optJSONArray("results").optJSONObject(0);
}
private void downloadObsTaxonAndUpdate() {
// Download the taxon URL
new Thread(new Runnable() {
@Override
public void run() {
final JSONObject taxon = downloadTaxon(mObservation.taxon_id);
if (taxon == null) return;
mTaxon = taxon;
if (taxon != null) {
try {
JSONObject defaultPhoto = taxon.getJSONObject("default_photo");
final String imageUrl = defaultPhoto.getString("square_url");
runOnUiThread(new Runnable() {
@Override
public void run() {
mTaxonImage = imageUrl;
UrlImageViewHelper.setUrlDrawable(mIdPic, mTaxonImage);
mTaxonIdName = TaxonUtils.getTaxonName(ObservationViewerActivity.this, mTaxon);
mTaxonScientificName = TaxonUtils.getTaxonScientificName(mApp, taxon);
mTaxonRankLevel = taxon.optInt("rank_level", 0);
mTaxonRank = taxon.optString("rank");
if (mApp.getShowScientificNameFirst()) {
// Show scientific name first, before common name
mTaxonicName.setText(mTaxonIdName);
TaxonUtils.setTaxonScientificName(mApp, mIdName, taxon);
} else {
mIdName.setText(mTaxonIdName);
TaxonUtils.setTaxonScientificName(mApp, mTaxonicName, taxon);
}
mTaxonicName.setVisibility(View.VISIBLE);
}
});
} catch (JSONException e) {
Logger.tag(TAG).error(e);
}
}
}
}).start();
}
private JSONObject downloadJson(String uri) {
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
try {
URL url = new URL(uri);
conn = (HttpURLConnection) url.openConnection();
String jwtToken = mApp.getJWTToken();
if (mApp.loggedIn() && (jwtToken != null)) conn.setRequestProperty ("Authorization", jwtToken);
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Load the results into a StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
} catch (MalformedURLException e) {
return null;
} catch (IOException e) {
return null;
} finally {
if (conn != null) {
conn.disconnect();
}
}
try {
return new JSONObject(jsonResults.toString());
} catch (JSONException e) {
return null;
}
}
private String formatObservedOn(Timestamp date, Timestamp time) {
StringBuilder format = new StringBuilder();
if (date != null) {
// Format the date part
Calendar today = Calendar.getInstance();
today.setTime(new Date());
Calendar calDate = Calendar.getInstance();
calDate.setTimeInMillis(date.getTime());
String dateFormatString;
if (today.get(Calendar.YEAR) > calDate.get(Calendar.YEAR)) {
// Previous year(s)
dateFormatString = getString(R.string.date_short);
} else {
// Current year
dateFormatString = getString(R.string.date_short_this_year);
}
SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormatString);
format.append(dateFormat.format(date));
}
if (time != null) {
// Format the time part
if (date != null) {
format.append(" • ");
}
String timeFormatString;
if (DateFormat.is24HourFormat(getApplicationContext())) {
timeFormatString = getString(R.string.time_short_24_hour);
} else {
timeFormatString = getString(R.string.time_short_12_hour);
}
SimpleDateFormat timeFormat = new SimpleDateFormat(timeFormatString);
format.append(timeFormat.format(time));
}
return format.toString();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent;
switch (item.getItemId()) {
case android.R.id.home:
prepareToExit();
return true;
case R.id.edit_observation:
intent = new Intent(Intent.ACTION_EDIT, mUri, this, ObservationEditor.class);
if (mTaxon != null) mApp.setServiceResult(ObservationEditor.TAXON, mTaxon.toString());
if (mObsJson != null) intent.putExtra(ObservationEditor.OBSERVATION_JSON, mObsJson);
startActivityForResult(intent, REQUEST_CODE_EDIT_OBSERVATION);
return true;
case R.id.flag_captive:
mFlagAsCaptive = !mFlagAsCaptive;
refreshDataQuality();
refreshMenu();
return true;
case R.id.follow_observation:
Intent serviceIntent = new Intent(INaturalistService.ACTION_FOLLOW_OBSERVATION, null, ObservationViewerActivity.this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.OBSERVATION_ID, mObservation.id);
ContextCompat.startForegroundService(ObservationViewerActivity.this, serviceIntent);
mFollowingObservation = true;
refreshMenu();
return true;
case R.id.duplicate:
intent = new Intent(Intent.ACTION_EDIT, mUri, this, ObservationEditor.class);
if (mObsJson != null) intent.putExtra(ObservationEditor.OBSERVATION_JSON, mObsJson);
intent.putExtra(ObservationEditor.DUPLICATE, true);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onBackPressed() {
if (mAddCommentContainer.getVisibility() == View.VISIBLE) {
// Currently showing the add comment dialog
discardAddComment();
} else {
prepareToExit();
}
}
private void prepareToExit() {
if (!mFlagAsCaptive) {
finish();
return;
}
// Ask the user if he really wants to mark observation as captive
mHelper.confirm(getString(R.string.flag_as_captive), getString(R.string.are_you_sure_you_want_to_flag_as_captive),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (!mReadOnly) {
// Local observation - just update the local DB instance
ContentValues cv = mObservation.getContentValues();
cv.put(Observation.CAPTIVE, true);
int count = getContentResolver().update(mObservation.getUri(), cv, null, null);
finish();
return;
}
// Flag as captive
Intent serviceIntent = new Intent(INaturalistService.ACTION_FLAG_OBSERVATION_AS_CAPTIVE, null, ObservationViewerActivity.this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.OBSERVATION_ID, mObservation.id);
ContextCompat.startForegroundService(ObservationViewerActivity.this, serviceIntent);
Toast.makeText(getApplicationContext(), R.string.observation_flagged_as_captive, Toast.LENGTH_LONG).show();
setResult(RESULT_FLAGGED_AS_CAPTIVE);
finish();
}
},
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
}, R.string.yes, R.string.no);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.observation_viewer_menu, menu);
mMenu = menu;
refreshMenu();
return true;
}
private void refreshMenu() {
if (mMenu == null) return;
MenuItem flagCaptive = mMenu.findItem(R.id.flag_captive);
MenuItem duplicate = mMenu.findItem(R.id.duplicate);
MenuItem edit = mMenu.findItem(R.id.edit_observation);
MenuItem follow = mMenu.findItem(R.id.follow_observation);
if (mReadOnly) {
edit.setVisible(false);
duplicate.setVisible(false);
} else {
edit.setVisible(true);
duplicate.setVisible(true);
}
flagCaptive.setChecked(mFlagAsCaptive);
if (mObservationSubscriptions == null) {
follow.setEnabled(false);
follow.setTitle(R.string.follow_this_observation);
} else {
follow.setEnabled(!mFollowingObservation);
follow.setTitle(isFollowingObservation() ?
R.string.unfollow_this_observation : R.string.follow_this_observation);
}
}
private boolean isFollowingObservation() {
if ((mObservationSubscriptions == null) || (mObservationSubscriptions.length() == 0)) {
return false;
}
for (int i = 0; i < mObservationSubscriptions.length(); i++) {
JSONObject subscription = mObservationSubscriptions.optJSONObject(i);
if ((subscription.optString("resource_type", "").equals("Observation")) && (subscription.optInt("resource_id", -1) == mObservation.id)) {
return true;
}
}
return false;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
return true;
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Bridge.saveInstanceState(this, outState);
}
private class ChangeAttributesReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Logger.tag(TAG).error("ChangeAttributesReceiver");
// Re-download the observation JSON so we'll refresh the annotations
mObservationReceiver = new ObservationReceiver();
IntentFilter filter = new IntentFilter(INaturalistService.ACTION_OBSERVATION_RESULT);
Logger.tag(TAG).info("Registering ACTION_OBSERVATION_RESULT");
BaseFragmentActivity.safeRegisterReceiver(mObservationReceiver, filter, ObservationViewerActivity.this);
mLoadObsJson = true;
Intent serviceIntent = new Intent(INaturalistService.ACTION_GET_OBSERVATION, null, ObservationViewerActivity.this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.OBSERVATION_ID, mObservation.id);
serviceIntent.putExtra(INaturalistService.GET_PROJECTS, false);
ContextCompat.startForegroundService(ObservationViewerActivity.this, serviceIntent);
}
}
private void refreshFollowStatus() {
if (mObservation == null) return;
Intent serviceIntent = new Intent(INaturalistService.ACTION_GET_OBSERVATION_SUBSCRIPTIONS, null, ObservationViewerActivity.this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.OBSERVATION_ID, mObservation.id);
ContextCompat.startForegroundService(ObservationViewerActivity.this, serviceIntent);
mObservationSubscriptions = null;
mFollowingObservation = false;
refreshMenu();
}
private class AttributesReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Logger.tag(TAG).info("AttributesReceiver");
BetterJSONObject resultsObj = (BetterJSONObject) mApp.getServiceResult(INaturalistService.GET_ATTRIBUTES_FOR_TAXON_RESULT);
if (resultsObj == null) {
mAttributes = new SerializableJSONArray();
refreshAttributes();
return;
}
mAttributes = resultsObj.getJSONArray("results");
refreshAttributes();
}
}
private class ObservationFollowReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Logger.tag(TAG).error("ObservationFollowReceiver - result - " + mObservationSubscriptions);
boolean success = intent.getBooleanExtra(INaturalistService.SUCCESS, false);
if (!success) {
mFollowingObservation = false;
Toast.makeText(getApplicationContext(), getString(
isFollowingObservation() ?
R.string.could_not_unfollow_observation : R.string.could_not_follow_observation
), Toast.LENGTH_LONG).show();
refreshMenu();
return;
}
mFollowingObservation = false;
if (!isFollowingObservation()) {
mObservationSubscriptions = new JSONArray();
try {
JSONObject item = new JSONObject();
item.put("resource_type", "Observation");
item.put("resource_id", mObservation.id);
mObservationSubscriptions.put(item);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
mObservationSubscriptions = new JSONArray();
}
refreshMenu();
}
}
private class ObservationSubscriptionsReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Logger.tag(TAG).error("ObservationSubscriptionsReceiver - result");
boolean isSharedOnApp = intent.getBooleanExtra(INaturalistService.IS_SHARED_ON_APP, false);
SerializableJSONArray subscriptions;
if (isSharedOnApp) {
subscriptions = (SerializableJSONArray) mApp.getServiceResult(INaturalistService.ACTION_GET_OBSERVATION_SUBSCRIPTIONS_RESULT);
} else {
subscriptions = (SerializableJSONArray) intent.getSerializableExtra(INaturalistService.RESULTS);
}
if ((subscriptions == null) || (subscriptions.getJSONArray() == null)) {
mObservationSubscriptions = null;
refreshMenu();
return;
}
JSONArray results = subscriptions.getJSONArray();
mObservationSubscriptions = results;
refreshMenu();
}
}
private class DownloadObservationReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Logger.tag(TAG).error("DownloadObservationReceiver - OBSERVATION_RESULT");
BaseFragmentActivity.safeUnregisterReceiver(mDownloadObservationReceiver, ObservationViewerActivity.this);
boolean isSharedOnApp = intent.getBooleanExtra(INaturalistService.IS_SHARED_ON_APP, false);
Observation observation;
if (isSharedOnApp) {
observation = (Observation) mApp.getServiceResult(INaturalistService.ACTION_OBSERVATION_RESULT);
} else {
observation = (Observation) intent.getSerializableExtra(INaturalistService.OBSERVATION_RESULT);
}
if (mObservation == null) {
reloadObservation(null, false);
mObsJson = null;
}
if (observation == null) {
// Couldn't retrieve observation details (probably deleted)
mCommentsIds = new ArrayList<BetterJSONObject>();
mFavorites = new ArrayList<BetterJSONObject>();
refreshActivity();
refreshFavorites();
return;
}
if (!observation.id.equals(mObservation.id)) {
Logger.tag(TAG).error(String.format("DownloadObservationReceiver: Got old observation result for id %d, while current observation is %d", observation.id, mObservation.id));
return;
}
JSONArray projects = observation.projects.getJSONArray();
JSONArray comments = observation.comments.getJSONArray();
JSONArray ids = observation.identifications.getJSONArray();
JSONArray favs = observation.favorites.getJSONArray();
ArrayList<BetterJSONObject> results = new ArrayList<BetterJSONObject>();
ArrayList<BetterJSONObject> favResults = new ArrayList<BetterJSONObject>();
ArrayList<BetterJSONObject> projectResults = new ArrayList<BetterJSONObject>();
// #560 - refresh data quality grade
mObservation.captive = observation.captive;
mObservation.quality_grade = observation.quality_grade;
mIdCount = 0;
mCommentCount = 0;
try {
for (int i = 0; i < projects.length(); i++) {
BetterJSONObject project = new BetterJSONObject(projects.getJSONObject(i));
projectResults.add(project);
}
for (int i = 0; i < comments.length(); i++) {
BetterJSONObject comment = new BetterJSONObject(comments.getJSONObject(i));
comment.put("type", "comment");
results.add(comment);
mCommentCount++;
}
for (int i = 0; i < ids.length(); i++) {
BetterJSONObject id = new BetterJSONObject(ids.getJSONObject(i));
id.put("type", "identification");
results.add(id);
mIdCount++;
}
for (int i = 0; i < favs.length(); i++) {
BetterJSONObject fav = new BetterJSONObject(favs.getJSONObject(i));
favResults.add(fav);
}
} catch (JSONException e) {
Logger.tag(TAG).error(e);
}
Comparator<BetterJSONObject> comp = new Comparator<BetterJSONObject>() {
@Override
public int compare(BetterJSONObject lhs, BetterJSONObject rhs) {
Timestamp date1 = lhs.getTimestamp("created_at");
Timestamp date2 = rhs.getTimestamp("created_at");
return date1.compareTo(date2);
}
};
Collections.sort(results, comp);
Collections.sort(favResults, comp);
mCommentsIds = results;
mFavorites = favResults;
mProjects = projectResults;
if (mReloadObs) {
// Reload entire observation details (not just the comments/favs)
mObservation = observation;
if (!mReadOnly) {
mUri = mObservation.getUri();
getIntent().setData(mUri);
}
}
if (mReloadObs || mLoadObsJson) {
if (isSharedOnApp) {
mObsJson = (String) mApp.getServiceResult(INaturalistService.OBSERVATION_JSON_RESULT);
} else {
mObsJson = intent.getStringExtra(INaturalistService.OBSERVATION_JSON_RESULT);
}
if (mTaxonJson == null) {
new Thread(new Runnable() {
@Override
public void run() {
downloadCommunityTaxon(false);
}
}).start();
}
}
mLoadObsJson = false;
if (mReloadTaxon) {
// Reload just the taxon part, if changed
if (((mObservation.taxon_id == null) && (observation.taxon_id != null)) ||
((mObservation.taxon_id != null) && (observation.taxon_id == null)) ||
(mObservation.taxon_id != observation.taxon_id)) {
Logger.tag(TAG).debug("ObservationViewerActivity - ObservationReceiver: Updated taxon: " + mObservation.id + ":" + mObservation.preferred_common_name + ":" + mObservation.taxon_id);
Logger.tag(TAG).debug("ObservationViewerActivity - ObservationReceiver: Updated taxon (new): " + observation.id + ":" + observation.preferred_common_name + ":" + observation.taxon_id);
mObservation.species_guess = observation.species_guess;
mObservation.taxon_id = observation.taxon_id;
mObservation.preferred_common_name = observation.preferred_common_name;
mObservation.iconic_taxon_name = observation.iconic_taxon_name;
mTaxonScientificName = null;
mTaxonIdName = null;
mTaxonImage = null;
}
mReloadTaxon = false;
if (!mReadOnly) {
// Update observation's taxon in DB
ContentValues cv = mObservation.getContentValues();
getContentResolver().update(mUri, cv, null, null);
Logger.tag(TAG).debug("ObservationViewerActivity - ObservationReceiver - update obs: " + mObservation.id + ":" + mObservation.preferred_common_name + ":" + mObservation.taxon_id);
}
}
reloadPhotos();
loadObservationIntoUI();
setupMap();
refreshActivity();
refreshFavorites();
resizeActivityList();
resizeFavList();
refreshProjectList();
refreshDataQuality();
refreshAttributes();
}
}
private class ObservationReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Logger.tag(TAG).error("ObservationReceiver - OBSERVATION_RESULT");
BaseFragmentActivity.safeUnregisterReceiver(mObservationReceiver, ObservationViewerActivity.this);
mLoadingObservation = false;
boolean isSharedOnApp = intent.getBooleanExtra(INaturalistService.IS_SHARED_ON_APP, false);
Observation observation;
if (isSharedOnApp) {
observation = (Observation) mApp.getServiceResult(INaturalistService.ACTION_OBSERVATION_RESULT);
} else {
observation = (Observation) intent.getSerializableExtra(INaturalistService.OBSERVATION_RESULT);
}
if (mObservation == null) {
reloadObservation(null, false);
mObsJson = null;
}
if (observation == null) {
// Couldn't retrieve observation details (probably deleted)
mCommentsIds = new ArrayList<BetterJSONObject>();
mFavorites = new ArrayList<BetterJSONObject>();
refreshActivity();
refreshFavorites();
return;
}
if (!observation.id.equals(mObservation.id)) {
Logger.tag(TAG).error(String.format("ObservationReceiver: Got old observation result for id %d, while current observation is %d", observation.id, mObservation.id));
return;
}
JSONArray projects = observation.projects.getJSONArray();
JSONArray comments = observation.comments.getJSONArray();
JSONArray ids = observation.identifications.getJSONArray();
JSONArray favs = observation.favorites.getJSONArray();
ArrayList<BetterJSONObject> results = new ArrayList<BetterJSONObject>();
ArrayList<BetterJSONObject> favResults = new ArrayList<BetterJSONObject>();
ArrayList<BetterJSONObject> projectResults = new ArrayList<BetterJSONObject>();
// #560 - refresh data quality grade
mObservation.captive = observation.captive;
mObservation.quality_grade = observation.quality_grade;
mIdCount = 0;
mCommentCount = 0;
try {
for (int i = 0; i < projects.length(); i++) {
BetterJSONObject project = new BetterJSONObject(projects.getJSONObject(i));
projectResults.add(project);
}
for (int i = 0; i < comments.length(); i++) {
BetterJSONObject comment = new BetterJSONObject(comments.getJSONObject(i));
comment.put("type", "comment");
results.add(comment);
mCommentCount++;
}
for (int i = 0; i < ids.length(); i++) {
BetterJSONObject id = new BetterJSONObject(ids.getJSONObject(i));
id.put("type", "identification");
results.add(id);
mIdCount++;
}
for (int i = 0; i < favs.length(); i++) {
BetterJSONObject fav = new BetterJSONObject(favs.getJSONObject(i));
favResults.add(fav);
}
} catch (JSONException e) {
Logger.tag(TAG).error(e);
}
Comparator<BetterJSONObject> comp = new Comparator<BetterJSONObject>() {
@Override
public int compare(BetterJSONObject lhs, BetterJSONObject rhs) {
Timestamp date1 = lhs.getTimestamp("created_at");
Timestamp date2 = rhs.getTimestamp("created_at");
return date1.compareTo(date2);
}
};
Collections.sort(results, comp);
Collections.sort(favResults, comp);
mCommentsIds = results;
mFavorites = favResults;
mProjects = projectResults;
if (mReloadObs) {
// Reload entire observation details (not just the comments/favs)
mObservation = observation;
}
if (mReloadObs || mLoadObsJson) {
if (isSharedOnApp) {
mObsJson = (String) mApp.getServiceResult(INaturalistService.OBSERVATION_JSON_RESULT);
} else {
mObsJson = intent.getStringExtra(INaturalistService.OBSERVATION_JSON_RESULT);
}
if (mTaxonJson == null) {
new Thread(new Runnable() {
@Override
public void run() {
downloadCommunityTaxon(false);
}
}).start();
}
}
mLoadObsJson = false;
if (mReloadTaxon) {
// Reload just the taxon part, if changed
if (((mObservation.taxon_id == null) && (observation.taxon_id != null)) ||
((mObservation.taxon_id != null) && (observation.taxon_id == null)) ||
(mObservation.taxon_id != observation.taxon_id)) {
Logger.tag(TAG).debug("ObservationViewerActivity - ObservationReceiver: Updated taxon: " + mObservation.id + ":" + mObservation.preferred_common_name + ":" + mObservation.taxon_id);
Logger.tag(TAG).debug("ObservationViewerActivity - ObservationReceiver: Updated taxon (new): " + observation.id + ":" + observation.preferred_common_name + ":" + observation.taxon_id);
mObservation.species_guess = observation.species_guess;
mObservation.taxon_id = observation.taxon_id;
mObservation.preferred_common_name = observation.preferred_common_name;
mObservation.iconic_taxon_name = observation.iconic_taxon_name;
mTaxonScientificName = null;
mTaxonIdName = null;
mTaxonImage = null;
}
mReloadTaxon = false;
if (!mReadOnly) {
// Update observation's taxon in DB
ContentValues cv = mObservation.getContentValues();
getContentResolver().update(mUri, cv, null, null);
Logger.tag(TAG).debug("ObservationViewerActivity - ObservationReceiver - update obs: " + mObservation.id + ":" + mObservation.preferred_common_name + ":" + mObservation.taxon_id);
}
// Get latest annotations since community taxon might have changed
new Thread(new Runnable() {
@Override
public void run() {
downloadCommunityTaxon(true);
}
}).start();
}
if (mReloadObs && mReadOnly && mObservation.id != null && mApp.loggedIn()) {
// See if this read-only observation is in fact our own observation (e.g. viewed from explore screen)
if (mObservation.user_login.toLowerCase().equals(mApp.currentUserLogin().toLowerCase())) {
// Our own observation
Cursor c = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "id = ?", new String[]{String.valueOf(mObservation.id)}, Observation.DEFAULT_SORT_ORDER);
if (c.getCount() > 0) {
// Observation available locally in the DB - just show/edit it
mReadOnly = false;
c.moveToFirst();
mObservation = new Observation(c);
mReloadObs = false;
mUri = mObservation.getUri();
getIntent().setData(mUri);
} else {
// Observation not downloaded yet - download and save it
Intent serviceIntent = new Intent(INaturalistService.ACTION_GET_AND_SAVE_OBSERVATION, null, ObservationViewerActivity.this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.OBSERVATION_ID, mObservation.id);
ContextCompat.startForegroundService(ObservationViewerActivity.this, serviceIntent);
mReadOnly = false;
mReloadObs = true;
}
c.close();
refreshMenu();
}
}
reloadPhotos();
loadObservationIntoUI();
setupMap();
refreshActivity();
refreshFavorites();
resizeActivityList();
resizeFavList();
refreshProjectList();
refreshDataQuality();
refreshAttributes();
}
}
private void downloadCommunityTaxon(boolean downloadFromOriginalObservation) {
JSONObject observation;
try {
observation = new JSONObject(mObsJson);
} catch (JSONException e) {
Logger.tag(TAG).error(e);
return;
}
int taxonId = -1;
// Use current taxon
if (observation.has("taxon")) {
JSONObject taxon = observation.optJSONObject("taxon");
if (taxon != null) {
taxonId = taxon.optInt("id");
}
}
if (taxonId == -1) {
// No taxon - get the generic attributes (no taxon)
Intent serviceIntent = new Intent(INaturalistService.ACTION_GET_ATTRIBUTES_FOR_TAXON, null, ObservationViewerActivity.this, INaturalistService.class);
ContextCompat.startForegroundService(this, serviceIntent);
return;
}
if (downloadFromOriginalObservation) {
taxonId = mObservation.taxon_id;
}
JSONObject taxon = downloadTaxon(taxonId);
if (taxon == null) {
mAttributes = new SerializableJSONArray();
runOnUiThread(new Runnable() {
@Override
public void run() {
refreshAttributes();
}
});
return;
}
mTaxonJson = taxon.toString();
// Now that we have full taxon details, we can retrieve the annotations/attributes for that taxon
Intent serviceIntent = new Intent(INaturalistService.ACTION_GET_ATTRIBUTES_FOR_TAXON, null, ObservationViewerActivity.this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.TAXON_ID, taxon.optInt("id"));
serviceIntent.putExtra(INaturalistService.ANCESTORS, new SerializableJSONArray(taxon.optJSONArray("ancestor_ids")));
ContextCompat.startForegroundService(this, serviceIntent);
}
private void reloadPhotos() {
mLoadingPhotos.setVisibility(View.GONE);
mPhotosAdapter = new PhotosViewPagerAdapter();
mPhotosViewPager.setAdapter(mPhotosAdapter);
mIndicator.setViewPager(mPhotosViewPager);
}
private void refreshAttributes() {
if ((mObservation != null) && (mObservation.id == null)) {
// Don't show attributes for non-synced observations
mAnnotationSection.setVisibility(View.GONE);
return;
}
if (mAttributes == null) {
mAnnotationSection.setVisibility(View.VISIBLE);
mLoadingAnnotations.setVisibility(View.VISIBLE);
mAnnotationsContent.setVisibility(View.GONE);
return;
} else if (mAttributes.getJSONArray().length() == 0) {
mAnnotationSection.setVisibility(View.GONE);
return;
}
mAnnotationsContent.setVisibility(View.VISIBLE);
mAnnotationSection.setVisibility(View.VISIBLE);
mLoadingAnnotations.setVisibility(View.GONE);
JSONArray obsAnnotations = null;
if (mObsJson != null) {
try {
JSONObject obs = new JSONObject(mObsJson);
obsAnnotations = obs.getJSONArray("annotations");
} catch (JSONException e) {
Logger.tag(TAG).error(e);
}
}
try {
mAnnotationsList.setAdapter(new AnnotationsAdapter(this, this, mObservation.toJSONObject(), mTaxonJson != null ? new JSONObject(mTaxonJson) : null, mAttributes.getJSONArray(), obsAnnotations));
} catch (JSONException e) {
Logger.tag(TAG).error(e);
}
ActivityHelper.resizeList(mAnnotationsList);
if (mAnnotationsList.getAdapter().getCount() == 0) {
// No visible annotation - hide the entire section
mAnnotationSection.setVisibility(View.GONE);
}
}
private void resizeFavList() {
final Handler handler = new Handler();
if ((mFavoritesTabContainer.getVisibility() == View.VISIBLE) && (mFavoritesList.getVisibility() == View.VISIBLE) && (mFavoritesList.getWidth() == 0)) {
// UI not initialized yet - try later
handler.postDelayed(new Runnable() {
@Override
public void run() {
resizeFavList();
}
}, 100);
return;
}
handler.postDelayed(new Runnable() {
@Override
public void run() {
setListViewHeightBasedOnItems(mFavoritesList);
}
}, 100);
}
private void resizeActivityList() {
final Handler handler = new Handler();
if ((mCommentsIdsList.getVisibility() == View.VISIBLE) && (mActivityTabContainer.getVisibility() == View.VISIBLE) && (mCommentsIdsList.getWidth() == 0)) {
// UI not initialized yet - try later
handler.postDelayed(new Runnable() {
@Override
public void run() {
resizeActivityList();
}
}, 100);
return;
}
mCommentsIdsList.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView absListView, int i) {
}
@Override
public void onScroll(AbsListView absListView, int i, int i1, int i2) {
int height = setListViewHeightBasedOnItems(mCommentsIdsList);
View background = findViewById(R.id.comment_id_list_background);
ViewGroup.LayoutParams params = background.getLayoutParams();
if (params.height != height) {
params.height = height;
background.requestLayout();
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Logger.tag(TAG).debug("onActivityResult - " + requestCode + ":" + resultCode);
if (requestCode == SHARE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// TODO - RESULT_OK is never returned + need to add "destination" param (what type of share was performed)
AnalyticsClient.getInstance().logEvent(AnalyticsClient.EVENT_NAME_OBS_SHARE_FINISHED);
} else {
AnalyticsClient.getInstance().logEvent(AnalyticsClient.EVENT_NAME_OBS_SHARE_CANCELLED);
}
} else if (requestCode == REQUEST_CODE_EDIT_OBSERVATION) {
Logger.tag(TAG).debug("onActivityResult - EDIT_OBS: " + requestCode + ":" + resultCode);
if ((resultCode == ObservationEditor.RESULT_DELETED) || (resultCode == ObservationEditor.RESULT_RETURN_TO_OBSERVATION_LIST)) {
// User deleted the observation (or did a batch-edit)
Logger.tag(TAG).debug("onActivityResult - EDIT_OBS: Finish");
setResult(RESULT_OBSERVATION_CHANGED);
finish();
return;
} else if (resultCode == ObservationEditor.RESULT_REFRESH_OBS) {
// User made changes to observation - refresh the view
reloadObservation(null, true);
reloadPhotos();
loadObservationIntoUI();
getCommentIdList();
setupMap();
refreshActivity();
refreshFavorites();
resizeActivityList();
resizeFavList();
refreshProjectList();
refreshDataQuality();
refreshAttributes();
setResult(RESULT_OBSERVATION_CHANGED);
}
} if (requestCode == NEW_ID_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// Add the ID
final Integer taxonId = data.getIntExtra(IdentificationActivity.TAXON_ID, 0);
String taxonName = data.getStringExtra(IdentificationActivity.TAXON_NAME);
String speciesGuess = data.getStringExtra(IdentificationActivity.SPECIES_GUESS);
final String idRemarks = data.getStringExtra(IdentificationActivity.ID_REMARKS);
final boolean fromSuggestion = data.getBooleanExtra(IdentificationActivity.FROM_SUGGESTION, false);
checkForTaxonDisagreement(taxonId, taxonName, speciesGuess, new onDisagreement() {
@Override
public void onDisagreement(boolean disagreement) {
Intent serviceIntent = new Intent(INaturalistService.ACTION_ADD_IDENTIFICATION, null, ObservationViewerActivity.this, INaturalistService.class);
serviceIntent.putExtra(INaturalistService.OBSERVATION_ID, mObservation.id);
serviceIntent.putExtra(INaturalistService.TAXON_ID, taxonId);
serviceIntent.putExtra(INaturalistService.IDENTIFICATION_BODY, idRemarks);
serviceIntent.putExtra(INaturalistService.DISAGREEMENT, disagreement);
serviceIntent.putExtra(INaturalistService.FROM_VISION, fromSuggestion);
ContextCompat.startForegroundService(ObservationViewerActivity.this, serviceIntent);
try {
JSONObject eventParams = new JSONObject();
eventParams.put(AnalyticsClient.EVENT_PARAM_VIA, AnalyticsClient.EVENT_VALUE_VIEW_OBS_ADD);
eventParams.put(AnalyticsClient.EVENT_PARAM_FROM_VISION_SUGGESTION, fromSuggestion);
AnalyticsClient.getInstance().logEvent(AnalyticsClient.EVENT_NAME_OBS_ADD_ID, eventParams);
} catch (JSONException e) {
Logger.tag(TAG).error(e);
}
// Show a loading progress until the new comments/IDs are loaded
mCommentsIds = null;
refreshActivity();
// Refresh the comment/id list
mReloadTaxon = true;
IntentFilter filter = new IntentFilter(INaturalistService.ACTION_OBSERVATION_RESULT);
BaseFragmentActivity.safeRegisterReceiver(mObservationReceiver, filter, ObservationViewerActivity.this);
}
});
}
} else if ((requestCode == REQUEST_CODE_LOGIN) && (resultCode == Activity.RESULT_OK)) {
// Show a loading progress until the new comments/IDs are loaded
mCommentsIds = null;
mFavorites = null;
refreshActivity();
refreshFavorites();
// Refresh the comment/id list
IntentFilter filter = new IntentFilter(INaturalistService.ACTION_OBSERVATION_RESULT);
BaseFragmentActivity.safeRegisterReceiver(mObservationReceiver, filter, this);
Intent serviceIntent2 = new Intent(INaturalistService.ACTION_GET_OBSERVATION, null, this, INaturalistService.class);
serviceIntent2.putExtra(INaturalistService.OBSERVATION_ID, mObservation.id);
serviceIntent2.putExtra(INaturalistService.GET_PROJECTS, false);
ContextCompat.startForegroundService(this, serviceIntent2);
} else if (requestCode == OBSERVATION_PHOTOS_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
Integer setFirstPhotoIndex = data.getIntExtra(ObservationPhotosViewer.SET_DEFAULT_PHOTO_INDEX, -1);
Integer deletePhotoIndex = data.getIntExtra(ObservationPhotosViewer.DELETE_PHOTO_INDEX, -1);
Integer duplicatePhotoIndex = data.getIntExtra(ObservationPhotosViewer.DUPLICATE_PHOTO_INDEX, -1);
if (data.hasExtra(ObservationPhotosViewer.REPLACED_PHOTOS)) {
// Photos the user has edited
String rawReplacedPhotos = data.getStringExtra(ObservationPhotosViewer.REPLACED_PHOTOS);
rawReplacedPhotos = rawReplacedPhotos.substring(1, rawReplacedPhotos.length() - 1);
String parts[] = rawReplacedPhotos.split(",");
List<Pair<Uri, Long>> replacedPhotos = new ArrayList<>();
for (String value : parts) {
value = value.trim();
String[] innerParts = value.substring(5, value.length() - 1).split(" ", 2);
replacedPhotos.add(new Pair<Uri, Long>(Uri.parse(innerParts[0]), Long.valueOf(innerParts[1])));
}
for (Pair<Uri, Long> replacedPhoto : replacedPhotos) {
int index = replacedPhoto.second.intValue();
Uri photoUri = replacedPhoto.first;
// Delete old photo
Logger.tag(TAG).debug(String.format(Locale.ENGLISH, "Replacing/deleting previous photo at index: %d: %s", index, photoUri));
deletePhoto(index, false);
// Add new photo instead
Uri createdUri = createObservationPhotoForPhoto(photoUri, index, false);
}
reloadPhotos();
}
if (setFirstPhotoIndex > -1) {
// Set photo as first
if (setFirstPhotoIndex < mPhotosAdapter.getPhotoCount()) {
mPhotosAdapter.setAsFirstPhoto(setFirstPhotoIndex);
}
AnalyticsClient.getInstance().logEvent(AnalyticsClient.EVENT_NAME_OBS_NEW_DEFAULT_PHOTO);
} else if (deletePhotoIndex > -1) {
// Delete photo
deletePhoto(deletePhotoIndex, true);
AnalyticsClient.getInstance().logEvent(AnalyticsClient.EVENT_NAME_OBS_DELETE_PHOTO);
} else if (duplicatePhotoIndex > -1) {
// Duplicate photo
duplicatePhoto(duplicatePhotoIndex);
}
}
}
}
private interface onDisagreement {
void onDisagreement(boolean disagreement);
}
private void checkForTaxonDisagreement(int taxonId, String name, String scientificName, final onDisagreement cb) {
if ((mTaxonJson == null) || (mObsJson == null)) {
// We don't have the JSON structures for the observation and the taxon - cannot check for possible disagreement
cb.onDisagreement(false);
return;
}
BetterJSONObject taxon = new BetterJSONObject(mTaxonJson);
int communityTaxonId = taxon.getInt("id");
JSONArray ancestors = taxon.getJSONArray("ancestor_ids").getJSONArray();
// See if the current ID taxon is an ancestor of the current observation taxon / community taxon
boolean disagreement = false;
for (int i = 0; i < ancestors.length(); i++) {
int currentTaxonId = ancestors.optInt(i);
if (currentTaxonId == taxonId) {
disagreement = true;
break;
}
}
if ((!disagreement) || (communityTaxonId == taxonId)) {
// No disagreement here
cb.onDisagreement(false);
return;
}
// Show disagreement dialog
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ViewGroup dialogContent = (ViewGroup) inflater.inflate(R.layout.explicit_disagreement, null, false);
TextView questionText = (TextView) dialogContent.findViewById(R.id.question);
final RadioButton disagreementRadioButton = (RadioButton) dialogContent.findViewById(R.id.disagreement);
final RadioButton noDisagreemenRadioButton = (RadioButton) dialogContent.findViewById(R.id.no_disagreement);
String taxonName = String.format("%s (%s)", name, scientificName);
String communityTaxonName = String.format("%s (%s)", TaxonUtils.getTaxonName(this, taxon.getJSONObject()), TaxonUtils.getTaxonScientificName(mApp, taxon.getJSONObject()));
questionText.setText(Html.fromHtml(String.format(getString(R.string.do_you_think_this_could_be), communityTaxonName)));
noDisagreemenRadioButton.setText(Html.fromHtml(String.format(getString(R.string.i_dont_know_but), taxonName)));
disagreementRadioButton.setText(Html.fromHtml(String.format(getString(R.string.no_but_it_is_a_member_of_taxon), taxonName)));
mHelper.confirm(getString(R.string.potential_disagreement), dialogContent, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
boolean isDisagreement = disagreementRadioButton.isChecked();
cb.onDisagreement(isDisagreement);
}
}, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Canceled dialog - nothing to do here
}
}, R.string.submit, R.string.cancel);
}
private void refreshProjectList() {
if ((mProjects != null) && (mProjects.size() > 0)) {
mIncludedInProjectsContainer.setVisibility(View.VISIBLE);
int count = mProjects.size();
mIncludedInProjects.setText(getResources().getQuantityString(R.plurals.included_in_projects, count, count));
} else {
mIncludedInProjectsContainer.setVisibility(View.GONE);
}
}
/**
* Sets ListView height dynamically based on the height of the items.
*
* @param listView to be resized
*/
public int setListViewHeightBasedOnItems(final ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter != null) {
int numberOfItems = listAdapter.getCount();
// Get total height of all items.
int totalItemsHeight = 0;
for (int itemPos = 0; itemPos < numberOfItems; itemPos++) {
View item = listAdapter.getView(itemPos, null, listView);
item.measure(MeasureSpec.makeMeasureSpec(listView.getWidth(), MeasureSpec.AT_MOST), MeasureSpec.UNSPECIFIED);
totalItemsHeight += item.getMeasuredHeight();
}
// Get total height of all item dividers.
int totalDividersHeight = listView.getDividerHeight() *
(numberOfItems - 1);
// Set list height.
ViewGroup.LayoutParams params = listView.getLayoutParams();
int paddingHeight = (int) getResources().getDimension(R.dimen.actionbar_height);
int newHeight = totalItemsHeight + totalDividersHeight;
if (params.height != newHeight) {
params.height = totalItemsHeight + totalDividersHeight;
listView.setLayoutParams(params);
listView.requestLayout();
}
return params.height;
} else {
return 0;
}
}
@Override
protected void onPause() {
super.onPause();
BaseFragmentActivity.safeUnregisterReceiver(mObservationReceiver, this);
BaseFragmentActivity.safeUnregisterReceiver(mAttributesReceiver, this);
BaseFragmentActivity.safeUnregisterReceiver(mChangeAttributesReceiver, this);
BaseFragmentActivity.safeUnregisterReceiver(mDownloadObservationReceiver, this);
BaseFragmentActivity.safeUnregisterReceiver(mObservationSubscriptionsReceiver, this);
BaseFragmentActivity.safeUnregisterReceiver(mObservationFollowReceiver, this);
if (mPhotosAdapter != null) {
mPhotosAdapter.pause();
}
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
private void deletePhoto(int position, boolean refreshPositions) {
PhotosViewPagerAdapter adapter = mPhotosAdapter;
if (position >= adapter.getPhotoCount()) {
return;
}
Cursor cursor = adapter.getCursor();
cursor.moveToPosition(position);
ObservationPhoto op = new ObservationPhoto(cursor);
// Mark photo as deleted
Logger.tag(TAG).debug(String.format("Marking photo for deletion: %s", op.toString()));
ContentValues cv = new ContentValues();
cv.put(ObservationPhoto.IS_DELETED, 1);
int updateCount = getContentResolver().update(op.getUri(), cv, null, null);
reloadPhotos();
if (refreshPositions) {
// Refresh the positions of all other photos
adapter = mPhotosAdapter;
adapter.refreshPhotoPositions(null, false);
}
}
private void duplicatePhoto(int position) {
PhotosViewPagerAdapter adapter = mPhotosAdapter;
if (position >= adapter.getPhotoCount()) {
return;
}
Cursor cursor = adapter.getCursor();
cursor.moveToPosition(position);
ObservationPhoto op = new ObservationPhoto(cursor);
// Add a duplicate of this photo (in a position ahead of this one)
// Copy file
String photoUrl = op.photo_url;
String photoFileName = op.photo_filename;
final File destFile = new File(getFilesDir(), UUID.randomUUID().toString() + ".jpeg");
Logger.tag(TAG).info("Duplicate: " + op + ":" + photoFileName + ":" + photoUrl);
if (photoFileName != null) {
// Local file - copy it
try {
FileUtils.copyFile(new File(photoFileName), destFile);
addDuplicatedPhoto(op, destFile);
} catch (IOException e) {
Logger.tag(TAG).error(e);
Toast.makeText(getApplicationContext(), getString(R.string.couldnt_duplicate_photo), Toast.LENGTH_SHORT).show();
return;
}
} else {
// Online only - need to download it and then copy
Glide.with(this)
.asBitmap()
.load(photoUrl)
.apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.AUTOMATIC))
.into(new CustomTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
// Save downloaded bitmap into local file
try {
OutputStream outStream = new FileOutputStream(destFile);
resource.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.close();
addDuplicatedPhoto(op, destFile);
} catch (Exception e) {
Logger.tag(TAG).error(e);
Toast.makeText(getApplicationContext(), getString(R.string.couldnt_duplicate_photo), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onLoadCleared(@Nullable Drawable placeholder) {
}
@Override
public void onLoadFailed(@Nullable Drawable errorDrawable) {
Logger.tag(TAG).error("onLoadedFailed");
Toast.makeText(getApplicationContext(), getString(R.string.couldnt_duplicate_photo), Toast.LENGTH_SHORT).show();
}
});
}
}
private void addDuplicatedPhoto(ObservationPhoto originalPhoto, File duplicatedPhotoFile) {
// Create new photo observation with the duplicated photo file
Uri createdUri = createObservationPhotoForPhoto(Uri.fromFile(duplicatedPhotoFile), originalPhoto.position, true);
if (createdUri == null) {
Logger.tag(TAG).error("addDuplicatedPhoto - couldn't create duplicate OP");
Toast.makeText(getApplicationContext(), getString(R.string.couldnt_duplicate_photo), Toast.LENGTH_SHORT).show();
return;
}
reloadPhotos();
// Refresh the positions of all other photos
mPhotosAdapter.refreshPhotoPositions(originalPhoto.position, false);
}
private Uri createObservationPhotoForPhoto(Uri photoUri, int position, boolean isDuplicated) {
String path = FileUtils.getPath(this, photoUri);
String extension = FileUtils.getExtension(this, photoUri);
if ((extension == null) && (path != null)) {
int i = path.lastIndexOf('.');
if (i >= 0) {
extension = path.substring(i + 1).toLowerCase();
}
}
if ((extension == null) || (
(!extension.toLowerCase().equals("jpg")) &&
(!extension.toLowerCase().equals("jpeg")) &&
(!extension.toLowerCase().equals("png"))
)) {
return null;
}
// Resize photo to 2048x2048 max
String resizedPhoto = ImageUtils.resizeImage(this, path, photoUri, 2048);
if (resizedPhoto == null) {
return null;
}
ObservationPhoto op = new ObservationPhoto();
op.uuid = UUID.randomUUID().toString();
ContentValues cv = op.getContentValues();
cv.put(ObservationPhoto._OBSERVATION_ID, mObservation._id);
cv.put(ObservationPhoto.OBSERVATION_ID, mObservation.id);
cv.put(ObservationPhoto.PHOTO_FILENAME, resizedPhoto);
cv.put(ObservationPhoto.ORIGINAL_PHOTO_FILENAME, (String)null);
cv.put(ObservationPhoto.POSITION, position);
cv.put(ObservationPhoto.OBSERVATION_UUID, mObservation.uuid);
return getContentResolver().insert(ObservationPhoto.CONTENT_URI, cv);
}
// Returns a minimal version of an observation JSON (used to lower memory usage)
private JSONObject getMinimalObservation(JSONObject observation) {
JSONObject minimaldObs = new JSONObject();
try {
minimaldObs.put("id", observation.optInt("id"));
if (observation.has("votes") && !observation.isNull("votes")) minimaldObs.put("votes", observation.optJSONArray("votes"));
if (observation.has("observed_on") && !observation.isNull("observed_on")) minimaldObs.put("observed_on", observation.optString("observed_on"));
if (observation.has("location") && !observation.isNull("location")) minimaldObs.put("location", observation.optString("location"));
if (observation.has("photos") && !observation.isNull("photos")) {
minimaldObs.put("photo_count", observation.optJSONArray("photos").length());
} else {
minimaldObs.put("photo_count", 0);
}
if (observation.has("identifications") && !observation.isNull("identifications")) {
minimaldObs.put("identification_count", observation.optJSONArray("identifications").length());
} else {
minimaldObs.put("identification_count", 0);
}
if (observation.has("community_taxon") && !observation.isNull("community_taxon")) minimaldObs.put("community_taxon", observation.optJSONObject("community_taxon"));
} catch (JSONException e) {
Logger.tag(TAG).error(e);
return null;
}
return minimaldObs;
}
}
|
#1014 - crash fix
|
iNaturalist/src/main/java/org/inaturalist/android/ObservationViewerActivity.java
|
#1014 - crash fix
|
|
Java
|
mit
|
30e258dd736909ac05c9bdae18ec001fce002c6f
| 0
|
LonamiWebs/Stringlate,LonamiWebs/Stringlate,LonamiWebs/Stringlate
|
package io.github.lonamiwebs.stringlate.classes.repos;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Log;
import android.util.Pair;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InvalidObjectException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import io.github.lonamiwebs.stringlate.R;
import io.github.lonamiwebs.stringlate.classes.LocaleString;
import io.github.lonamiwebs.stringlate.classes.Messenger;
import io.github.lonamiwebs.stringlate.classes.resources.Resources;
import io.github.lonamiwebs.stringlate.classes.resources.ResourcesParser;
import io.github.lonamiwebs.stringlate.classes.resources.tags.ResTag;
import io.github.lonamiwebs.stringlate.git.GitWrapper;
import io.github.lonamiwebs.stringlate.interfaces.StringsSource;
import io.github.lonamiwebs.stringlate.settings.RepoSettings;
import io.github.lonamiwebs.stringlate.settings.SourceSettings;
import io.github.lonamiwebs.stringlate.utilities.Utils;
import io.github.lonamiwebs.stringlate.utilities.ZipUtils;
// Represents a locally saved string repository, which can be synchronized from any StringsSource
public class RepoHandler implements Comparable<RepoHandler> {
//region Members
private final Context mContext;
public final RepoSettings settings; // Public to avoid a lot of wrapper methods
private final SourceSettings mSourceSettings;
private final File mRoot;
private final File mProgressFile;
private final ArrayList<String> mLocales = new ArrayList<>();
private static final String BASE_DIR = "repos";
public static final String DEFAULT_LOCALE = "default";
//endregion
//region Constructors
public static RepoHandler fromBundle(Context context, Bundle bundle) {
return new RepoHandler(context, bundle.getString("source"));
}
public RepoHandler(Context context, final String source) {
mContext = context;
mRoot = new File(mContext.getFilesDir(), BASE_DIR + "/" + getId(source));
settings = new RepoSettings(mRoot);
settings.setSource(source);
mSourceSettings = new SourceSettings(mRoot);
settings.checkUpgradeSettingsToSpecific(mSourceSettings);
mProgressFile = new File(mRoot, "translation_progress.json");
loadLocales();
}
private RepoHandler(Context context, File root) {
mContext = context;
mRoot = root;
settings = new RepoSettings(mRoot);
mSourceSettings = new SourceSettings(mRoot);
settings.checkUpgradeSettingsToSpecific(mSourceSettings);
mProgressFile = new File(mRoot, "translation_progress.json");
loadLocales();
}
//endregion
//region Utilities
// Retrieves the File object for the given locale
private File getResourcesFile(@NonNull String locale) {
return new File(mRoot, locale + "/strings.xml");
}
private File getDefaultResourcesFile(@NonNull String filename) {
return new File(mRoot, DEFAULT_LOCALE + "/" + filename);
}
// An application may want to split their translations into several files. We
// can just save them as strings.xml, strings2.xml, strings3.xml... and save
// a map somewhere else to store "strings%d.xml -> original-path.xml".
private File getUniqueDefaultResourcesFile() {
File result = getDefaultResourcesFile("strings.xml");
if (result.isFile()) {
int i = 2;
while (result.isFile()) {
result = getDefaultResourcesFile("strings" + i + ".xml");
i++;
}
}
return result;
}
@NonNull
public File[] getDefaultResourcesFiles() {
File root = new File(mRoot, DEFAULT_LOCALE);
if (root.isDirectory()) {
File[] files = root.listFiles();
if (files != null)
return files;
}
return new File[0];
}
public boolean hasDefaultLocale() {
return getDefaultResourcesFiles().length > 0;
}
// Determines whether a given locale is saved or not
private boolean hasLocale(@NonNull String locale) {
return getResourcesFile(locale).isFile();
}
// Determines whether any file has been modified,
// i.e. it is not the original downloaded file any more.
// Note that previous modifications do NOT imply the file being unsaved.
public boolean anyModified() {
for (String locale : mLocales)
if (Resources.fromFile(getResourcesFile(locale)).wasModified())
return true;
return false;
}
// Determines whether the repository is empty (has no saved locales) or not
public boolean isEmpty() {
return mLocales.isEmpty();
}
// Deletes the repository erasing its existence from Earth. Forever. (Unless added again)
public boolean delete() {
boolean ok = Utils.deleteRecursive(mRoot);
Messenger.notifyRepoRemoved(this);
return ok;
}
private File getTempImportDir() {
return new File(mContext.getCacheDir(), "tmp_import");
}
private File getTempImportBackupDir() {
return new File(mContext.getCacheDir(), "tmp_import_backup");
}
private static String getId(String gitUrl) {
return Integer.toHexString(gitUrl.hashCode());
}
//endregion
//region Locales
//region Loading locale files
private void loadLocales() {
mLocales.clear();
if (mRoot.isDirectory()) {
for (File localeDir : mRoot.listFiles()) {
if (localeDir.isDirectory()) {
mLocales.add(localeDir.getName());
}
}
}
Collections.sort(mLocales, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return LocaleString.getDisplay(s1).compareTo(LocaleString.getDisplay(s2));
}
});
}
public ArrayList<String> getLocales() {
return mLocales;
}
//endregion
//region Creating and deleting locale files
public boolean createLocale(String locale) {
if (hasLocale(locale))
return true;
Resources resources = Resources.fromFile(getResourcesFile(locale));
if (!resources.save())
return false;
mLocales.add(locale);
return true;
}
public void deleteLocale(String locale) {
if (hasLocale(locale)) {
Resources.fromFile(getResourcesFile(locale)).delete();
mLocales.remove(locale);
}
}
//endregion
//region Downloading locale files
// Should be called from a background thread
public boolean syncResources(final StringsSource source,
final Messenger.OnRepoSyncProgress callback) {
if (!mSourceSettings.getName().equals(source.getName())) {
// if (!sourceName.isEmpty()) { ... }
// TODO Warn the user they're using a different source for the strings?
mSourceSettings.reset(source.getName());
}
final File tmpWorkDir = new File(mContext.getCacheDir(), "tmp_sync_" + mRoot.getName());
if (tmpWorkDir.isDirectory())
if (!Utils.deleteRecursive(tmpWorkDir))
return false;
if (!source.setup(mContext, mSourceSettings, tmpWorkDir, callback)) {
source.dispose();
return false;
}
callback.onUpdate(2, (0f / 3f));
// Delete all the previous default resources since their
// names might have changed, been removed, or some new added.
settings.clearRemotePaths();
for (File f : getDefaultResourcesFiles()) {
if (!f.delete()) {
source.dispose();
return false;
}
}
for (String locale : source.getLocales()) {
if (locale == null)
continue; // Should not happen
// Load in memory the old saved resources. We need to work
// on this file because we're going to be merging changes.
Resources resources = loadResources(locale);
// Add new translated tags without overwriting existing ones
for (ResTag rt : source.getResources(locale))
if (!resources.wasModified(rt.getId()))
resources.addTag(rt);
// Save the changes
resources.save();
}
callback.onUpdate(2, (1f / 3f));
// Default resources are treated specially, since their name matters. The name for
// non-default resources doesn't because it can be inferred from defaults' (for now).
for (String originalName : source.getDefaultResources()) {
boolean okay;
final File resourceFile = getUniqueDefaultResourcesFile();
final String xml = source.getDefaultResourceXml(originalName);
if (xml == null) {
// We don't know how the original XML looked like, that's okay
final Resources resources = Resources.fromFile(resourceFile);
for (ResTag rt : source.getDefaultResource(originalName))
resources.addTag(rt); // Copy the resources to the new local file
okay = resources.save();
} else {
// We have the original XML available, so clean it up and preserve its structure
okay = ResourcesParser.cleanXml(xml, resourceFile);
}
if (okay) {
// Save the map unique -> original since this is a valid file
settings.addRemotePath(resourceFile.getName(), originalName);
} else {
// Something went wrong, either saving, cleaning the XML, or it has no strings
// Clean up the file we may have made, if it exists, or give up if it fails
if (resourceFile.isFile()) {
if (!resourceFile.delete()) {
source.dispose();
return false;
}
}
}
}
callback.onUpdate(2, (2f / 3f));
// Check out if we have any icon for this repository
File icon = source.getIcon();
if (icon != null) {
// We have an icon to show, copy it to our repository root
// and save it's path (we must keep track of the used extension)
File newIcon = new File(mRoot, icon.getName());
if (!newIcon.isFile() || newIcon.delete()) {
if (icon.renameTo(newIcon)) // TODO Do NOT rename the icon, rather copy it
settings.setIconFile(newIcon);
}
}
// Clean old unused strings which now don't exist on the default resources files
unusedStringsCleanup();
source.dispose(); // Clean resources
loadLocales(); // Reload the locales
callback.onUpdate(2, (3f / 3f));
return true;
}
private void unusedStringsCleanup() {
final Resources defaultResources = loadDefaultResources();
for (String locale : getLocales()) {
if (locale.equals(DEFAULT_LOCALE))
continue;
final Resources resources = loadResources(locale);
// Find those which we need to remove (we can't remove them right
// away unless with used an Iterator<ResTag>, but this also works)
final ArrayList<String> toRemove = new ArrayList<>();
for (ResTag rt : resources)
if (!defaultResources.contains(rt.getId()))
toRemove.add(rt.getId());
// Do remove the unused strings and save
for (String remove : toRemove)
resources.deleteId(remove);
resources.save();
}
}
//endregion
//region Loading resources
public Resources loadDefaultResources() {
// Mix up all the resource files into one
Resources resources = Resources.empty();
for (File f : getDefaultResourcesFiles()) {
for (ResTag rt : Resources.fromFile(f)) {
resources.addTag(rt);
}
}
return resources;
}
public Resources loadResources(@NonNull String locale) {
return Resources.fromFile(getResourcesFile(locale));
}
@NonNull
// Returns "" if the template wasn't applied successfully
// TODO Handle the above case more gracefully, display a toast error maybe
public String applyTemplate(File template, String locale) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
if (applyTemplate(template, locale, out))
return out.toString();
else
return "";
}
// Returns TRUE if the template can be applied.
// This means that if for the given template there is no available
// string on the given locale, the apply cannot be applied since
// there will be no strings to replace.
public boolean canApplyTemplate(File template, String locale) {
if (hasLocale(locale) && template.isFile()) {
Resources templateResources = Resources.fromFile(template);
Resources localeResources = loadResources(locale);
for (ResTag rt : localeResources)
if (templateResources.contains(rt.getId()))
return true;
}
return false;
}
// TODO Why do I load the resources all the time - can't I just pass the loaded one?
// Returns TRUE if the template was applied successfully
public boolean applyTemplate(File template, String locale, OutputStream out) {
return hasLocale(locale) &&
template.isFile() &&
ResourcesParser.applyTemplate(template, loadResources(locale), out);
}
@NonNull
public String mergeDefaultTemplate(String locale) {
// TODO What should we do if any fails? How can it even fail? No translations for a file?
File[] files = getDefaultResourcesFiles();
if (files.length > 1) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
for (File template : files) {
String header = mContext.getString(R.string.xml_comment_filename, template.getName());
try {
out.write(header.getBytes());
applyTemplate(template, locale, out);
out.write("\n".getBytes());
} catch (IOException ignored) {
}
}
return out.toString();
} else {
return applyTemplate(files[0], locale);
}
}
//endregion
//endregion
//region Static repository listing
public static ArrayList<RepoHandler> listRepositories(Context context) {
ArrayList<RepoHandler> repositories = new ArrayList<>();
File root = new File(context.getFilesDir(), BASE_DIR);
if (root.isDirectory()) {
for (File f : root.listFiles()) {
if (isValidRepoDir(f)) {
repositories.add(new RepoHandler(context, f));
}
}
}
return repositories;
}
private static boolean isValidRepoDir(File dir) {
return dir.isDirectory() && RepoSettings.exists(dir);
}
//endregion
//region Settings
@NonNull
public String getSourceName() {
return mSourceSettings.getName();
}
public boolean isGitHubRepository() {
if (!mSourceSettings.getName().equals("git"))
return false;
try {
GitWrapper.getGitHubOwnerRepo(settings.getSource());
return true;
} catch (InvalidObjectException ignored) {
return false;
}
}
public boolean hasRemoteUrls() {
return mSourceSettings.getName().equals("git") &&
getDefaultResourcesFiles().length == settings.getRemotePaths().size();
}
// Return a map consisting of (default local resources/templates, remote path)
// and replacing the "values" by the corresponding "values-xx"
public HashMap<File, String> getTemplateRemotePaths(String locale) {
HashMap<File, String> result = new HashMap<>();
HashMap<String, String> fileRemote = settings.getRemotePaths();
for (Map.Entry<String, String> fr : fileRemote.entrySet()) {
File template = getDefaultResourcesFile(fr.getKey());
String remote = fr.getValue().replace("/values/", "/values-" + locale + "/");
result.put(template, remote);
}
return result;
}
@NonNull
public String getUsedTranslationService() {
final String result = (String)mSourceSettings.get("translation_service");
return result == null ? "" : result;
}
@NonNull
public ArrayList<String> getRemoteBranches() {
if (getSourceName().equals("git")) {
return mSourceSettings.getArray("remote_branches");
} else {
return new ArrayList<>();
}
}
// Used to save the translation progress, calculated on the
// TranslateActivity, to quickly reuse it on the history screen
public boolean saveProgress(RepoProgress progress) {
try {
return Utils.writeFile(mProgressFile, progress.toJson().toString());
} catch (JSONException e) {
e.printStackTrace();
return false;
}
}
// Gets the progress of the last calculated progress locale
public RepoProgress loadProgress() {
try {
final String json = Utils.readFile(mProgressFile);
if (!json.isEmpty())
return RepoProgress.fromJson(new JSONObject(json));
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
//endregion
//region To other objects
@Override
public String toString() {
// https:// part is a bit redundant, also omit the `.git` part if it exists
String url = settings.getSource();
try {
int end = url.endsWith(".git") ? url.lastIndexOf('.') : url.length();
return url.substring(url.indexOf("://") + 3, end);
} catch (StringIndexOutOfBoundsException e) {
Log.w("RepoHandler", "Please report that \"" + url + "\" got somehow saved…");
return url; // We must have a really weird url. Maybe saved invalid repo somehow?
}
}
public String getHost() {
String url = settings.getSource();
try {
return new URL(url).getHost();
} catch (MalformedURLException e) {
// Should never happen
e.printStackTrace();
}
return url;
}
public String getPath() {
String url = settings.getSource();
try {
String path = new URL(url).getPath();
int end = path.endsWith(".git") ? path.lastIndexOf('.') : path.length();
return path.substring(0, end);
} catch (MalformedURLException e) {
// Should never happen
e.printStackTrace();
}
return url;
}
public String getProjectName() {
String name = settings.getProjectName();
if (name.isEmpty()) {
name = nameFromSource(settings.getSource());
settings.setProjectName(name);
}
return name;
}
private static String nameFromSource(String source) {
int slash = source.lastIndexOf('/');
if (slash < 0)
return source; // Should not happen
source = source.substring(slash + 1);
int dot = source.lastIndexOf('.');
if (dot >= 0)
source = source.substring(0, dot);
return source;
}
public String toOwnerRepo() throws InvalidObjectException {
Pair<String, String> pair = GitWrapper.getGitHubOwnerRepo(settings.getSource());
return String.format("%s/%s", pair.first, pair.second);
}
public Bundle toBundle() {
Bundle result = new Bundle();
result.putString("source", settings.getSource());
return result;
}
//endregion
//region Interface implementations
@Override
public int compareTo(@NonNull RepoHandler o) {
return toString().compareTo(o.toString());
}
@Override
public boolean equals(Object obj) {
return this == obj ||
(obj instanceof RepoHandler && mRoot.equals(((RepoHandler) obj).mRoot));
}
//endregion
//region Backwards-compatible code
public static boolean checkUpgradeRepositories(Context context) {
// The regex used to match for 'strings-locale.xml' files
Pattern localesPattern = Pattern.compile("strings(?:-([\\w-]+))?\\.xml");
File root = new File(context.getFilesDir(), BASE_DIR);
if (!root.isDirectory()) {
// The user never used Stringlate
return true;
}
boolean allOk = true;
for (File owner : root.listFiles()) {
if (isValidRepoDir(owner)) {
// Skip repositories which are valid - these don't need to be converted
continue;
}
for (File repository : owner.listFiles()) {
if (!repository.isDirectory()) {
// If this is not a directory, whatever it is, is not valid
continue;
}
// We now have a valid old repository.
// The first step is to create a new instance so the settings get created
RepoHandler repo = new RepoHandler(context,
GitWrapper.buildGitHubUrl(owner.getName(), repository.getName()));
// The second step is to scan the files under 'repository'
// These will be named 'strings-locale.xml'
for (File strings : repository.listFiles()) {
Matcher m = localesPattern.matcher(strings.getName());
if (m.matches()) {
// Retrieve the locale and copy it to the new location
if (m.group(1) == null) {
// Default locale. Make sure to clean it too. Since only
// strings.xml files were supported, assume this is the name
File newStrings = repo.getDefaultResourcesFile("strings.xml");
ResourcesParser.cleanXml(strings, newStrings);
} else {
String locale = m.group(1);
File newStrings = repo.getResourcesFile(locale);
// Ensure the parent directory exists before moving the file
if (!newStrings.getParentFile().isDirectory())
allOk &= newStrings.getParentFile().mkdirs();
allOk &= strings.renameTo(newStrings);
}
}
if (strings.isFile()) {
// After we're done processing the file, delete it
allOk &= strings.delete();
}
}
// After we're done processing the whole repository, delete it
allOk &= repository.delete();
}
// After we're done processing all the repositories from this owner, delete it
allOk &= owner.delete();
}
return allOk;
}
//endregion
//region Importing and exporting
public void importZip(InputStream inputStream) {
try {
// Get temporary import directory and delete any previous directory
File dir = getTempImportDir();
File backupDir = getTempImportBackupDir();
if (!Utils.deleteRecursive(dir) || !Utils.deleteRecursive(backupDir))
throw new IOException("Could not delete old temporary directories.");
// Unzip the given input stream
ZipUtils.unzipRecursive(inputStream, dir);
// Ensure it's a valid repository (only one parent directory, containing settings)
final File[] unzippedFiles = dir.listFiles();
if (unzippedFiles == null || unzippedFiles.length != 1)
throw new IOException("There should only be 1 unzipped file (the repository's root).");
final File root = unzippedFiles[0];
if (!RepoSettings.exists(root))
throw new IOException("The specified .zip file does not seem valid.");
// Nice, unzipping worked. Now try moving the current repository
// to yet another temporary location, because we don't want to lose
// it in case something goes wrong and we need to revert…
if (!mRoot.renameTo(backupDir))
throw new IOException("Could not move the current repository to its backup location.");
if (!root.renameTo(mRoot)) {
// Try reverting the state, hopefully no data was lost
String extra = backupDir.renameTo(mRoot) ? "" : " Failed to recover its previous state.";
throw new IOException("Could not move the temporary repository to its new location." + extra);
}
Messenger.notifyRepoAdded(this);
} catch (IOException e) {
e.printStackTrace();
}
}
public void exportZip(OutputStream output) {
try {
ZipUtils.zipFolder(mRoot, output);
} catch (IOException e) {
e.printStackTrace();
}
}
//endregion
}
|
src/app/src/main/java/io/github/lonamiwebs/stringlate/classes/repos/RepoHandler.java
|
package io.github.lonamiwebs.stringlate.classes.repos;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Log;
import android.util.Pair;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InvalidObjectException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import io.github.lonamiwebs.stringlate.R;
import io.github.lonamiwebs.stringlate.classes.LocaleString;
import io.github.lonamiwebs.stringlate.classes.Messenger;
import io.github.lonamiwebs.stringlate.classes.resources.Resources;
import io.github.lonamiwebs.stringlate.classes.resources.ResourcesParser;
import io.github.lonamiwebs.stringlate.classes.resources.tags.ResTag;
import io.github.lonamiwebs.stringlate.git.GitWrapper;
import io.github.lonamiwebs.stringlate.interfaces.StringsSource;
import io.github.lonamiwebs.stringlate.settings.RepoSettings;
import io.github.lonamiwebs.stringlate.settings.SourceSettings;
import io.github.lonamiwebs.stringlate.utilities.Utils;
import io.github.lonamiwebs.stringlate.utilities.ZipUtils;
// Represents a locally saved string repository, which can be synchronized from any StringsSource
public class RepoHandler implements Comparable<RepoHandler> {
//region Members
private final Context mContext;
public final RepoSettings settings; // Public to avoid a lot of wrapper methods
private final SourceSettings mSourceSettings;
private final File mRoot;
private final File mProgressFile;
private final ArrayList<String> mLocales = new ArrayList<>();
private static final String BASE_DIR = "repos";
public static final String DEFAULT_LOCALE = "default";
//endregion
//region Constructors
public static RepoHandler fromBundle(Context context, Bundle bundle) {
return new RepoHandler(context, bundle.getString("source"));
}
public RepoHandler(Context context, final String source) {
mContext = context;
mRoot = new File(mContext.getFilesDir(), BASE_DIR + "/" + getId(source));
settings = new RepoSettings(mRoot);
settings.setSource(source);
mSourceSettings = new SourceSettings(mRoot);
settings.checkUpgradeSettingsToSpecific(mSourceSettings);
mProgressFile = new File(mRoot, "translation_progress.json");
loadLocales();
}
private RepoHandler(Context context, File root) {
mContext = context;
mRoot = root;
settings = new RepoSettings(mRoot);
mSourceSettings = new SourceSettings(mRoot);
settings.checkUpgradeSettingsToSpecific(mSourceSettings);
mProgressFile = new File(mRoot, "translation_progress.json");
loadLocales();
}
//endregion
//region Utilities
// Retrieves the File object for the given locale
private File getResourcesFile(@NonNull String locale) {
return new File(mRoot, locale + "/strings.xml");
}
private File getDefaultResourcesFile(@NonNull String filename) {
return new File(mRoot, DEFAULT_LOCALE + "/" + filename);
}
// An application may want to split their translations into several files. We
// can just save them as strings.xml, strings2.xml, strings3.xml... and save
// a map somewhere else to store "strings%d.xml -> original-path.xml".
private File getUniqueDefaultResourcesFile() {
File result = getDefaultResourcesFile("strings.xml");
if (result.isFile()) {
int i = 2;
while (result.isFile()) {
result = getDefaultResourcesFile("strings" + i + ".xml");
i++;
}
}
return result;
}
@NonNull
public File[] getDefaultResourcesFiles() {
File root = new File(mRoot, DEFAULT_LOCALE);
if (root.isDirectory()) {
File[] files = root.listFiles();
if (files != null)
return files;
}
return new File[0];
}
public boolean hasDefaultLocale() {
return getDefaultResourcesFiles().length > 0;
}
// Determines whether a given locale is saved or not
private boolean hasLocale(@NonNull String locale) {
return getResourcesFile(locale).isFile();
}
// Determines whether any file has been modified,
// i.e. it is not the original downloaded file any more.
// Note that previous modifications do NOT imply the file being unsaved.
public boolean anyModified() {
for (String locale : mLocales)
if (Resources.fromFile(getResourcesFile(locale)).wasModified())
return true;
return false;
}
// Determines whether the repository is empty (has no saved locales) or not
public boolean isEmpty() {
return mLocales.isEmpty();
}
// Deletes the repository erasing its existence from Earth. Forever. (Unless added again)
public boolean delete() {
boolean ok = Utils.deleteRecursive(mRoot);
Messenger.notifyRepoRemoved(this);
return ok;
}
private File getTempImportDir() {
return new File(mContext.getCacheDir(), "tmp_import");
}
private File getTempImportBackupDir() {
return new File(mContext.getCacheDir(), "tmp_import_backup");
}
private static String getId(String gitUrl) {
return Integer.toHexString(gitUrl.hashCode());
}
//endregion
//region Locales
//region Loading locale files
private void loadLocales() {
mLocales.clear();
if (mRoot.isDirectory()) {
for (File localeDir : mRoot.listFiles()) {
if (localeDir.isDirectory()) {
mLocales.add(localeDir.getName());
}
}
}
Collections.sort(mLocales, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return LocaleString.getDisplay(s1).compareTo(LocaleString.getDisplay(s2));
}
});
}
public ArrayList<String> getLocales() {
return mLocales;
}
//endregion
//region Creating and deleting locale files
public boolean createLocale(String locale) {
if (hasLocale(locale))
return true;
Resources resources = Resources.fromFile(getResourcesFile(locale));
if (!resources.save())
return false;
mLocales.add(locale);
return true;
}
public void deleteLocale(String locale) {
if (hasLocale(locale)) {
Resources.fromFile(getResourcesFile(locale)).delete();
mLocales.remove(locale);
}
}
//endregion
//region Downloading locale files
// Should be called from a background thread
public boolean syncResources(final StringsSource source,
final Messenger.OnRepoSyncProgress callback) {
if (!mSourceSettings.getName().equals(source.getName())) {
// if (!sourceName.isEmpty()) { ... }
// TODO Warn the user they're using a different source for the strings?
mSourceSettings.reset(source.getName());
}
final File tmpWorkDir = new File(mContext.getCacheDir(), "tmp_sync_" + mRoot.getName());
if (tmpWorkDir.isDirectory())
if (!Utils.deleteRecursive(tmpWorkDir))
return false;
if (!source.setup(mContext, mSourceSettings, tmpWorkDir, callback)) {
source.dispose();
delete(); // Delete settings
}
callback.onUpdate(2, (0f / 3f));
// Delete all the previous default resources since their
// names might have changed, been removed, or some new added.
settings.clearRemotePaths();
for (File f : getDefaultResourcesFiles())
if (!f.delete())
return false;
for (String locale : source.getLocales()) {
if (locale == null)
continue; // Should not happen
// Load in memory the old saved resources. We need to work
// on this file because we're going to be merging changes.
Resources resources = loadResources(locale);
// Add new translated tags without overwriting existing ones
for (ResTag rt : source.getResources(locale))
if (!resources.wasModified(rt.getId()))
resources.addTag(rt);
// Save the changes
resources.save();
}
callback.onUpdate(2, (1f / 3f));
// Default resources are treated specially, since their name matters. The name for
// non-default resources doesn't because it can be inferred from defaults' (for now).
for (String originalName : source.getDefaultResources()) {
boolean okay;
final File resourceFile = getUniqueDefaultResourcesFile();
final String xml = source.getDefaultResourceXml(originalName);
if (xml == null) {
// We don't know how the original XML looked like, that's okay
final Resources resources = Resources.fromFile(resourceFile);
for (ResTag rt : source.getDefaultResource(originalName))
resources.addTag(rt); // Copy the resources to the new local file
okay = resources.save();
} else {
// We have the original XML available, so clean it up and preserve its structure
okay = ResourcesParser.cleanXml(xml, resourceFile);
}
if (okay) {
// Save the map unique -> original since this is a valid file
settings.addRemotePath(resourceFile.getName(), originalName);
} else {
// Something went wrong, either saving, cleaning the XML, or it has no strings
// Clean up the file we may have made, if it exists, or give up if it fails
if (resourceFile.isFile())
if (!resourceFile.delete())
return false;
}
}
callback.onUpdate(2, (2f / 3f));
// Check out if we have any icon for this repository
File icon = source.getIcon();
if (icon != null) {
// We have an icon to show, copy it to our repository root
// and save it's path (we must keep track of the used extension)
File newIcon = new File(mRoot, icon.getName());
if (!newIcon.isFile() || newIcon.delete()) {
if (icon.renameTo(newIcon)) // TODO Do NOT rename the icon, rather copy it
settings.setIconFile(newIcon);
}
}
// Clean old unused strings which now don't exist on the default resources files
unusedStringsCleanup();
source.dispose(); // Clean resources
loadLocales(); // Reload the locales
callback.onUpdate(2, (3f / 3f));
return true;
}
private void unusedStringsCleanup() {
final Resources defaultResources = loadDefaultResources();
for (String locale : getLocales()) {
if (locale.equals(DEFAULT_LOCALE))
continue;
final Resources resources = loadResources(locale);
// Find those which we need to remove (we can't remove them right
// away unless with used an Iterator<ResTag>, but this also works)
final ArrayList<String> toRemove = new ArrayList<>();
for (ResTag rt : resources)
if (!defaultResources.contains(rt.getId()))
toRemove.add(rt.getId());
// Do remove the unused strings and save
for (String remove : toRemove)
resources.deleteId(remove);
resources.save();
}
}
//endregion
//region Loading resources
public Resources loadDefaultResources() {
// Mix up all the resource files into one
Resources resources = Resources.empty();
for (File f : getDefaultResourcesFiles()) {
for (ResTag rt : Resources.fromFile(f)) {
resources.addTag(rt);
}
}
return resources;
}
public Resources loadResources(@NonNull String locale) {
return Resources.fromFile(getResourcesFile(locale));
}
@NonNull
// Returns "" if the template wasn't applied successfully
// TODO Handle the above case more gracefully, display a toast error maybe
public String applyTemplate(File template, String locale) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
if (applyTemplate(template, locale, out))
return out.toString();
else
return "";
}
// Returns TRUE if the template can be applied.
// This means that if for the given template there is no available
// string on the given locale, the apply cannot be applied since
// there will be no strings to replace.
public boolean canApplyTemplate(File template, String locale) {
if (hasLocale(locale) && template.isFile()) {
Resources templateResources = Resources.fromFile(template);
Resources localeResources = loadResources(locale);
for (ResTag rt : localeResources)
if (templateResources.contains(rt.getId()))
return true;
}
return false;
}
// TODO Why do I load the resources all the time - can't I just pass the loaded one?
// Returns TRUE if the template was applied successfully
public boolean applyTemplate(File template, String locale, OutputStream out) {
return hasLocale(locale) &&
template.isFile() &&
ResourcesParser.applyTemplate(template, loadResources(locale), out);
}
@NonNull
public String mergeDefaultTemplate(String locale) {
// TODO What should we do if any fails? How can it even fail? No translations for a file?
File[] files = getDefaultResourcesFiles();
if (files.length > 1) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
for (File template : files) {
String header = mContext.getString(R.string.xml_comment_filename, template.getName());
try {
out.write(header.getBytes());
applyTemplate(template, locale, out);
out.write("\n".getBytes());
} catch (IOException ignored) {
}
}
return out.toString();
} else {
return applyTemplate(files[0], locale);
}
}
//endregion
//endregion
//region Static repository listing
public static ArrayList<RepoHandler> listRepositories(Context context) {
ArrayList<RepoHandler> repositories = new ArrayList<>();
File root = new File(context.getFilesDir(), BASE_DIR);
if (root.isDirectory()) {
for (File f : root.listFiles()) {
if (isValidRepoDir(f)) {
repositories.add(new RepoHandler(context, f));
}
}
}
return repositories;
}
private static boolean isValidRepoDir(File dir) {
return dir.isDirectory() && RepoSettings.exists(dir);
}
//endregion
//region Settings
@NonNull
public String getSourceName() {
return mSourceSettings.getName();
}
public boolean isGitHubRepository() {
if (!mSourceSettings.getName().equals("git"))
return false;
try {
GitWrapper.getGitHubOwnerRepo(settings.getSource());
return true;
} catch (InvalidObjectException ignored) {
return false;
}
}
public boolean hasRemoteUrls() {
return mSourceSettings.getName().equals("git") &&
getDefaultResourcesFiles().length == settings.getRemotePaths().size();
}
// Return a map consisting of (default local resources/templates, remote path)
// and replacing the "values" by the corresponding "values-xx"
public HashMap<File, String> getTemplateRemotePaths(String locale) {
HashMap<File, String> result = new HashMap<>();
HashMap<String, String> fileRemote = settings.getRemotePaths();
for (Map.Entry<String, String> fr : fileRemote.entrySet()) {
File template = getDefaultResourcesFile(fr.getKey());
String remote = fr.getValue().replace("/values/", "/values-" + locale + "/");
result.put(template, remote);
}
return result;
}
@NonNull
public String getUsedTranslationService() {
final String result = (String)mSourceSettings.get("translation_service");
return result == null ? "" : result;
}
@NonNull
public ArrayList<String> getRemoteBranches() {
if (getSourceName().equals("git")) {
return mSourceSettings.getArray("remote_branches");
} else {
return new ArrayList<>();
}
}
// Used to save the translation progress, calculated on the
// TranslateActivity, to quickly reuse it on the history screen
public boolean saveProgress(RepoProgress progress) {
try {
return Utils.writeFile(mProgressFile, progress.toJson().toString());
} catch (JSONException e) {
e.printStackTrace();
return false;
}
}
// Gets the progress of the last calculated progress locale
public RepoProgress loadProgress() {
try {
final String json = Utils.readFile(mProgressFile);
if (!json.isEmpty())
return RepoProgress.fromJson(new JSONObject(json));
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
//endregion
//region To other objects
@Override
public String toString() {
// https:// part is a bit redundant, also omit the `.git` part if it exists
String url = settings.getSource();
try {
int end = url.endsWith(".git") ? url.lastIndexOf('.') : url.length();
return url.substring(url.indexOf("://") + 3, end);
} catch (StringIndexOutOfBoundsException e) {
Log.w("RepoHandler", "Please report that \"" + url + "\" got somehow saved…");
return url; // We must have a really weird url. Maybe saved invalid repo somehow?
}
}
public String getHost() {
String url = settings.getSource();
try {
return new URL(url).getHost();
} catch (MalformedURLException e) {
// Should never happen
e.printStackTrace();
}
return url;
}
public String getPath() {
String url = settings.getSource();
try {
String path = new URL(url).getPath();
int end = path.endsWith(".git") ? path.lastIndexOf('.') : path.length();
return path.substring(0, end);
} catch (MalformedURLException e) {
// Should never happen
e.printStackTrace();
}
return url;
}
public String getProjectName() {
String name = settings.getProjectName();
if (name.isEmpty()) {
name = nameFromSource(settings.getSource());
settings.setProjectName(name);
}
return name;
}
private static String nameFromSource(String source) {
int slash = source.lastIndexOf('/');
if (slash < 0)
return source; // Should not happen
source = source.substring(slash + 1);
int dot = source.lastIndexOf('.');
if (dot >= 0)
source = source.substring(0, dot);
return source;
}
public String toOwnerRepo() throws InvalidObjectException {
Pair<String, String> pair = GitWrapper.getGitHubOwnerRepo(settings.getSource());
return String.format("%s/%s", pair.first, pair.second);
}
public Bundle toBundle() {
Bundle result = new Bundle();
result.putString("source", settings.getSource());
return result;
}
//endregion
//region Interface implementations
@Override
public int compareTo(@NonNull RepoHandler o) {
return toString().compareTo(o.toString());
}
@Override
public boolean equals(Object obj) {
return this == obj ||
(obj instanceof RepoHandler && mRoot.equals(((RepoHandler) obj).mRoot));
}
//endregion
//region Backwards-compatible code
public static boolean checkUpgradeRepositories(Context context) {
// The regex used to match for 'strings-locale.xml' files
Pattern localesPattern = Pattern.compile("strings(?:-([\\w-]+))?\\.xml");
File root = new File(context.getFilesDir(), BASE_DIR);
if (!root.isDirectory()) {
// The user never used Stringlate
return true;
}
boolean allOk = true;
for (File owner : root.listFiles()) {
if (isValidRepoDir(owner)) {
// Skip repositories which are valid - these don't need to be converted
continue;
}
for (File repository : owner.listFiles()) {
if (!repository.isDirectory()) {
// If this is not a directory, whatever it is, is not valid
continue;
}
// We now have a valid old repository.
// The first step is to create a new instance so the settings get created
RepoHandler repo = new RepoHandler(context,
GitWrapper.buildGitHubUrl(owner.getName(), repository.getName()));
// The second step is to scan the files under 'repository'
// These will be named 'strings-locale.xml'
for (File strings : repository.listFiles()) {
Matcher m = localesPattern.matcher(strings.getName());
if (m.matches()) {
// Retrieve the locale and copy it to the new location
if (m.group(1) == null) {
// Default locale. Make sure to clean it too. Since only
// strings.xml files were supported, assume this is the name
File newStrings = repo.getDefaultResourcesFile("strings.xml");
ResourcesParser.cleanXml(strings, newStrings);
} else {
String locale = m.group(1);
File newStrings = repo.getResourcesFile(locale);
// Ensure the parent directory exists before moving the file
if (!newStrings.getParentFile().isDirectory())
allOk &= newStrings.getParentFile().mkdirs();
allOk &= strings.renameTo(newStrings);
}
}
if (strings.isFile()) {
// After we're done processing the file, delete it
allOk &= strings.delete();
}
}
// After we're done processing the whole repository, delete it
allOk &= repository.delete();
}
// After we're done processing all the repositories from this owner, delete it
allOk &= owner.delete();
}
return allOk;
}
//endregion
//region Importing and exporting
public void importZip(InputStream inputStream) {
try {
// Get temporary import directory and delete any previous directory
File dir = getTempImportDir();
File backupDir = getTempImportBackupDir();
if (!Utils.deleteRecursive(dir) || !Utils.deleteRecursive(backupDir))
throw new IOException("Could not delete old temporary directories.");
// Unzip the given input stream
ZipUtils.unzipRecursive(inputStream, dir);
// Ensure it's a valid repository (only one parent directory, containing settings)
final File[] unzippedFiles = dir.listFiles();
if (unzippedFiles == null || unzippedFiles.length != 1)
throw new IOException("There should only be 1 unzipped file (the repository's root).");
final File root = unzippedFiles[0];
if (!RepoSettings.exists(root))
throw new IOException("The specified .zip file does not seem valid.");
// Nice, unzipping worked. Now try moving the current repository
// to yet another temporary location, because we don't want to lose
// it in case something goes wrong and we need to revert…
if (!mRoot.renameTo(backupDir))
throw new IOException("Could not move the current repository to its backup location.");
if (!root.renameTo(mRoot)) {
// Try reverting the state, hopefully no data was lost
String extra = backupDir.renameTo(mRoot) ? "" : " Failed to recover its previous state.";
throw new IOException("Could not move the temporary repository to its new location." + extra);
}
Messenger.notifyRepoAdded(this);
} catch (IOException e) {
e.printStackTrace();
}
}
public void exportZip(OutputStream output) {
try {
ZipUtils.zipFolder(mRoot, output);
} catch (IOException e) {
e.printStackTrace();
}
}
//endregion
}
|
Do not delete the whole, potentially previous, repository on a fail
|
src/app/src/main/java/io/github/lonamiwebs/stringlate/classes/repos/RepoHandler.java
|
Do not delete the whole, potentially previous, repository on a fail
|
|
Java
|
mit
|
453b336cc71adb7641bdcc5f1b41491ad4c453e1
| 0
|
nevercast/OpenModsLib,OpenMods/OpenModsLib,OpenMods/OpenModsLib
|
package openmods.utils;
import java.util.*;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.ISidedInventory;
import net.minecraft.inventory.InventoryLargeChest;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityChest;
import net.minecraft.world.World;
import net.minecraftforge.common.ForgeDirection;
import openmods.GenericInventory;
import openmods.integration.Integration;
import openmods.sync.SyncableFlags;
import com.google.common.collect.Lists;
public class InventoryUtils {
/***
* Try to merge the supplied stack into the supplied slot in the target
* inventory
*
* @param targetInventory
* Although it doesn't return anything, it'll REDUCE the stack
* size of the stack that you pass in
*
* @param slot
* @param stack
*/
public static void tryMergeStacks(IInventory targetInventory, int slot, ItemStack stack) {
if (targetInventory.isItemValidForSlot(slot, stack)) {
ItemStack targetStack = targetInventory.getStackInSlot(slot);
if (targetStack == null) {
targetInventory.setInventorySlotContents(slot, stack.copy());
stack.stackSize = 0;
} else {
if (targetInventory.isItemValidForSlot(slot, stack) &&
areMergeCandidates(stack, targetStack)) {
int space = targetStack.getMaxStackSize()
- targetStack.stackSize;
int mergeAmount = Math.min(space, stack.stackSize);
ItemStack copy = targetStack.copy();
copy.stackSize += mergeAmount;
targetInventory.setInventorySlotContents(slot, copy);
stack.stackSize -= mergeAmount;
}
}
}
}
protected static boolean areMergeCandidates(ItemStack source, ItemStack target) {
return source.isItemEqual(target)
&& ItemStack.areItemStackTagsEqual(source, target)
&& target.stackSize < target.getMaxStackSize();
}
public static void insertItemIntoInventory(IInventory inventory, ItemStack stack) {
insertItemIntoInventory(inventory, stack, ForgeDirection.UNKNOWN, -1);
}
public static void insertItemIntoInventory(IInventory inventory, ItemStack stack, ForgeDirection side, int intoSlot) {
insertItemIntoInventory(inventory, stack, side, intoSlot, true);
}
/***
* Insert the stack into the target inventory. Pass -1 if you don't care
* which slot
*
* @param inventory
* @param stack
* @param side
* The side of the block you're inserting into
*/
public static void insertItemIntoInventory(IInventory inventory, ItemStack stack, ForgeDirection side, int intoSlot, boolean doMove) {
if (stack == null) { return; }
IInventory targetInventory = inventory;
// if we're not meant to move, make a clone of the inventory
if (!doMove) {
targetInventory = new GenericInventory("temporary.inventory", false, targetInventory.getSizeInventory());
((GenericInventory)targetInventory).copyFrom(inventory);
}
int i = 0;
int[] attemptSlots = new int[0];
// if it's a sided inventory, get all the accessible slots
if (inventory instanceof ISidedInventory
&& side != ForgeDirection.UNKNOWN) {
attemptSlots = ((ISidedInventory)inventory).getAccessibleSlotsFromSide(side.ordinal());
if (attemptSlots == null) {
attemptSlots = new int[0];
}
} else {
// if it's just a standard inventory, get all slots
attemptSlots = new int[inventory.getSizeInventory()];
for (int a = 0; a < inventory.getSizeInventory(); a++) {
attemptSlots[a] = a;
}
}
// if we've defining a specific slot, we'll just use that
if (intoSlot > -1) {
Set<Integer> x = new HashSet<Integer>();
for (int attemptedSlot : attemptSlots) {
x.add(attemptedSlot);
}
if (x.contains(intoSlot)) {
attemptSlots = new int[] { intoSlot };
} else {
attemptSlots = new int[0];
}
}
while (stack.stackSize > 0 && i < attemptSlots.length) {
if (side != ForgeDirection.UNKNOWN
&& inventory instanceof ISidedInventory) {
if (!((ISidedInventory)inventory).canInsertItem(intoSlot, stack, side.ordinal())) {
i++;
continue;
}
}
tryMergeStacks(targetInventory, attemptSlots[i], stack);
i++;
}
}
/***
* Move an item from the fromInventory, into the target. The target can be
* an inventory or pipe.
* Double checks are automagically wrapped. If you're not bothered what slot
* you insert into,
* pass -1 for intoSlot. If you're passing false for doMove, it'll create a
* dummy inventory and
* make its calculations on that instead
*
* @param fromInventory
* the inventory the item is coming from
* @param fromSlot
* the slot the item is coming from
* @param target
* the inventory you want the item to be put into. can be BC pipe
* or IInventory
* @param intoSlot
* the target slot. Pass -1 for any slot
* @param maxAmount
* The maximum amount you wish to pass
* @param direction
* The direction of the move. Pass UNKNOWN if not applicable
* @param doMove
* @return The amount of items moved
*/
public static int moveItemInto(IInventory fromInventory, int fromSlot, Object target, int intoSlot, int maxAmount, ForgeDirection direction, boolean doMove) {
fromInventory = InventoryUtils.getInventory(fromInventory);
// if we dont have a stack in the source location, return 0
ItemStack sourceStack = fromInventory.getStackInSlot(fromSlot);
if (sourceStack == null) { return 0; }
if (fromInventory instanceof ISidedInventory
&& !((ISidedInventory)fromInventory).canExtractItem(fromSlot, sourceStack, direction.ordinal())) { return 0; }
// create a clone of our source stack and set the size to either
// maxAmount or the stackSize
ItemStack clonedSourceStack = sourceStack.copy();
clonedSourceStack.stackSize = Math.min(clonedSourceStack.stackSize, maxAmount);
int amountToMove = clonedSourceStack.stackSize;
int inserted = 0;
// if it's a pipe, try accept it
if (target instanceof TileEntity && Integration.modBuildCraft().isPipe((TileEntity)target)) {
inserted = Integration.modBuildCraft().tryAcceptIntoPipe((TileEntity)target, clonedSourceStack, doMove, direction);
clonedSourceStack.stackSize -= inserted;
// if it's an inventory
} else if (target instanceof IInventory) {
IInventory targetInventory = getInventory((IInventory)target);
ForgeDirection side = direction.getOpposite();
// try insert the item into the target inventory. this'll reduce the
// stackSize of our stack
InventoryUtils.insertItemIntoInventory(targetInventory, clonedSourceStack, side, intoSlot, doMove);
inserted = amountToMove - clonedSourceStack.stackSize;
}
// if we've done the move, reduce/remove the stack from our source
// inventory
if (doMove) {
ItemStack newSourcestack = sourceStack.copy();
newSourcestack.stackSize -= inserted;
if (newSourcestack.stackSize == 0) {
fromInventory.setInventorySlotContents(fromSlot, null);
} else {
fromInventory.setInventorySlotContents(fromSlot, newSourcestack);
}
}
return inserted;
}
/***
* Returns the inventory at the passed in coordinates. If it's a double
* chest it'll wrap the inventory
*
* @param world
* @param x
* @param y
* @param z
* @return
*/
public static IInventory getInventory(World world, int x, int y, int z) {
TileEntity tileEntity = world.getBlockTileEntity(x, y, z);
if (tileEntity instanceof TileEntityChest) {
int chestId = world.getBlockId(x, y, z);
if (world.getBlockId(x - 1, y, z) == chestId) return new InventoryLargeChest("Large chest", (IInventory)world.getBlockTileEntity(x - 1, y, z), (IInventory)tileEntity);
if (world.getBlockId(x + 1, y, z) == chestId) return new InventoryLargeChest("Large chest", (IInventory)tileEntity, (IInventory)world.getBlockTileEntity(x + 1, y, z));
if (world.getBlockId(x, y, z - 1) == chestId) return new InventoryLargeChest("Large chest", (IInventory)world.getBlockTileEntity(x, y, z - 1), (IInventory)tileEntity);
if (world.getBlockId(x, y, z + 1) == chestId) return new InventoryLargeChest("Large chest", (IInventory)tileEntity, (IInventory)world.getBlockTileEntity(x, y, z + 1));
}
return (tileEntity instanceof IInventory)? (IInventory)tileEntity : null;
}
/***
* Gets the inventory relative to the passed in coordinates.
*
* @param world
* @param x
* @param y
* @param z
* @param direction
* @return
*/
public static IInventory getInventory(World world, int x, int y, int z, ForgeDirection direction) {
if (direction != null && direction != ForgeDirection.UNKNOWN) {
x += direction.offsetX;
y += direction.offsetY;
z += direction.offsetZ;
}
return getInventory(world, x, y, z);
}
public static IInventory getInventory(IInventory inventory) {
if (inventory instanceof TileEntityChest) {
TileEntity te = (TileEntity)inventory;
return getInventory(te.worldObj, te.xCoord, te.yCoord, te.zCoord);
}
return inventory;
}
public static List<ItemStack> getInventoryContents(IInventory inventory) {
List<ItemStack> result = Lists.newArrayList();
for (int i = 0; i < inventory.getSizeInventory(); i++) {
ItemStack slot = inventory.getStackInSlot(i);
if (slot != null) result.add(slot);
}
return result;
}
/***
* Get the indexes of all slots containing a stack of the supplied item
* type.
*
* @param inventory
* @param stack
* @return Returns a set of the slot indexes
*/
public static Set<Integer> getSlotsWithStack(IInventory inventory, ItemStack stack) {
inventory = getInventory(inventory);
Set<Integer> slots = new HashSet<Integer>();
for (int i = 0; i < inventory.getSizeInventory(); i++) {
ItemStack stackInSlot = inventory.getStackInSlot(i);
if (stackInSlot != null && stackInSlot.isItemEqual(stack)) {
slots.add(i);
}
}
return slots;
}
/***
* Get the first slot containing an item type matching the supplied type.
*
* @param inventory
* @param stack
* @return Returns -1 if none found
*/
public static int getFirstSlotWithStack(IInventory inventory, ItemStack stack) {
inventory = getInventory(inventory);
for (int i = 0; i < inventory.getSizeInventory(); i++) {
ItemStack stackInSlot = inventory.getStackInSlot(i);
if (stackInSlot != null && stackInSlot.isItemEqual(stack)) { return i; }
}
return -1;
}
/***
* Consume ONE of the supplied item types
*
* @param inventory
* @param stack
* @return Returns whether or not it was able to
*/
public static boolean consumeInventoryItem(IInventory inventory, ItemStack stack) {
int slotWithStack = getFirstSlotWithStack(inventory, stack);
if (slotWithStack > -1) {
ItemStack stackInSlot = inventory.getStackInSlot(slotWithStack);
stackInSlot.stackSize--;
if (stackInSlot.stackSize == 0) {
inventory.setInventorySlotContents(slotWithStack, null);
}
return true;
}
return false;
}
/**
* Get the first slot index in an inventory with an item
*
* @param invent
* @return The slot index, or -1 if the inventory is empty
*/
public static int getSlotIndexOfNextStack(IInventory invent) {
for (int i = 0; i < invent.getSizeInventory(); i++) {
ItemStack stack = invent.getStackInSlot(i);
if (stack != null) { return i; }
}
return -1;
}
/***
* Removes an item stack from the inventory and returns a copy of it
*
* @param invent
* @return A copy of the stack it removed
*/
public static ItemStack removeNextItemStack(IInventory invent) {
int nextFilledSlot = getSlotIndexOfNextStack(invent);
if (nextFilledSlot > -1) {
ItemStack copy = invent.getStackInSlot(nextFilledSlot).copy();
invent.setInventorySlotContents(nextFilledSlot, null);
return copy;
}
return null;
}
public static int moveItemsFromOneOfSides(TileEntity currentTile, int maxAmount, int intoSlot, SyncableFlags sideFlags) {
return moveItemsFromOneOfSides(currentTile, null, maxAmount, intoSlot, sideFlags);
}
public static int moveItemsFromOneOfSides(TileEntity intoInventory, ItemStack stack, int maxAmount, Enum<?> intoSlot, SyncableFlags sideFlags) {
return moveItemsFromOneOfSides(intoInventory, stack, maxAmount, intoSlot.ordinal(), sideFlags);
}
/***
*
* @param intoInventory
* @param stack
* @param maxAmount
* @param intoSlot
* @param back
* @return
*/
public static int moveItemsFromOneOfSides(TileEntity intoInventory, ItemStack stack, int maxAmount, int intoSlot, SyncableFlags sideFlags) {
// shuffle the active sides
List<Integer> sides = new ArrayList<Integer>();
sides.addAll(sideFlags.getActiveSlots());
Collections.shuffle(sides);
if (!(intoInventory instanceof IInventory)) { return 0; }
// loop through the shuffled sides
for (Integer dir : sides) {
ForgeDirection directionToExtractItem = ForgeDirection.getOrientation(dir);
TileEntity tileOnSurface = BlockUtils.getTileInDirection(intoInventory, directionToExtractItem);
// if it's an inventory
if (tileOnSurface instanceof IInventory) {
// get the slots that contain the stack we want
Set<Integer> slots = null;
if (stack == null) {
slots = getAllSlots((IInventory)tileOnSurface);
} else {
slots = InventoryUtils.getSlotsWithStack((IInventory)tileOnSurface, stack);
}
// for each of the slots
for (Integer slot : slots) {
// if we can move it into our machine
int moved = InventoryUtils.moveItemInto((IInventory)tileOnSurface, slot, getInventory((IInventory)intoInventory), intoSlot, maxAmount, directionToExtractItem.getOpposite(), true);
if (moved > 0) { return moved; }
}
}
}
return 0;
}
/**
* Tests to see if an item stack can be inserted in to an inventory Does not
* perform the insertion, only tests the possibility
*
* @param inventory
* The inventory to insert the stack into
* @param item
* the stack to insert
* @return the amount of items that could be put in to the stack
*/
public static int testInventoryInsertion(IInventory inventory, ItemStack item) {
if (item == null || item.stackSize == 0) return 0;
if (inventory == null) return 0;
int slotCount = inventory.getSizeInventory();
/*
* Allows counting down the item size, without cloning or changing the
* object
*/
int itemSizeCounter = item.stackSize;
for (int i = 0; i < slotCount && itemSizeCounter > 0; i++) {
if (!inventory.isItemValidForSlot(i, item)) continue;
ItemStack inventorySlot = inventory.getStackInSlot(i);
/*
* If the slot is empty, dump the biggest stack we can, taking in to
* consideration, the remaining amount of stack
*/
if (inventorySlot == null) {
itemSizeCounter -= Math.min(Math.min(itemSizeCounter, inventory.getInventoryStackLimit()), item.getMaxStackSize());
}
/* If the slot is not empty, check that these items stack */
else if (areMergeCandidates(item, inventorySlot)) {
/* If they stack, decrement by the amount of space that remains */
int space = inventorySlot.getMaxStackSize()
- inventorySlot.stackSize;
itemSizeCounter -= Math.min(itemSizeCounter, space);
}
}
// itemSizeCounter might be less than zero here. It shouldn't be, but I
// don't trust me. -NC
if (itemSizeCounter != item.stackSize) {
itemSizeCounter = Math.max(itemSizeCounter, 0);
return item.stackSize - itemSizeCounter;
}
return 0;
}
public static Set<Integer> getAllSlots(IInventory inventory) {
inventory = getInventory(inventory);
Set<Integer> slots = new HashSet<Integer>();
for (int i = 0; i < inventory.getSizeInventory(); i++) {
slots.add(i);
}
return slots;
}
public static int moveItemsToOneOfSides(TileEntity currentTile, Enum<?> fromSlot, int maxAmount, SyncableFlags sideFlags) {
return moveItemsToOneOfSides(currentTile, fromSlot.ordinal(), maxAmount, sideFlags);
}
public static int moveItemsToOneOfSides(TileEntity currentTile, int fromSlot, int maxAmount, SyncableFlags sideFlags) {
// if the current tile isn't an inventory, do nothing
if (!(currentTile instanceof IInventory)) { return 0; }
// wrap it. Sure, we dont need to really as this'll never be a double
// chest
// but, whatevs.
IInventory inventory = getInventory((IInventory)currentTile);
// if we've not got a stack in that slot, we dont care.
if (inventory.getStackInSlot(fromSlot) == null) { return 0; }
// shuffle the sides that have been passed in
List<Integer> sides = new ArrayList<Integer>();
sides.addAll(sideFlags.getActiveSlots());
Collections.shuffle(sides);
for (Integer dir : sides) {
// grab the tile in the current direction
ForgeDirection directionToOutputItem = ForgeDirection.getOrientation(dir);
TileEntity tileOnSurface = currentTile.worldObj.getBlockTileEntity(currentTile.xCoord
+ directionToOutputItem.offsetX, currentTile.yCoord
+ directionToOutputItem.offsetY, currentTile.zCoord
+ directionToOutputItem.offsetZ);
if (tileOnSurface == null) { return 0; }
int moved = InventoryUtils.moveItemInto(inventory, fromSlot, tileOnSurface, -1, maxAmount, directionToOutputItem, true);
// move the object from our inventory, in the specified slot, to a
// pipe or any slot in an inventory in a particular direction
if (moved > 0) { return moved; }
}
return 0;
}
public static boolean inventoryIsEmpty(IInventory inventory) {
for (int i = 0, l = inventory.getSizeInventory(); i < l; i++)
if (inventory.getStackInSlot(i) != null) return false;
return true;
}
public static boolean tryMergeStacks(ItemStack stackToMerge, ItemStack stackInSlot) {
if (stackInSlot == null || !stackInSlot.isItemEqual(stackToMerge) || !ItemStack.areItemStackTagsEqual(stackToMerge, stackInSlot)) return false;
int newStackSize = stackInSlot.stackSize + stackToMerge.stackSize;
final int maxStackSize = stackToMerge.getMaxStackSize();
if (newStackSize <= maxStackSize) {
stackToMerge.stackSize = 0;
stackInSlot.stackSize = newStackSize;
return true;
} else if (stackInSlot.stackSize < maxStackSize) {
stackToMerge.stackSize -= maxStackSize - stackInSlot.stackSize;
stackInSlot.stackSize = maxStackSize;
return true;
}
return false;
}
}
|
src/openmods/utils/InventoryUtils.java
|
package openmods.utils;
import java.util.*;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.ISidedInventory;
import net.minecraft.inventory.InventoryLargeChest;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityChest;
import net.minecraft.world.World;
import net.minecraftforge.common.ForgeDirection;
import openmods.GenericInventory;
import openmods.integration.Integration;
import openmods.sync.SyncableFlags;
import com.google.common.collect.Lists;
public class InventoryUtils {
/***
* Try to merge the supplied stack into the supplied slot in the target
* inventory
*
* @param targetInventory
* Although it doesn't return anything, it'll REDUCE the stack
* size of the stack that you pass in
*
* @param slot
* @param stack
*/
public static void tryMergeStacks(IInventory targetInventory, int slot, ItemStack stack) {
if (targetInventory.isItemValidForSlot(slot, stack)) {
ItemStack targetStack = targetInventory.getStackInSlot(slot);
if (targetStack == null) {
targetInventory.setInventorySlotContents(slot, stack.copy());
stack.stackSize = 0;
} else {
boolean valid = targetInventory.isItemValidForSlot(slot, stack);
if (valid
&& stack.isItemEqual(targetStack)
&& ItemStack.areItemStackTagsEqual(stack, targetStack)
&& targetStack.stackSize < targetStack.getMaxStackSize()) {
int space = targetStack.getMaxStackSize()
- targetStack.stackSize;
int mergeAmount = Math.min(space, stack.stackSize);
ItemStack copy = targetStack.copy();
copy.stackSize += mergeAmount;
targetInventory.setInventorySlotContents(slot, copy);
stack.stackSize -= mergeAmount;
}
}
}
}
public static void insertItemIntoInventory(IInventory inventory, ItemStack stack) {
insertItemIntoInventory(inventory, stack, ForgeDirection.UNKNOWN, -1);
}
public static void insertItemIntoInventory(IInventory inventory, ItemStack stack, ForgeDirection side, int intoSlot) {
insertItemIntoInventory(inventory, stack, side, intoSlot, true);
}
/***
* Insert the stack into the target inventory. Pass -1 if you don't care
* which slot
*
* @param inventory
* @param stack
* @param side
* The side of the block you're inserting into
*/
public static void insertItemIntoInventory(IInventory inventory, ItemStack stack, ForgeDirection side, int intoSlot, boolean doMove) {
if (stack == null) { return; }
IInventory targetInventory = inventory;
// if we're not meant to move, make a clone of the inventory
if (!doMove) {
targetInventory = new GenericInventory("temporary.inventory", false, targetInventory.getSizeInventory());
((GenericInventory)targetInventory).copyFrom(inventory);
}
int i = 0;
int[] attemptSlots = new int[0];
// if it's a sided inventory, get all the accessible slots
if (inventory instanceof ISidedInventory
&& side != ForgeDirection.UNKNOWN) {
attemptSlots = ((ISidedInventory)inventory).getAccessibleSlotsFromSide(side.ordinal());
if (attemptSlots == null) {
attemptSlots = new int[0];
}
} else {
// if it's just a standard inventory, get all slots
attemptSlots = new int[inventory.getSizeInventory()];
for (int a = 0; a < inventory.getSizeInventory(); a++) {
attemptSlots[a] = a;
}
}
// if we've defining a specific slot, we'll just use that
if (intoSlot > -1) {
Set<Integer> x = new HashSet<Integer>();
for (int attemptedSlot : attemptSlots) {
x.add(attemptedSlot);
}
if (x.contains(intoSlot)) {
attemptSlots = new int[] { intoSlot };
} else {
attemptSlots = new int[0];
}
}
while (stack.stackSize > 0 && i < attemptSlots.length) {
if (side != ForgeDirection.UNKNOWN
&& inventory instanceof ISidedInventory) {
if (!((ISidedInventory)inventory).canInsertItem(intoSlot, stack, side.ordinal())) {
i++;
continue;
}
}
tryMergeStacks(targetInventory, attemptSlots[i], stack);
i++;
}
}
/***
* Move an item from the fromInventory, into the target. The target can be
* an inventory or pipe.
* Double checks are automagically wrapped. If you're not bothered what slot
* you insert into,
* pass -1 for intoSlot. If you're passing false for doMove, it'll create a
* dummy inventory and
* make its calculations on that instead
*
* @param fromInventory
* the inventory the item is coming from
* @param fromSlot
* the slot the item is coming from
* @param target
* the inventory you want the item to be put into. can be BC pipe
* or IInventory
* @param intoSlot
* the target slot. Pass -1 for any slot
* @param maxAmount
* The maximum amount you wish to pass
* @param direction
* The direction of the move. Pass UNKNOWN if not applicable
* @param doMove
* @return The amount of items moved
*/
public static int moveItemInto(IInventory fromInventory, int fromSlot, Object target, int intoSlot, int maxAmount, ForgeDirection direction, boolean doMove) {
fromInventory = InventoryUtils.getInventory(fromInventory);
// if we dont have a stack in the source location, return 0
ItemStack sourceStack = fromInventory.getStackInSlot(fromSlot);
if (sourceStack == null) { return 0; }
if (fromInventory instanceof ISidedInventory
&& !((ISidedInventory)fromInventory).canExtractItem(fromSlot, sourceStack, direction.ordinal())) { return 0; }
// create a clone of our source stack and set the size to either
// maxAmount or the stackSize
ItemStack clonedSourceStack = sourceStack.copy();
clonedSourceStack.stackSize = Math.min(clonedSourceStack.stackSize, maxAmount);
int amountToMove = clonedSourceStack.stackSize;
int inserted = 0;
// if it's a pipe, try accept it
if (target instanceof TileEntity && Integration.modBuildCraft().isPipe((TileEntity)target)) {
inserted = Integration.modBuildCraft().tryAcceptIntoPipe((TileEntity)target, clonedSourceStack, doMove, direction);
clonedSourceStack.stackSize -= inserted;
// if it's an inventory
} else if (target instanceof IInventory) {
IInventory targetInventory = getInventory((IInventory)target);
ForgeDirection side = direction.getOpposite();
// try insert the item into the target inventory. this'll reduce the
// stackSize of our stack
InventoryUtils.insertItemIntoInventory(targetInventory, clonedSourceStack, side, intoSlot, doMove);
inserted = amountToMove - clonedSourceStack.stackSize;
}
// if we've done the move, reduce/remove the stack from our source
// inventory
if (doMove) {
ItemStack newSourcestack = sourceStack.copy();
newSourcestack.stackSize -= inserted;
if (newSourcestack.stackSize == 0) {
fromInventory.setInventorySlotContents(fromSlot, null);
} else {
fromInventory.setInventorySlotContents(fromSlot, newSourcestack);
}
}
return inserted;
}
/***
* Returns the inventory at the passed in coordinates. If it's a double
* chest it'll wrap the inventory
*
* @param world
* @param x
* @param y
* @param z
* @return
*/
public static IInventory getInventory(World world, int x, int y, int z) {
TileEntity tileEntity = world.getBlockTileEntity(x, y, z);
if (tileEntity instanceof TileEntityChest) {
int chestId = world.getBlockId(x, y, z);
if (world.getBlockId(x - 1, y, z) == chestId) return new InventoryLargeChest("Large chest", (IInventory)world.getBlockTileEntity(x - 1, y, z), (IInventory)tileEntity);
if (world.getBlockId(x + 1, y, z) == chestId) return new InventoryLargeChest("Large chest", (IInventory)tileEntity, (IInventory)world.getBlockTileEntity(x + 1, y, z));
if (world.getBlockId(x, y, z - 1) == chestId) return new InventoryLargeChest("Large chest", (IInventory)world.getBlockTileEntity(x, y, z - 1), (IInventory)tileEntity);
if (world.getBlockId(x, y, z + 1) == chestId) return new InventoryLargeChest("Large chest", (IInventory)tileEntity, (IInventory)world.getBlockTileEntity(x, y, z + 1));
}
return (tileEntity instanceof IInventory)? (IInventory)tileEntity : null;
}
/***
* Gets the inventory relative to the passed in coordinates.
*
* @param world
* @param x
* @param y
* @param z
* @param direction
* @return
*/
public static IInventory getInventory(World world, int x, int y, int z, ForgeDirection direction) {
if (direction != null && direction != ForgeDirection.UNKNOWN) {
x += direction.offsetX;
y += direction.offsetY;
z += direction.offsetZ;
}
return getInventory(world, x, y, z);
}
public static IInventory getInventory(IInventory inventory) {
if (inventory instanceof TileEntityChest) {
TileEntity te = (TileEntity)inventory;
return getInventory(te.worldObj, te.xCoord, te.yCoord, te.zCoord);
}
return inventory;
}
public static List<ItemStack> getInventoryContents(IInventory inventory) {
List<ItemStack> result = Lists.newArrayList();
for (int i = 0; i < inventory.getSizeInventory(); i++) {
ItemStack slot = inventory.getStackInSlot(i);
if (slot != null) result.add(slot);
}
return result;
}
/***
* Get the indexes of all slots containing a stack of the supplied item
* type.
*
* @param inventory
* @param stack
* @return Returns a set of the slot indexes
*/
public static Set<Integer> getSlotsWithStack(IInventory inventory, ItemStack stack) {
inventory = getInventory(inventory);
Set<Integer> slots = new HashSet<Integer>();
for (int i = 0; i < inventory.getSizeInventory(); i++) {
ItemStack stackInSlot = inventory.getStackInSlot(i);
if (stackInSlot != null && stackInSlot.isItemEqual(stack)) {
slots.add(i);
}
}
return slots;
}
/***
* Get the first slot containing an item type matching the supplied type.
*
* @param inventory
* @param stack
* @return Returns -1 if none found
*/
public static int getFirstSlotWithStack(IInventory inventory, ItemStack stack) {
inventory = getInventory(inventory);
for (int i = 0; i < inventory.getSizeInventory(); i++) {
ItemStack stackInSlot = inventory.getStackInSlot(i);
if (stackInSlot != null && stackInSlot.isItemEqual(stack)) { return i; }
}
return -1;
}
/***
* Consume ONE of the supplied item types
*
* @param inventory
* @param stack
* @return Returns whether or not it was able to
*/
public static boolean consumeInventoryItem(IInventory inventory, ItemStack stack) {
int slotWithStack = getFirstSlotWithStack(inventory, stack);
if (slotWithStack > -1) {
ItemStack stackInSlot = inventory.getStackInSlot(slotWithStack);
stackInSlot.stackSize--;
if (stackInSlot.stackSize == 0) {
inventory.setInventorySlotContents(slotWithStack, null);
}
return true;
}
return false;
}
/**
* Get the first slot index in an inventory with an item
*
* @param invent
* @return The slot index, or -1 if the inventory is empty
*/
public static int getSlotIndexOfNextStack(IInventory invent) {
for (int i = 0; i < invent.getSizeInventory(); i++) {
ItemStack stack = invent.getStackInSlot(i);
if (stack != null) { return i; }
}
return -1;
}
/***
* Removes an item stack from the inventory and returns a copy of it
*
* @param invent
* @return A copy of the stack it removed
*/
public static ItemStack removeNextItemStack(IInventory invent) {
int nextFilledSlot = getSlotIndexOfNextStack(invent);
if (nextFilledSlot > -1) {
ItemStack copy = invent.getStackInSlot(nextFilledSlot).copy();
invent.setInventorySlotContents(nextFilledSlot, null);
return copy;
}
return null;
}
public static int moveItemsFromOneOfSides(TileEntity currentTile, int maxAmount, int intoSlot, SyncableFlags sideFlags) {
return moveItemsFromOneOfSides(currentTile, null, maxAmount, intoSlot, sideFlags);
}
public static int moveItemsFromOneOfSides(TileEntity intoInventory, ItemStack stack, int maxAmount, Enum<?> intoSlot, SyncableFlags sideFlags) {
return moveItemsFromOneOfSides(intoInventory, stack, maxAmount, intoSlot.ordinal(), sideFlags);
}
/***
*
* @param intoInventory
* @param stack
* @param maxAmount
* @param intoSlot
* @param back
* @return
*/
public static int moveItemsFromOneOfSides(TileEntity intoInventory, ItemStack stack, int maxAmount, int intoSlot, SyncableFlags sideFlags) {
// shuffle the active sides
List<Integer> sides = new ArrayList<Integer>();
sides.addAll(sideFlags.getActiveSlots());
Collections.shuffle(sides);
if (!(intoInventory instanceof IInventory)) { return 0; }
// loop through the shuffled sides
for (Integer dir : sides) {
ForgeDirection directionToExtractItem = ForgeDirection.getOrientation(dir);
TileEntity tileOnSurface = BlockUtils.getTileInDirection(intoInventory, directionToExtractItem);
// if it's an inventory
if (tileOnSurface instanceof IInventory) {
// get the slots that contain the stack we want
Set<Integer> slots = null;
if (stack == null) {
slots = getAllSlots((IInventory)tileOnSurface);
} else {
slots = InventoryUtils.getSlotsWithStack((IInventory)tileOnSurface, stack);
}
// for each of the slots
for (Integer slot : slots) {
// if we can move it into our machine
int moved = InventoryUtils.moveItemInto((IInventory)tileOnSurface, slot, getInventory((IInventory)intoInventory), intoSlot, maxAmount, directionToExtractItem.getOpposite(), true);
if (moved > 0) { return moved; }
}
}
}
return 0;
}
/**
* Tests to see if an item stack can be inserted in to an inventory Does not
* perform the insertion, only tests the possibility
*
* @param inventory
* The inventory to insert the stack into
* @param item
* the stack to insert
* @return the amount of items that could be put in to the stack
*/
public static int testInventoryInsertion(IInventory inventory, ItemStack item) {
if (item == null || item.stackSize == 0) return 0;
if (inventory == null) return 0;
int slotCount = inventory.getSizeInventory();
/*
* Allows counting down the item size, without cloning or changing the
* object
*/
int itemSizeCounter = item.stackSize;
for (int i = 0; i < slotCount && itemSizeCounter > 0; i++) {
if (!inventory.isItemValidForSlot(i, item)) continue;
ItemStack inventorySlot = inventory.getStackInSlot(i);
/*
* If the slot is empty, dump the biggest stack we can, taking in to
* consideration, the remaining amount of stack
*/
if (inventorySlot == null) {
itemSizeCounter -= Math.min(Math.min(itemSizeCounter, inventory.getInventoryStackLimit()), item.getMaxStackSize());
}
/* If the slot is not empty, check that these items stack */
else if (item.isItemEqual(inventorySlot)
&& inventorySlot.stackSize < inventorySlot.getMaxStackSize()) {
/* If they stack, decrement by the amount of space that remains */
int space = inventorySlot.getMaxStackSize()
- inventorySlot.stackSize;
itemSizeCounter -= Math.min(itemSizeCounter, space);
}
}
// itemSizeCounter might be less than zero here. It shouldn't be, but I
// don't trust me. -NC
if (itemSizeCounter != item.stackSize) {
itemSizeCounter = Math.max(itemSizeCounter, 0);
return item.stackSize - itemSizeCounter;
}
return 0;
}
public static Set<Integer> getAllSlots(IInventory inventory) {
inventory = getInventory(inventory);
Set<Integer> slots = new HashSet<Integer>();
for (int i = 0; i < inventory.getSizeInventory(); i++) {
slots.add(i);
}
return slots;
}
public static int moveItemsToOneOfSides(TileEntity currentTile, Enum<?> fromSlot, int maxAmount, SyncableFlags sideFlags) {
return moveItemsToOneOfSides(currentTile, fromSlot.ordinal(), maxAmount, sideFlags);
}
public static int moveItemsToOneOfSides(TileEntity currentTile, int fromSlot, int maxAmount, SyncableFlags sideFlags) {
// if the current tile isn't an inventory, do nothing
if (!(currentTile instanceof IInventory)) { return 0; }
// wrap it. Sure, we dont need to really as this'll never be a double
// chest
// but, whatevs.
IInventory inventory = getInventory((IInventory)currentTile);
// if we've not got a stack in that slot, we dont care.
if (inventory.getStackInSlot(fromSlot) == null) { return 0; }
// shuffle the sides that have been passed in
List<Integer> sides = new ArrayList<Integer>();
sides.addAll(sideFlags.getActiveSlots());
Collections.shuffle(sides);
for (Integer dir : sides) {
// grab the tile in the current direction
ForgeDirection directionToOutputItem = ForgeDirection.getOrientation(dir);
TileEntity tileOnSurface = currentTile.worldObj.getBlockTileEntity(currentTile.xCoord
+ directionToOutputItem.offsetX, currentTile.yCoord
+ directionToOutputItem.offsetY, currentTile.zCoord
+ directionToOutputItem.offsetZ);
if (tileOnSurface == null) { return 0; }
int moved = InventoryUtils.moveItemInto(inventory, fromSlot, tileOnSurface, -1, maxAmount, directionToOutputItem, true);
// move the object from our inventory, in the specified slot, to a
// pipe or any slot in an inventory in a particular direction
if (moved > 0) { return moved; }
}
return 0;
}
public static boolean inventoryIsEmpty(IInventory inventory) {
for (int i = 0, l = inventory.getSizeInventory(); i < l; i++)
if (inventory.getStackInSlot(i) != null) return false;
return true;
}
public static boolean tryMergeStacks(ItemStack stackToMerge, ItemStack stackInSlot) {
if (stackInSlot == null || !stackInSlot.isItemEqual(stackToMerge) || !ItemStack.areItemStackTagsEqual(stackToMerge, stackInSlot)) return false;
int newStackSize = stackInSlot.stackSize + stackToMerge.stackSize;
final int maxStackSize = stackToMerge.getMaxStackSize();
if (newStackSize <= maxStackSize) {
stackToMerge.stackSize = 0;
stackInSlot.stackSize = newStackSize;
return true;
} else if (stackInSlot.stackSize < maxStackSize) {
stackToMerge.stackSize -= maxStackSize - stackInSlot.stackSize;
stackInSlot.stackSize = maxStackSize;
return true;
}
return false;
}
}
|
More tag correctness
|
src/openmods/utils/InventoryUtils.java
|
More tag correctness
|
|
Java
|
epl-1.0
|
949cc7b4e3c5745bbf7daf3f57892eb7c8fe842f
| 0
|
JoanesMiranda/jogoDomino
|
package br.com.domino.view;
import java.awt.GridLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import br.com.domino.model.Actions;
import br.com.domino.model.Pecas;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.awt.event.ActionEvent;
import javax.swing.border.LineBorder;
import java.awt.Color;
public class TelaDoJogo extends JFrame {
String l1 = "", l2 = "", l3 = "", l4 = "", l5 = "", l6 = "", l7 = "", l8 = "", l9 = "", l10 = "", l11 = "",
l12 = "", l13 = "", l14 = "", l15 = "", l16 = "", l17 = "", l18 = "", l19 = "", l20 = "", l21 = "",
l22 = "", l23 = "", l24 = "", l25 = "", l26 = "", l27 = "", l28 = "";
JButton btnhumano1;
JButton btnhumano2;
JButton btnhumano3;
JButton btnhumano4;
JButton btnhumano5;
JButton btnhumano6;
JButton btnhumano7;
JButton btnhumano8;
JButton btnhumano9;
JButton btnhumano10;
JButton btnhumano11;
JButton btnhumano12;
JButton btnhumano13;
JButton btnhumano14;
JButton btnhumano15;
JButton btnhumano16;
JButton btnhumano17;
JButton btnhumano18;
JButton btnmaquina1;
JButton btnmaquina2;
JButton btnmaquina3;
JButton btnmaquina4;
JButton btnmaquina5;
JButton btnmaquina6;
JButton btnmaquina7;
JButton btnmaquina8;
JButton btnmaquina9;
JButton btnmaquina10;
JButton btnmaquina11;
JButton btnmaquina12;
JButton btnmaquina13;
JButton btnmaquina14;
JButton btnmaquina15;
JButton btnmaquina16;
JButton btnmaquina17;
JButton btnmaquina18;
JButton btn_1;
JButton btn_2;
JButton btn_3;
JButton btn_4;
JButton btn_5;
JButton btn_6;
JButton btn_7;
JButton btn_8;
JButton btn_9;
JButton btn_10;
JButton btn_11;
JButton btn_12;
JButton btn_13;
JButton btn_14;
JButton btn_15;
JButton btn_16;
JButton btn_17;
JButton btn_18;
JButton btn_19;
JButton btn_20;
JButton btn_21;
JButton btn_22;
JButton btn_23;
JButton btn_24;
JButton btn_25;
JButton btn_26;
JButton btn_27;
JButton btn_28;
public void desabilitaBotoesHumano() {
btnhumano1.setEnabled(false);
btnhumano2.setEnabled(false);
btnhumano3.setEnabled(false);
btnhumano4.setEnabled(false);
btnhumano5.setEnabled(false);
btnhumano6.setEnabled(false);
btnhumano7.setEnabled(false);
btnhumano8.setEnabled(false);
btnhumano9.setEnabled(false);
btnhumano10.setEnabled(false);
btnhumano11.setEnabled(false);
btnhumano12.setEnabled(false);
btnhumano13.setEnabled(false);
btnhumano14.setEnabled(false);
btnhumano15.setEnabled(false);
btnhumano16.setEnabled(false);
btnhumano17.setEnabled(false);
btnhumano18.setEnabled(false);
}
public void habilitaBotoesHumano() {
btnhumano1.setEnabled(true);
btnhumano2.setEnabled(true);
btnhumano3.setEnabled(true);
btnhumano4.setEnabled(true);
btnhumano5.setEnabled(true);
btnhumano6.setEnabled(true);
btnhumano7.setEnabled(true);
btnhumano8.setEnabled(true);
btnhumano9.setEnabled(true);
btnhumano10.setEnabled(true);
btnhumano11.setEnabled(true);
btnhumano12.setEnabled(true);
btnhumano13.setEnabled(true);
btnhumano14.setEnabled(true);
btnhumano15.setEnabled(true);
btnhumano16.setEnabled(true);
btnhumano17.setEnabled(true);
btnhumano18.setEnabled(true);
}
public void desabilitaBotoesMaquina() {
btnmaquina1.setEnabled(false);
btnmaquina2.setEnabled(false);
btnmaquina3.setEnabled(false);
btnmaquina4.setEnabled(false);
btnmaquina5.setEnabled(false);
btnmaquina6.setEnabled(false);
btnmaquina7.setEnabled(false);
btnmaquina8.setEnabled(false);
btnmaquina9.setEnabled(false);
btnmaquina10.setEnabled(false);
btnmaquina11.setEnabled(false);
btnmaquina12.setEnabled(false);
btnmaquina13.setEnabled(false);
btnmaquina14.setEnabled(false);
btnmaquina15.setEnabled(false);
btnmaquina16.setEnabled(false);
btnmaquina17.setEnabled(false);
btnmaquina18.setEnabled(false);
}
public void habilitaBotoesMaquina() {
btnmaquina1.setEnabled(true);
btnmaquina2.setEnabled(true);
btnmaquina3.setEnabled(true);
btnmaquina4.setEnabled(true);
btnmaquina5.setEnabled(true);
btnmaquina6.setEnabled(true);
btnmaquina7.setEnabled(true);
btnmaquina8.setEnabled(true);
btnmaquina9.setEnabled(true);
btnmaquina10.setEnabled(true);
btnmaquina11.setEnabled(true);
btnmaquina12.setEnabled(true);
btnmaquina13.setEnabled(true);
btnmaquina14.setEnabled(true);
btnmaquina15.setEnabled(true);
btnmaquina16.setEnabled(true);
btnmaquina17.setEnabled(true);
btnmaquina18.setEnabled(true);
}
int contadorCompraMaquina = 7;
public void insereImagenNoBotao(int contadorMaquina) {
++contadorMaquina;
switch (contadorMaquina) {
case 8:
btnmaquina8.setEnabled(true);
btnmaquina8.setIcon(new ImageIcon(".//resource//imagens//preta.png"));
break;
case 9:
btnmaquina9.setEnabled(true);
btnmaquina9.setIcon(new ImageIcon(".//resource//imagens//preta.png"));
break;
case 10:
btnmaquina10.setEnabled(true);
btnmaquina10.setIcon(new ImageIcon(".//resource//imagens//preta.png"));
break;
case 11:
btnmaquina11.setEnabled(true);
btnmaquina11.setIcon(new ImageIcon(".//resource//imagens//preta.png"));
break;
case 12:
btnmaquina12.setEnabled(true);
btnmaquina12.setIcon(new ImageIcon(".//resource//imagens//preta.png"));
break;
case 13:
btnmaquina13.setEnabled(true);
btnmaquina13.setIcon(new ImageIcon(".//resource//imagens//preta.png"));
break;
case 14:
btnmaquina14.setEnabled(true);
btnmaquina14.setIcon(new ImageIcon(".//resource//imagens//preta.png"));
break;
case 15:
btnmaquina15.setEnabled(true);
btnmaquina15.setIcon(new ImageIcon(".//resource//imagens//preta.png"));
break;
case 16:
btnmaquina16.setEnabled(true);
btnmaquina16.setIcon(new ImageIcon(".//resource//imagens//preta.png"));
break;
case 17:
btnmaquina17.setEnabled(true);
btnmaquina17.setIcon(new ImageIcon(".//resource//imagens//preta.png"));
break;
case 18:
btnmaquina18.setEnabled(true);
btnmaquina18.setIcon(new ImageIcon(".//resource//imagens//preta.png"));
break;
default:
break;
}
}
int aux = 0;
int aux2 = 0;
boolean pedraDiferente = false;
Actions al = new Actions();
ArrayList<Pecas> arrayH = new ArrayList<Pecas>();
ArrayList<Pecas> arrayM = new ArrayList<Pecas>();
Boolean vezDoJogo = true;
// recebe todas as pedras do caminho do jogo do domino
ArrayList<Pecas> arrayTabuleiro = new ArrayList<Pecas>();
private static final long serialVersionUID = 1L;
public TelaDoJogo() {
ArrayList<Pecas> array = new ArrayList<Pecas>();
for (Pecas pecas : al.embaralhaPedrasDomino()) {
array.add(pecas);
}
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu mnMenu = new JMenu("Menu");
menuBar.add(mnMenu);
JMenuItem mntmNovoJogo = new JMenuItem("Novo Jogo");
mnMenu.add(mntmNovoJogo);
JMenuItem mntmSalvarJogo = new JMenuItem("Salvar Jogo");
mnMenu.add(mntmSalvarJogo);
JMenuItem mntmInstrues = new JMenuItem("Instru\u00E7\u00F5es");
mntmInstrues.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new TelaInstrucoes().setVisible(true);
}
});
mnMenu.add(mntmInstrues);
JMenuItem mntmSair = new JMenuItem("Sair");
mntmSair.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
dispose();
}
});
mnMenu.add(mntmSair);
getContentPane().setLayout(null);
ImageIcon iconMaquina = new ImageIcon(".//resource//imagens//sasuke.png");
JLabel lblIconemaquina = new JLabel(iconMaquina);
lblIconemaquina.setBounds(0, 0, 73, 100);
getContentPane().add(lblIconemaquina);
JLabel lblNomemaquina = new JLabel("Joanes Machine dos Santos");
lblNomemaquina.setFont(new Font("Times New Roman", Font.BOLD, 14));
lblNomemaquina.setBounds(77, 32, 195, 25);
getContentPane().add(lblNomemaquina);
ImageIcon iconJogador = new ImageIcon(".//resource//imagens//naruto.png");
JLabel lblIconejogador = new JLabel(iconJogador);
lblIconejogador.setBounds(0, 561, 73, 100);
getContentPane().add(lblIconejogador);
JLabel lblNomejogador = new JLabel("Emerson Sousa Pereira");
lblNomejogador.setFont(new Font("Times New Roman", Font.BOLD, 14));
lblNomejogador.setBounds(77, 596, 217, 36);
getContentPane().add(lblNomejogador);
JPanel panel_pecasMaquina = new JPanel();
panel_pecasMaquina.setBounds(304, 0, 958, 81);
getContentPane().add(panel_pecasMaquina);
panel_pecasMaquina.setLayout(new GridLayout(1, 20, 0, 0));
btnmaquina1 = new JButton("");
btnmaquina1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnmaquina2 = new JButton("");
btnmaquina3 = new JButton("");
btnmaquina4 = new JButton("");
btnmaquina5 = new JButton("");
btnmaquina6 = new JButton("");
btnmaquina7 = new JButton("");
btnmaquina8 = new JButton("");
btnmaquina8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnmaquina9 = new JButton("");
btnmaquina10 = new JButton("");
btnmaquina11 = new JButton("");
btnmaquina12 = new JButton("");
btnmaquina13 = new JButton("");
btnmaquina14 = new JButton("");
btnmaquina15 = new JButton("");
btnmaquina16 = new JButton("");
btnmaquina17 = new JButton("");
btnmaquina18 = new JButton("");
panel_pecasMaquina.add(btnmaquina1);
panel_pecasMaquina.add(btnmaquina2);
panel_pecasMaquina.add(btnmaquina3);
panel_pecasMaquina.add(btnmaquina4);
panel_pecasMaquina.add(btnmaquina5);
panel_pecasMaquina.add(btnmaquina6);
panel_pecasMaquina.add(btnmaquina7);
panel_pecasMaquina.add(btnmaquina8);
panel_pecasMaquina.add(btnmaquina9);
panel_pecasMaquina.add(btnmaquina10);
panel_pecasMaquina.add(btnmaquina11);
panel_pecasMaquina.add(btnmaquina12);
panel_pecasMaquina.add(btnmaquina13);
panel_pecasMaquina.add(btnmaquina14);
panel_pecasMaquina.add(btnmaquina15);
panel_pecasMaquina.add(btnmaquina16);
panel_pecasMaquina.add(btnmaquina17);
panel_pecasMaquina.add(btnmaquina18);
JPanel panel_pecasJogador = new JPanel();
panel_pecasJogador.setBounds(304, 580, 958, 81);
getContentPane().add(panel_pecasJogador);
panel_pecasJogador.setLayout(new GridLayout(1, 20, 0, 0));
btnhumano1 = new JButton("");
btnhumano1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
++aux2;
Pecas p1 = arrayH.get(0);
String ladoa = p1.getLadoEsquerdo().toString();
String ladob = p1.getLadoDireito().toString();
System.out.println(l1 = ladoa + ladob);
switch (aux2) {
case 1:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_1.setEnabled(true);
btn_1.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 1) {
// obs: tem que inverter os valores antes de inserir
// no array.
Pecas novop = new Pecas(p1.getLadoDireito(), p1.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano1.setEnabled(false);
btn_1.setEnabled(true);
btn_1.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 2) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_1.setEnabled(true);
btn_1.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 2:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 1) {
Pecas novop = new Pecas(p1.getLadoDireito(), p1.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano1.setEnabled(false);
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 2) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 3:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 1) {
Pecas novop = new Pecas(p1.getLadoDireito(), p1.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano1.setEnabled(false);
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 2) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 4:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 1) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 2) {
Pecas novop = new Pecas(p1.getLadoDireito(), p1.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano1.setEnabled(false);
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 5:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 1) {
Pecas novop = new Pecas(p1.getLadoDireito(), p1.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano1.setEnabled(false);
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 2) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 6:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 1) {
Pecas novop = new Pecas(p1.getLadoDireito(), p1.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano1.setEnabled(false);
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 2) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 7:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 1) {
Pecas novop = new Pecas(p1.getLadoDireito(), p1.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano1.setEnabled(false);
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 2) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 8:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 1) {
Pecas novop = new Pecas(p1.getLadoDireito(), p1.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano1.setEnabled(false);
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 2) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 9:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 1) {
Pecas novop = new Pecas(p1.getLadoDireito(), p1.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano1.setEnabled(false);
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 2) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 10:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 1) {
Pecas novop = new Pecas(p1.getLadoDireito(), p1.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano1.setEnabled(false);
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 2) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 11:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 1) {
Pecas novop = new Pecas(p1.getLadoDireito(), p1.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano1.setEnabled(false);
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 2) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 12:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 1) {
Pecas novop = new Pecas(p1.getLadoDireito(), p1.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano1.setEnabled(false);
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 2) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 13:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//verticias2//" + l1 + ".png"));
} else {
if (al.verificaLadosPedraDireita(arrayTabuleiro, p1) == 1) {
// obs: tem que inverter os valores antes de inserir
// no array.
Pecas novop = new Pecas(p1.getLadoDireito(), p1.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano1.setEnabled(false);
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//verticais2//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraDireita(arrayTabuleiro, p1) == 2) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//verticais2//" + l1 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_14.setEnabled(true);
btn_14.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_14.setEnabled(true);
btn_14.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
default:
JOptionPane.showMessageDialog(null, "Peas esgotadas");
break;
}
}
});
btnhumano2 = new JButton("");
btnhumano2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
++aux2;
Pecas p2 = arrayH.get(1);
String ladoa = p2.getLadoEsquerdo().toString();
String ladob = p2.getLadoDireito().toString();
System.out.println(l2 = ladoa + ladob);
switch (aux2) {
case 1:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_1.setEnabled(true);
btn_1.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 1) {
Pecas novop = new Pecas(p2.getLadoDireito(), p2.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano2.setEnabled(false);
btn_1.setEnabled(true);
btn_1.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 2) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_1.setEnabled(true);
btn_1.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 2:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 1) {
Pecas novop = new Pecas(p2.getLadoDireito(), p2.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano2.setEnabled(false);
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 2) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 3:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 1) {
Pecas novop = new Pecas(p2.getLadoDireito(), p2.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano2.setEnabled(false);
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 2) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 4:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 1) {
Pecas novop = new Pecas(p2.getLadoDireito(), p2.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano2.setEnabled(false);
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 2) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 5:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 1) {
Pecas novop = new Pecas(p2.getLadoDireito(), p2.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano2.setEnabled(false);
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 2) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 6:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 1) {
Pecas novop = new Pecas(p2.getLadoDireito(), p2.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano2.setEnabled(false);
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 2) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 7:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 1) {
Pecas novop = new Pecas(p2.getLadoDireito(), p2.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano2.setEnabled(false);
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 2) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 8:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 1) {
Pecas novop = new Pecas(p2.getLadoDireito(), p2.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano2.setEnabled(false);
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 2) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 9:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 1) {
Pecas novop = new Pecas(p2.getLadoDireito(), p2.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano2.setEnabled(false);
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 2) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 10:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 1) {
Pecas novop = new Pecas(p2.getLadoDireito(), p2.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano2.setEnabled(false);
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 2) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 11:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 1) {
Pecas novop = new Pecas(p2.getLadoDireito(), p2.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano2.setEnabled(false);
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 2) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 12:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 1) {
Pecas novop = new Pecas(p2.getLadoDireito(), p2.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano2.setEnabled(false);
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 2) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 13:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//verticias2//" + l2 + ".png"));
} else {
if (al.verificaLadosPedraDireita(arrayTabuleiro, p2) == 1) {
// obs: tem que inverter os valores antes de inserir
// no array.
Pecas novop = new Pecas(p2.getLadoDireito(), p2.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano2.setEnabled(false);
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//verticais2//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraDireita(arrayTabuleiro, p2) == 2) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//verticais2//" + l2 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_14.setEnabled(true);
btn_14.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_14.setEnabled(true);
btn_14.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
default:
JOptionPane.showMessageDialog(null, "Peas esgotadas");
break;
}
}
});
btnhumano3 = new JButton("");
btnhumano3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux2;
Pecas p3 = arrayH.get(2);
String ladoa = p3.getLadoEsquerdo().toString();
String ladob = p3.getLadoDireito().toString();
System.out.println(l3 = ladoa + ladob);
switch (aux2) {
case 1:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_1.setEnabled(true);
btn_1.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 1) {
Pecas novop = new Pecas(p3.getLadoDireito(), p3.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano3.setEnabled(false);
btn_1.setEnabled(true);
btn_1.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 2) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_1.setEnabled(true);
btn_1.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 2:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 1) {
Pecas novop = new Pecas(p3.getLadoDireito(), p3.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano3.setEnabled(false);
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 2) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 3:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 1) {
Pecas novop = new Pecas(p3.getLadoDireito(), p3.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano3.setEnabled(false);
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 2) {
arrayTabuleiro.add(p3);
btnhumano2.setEnabled(false);
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 4:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 1) {
Pecas novop = new Pecas(p3.getLadoDireito(), p3.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano3.setEnabled(false);
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 2) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 5:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 1) {
Pecas novop = new Pecas(p3.getLadoDireito(), p3.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano2.setEnabled(false);
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 2) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 6:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 1) {
Pecas novop = new Pecas(p3.getLadoDireito(), p3.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano3.setEnabled(false);
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 2) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 7:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 1) {
Pecas novop = new Pecas(p3.getLadoDireito(), p3.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano3.setEnabled(false);
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 2) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 8:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 1) {
Pecas novop = new Pecas(p3.getLadoDireito(), p3.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano3.setEnabled(false);
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 2) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 9:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 1) {
Pecas novop = new Pecas(p3.getLadoDireito(), p3.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano3.setEnabled(false);
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 2) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 10:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 1) {
Pecas novop = new Pecas(p3.getLadoDireito(), p3.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano3.setEnabled(false);
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 2) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 11:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 1) {
Pecas novop = new Pecas(p3.getLadoDireito(), p3.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano3.setEnabled(false);
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 2) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 12:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 1) {
Pecas novop = new Pecas(p3.getLadoDireito(), p3.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano3.setEnabled(false);
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horintais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 2) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 13:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//verticias2//" + l3 + ".png"));
} else {
if (al.verificaLadosPedraDireita(arrayTabuleiro, p3) == 1) {
// obs: tem que inverter os valores antes de inserir
// no array.
Pecas novop = new Pecas(p3.getLadoDireito(), p3.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano3.setEnabled(false);
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//verticais2//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraDireita(arrayTabuleiro, p3) == 2) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//verticais2//" + l3 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_14.setEnabled(true);
btn_14.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_14.setEnabled(true);
btn_14.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
default:
JOptionPane.showMessageDialog(null, "Peas esgotadas");
break;
}
}
});
btnhumano4 = new JButton("");
btnhumano4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux2;
Pecas p4 = arrayH.get(3);
String ladoa = p4.getLadoEsquerdo().toString();
String ladob = p4.getLadoDireito().toString();
System.out.println(l4 = ladoa + ladob);
switch (aux2) {
case 1:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_1.setEnabled(true);
btn_1.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 1) {
Pecas novop = new Pecas(p4.getLadoDireito(), p4.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano4.setEnabled(false);
btn_1.setEnabled(true);
btn_1.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 2) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_1.setEnabled(true);
btn_1.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 2:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 1) {
Pecas novop = new Pecas(p4.getLadoDireito(), p4.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano4.setEnabled(false);
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 2) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 3:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 1) {
Pecas novop = new Pecas(p4.getLadoDireito(), p4.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano4.setEnabled(false);
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 2) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 4:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 1) {
Pecas novop = new Pecas(p4.getLadoDireito(), p4.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano4.setEnabled(false);
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 2) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 5:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 1) {
Pecas novop = new Pecas(p4.getLadoDireito(), p4.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano4.setEnabled(false);
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 2) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 6:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 1) {
Pecas novop = new Pecas(p4.getLadoDireito(), p4.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano4.setEnabled(false);
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 2) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 7:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 1) {
Pecas novop = new Pecas(p4.getLadoDireito(), p4.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano4.setEnabled(false);
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 2) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 8:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 1) {
Pecas novop = new Pecas(p4.getLadoDireito(), p4.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano4.setEnabled(false);
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 2) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 9:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 1) {
Pecas novop = new Pecas(p4.getLadoDireito(), p4.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano4.setEnabled(false);
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 2) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 10:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 1) {
Pecas novop = new Pecas(p4.getLadoDireito(), p4.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano4.setEnabled(false);
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 2) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 11:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 1) {
Pecas novop = new Pecas(p4.getLadoDireito(), p4.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano4.setEnabled(false);
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 2) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 12:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 1) {
Pecas novop = new Pecas(p4.getLadoDireito(), p4.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano4.setEnabled(false);
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 2) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 13:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p4);
btnhumano2.setEnabled(false);
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//verticias2//" + l4 + ".png"));
} else {
if (al.verificaLadosPedraDireita(arrayTabuleiro, p4) == 1) {
// obs: tem que inverter os valores antes de inserir
// no array.
Pecas novop = new Pecas(p4.getLadoDireito(), p4.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano2.setEnabled(false);
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//verticais2//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraDireita(arrayTabuleiro, p4) == 2) {
arrayTabuleiro.add(p4);
btnhumano2.setEnabled(false);
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//verticais2//" + l4 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_14.setEnabled(true);
btn_14.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_14.setEnabled(true);
btn_14.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
default:
JOptionPane.showMessageDialog(null, "Peas esgotadas");
break;
}
}
});
btnhumano5 = new JButton("");
btnhumano5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
++aux2;
Pecas p5 = arrayH.get(4);
String ladoa = p5.getLadoEsquerdo().toString();
String ladob = p5.getLadoDireito().toString();
System.out.println(l5 = ladoa + ladob);
switch (aux2) {
case 1:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_1.setEnabled(true);
btn_1.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 1) {
Pecas novop = new Pecas(p5.getLadoDireito(), p5.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano5.setEnabled(false);
btn_1.setEnabled(true);
btn_1.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 2) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_1.setEnabled(true);
btn_1.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 2:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 1) {
Pecas novop = new Pecas(p5.getLadoDireito(), p5.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano5.setEnabled(false);
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 2) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 3:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 1) {
Pecas novop = new Pecas(p5.getLadoDireito(), p5.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano5.setEnabled(false);
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 2) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 4:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 1) {
Pecas novop = new Pecas(p5.getLadoDireito(), p5.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano5.setEnabled(false);
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 2) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 5:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 1) {
Pecas novop = new Pecas(p5.getLadoDireito(), p5.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano5.setEnabled(false);
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 2) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 6:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 1) {
Pecas novop = new Pecas(p5.getLadoDireito(), p5.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano5.setEnabled(false);
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 2) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 7:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 1) {
Pecas novop = new Pecas(p5.getLadoDireito(), p5.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano5.setEnabled(false);
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 2) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 8:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 1) {
Pecas novop = new Pecas(p5.getLadoDireito(), p5.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano5.setEnabled(false);
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 2) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 9:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 1) {
Pecas novop = new Pecas(p5.getLadoDireito(), p5.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano5.setEnabled(false);
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 2) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 10:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 1) {
Pecas novop = new Pecas(p5.getLadoDireito(), p5.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano5.setEnabled(false);
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 2) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 11:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 1) {
Pecas novop = new Pecas(p5.getLadoDireito(), p5.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano5.setEnabled(false);
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 2) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 12:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 1) {
Pecas novop = new Pecas(p5.getLadoDireito(), p5.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano5.setEnabled(false);
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 2) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 13:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p5);
btnhumano2.setEnabled(false);
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//verticias2//" + l5 + ".png"));
} else {
if (al.verificaLadosPedraDireita(arrayTabuleiro, p5) == 1) {
// obs: tem que inverter os valores antes de inserir
// no array.
Pecas novop = new Pecas(p5.getLadoDireito(), p5.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano2.setEnabled(false);
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//verticais2//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraDireita(arrayTabuleiro, p5) == 2) {
arrayTabuleiro.add(p5);
btnhumano2.setEnabled(false);
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//verticais2//" + l5 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_14.setEnabled(true);
btn_14.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_14.setEnabled(true);
btn_14.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
default:
JOptionPane.showMessageDialog(null, "Peas esgotadas");
break;
}
}
});
btnhumano6 = new JButton("");
btnhumano6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux2;
Pecas p6 = arrayH.get(5);
String ladoa = p6.getLadoEsquerdo().toString();
String ladob = p6.getLadoDireito().toString();
System.out.println(l6 = ladoa + ladob);
switch (aux2) {
case 1:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_1.setEnabled(true);
btn_1.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 1) {
Pecas novop = new Pecas(p6.getLadoDireito(), p6.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano2.setEnabled(false);
btn_1.setEnabled(true);
btn_1.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 2) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_1.setEnabled(true);
btn_1.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 2:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 1) {
Pecas novop = new Pecas(p6.getLadoDireito(), p6.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano6.setEnabled(false);
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 2) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 3:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 1) {
Pecas novop = new Pecas(p6.getLadoDireito(), p6.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano6.setEnabled(false);
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 2) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 4:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 1) {
Pecas novop = new Pecas(p6.getLadoDireito(), p6.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano6.setEnabled(false);
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 2) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 5:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 1) {
Pecas novop = new Pecas(p6.getLadoDireito(), p6.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano6.setEnabled(false);
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 2) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 6:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 1) {
Pecas novop = new Pecas(p6.getLadoDireito(), p6.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano6.setEnabled(false);
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 2) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 7:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 1) {
Pecas novop = new Pecas(p6.getLadoDireito(), p6.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano6.setEnabled(false);
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 2) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 8:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 1) {
Pecas novop = new Pecas(p6.getLadoDireito(), p6.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano6.setEnabled(false);
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 2) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 9:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 1) {
Pecas novop = new Pecas(p6.getLadoDireito(), p6.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano6.setEnabled(false);
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 2) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 10:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 1) {
Pecas novop = new Pecas(p6.getLadoDireito(), p6.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano6.setEnabled(false);
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 2) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 11:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 1) {
Pecas novop = new Pecas(p6.getLadoDireito(), p6.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano6.setEnabled(false);
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 2) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 12:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 1) {
Pecas novop = new Pecas(p6.getLadoDireito(), p6.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano6.setEnabled(false);
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 2) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 13:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//verticias2//" + l6 + ".png"));
} else {
if (al.verificaLadosPedraDireita(arrayTabuleiro, p6) == 1) {
// obs: tem que inverter os valores antes de inserir
// no array.
Pecas novop = new Pecas(p6.getLadoDireito(), p6.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano6.setEnabled(false);
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//verticais2//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraDireita(arrayTabuleiro, p6) == 2) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//verticais2//" + l6 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_14.setEnabled(true);
btn_14.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_14.setEnabled(true);
btn_14.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
default:
JOptionPane.showMessageDialog(null, "Peas esgotadas");
break;
}
}
});
btnhumano7 = new JButton("");
btnhumano7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
++aux2;
Pecas p7 = arrayH.get(6);
String ladoa = p7.getLadoEsquerdo().toString();
String ladob = p7.getLadoDireito().toString();
System.out.println(l7 = ladoa + ladob);
switch (aux2) {
case 1:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_1.setEnabled(true);
btn_1.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 1) {
Pecas novop = new Pecas(p7.getLadoDireito(), p7.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano7.setEnabled(false);
btn_1.setEnabled(true);
btn_1.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 2) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_1.setEnabled(true);
btn_1.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 2:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 1) {
Pecas novop = new Pecas(p7.getLadoDireito(), p7.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano7.setEnabled(false);
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 2) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 3:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 1) {
Pecas novop = new Pecas(p7.getLadoDireito(), p7.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano7.setEnabled(false);
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 2) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 4:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 1) {
Pecas novop = new Pecas(p7.getLadoDireito(), p7.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano7.setEnabled(false);
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 2) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 5:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 1) {
Pecas novop = new Pecas(p7.getLadoDireito(), p7.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano7.setEnabled(false);
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 2) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 6:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 1) {
Pecas novop = new Pecas(p7.getLadoDireito(), p7.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano7.setEnabled(false);
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 2) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 7:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 1) {
Pecas novop = new Pecas(p7.getLadoDireito(), p7.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano7.setEnabled(false);
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 2) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 8:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 1) {
Pecas novop = new Pecas(p7.getLadoDireito(), p7.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano7.setEnabled(false);
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 2) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 9:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 1) {
Pecas novop = new Pecas(p7.getLadoDireito(), p7.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano7.setEnabled(false);
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 2) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 10:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 1) {
Pecas novop = new Pecas(p7.getLadoDireito(), p7.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano7.setEnabled(false);
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 2) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 11:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 1) {
Pecas novop = new Pecas(p7.getLadoDireito(), p7.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano7.setEnabled(false);
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 2) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 12:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 1) {
Pecas novop = new Pecas(p7.getLadoDireito(), p7.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano7.setEnabled(false);
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 2) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
if (valor == "") {
JOptionPane.showMessageDialog(null, "Maquina passa ou compra");
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//verticais2//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 13:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p7);
btnhumano2.setEnabled(false);
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//verticias2//" + l7 + ".png"));
} else {
if (al.verificaLadosPedraDireita(arrayTabuleiro, p7) == 1) {
// obs: tem que inverter os valores antes de inserir
// no array.
Pecas novop = new Pecas(p7.getLadoDireito(), p7.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano2.setEnabled(false);
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//verticais2//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraDireita(arrayTabuleiro, p7) == 2) {
arrayTabuleiro.add(p7);
btnhumano2.setEnabled(false);
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//verticais2//" + l7 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// possui um rando com 0 e 1, caso 0 a maquina
////////////////////////////////////////////////////////////////////////////////////////////////////////////// passa,
////////////////////////////////////////////////////////////////////////////////////////////////////////////// caso
////////////////////////////////////////////////////////////////////////////////////////////////////////////// 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////// ela
////////////////////////////////////////////////////////////////////////////////////////////////////////////// faz
////////////////////////////////////////////////////////////////////////////////////////////////////////////// uma
////////////////////////////////////////////////////////////////////////////////////////////////////////////// compra
////////////////////////////////////////////////////////////////////////////////////////////////////////////// no
////////////////////////////////////////////////////////////////////////////////////////////////////////////// array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no
// array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no
// tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_14.setEnabled(true);
btn_14.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_14.setEnabled(true);
btn_14.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
default:
JOptionPane.showMessageDialog(null, "Peas esgotadas");
break;
}
}
});
btnhumano8 = new JButton("");
btnhumano8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnhumano9 = new JButton("");
btnhumano9.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnhumano10 = new JButton("");
btnhumano11 = new JButton("");
btnhumano12 = new JButton("");
btnhumano13 = new JButton("");
btnhumano14 = new JButton("");
btnhumano15 = new JButton("");
btnhumano16 = new JButton("");
btnhumano17 = new JButton("");
btnhumano18 = new JButton("");
btnhumano18.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
panel_pecasJogador.add(btnhumano1);
panel_pecasJogador.add(btnhumano2);
panel_pecasJogador.add(btnhumano3);
panel_pecasJogador.add(btnhumano4);
panel_pecasJogador.add(btnhumano5);
panel_pecasJogador.add(btnhumano6);
panel_pecasJogador.add(btnhumano7);
panel_pecasJogador.add(btnhumano8);
panel_pecasJogador.add(btnhumano9);
panel_pecasJogador.add(btnhumano10);
panel_pecasJogador.add(btnhumano11);
panel_pecasJogador.add(btnhumano12);
panel_pecasJogador.add(btnhumano13);
panel_pecasJogador.add(btnhumano14);
panel_pecasJogador.add(btnhumano15);
panel_pecasJogador.add(btnhumano16);
panel_pecasJogador.add(btnhumano17);
panel_pecasJogador.add(btnhumano18);
JPanel panel_pecasAescolher = new JPanel();
panel_pecasAescolher.setBounds(0, 145, 330, 405);
getContentPane().add(panel_pecasAescolher);
panel_pecasAescolher.setLayout(new GridLayout(5, 6, 5, 5));
ImageIcon pecavirada = new ImageIcon(".//resource//imagens//pecavirada.png");
JButton btnpeca1 = new JButton(pecavirada);
btnpeca1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(0);
array.remove(0);
Pecas vazia = new Pecas(null, null);
array.add(0, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l1 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca1.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l1 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca1.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l1 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca1.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l1 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca1.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l1 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca1.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l1 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca1.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l1 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca1.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l1 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca1.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l1 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca1.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l1 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca1.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l1 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca1.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l1 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca1.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l1 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca1.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l1 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca1.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l1 + ".png"));
break;
case 15:
arrayH.add(p);
btnpeca1.setEnabled(false);
btnhumano8.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l1 + ".png"));
break;
case 16:
arrayH.add(p);
btnpeca1.setEnabled(false);
btnhumano9.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l1 + ".png"));
break;
case 17:
arrayH.add(p);
btnpeca1.setEnabled(false);
btnhumano10.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l1 + ".png"));
break;
case 18:
arrayH.add(p);
btnpeca1.setEnabled(false);
btnhumano11.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l1 + ".png"));
break;
case 19:
arrayH.add(p);
btnpeca1.setEnabled(false);
btnhumano12.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l1 + ".png"));
break;
case 20:
arrayH.add(p);
btnpeca1.setEnabled(false);
btnhumano13.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l1 + ".png"));
break;
case 21:
arrayH.add(p);
btnpeca1.setEnabled(false);
btnhumano14.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l1 + ".png"));
break;
case 22:
arrayH.add(p);
btnpeca1.setEnabled(false);
btnhumano15.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l1 + ".png"));
break;
case 23:
arrayH.add(p);
btnpeca1.setEnabled(false);
btnhumano16.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l1 + ".png"));
break;
case 24:
arrayH.add(p);
btnpeca1.setEnabled(false);
btnhumano17.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l1 + ".png"));
break;
case 25:
arrayH.add(p);
btnpeca1.setEnabled(false);
btnhumano18.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l1 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca2 = new JButton(pecavirada);
btnpeca2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(1);
array.remove(1);
Pecas vazia = new Pecas(null, null);
array.add(1, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l2 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca2.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l2 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca2.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l2 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca2.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l2 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca2.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l2 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca2.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l2 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca2.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l2 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca2.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l2 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca2.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l2 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca2.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l2 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca2.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l2 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca2.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l2 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca2.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l2 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca2.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l2 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca2.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l2 + ".png"));
break;
case 15:
arrayH.add(p);
btnpeca2.setEnabled(false);
btnhumano8.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l2 + ".png"));
break;
case 16:
arrayH.add(p);
btnpeca2.setEnabled(false);
btnhumano9.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l2 + ".png"));
break;
case 17:
arrayH.add(p);
btnpeca2.setEnabled(false);
btnhumano10.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l2 + ".png"));
break;
case 18:
arrayH.add(p);
btnpeca2.setEnabled(false);
btnhumano11.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l2 + ".png"));
break;
case 19:
arrayH.add(p);
btnpeca2.setEnabled(false);
btnhumano12.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l2 + ".png"));
break;
case 20:
arrayH.add(p);
btnpeca2.setEnabled(false);
btnhumano13.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l2 + ".png"));
break;
case 21:
arrayH.add(p);
btnpeca2.setEnabled(false);
btnhumano14.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l2 + ".png"));
break;
case 22:
arrayH.add(p);
btnpeca2.setEnabled(false);
btnhumano15.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l2 + ".png"));
break;
case 23:
arrayH.add(p);
btnpeca2.setEnabled(false);
btnhumano16.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l2 + ".png"));
break;
case 24:
arrayH.add(p);
btnpeca2.setEnabled(false);
btnhumano17.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l2 + ".png"));
break;
case 25:
arrayH.add(p);
btnpeca2.setEnabled(false);
btnhumano18.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l2 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca3 = new JButton(pecavirada);
btnpeca3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(2);
array.remove(2);
Pecas vazia = new Pecas(null, null);
array.add(2, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l3 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca3.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l3 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca3.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l3 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca3.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l3 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca3.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l3 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca3.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l3 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca3.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas/verticais1///" + l3 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca3.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l3 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca3.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l3 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca3.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l3 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca3.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l3 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca3.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l3 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca3.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l3 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca3.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l3 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca3.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l3 + ".png"));
break;
case 15:
arrayH.add(p);
btnpeca3.setEnabled(false);
btnhumano8.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l3 + ".png"));
break;
case 16:
arrayH.add(p);
btnpeca3.setEnabled(false);
btnhumano9.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l3 + ".png"));
break;
case 17:
arrayH.add(p);
btnpeca3.setEnabled(false);
btnhumano10.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l3 + ".png"));
break;
case 18:
arrayH.add(p);
btnpeca3.setEnabled(false);
btnhumano11.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l3 + ".png"));
break;
case 19:
arrayH.add(p);
btnpeca3.setEnabled(false);
btnhumano12.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l3 + ".png"));
break;
case 20:
arrayH.add(p);
btnpeca3.setEnabled(false);
btnhumano13.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l3 + ".png"));
break;
case 21:
arrayH.add(p);
btnpeca3.setEnabled(false);
btnhumano14.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l3 + ".png"));
break;
case 22:
arrayH.add(p);
btnpeca3.setEnabled(false);
btnhumano15.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l3 + ".png"));
break;
case 23:
arrayH.add(p);
btnpeca3.setEnabled(false);
btnhumano16.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l3 + ".png"));
break;
case 24:
arrayH.add(p);
btnpeca3.setEnabled(false);
btnhumano17.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l3 + ".png"));
break;
case 25:
arrayH.add(p);
btnpeca3.setEnabled(false);
btnhumano18.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l3 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca4 = new JButton(pecavirada);
btnpeca4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(3);
array.remove(3);
Pecas vazia = new Pecas(null, null);
array.add(3, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l4 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca4.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l4 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca4.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l4 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca4.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l4 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca4.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l4 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca4.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l4 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca4.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l4 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca4.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l4 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca4.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l4 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca4.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l4 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca4.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l4 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca4.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l4 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca4.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l4 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca4.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l4 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca4.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l4 + ".png"));
break;
case 15:
arrayH.add(p);
btnpeca4.setEnabled(false);
btnhumano8.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l4 + ".png"));
break;
case 16:
arrayH.add(p);
btnpeca4.setEnabled(false);
btnhumano9.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l4 + ".png"));
break;
case 17:
arrayH.add(p);
btnpeca4.setEnabled(false);
btnhumano10.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l4 + ".png"));
break;
case 18:
arrayH.add(p);
btnpeca4.setEnabled(false);
btnhumano11.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l4 + ".png"));
break;
case 19:
arrayH.add(p);
btnpeca4.setEnabled(false);
btnhumano12.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l4 + ".png"));
break;
case 20:
arrayH.add(p);
btnpeca4.setEnabled(false);
btnhumano13.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l4 + ".png"));
break;
case 21:
arrayH.add(p);
btnpeca4.setEnabled(false);
btnhumano14.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l4 + ".png"));
break;
case 22:
arrayH.add(p);
btnpeca4.setEnabled(false);
btnhumano15.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l4 + ".png"));
break;
case 23:
arrayH.add(p);
btnpeca4.setEnabled(false);
btnhumano16.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l4 + ".png"));
break;
case 24:
arrayH.add(p);
btnpeca4.setEnabled(false);
btnhumano17.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l4 + ".png"));
break;
case 25:
arrayH.add(p);
btnpeca4.setEnabled(false);
btnhumano18.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l4 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca5 = new JButton(pecavirada);
btnpeca5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(4);
array.remove(4);
Pecas vazia = new Pecas(null, null);
array.add(4, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l5 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca5.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l5 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca5.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l5 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca5.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l5 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca5.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l5 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca5.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l5 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca5.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l5 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca5.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l5 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca5.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l5 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca5.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l5 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca5.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l5 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca5.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l5 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca5.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l5 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca5.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l5 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca5.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l5 + ".png"));
break;
case 15:
arrayH.add(p);
btnpeca5.setEnabled(false);
btnhumano8.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l5 + ".png"));
break;
case 16:
arrayH.add(p);
btnpeca5.setEnabled(false);
btnhumano9.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l5 + ".png"));
break;
case 17:
arrayH.add(p);
btnpeca5.setEnabled(false);
btnhumano10.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l5 + ".png"));
break;
case 18:
arrayH.add(p);
btnpeca5.setEnabled(false);
btnhumano11.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l5 + ".png"));
break;
case 19:
arrayH.add(p);
btnpeca5.setEnabled(false);
btnhumano12.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l5 + ".png"));
break;
case 20:
arrayH.add(p);
btnpeca5.setEnabled(false);
btnhumano13.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l5 + ".png"));
break;
case 21:
arrayH.add(p);
btnpeca5.setEnabled(false);
btnhumano14.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l5 + ".png"));
break;
case 22:
arrayH.add(p);
btnpeca5.setEnabled(false);
btnhumano15.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l5 + ".png"));
break;
case 23:
arrayH.add(p);
btnpeca5.setEnabled(false);
btnhumano16.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l5 + ".png"));
break;
case 24:
arrayH.add(p);
btnpeca5.setEnabled(false);
btnhumano17.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l5 + ".png"));
break;
case 25:
arrayH.add(p);
btnpeca5.setEnabled(false);
btnhumano18.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l5 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca6 = new JButton(pecavirada);
btnpeca6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(5);
array.remove(5);
Pecas vazia = new Pecas(null, null);
array.add(5, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l6 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca6.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l6 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca6.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l6 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca6.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l6 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca6.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l6 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca6.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l6 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca6.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l6 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca6.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l6 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca6.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l6 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca6.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l6 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca6.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l6 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca6.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l6 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca6.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l6 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca6.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l6 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca6.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l6 + ".png"));
break;
case 15:
arrayH.add(p);
btnpeca6.setEnabled(false);
btnhumano8.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l6 + ".png"));
break;
case 16:
arrayH.add(p);
btnpeca6.setEnabled(false);
btnhumano9.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l6 + ".png"));
break;
case 17:
arrayH.add(p);
btnpeca6.setEnabled(false);
btnhumano10.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l6 + ".png"));
break;
case 18:
arrayH.add(p);
btnpeca6.setEnabled(false);
btnhumano11.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l6 + ".png"));
break;
case 19:
arrayH.add(p);
btnpeca6.setEnabled(false);
btnhumano12.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l6 + ".png"));
break;
case 20:
arrayH.add(p);
btnpeca6.setEnabled(false);
btnhumano13.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l6 + ".png"));
break;
case 21:
arrayH.add(p);
btnpeca6.setEnabled(false);
btnhumano14.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l6 + ".png"));
break;
case 22:
arrayH.add(p);
btnpeca6.setEnabled(false);
btnhumano15.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l6 + ".png"));
break;
case 23:
arrayH.add(p);
btnpeca6.setEnabled(false);
btnhumano16.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l6 + ".png"));
break;
case 24:
arrayH.add(p);
btnpeca6.setEnabled(false);
btnhumano17.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l6 + ".png"));
break;
case 25:
arrayH.add(p);
btnpeca6.setEnabled(false);
btnhumano18.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l6 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca7 = new JButton(pecavirada);
btnpeca7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(6);
array.remove(6);
Pecas vazia = new Pecas(null, null);
array.add(6, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l7 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca7.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l7 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca7.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l7 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca7.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l7 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca7.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l7 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca7.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l7 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca7.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l7 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca7.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l7 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca7.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l7 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca7.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l7 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca7.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l7 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca7.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l7 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca7.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l7 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca7.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l7 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca7.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l7 + ".png"));
break;
case 15:
arrayH.add(p);
btnpeca7.setEnabled(false);
btnhumano8.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l7 + ".png"));
break;
case 16:
arrayH.add(p);
btnpeca7.setEnabled(false);
btnhumano9.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l7 + ".png"));
break;
case 17:
arrayH.add(p);
btnpeca7.setEnabled(false);
btnhumano10.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l7 + ".png"));
break;
case 18:
arrayH.add(p);
btnpeca7.setEnabled(false);
btnhumano11.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l7 + ".png"));
break;
case 19:
arrayH.add(p);
btnpeca7.setEnabled(false);
btnhumano12.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l7 + ".png"));
break;
case 20:
arrayH.add(p);
btnpeca7.setEnabled(false);
btnhumano13.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l7 + ".png"));
break;
case 21:
arrayH.add(p);
btnpeca7.setEnabled(false);
btnhumano14.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l7 + ".png"));
break;
case 22:
arrayH.add(p);
btnpeca7.setEnabled(false);
btnhumano15.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l7 + ".png"));
break;
case 23:
arrayH.add(p);
btnpeca7.setEnabled(false);
btnhumano16.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l7 + ".png"));
break;
case 24:
arrayH.add(p);
btnpeca7.setEnabled(false);
btnhumano17.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l7 + ".png"));
break;
case 25:
arrayH.add(p);
btnpeca7.setEnabled(false);
btnhumano18.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l7 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca8 = new JButton(pecavirada);
btnpeca8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(7);
array.remove(7);
Pecas vazia = new Pecas(null, null);
array.add(7, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l8 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca8.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l8 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca8.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l8 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca8.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l8 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca8.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l8 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca8.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l8 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca8.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l8 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca8.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l8 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca8.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l8 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca8.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l8 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca8.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l8 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca8.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l8 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca8.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l8 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca8.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l8 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca8.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l8 + ".png"));
break;
case 15:
arrayH.add(p);
btnpeca8.setEnabled(false);
btnhumano8.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l8 + ".png"));
break;
case 16:
arrayH.add(p);
btnpeca8.setEnabled(false);
btnhumano9.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l8 + ".png"));
break;
case 17:
arrayH.add(p);
btnpeca8.setEnabled(false);
btnhumano10.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l8 + ".png"));
break;
case 18:
arrayH.add(p);
btnpeca8.setEnabled(false);
btnhumano11.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l8 + ".png"));
break;
case 19:
arrayH.add(p);
btnpeca8.setEnabled(false);
btnhumano12.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l8 + ".png"));
break;
case 20:
arrayH.add(p);
btnpeca8.setEnabled(false);
btnhumano13.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l8 + ".png"));
break;
case 21:
arrayH.add(p);
btnpeca8.setEnabled(false);
btnhumano14.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l8 + ".png"));
break;
case 22:
arrayH.add(p);
btnpeca8.setEnabled(false);
btnhumano15.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l8 + ".png"));
break;
case 23:
arrayH.add(p);
btnpeca8.setEnabled(false);
btnhumano16.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l8 + ".png"));
break;
case 24:
arrayH.add(p);
btnpeca8.setEnabled(false);
btnhumano17.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l8 + ".png"));
break;
case 25:
arrayH.add(p);
btnpeca8.setEnabled(false);
btnhumano18.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l8 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca9 = new JButton(pecavirada);
btnpeca9.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(8);
array.remove(8);
Pecas vazia = new Pecas(null, null);
array.add(8, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l9 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca9.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l9 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca9.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l9 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca9.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l9 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca9.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l9 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca9.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l9 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca9.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l9 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca9.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l9 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca9.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l9 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca9.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l9 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca9.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l9 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca9.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l9 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca9.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l9 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca9.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l9 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca9.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l9 + ".png"));
break;
case 15:
arrayH.add(p);
btnpeca9.setEnabled(false);
btnhumano8.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l9 + ".png"));
break;
case 16:
arrayH.add(p);
btnpeca9.setEnabled(false);
btnhumano9.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l9 + ".png"));
break;
case 17:
arrayH.add(p);
btnpeca9.setEnabled(false);
btnhumano10.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l9 + ".png"));
break;
case 18:
arrayH.add(p);
btnpeca9.setEnabled(false);
btnhumano11.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l9 + ".png"));
break;
case 19:
arrayH.add(p);
btnpeca9.setEnabled(false);
btnhumano12.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l9 + ".png"));
break;
case 20:
arrayH.add(p);
btnpeca9.setEnabled(false);
btnhumano13.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l9 + ".png"));
break;
case 21:
arrayH.add(p);
btnpeca9.setEnabled(false);
btnhumano14.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l9 + ".png"));
break;
case 22:
arrayH.add(p);
btnpeca9.setEnabled(false);
btnhumano15.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l9 + ".png"));
break;
case 23:
arrayH.add(p);
btnpeca9.setEnabled(false);
btnhumano16.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l9 + ".png"));
break;
case 24:
arrayH.add(p);
btnpeca9.setEnabled(false);
btnhumano17.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l9 + ".png"));
break;
case 25:
arrayH.add(p);
btnpeca9.setEnabled(false);
btnhumano18.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l9 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca10 = new JButton(pecavirada);
btnpeca10.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(9);
array.remove(9);
Pecas vazia = new Pecas(null, null);
array.add(9, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l26 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca10.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca10.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca10.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca10.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca10.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca10.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca10.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca10.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca10.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca10.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca10.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca10.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca10.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca10.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 15:
arrayH.add(p);
btnpeca10.setEnabled(false);
btnhumano8.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 16:
arrayH.add(p);
btnpeca10.setEnabled(false);
btnhumano9.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 17:
arrayH.add(p);
btnpeca10.setEnabled(false);
btnhumano10.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 18:
arrayH.add(p);
btnpeca10.setEnabled(false);
btnhumano11.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 19:
arrayH.add(p);
btnpeca10.setEnabled(false);
btnhumano12.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 20:
arrayH.add(p);
btnpeca10.setEnabled(false);
btnhumano13.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 21:
arrayH.add(p);
btnpeca10.setEnabled(false);
btnhumano14.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 22:
arrayH.add(p);
btnpeca10.setEnabled(false);
btnhumano15.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 23:
arrayH.add(p);
btnpeca10.setEnabled(false);
btnhumano16.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 24:
arrayH.add(p);
btnpeca10.setEnabled(false);
btnhumano17.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 25:
arrayH.add(p);
btnpeca10.setEnabled(false);
btnhumano18.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca11 = new JButton(pecavirada);
btnpeca11.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(10);
array.remove(10);
Pecas vazia = new Pecas(null, null);
array.add(10, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l11 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca11.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l11 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca11.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l11 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca11.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l11 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca11.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l11 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca11.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l11 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca11.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l11 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca11.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l11 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca11.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l11 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca11.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l11 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca11.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l11 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca11.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l11 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca11.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l11 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca11.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l11 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca11.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l11 + ".png"));
break;
case 15:
arrayH.add(p);
btnpeca11.setEnabled(false);
btnhumano8.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l11 + ".png"));
break;
case 16:
arrayH.add(p);
btnpeca11.setEnabled(false);
btnhumano9.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l11 + ".png"));
break;
case 17:
arrayH.add(p);
btnpeca11.setEnabled(false);
btnhumano10.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l11 + ".png"));
break;
case 18:
arrayH.add(p);
btnpeca11.setEnabled(false);
btnhumano11.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l11 + ".png"));
break;
case 19:
arrayH.add(p);
btnpeca11.setEnabled(false);
btnhumano12.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l11 + ".png"));
break;
case 20:
arrayH.add(p);
btnpeca11.setEnabled(false);
btnhumano13.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l11 + ".png"));
break;
case 21:
arrayH.add(p);
btnpeca11.setEnabled(false);
btnhumano14.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l11 + ".png"));
break;
case 22:
arrayH.add(p);
btnpeca11.setEnabled(false);
btnhumano15.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l11 + ".png"));
break;
case 23:
arrayH.add(p);
btnpeca11.setEnabled(false);
btnhumano16.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l11 + ".png"));
break;
case 24:
arrayH.add(p);
btnpeca11.setEnabled(false);
btnhumano17.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l11 + ".png"));
break;
case 25:
arrayH.add(p);
btnpeca11.setEnabled(false);
btnhumano18.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l11 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca12 = new JButton(pecavirada);
btnpeca12.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(11);
array.remove(11);
Pecas vazia = new Pecas(null, null);
array.add(11, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l12 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca12.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l12 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca12.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l12 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca12.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l12 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca12.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l12 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca12.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l12 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca12.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l12 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca12.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l12 + ".png"));
System.out.println("arrayH"+arrayH.size());
break;
case 8:
arrayM.add(p);
btnpeca12.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l12 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca12.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l12 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca12.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l12 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca12.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l12 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca12.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l12 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca12.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l12 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca12.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l12 + ".png"));
System.out.println("arrayM: "+arrayM.size());
break;
case 15:
arrayH.add(p);
btnpeca12.setEnabled(false);
btnhumano8.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l12 + ".png"));
break;
case 16:
arrayH.add(p);
btnpeca12.setEnabled(false);
btnhumano9.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l12 + ".png"));
break;
case 17:
arrayH.add(p);
btnpeca12.setEnabled(false);
btnhumano10.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l12 + ".png"));
break;
case 18:
arrayH.add(p);
btnpeca12.setEnabled(false);
btnhumano11.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l12 + ".png"));
break;
case 19:
arrayH.add(p);
btnpeca12.setEnabled(false);
btnhumano12.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l12 + ".png"));
break;
case 20:
arrayH.add(p);
btnpeca12.setEnabled(false);
btnhumano13.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l12 + ".png"));
break;
case 21:
arrayH.add(p);
btnpeca12.setEnabled(false);
btnhumano14.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l12 + ".png"));
break;
case 22:
arrayH.add(p);
btnpeca12.setEnabled(false);
btnhumano15.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l12 + ".png"));
break;
case 23:
arrayH.add(p);
btnpeca12.setEnabled(false);
btnhumano16.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l12 + ".png"));
break;
case 24:
arrayH.add(p);
btnpeca12.setEnabled(false);
btnhumano17.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l12 + ".png"));
break;
case 25:
arrayH.add(p);
btnpeca12.setEnabled(false);
btnhumano18.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l12 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca13 = new JButton(pecavirada);
btnpeca13.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(12);
array.remove(12);
Pecas vazia = new Pecas(null, null);
array.add(12, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l13 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca13.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l13 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca13.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l13 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca13.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l13 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca13.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l13 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca13.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l13 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca13.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l13 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca13.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l13 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca13.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l13 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca13.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l13 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca13.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l13 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca13.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l13 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca13.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l13 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca13.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l13 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca13.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l13 + ".png"));
break;
case 15:
arrayH.add(p);
btnpeca13.setEnabled(false);
btnhumano8.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l13 + ".png"));
break;
case 16:
arrayH.add(p);
btnpeca13.setEnabled(false);
btnhumano9.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l13 + ".png"));
break;
case 17:
arrayH.add(p);
btnpeca13.setEnabled(false);
btnhumano10.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l13 + ".png"));
break;
case 18:
arrayH.add(p);
btnpeca13.setEnabled(false);
btnhumano11.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l13 + ".png"));
break;
case 19:
arrayH.add(p);
btnpeca13.setEnabled(false);
btnhumano12.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l13 + ".png"));
break;
case 20:
arrayH.add(p);
btnpeca13.setEnabled(false);
btnhumano13.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l13 + ".png"));
break;
case 21:
arrayH.add(p);
btnpeca13.setEnabled(false);
btnhumano14.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l13 + ".png"));
break;
case 22:
arrayH.add(p);
btnpeca13.setEnabled(false);
btnhumano15.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l13 + ".png"));
break;
case 23:
arrayH.add(p);
btnpeca13.setEnabled(false);
btnhumano16.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l13 + ".png"));
break;
case 24:
arrayH.add(p);
btnpeca13.setEnabled(false);
btnhumano17.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l13 + ".png"));
break;
case 25:
arrayH.add(p);
btnpeca13.setEnabled(false);
btnhumano18.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l13 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca14 = new JButton(pecavirada);
btnpeca14.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(13);
array.remove(13);
Pecas vazia = new Pecas(null, null);
array.add(13, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l14 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca14.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l14 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca14.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l14 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca14.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l14 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca14.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l14 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca14.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l14 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca14.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l14 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca14.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l14 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca14.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l14 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca14.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l14 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca14.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l14 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca14.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l14 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca14.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l14 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca14.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l14 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca14.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l14 + ".png"));
break;
case 15:
arrayH.add(p);
btnpeca14.setEnabled(false);
btnhumano8.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l14 + ".png"));
break;
case 16:
arrayH.add(p);
btnpeca14.setEnabled(false);
btnhumano9.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l14 + ".png"));
break;
case 17:
arrayH.add(p);
btnpeca14.setEnabled(false);
btnhumano10.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l14 + ".png"));
break;
case 18:
arrayH.add(p);
btnpeca14.setEnabled(false);
btnhumano11.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l14 + ".png"));
break;
case 19:
arrayH.add(p);
btnpeca14.setEnabled(false);
btnhumano12.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l14 + ".png"));
break;
case 20:
arrayH.add(p);
btnpeca14.setEnabled(false);
btnhumano13.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l14 + ".png"));
break;
case 21:
arrayH.add(p);
btnpeca14.setEnabled(false);
btnhumano14.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l14 + ".png"));
break;
case 22:
arrayH.add(p);
btnpeca14.setEnabled(false);
btnhumano15.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l14 + ".png"));
break;
case 23:
arrayH.add(p);
btnpeca14.setEnabled(false);
btnhumano16.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l14 + ".png"));
break;
case 24:
arrayH.add(p);
btnpeca14.setEnabled(false);
btnhumano17.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l14 + ".png"));
break;
case 25:
arrayH.add(p);
btnpeca14.setEnabled(false);
btnhumano18.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l14 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca15 = new JButton(pecavirada);
btnpeca15.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(14);
array.remove(14);
Pecas vazia = new Pecas(null, null);
array.add(14, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l15 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca15.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l15 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca15.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l15 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca15.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l15 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca15.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l15 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca15.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l15 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca15.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l15 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca15.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l15 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca15.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l15 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca15.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l15 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca15.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l15 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca15.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l15 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca15.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l15 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca15.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l15 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca15.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l15 + ".png"));
break;
case 15:
arrayH.add(p);
btnpeca15.setEnabled(false);
btnhumano8.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l15 + ".png"));
break;
case 16:
arrayH.add(p);
btnpeca15.setEnabled(false);
btnhumano9.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l15 + ".png"));
break;
case 17:
arrayH.add(p);
btnpeca15.setEnabled(false);
btnhumano10.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l15 + ".png"));
break;
case 18:
arrayH.add(p);
btnpeca15.setEnabled(false);
btnhumano11.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l15 + ".png"));
break;
case 19:
arrayH.add(p);
btnpeca15.setEnabled(false);
btnhumano12.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l15 + ".png"));
break;
case 20:
arrayH.add(p);
btnpeca15.setEnabled(false);
btnhumano13.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l15 + ".png"));
break;
case 21:
arrayH.add(p);
btnpeca15.setEnabled(false);
btnhumano14.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l15 + ".png"));
break;
case 22:
arrayH.add(p);
btnpeca15.setEnabled(false);
btnhumano15.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l15 + ".png"));
break;
case 23:
arrayH.add(p);
btnpeca15.setEnabled(false);
btnhumano16.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l15 + ".png"));
break;
case 24:
arrayH.add(p);
btnpeca15.setEnabled(false);
btnhumano17.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l15 + ".png"));
break;
case 25:
arrayH.add(p);
btnpeca15.setEnabled(false);
btnhumano18.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l15 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca16 = new JButton(pecavirada);
btnpeca16.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(15);
array.remove(15);
Pecas vazia = new Pecas(null, null);
array.add(15, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l16 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca16.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l16 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca16.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l16 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca16.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l16 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca16.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l16 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca16.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l16 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca16.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l16 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca16.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l16 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca16.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l16 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca16.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l16 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca16.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l16 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca16.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l16 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca16.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l16 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca16.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l16 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca16.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l16 + ".png"));
break;
case 15:
arrayH.add(p);
btnpeca16.setEnabled(false);
btnhumano8.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l16 + ".png"));
break;
case 16:
arrayH.add(p);
btnpeca16.setEnabled(false);
btnhumano9.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l16 + ".png"));
break;
case 17:
arrayH.add(p);
btnpeca16.setEnabled(false);
btnhumano10.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l16 + ".png"));
break;
case 18:
arrayH.add(p);
btnpeca16.setEnabled(false);
btnhumano11.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l16 + ".png"));
break;
case 19:
arrayH.add(p);
btnpeca16.setEnabled(false);
btnhumano12.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l16 + ".png"));
break;
case 20:
arrayH.add(p);
btnpeca16.setEnabled(false);
btnhumano13.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l16 + ".png"));
break;
case 21:
arrayH.add(p);
btnpeca16.setEnabled(false);
btnhumano14.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l16 + ".png"));
break;
case 22:
arrayH.add(p);
btnpeca16.setEnabled(false);
btnhumano15.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l16 + ".png"));
break;
case 23:
arrayH.add(p);
btnpeca16.setEnabled(false);
btnhumano16.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l16 + ".png"));
break;
case 24:
arrayH.add(p);
btnpeca16.setEnabled(false);
btnhumano17.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l16 + ".png"));
break;
case 25:
arrayH.add(p);
btnpeca16.setEnabled(false);
btnhumano18.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l16 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca17 = new JButton(pecavirada);
btnpeca17.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(16);
array.remove(16);
Pecas vazia = new Pecas(null, null);
array.add(16, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l17 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca17.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l17 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca17.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l17 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca17.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l17 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca17.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l17 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca17.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l17 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca17.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l17 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca17.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l17 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca17.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l17 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca17.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l17 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca17.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l17 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca17.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l17 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca17.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l17 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca17.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l17 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca17.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l17 + ".png"));
break;
case 15:
arrayH.add(p);
btnpeca17.setEnabled(false);
btnhumano8.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l17 + ".png"));
break;
case 16:
arrayH.add(p);
btnpeca17.setEnabled(false);
btnhumano9.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l17 + ".png"));
break;
case 17:
arrayH.add(p);
btnpeca17.setEnabled(false);
btnhumano10.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l17 + ".png"));
break;
case 18:
arrayH.add(p);
btnpeca17.setEnabled(false);
btnhumano11.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l17 + ".png"));
break;
case 19:
arrayH.add(p);
btnpeca17.setEnabled(false);
btnhumano12.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l17 + ".png"));
break;
case 20:
arrayH.add(p);
btnpeca17.setEnabled(false);
btnhumano13.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l17 + ".png"));
break;
case 21:
arrayH.add(p);
btnpeca17.setEnabled(false);
btnhumano14.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l17 + ".png"));
break;
case 22:
arrayH.add(p);
btnpeca17.setEnabled(false);
btnhumano15.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l17 + ".png"));
break;
case 23:
arrayH.add(p);
btnpeca17.setEnabled(false);
btnhumano16.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l17 + ".png"));
break;
case 24:
arrayH.add(p);
btnpeca17.setEnabled(false);
btnhumano17.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l17 + ".png"));
break;
case 25:
arrayH.add(p);
btnpeca17.setEnabled(false);
btnhumano18.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l17 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca18 = new JButton(pecavirada);
btnpeca18.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(17);
array.remove(17);
Pecas vazia = new Pecas(null, null);
array.add(17, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l18 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca18.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l18 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca18.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l18 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca18.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l18 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca18.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l18 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca18.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l18 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca18.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l18 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca18.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l18 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca18.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l18 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca18.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l18 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca18.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l18 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca18.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l18 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca18.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l18 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca18.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l18 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca18.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l18 + ".png"));
break;
case 15:
arrayH.add(p);
btnpeca18.setEnabled(false);
btnhumano8.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l18 + ".png"));
break;
case 16:
arrayH.add(p);
btnpeca18.setEnabled(false);
btnhumano9.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l18 + ".png"));
break;
case 17:
arrayH.add(p);
btnpeca18.setEnabled(false);
btnhumano10.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l18 + ".png"));
break;
case 18:
arrayH.add(p);
btnpeca18.setEnabled(false);
btnhumano11.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l18 + ".png"));
break;
case 19:
arrayH.add(p);
btnpeca18.setEnabled(false);
btnhumano12.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l18 + ".png"));
break;
case 20:
arrayH.add(p);
btnpeca18.setEnabled(false);
btnhumano13.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l18 + ".png"));
break;
case 21:
arrayH.add(p);
btnpeca18.setEnabled(false);
btnhumano14.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l18 + ".png"));
break;
case 22:
arrayH.add(p);
btnpeca18.setEnabled(false);
btnhumano15.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l18 + ".png"));
break;
case 23:
arrayH.add(p);
btnpeca18.setEnabled(false);
btnhumano16.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l18 + ".png"));
break;
case 24:
arrayH.add(p);
btnpeca18.setEnabled(false);
btnhumano17.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l18 + ".png"));
break;
case 25:
arrayH.add(p);
btnpeca18.setEnabled(false);
btnhumano18.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l18 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca19 = new JButton(pecavirada);
btnpeca19.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(18);
array.remove(18);
Pecas vazia = new Pecas(null, null);
array.add(18, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l19 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca19.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l19 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca19.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l19 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca19.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l19 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca19.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l19 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca19.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l19 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca19.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l19 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca19.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l19 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca19.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l19 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca19.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l19 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca19.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l19 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca19.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l19 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca19.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l19 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca19.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l19 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca19.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l19 + ".png"));
break;
case 15:
arrayH.add(p);
btnpeca19.setEnabled(false);
btnhumano8.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l19 + ".png"));
break;
case 16:
arrayH.add(p);
btnpeca19.setEnabled(false);
btnhumano9.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l19 + ".png"));
break;
case 17:
arrayH.add(p);
btnpeca19.setEnabled(false);
btnhumano10.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l19 + ".png"));
break;
case 18:
arrayH.add(p);
btnpeca19.setEnabled(false);
btnhumano11.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l19 + ".png"));
break;
case 19:
arrayH.add(p);
btnpeca19.setEnabled(false);
btnhumano12.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l19 + ".png"));
break;
case 20:
arrayH.add(p);
btnpeca19.setEnabled(false);
btnhumano13.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l19 + ".png"));
break;
case 21:
arrayH.add(p);
btnpeca19.setEnabled(false);
btnhumano14.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l19 + ".png"));
break;
case 22:
arrayH.add(p);
btnpeca19.setEnabled(false);
btnhumano15.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l19 + ".png"));
break;
case 23:
arrayH.add(p);
btnpeca19.setEnabled(false);
btnhumano16.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l19 + ".png"));
break;
case 24:
arrayH.add(p);
btnpeca19.setEnabled(false);
btnhumano17.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l19 + ".png"));
break;
case 25:
arrayH.add(p);
btnpeca19.setEnabled(false);
btnhumano18.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l19 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca20 = new JButton(pecavirada);
btnpeca20.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(19);
array.remove(19);
Pecas vazia = new Pecas(null, null);
array.add(19, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l20 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca20.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l20 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca20.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l20 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca20.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l20 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca20.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l20 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca20.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l20 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca20.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l20 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca20.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l20 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca20.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l20 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca20.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l20 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca20.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l20 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca20.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l20 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca20.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l20 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca20.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l20 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca20.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l20 + ".png"));
break;
case 15:
arrayH.add(p);
btnpeca20.setEnabled(false);
btnhumano8.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l20 + ".png"));
break;
case 16:
arrayH.add(p);
btnpeca20.setEnabled(false);
btnhumano9.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l20 + ".png"));
break;
case 17:
arrayH.add(p);
btnpeca20.setEnabled(false);
btnhumano10.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l20 + ".png"));
break;
case 18:
arrayH.add(p);
btnpeca20.setEnabled(false);
btnhumano11.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l20 + ".png"));
break;
case 19:
arrayH.add(p);
btnpeca20.setEnabled(false);
btnhumano12.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l20 + ".png"));
break;
case 20:
arrayH.add(p);
btnpeca20.setEnabled(false);
btnhumano13.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l20 + ".png"));
break;
case 21:
arrayH.add(p);
btnpeca20.setEnabled(false);
btnhumano14.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l20 + ".png"));
break;
case 22:
arrayH.add(p);
btnpeca20.setEnabled(false);
btnhumano15.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l20 + ".png"));
break;
case 23:
arrayH.add(p);
btnpeca20.setEnabled(false);
btnhumano16.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l20 + ".png"));
break;
case 24:
arrayH.add(p);
btnpeca20.setEnabled(false);
btnhumano17.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l20 + ".png"));
break;
case 25:
arrayH.add(p);
btnpeca20.setEnabled(false);
btnhumano18.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l20 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca21 = new JButton(pecavirada);
btnpeca21.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(20);
array.remove(20);
Pecas vazia = new Pecas(null, null);
array.add(20, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l21 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca21.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l21 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca21.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l21 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca21.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l21 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca21.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l21 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca21.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l21 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca21.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l21 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca21.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l21 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca21.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l21 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca21.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l21 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca21.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l21 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca21.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l21 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca21.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l21 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca21.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l21 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca21.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l21 + ".png"));
break;
case 15:
arrayH.add(p);
btnpeca21.setEnabled(false);
btnhumano8.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l21 + ".png"));
break;
case 16:
arrayH.add(p);
btnpeca21.setEnabled(false);
btnhumano9.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l21 + ".png"));
break;
case 17:
arrayH.add(p);
btnpeca21.setEnabled(false);
btnhumano10.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l21 + ".png"));
break;
case 18:
arrayH.add(p);
btnpeca21.setEnabled(false);
btnhumano11.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l21 + ".png"));
break;
case 19:
arrayH.add(p);
btnpeca21.setEnabled(false);
btnhumano12.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l21 + ".png"));
break;
case 20:
arrayH.add(p);
btnpeca21.setEnabled(false);
btnhumano13.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l21 + ".png"));
break;
case 21:
arrayH.add(p);
btnpeca21.setEnabled(false);
btnhumano14.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l21 + ".png"));
break;
case 22:
arrayH.add(p);
btnpeca21.setEnabled(false);
btnhumano15.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l21 + ".png"));
break;
case 23:
arrayH.add(p);
btnpeca21.setEnabled(false);
btnhumano16.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l21 + ".png"));
break;
case 24:
arrayH.add(p);
btnpeca21.setEnabled(false);
btnhumano17.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l21 + ".png"));
break;
case 25:
arrayH.add(p);
btnpeca21.setEnabled(false);
btnhumano18.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l21 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca22 = new JButton(pecavirada);
btnpeca22.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(21);
array.remove(21);
Pecas vazia = new Pecas(null, null);
array.add(21, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l22 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca22.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l22 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca22.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l22 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca22.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l22 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca22.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l22 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca22.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l22 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca22.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l22 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca22.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l22 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca22.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l22 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca22.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l22 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca22.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l22 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca22.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l22 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca22.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l22 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca22.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l22 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca22.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l22 + ".png"));
break;
case 15:
arrayH.add(p);
btnpeca22.setEnabled(false);
btnhumano8.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l22 + ".png"));
break;
case 16:
arrayH.add(p);
btnpeca22.setEnabled(false);
btnhumano9.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l22 + ".png"));
break;
case 17:
arrayH.add(p);
btnpeca22.setEnabled(false);
btnhumano10.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l22 + ".png"));
break;
case 18:
arrayH.add(p);
btnpeca22.setEnabled(false);
btnhumano11.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l22 + ".png"));
break;
case 19:
arrayH.add(p);
btnpeca22.setEnabled(false);
btnhumano12.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l22 + ".png"));
break;
case 20:
arrayH.add(p);
btnpeca22.setEnabled(false);
btnhumano13.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l22 + ".png"));
break;
case 21:
arrayH.add(p);
btnpeca22.setEnabled(false);
btnhumano14.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l22 + ".png"));
break;
case 22:
arrayH.add(p);
btnpeca22.setEnabled(false);
btnhumano15.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l22 + ".png"));
break;
case 23:
arrayH.add(p);
btnpeca22.setEnabled(false);
btnhumano16.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l22 + ".png"));
break;
case 24:
arrayH.add(p);
btnpeca22.setEnabled(false);
btnhumano17.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l22 + ".png"));
break;
case 25:
arrayH.add(p);
btnpeca22.setEnabled(false);
btnhumano18.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l22 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca23 = new JButton(pecavirada);
btnpeca23.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(22);
array.remove(22);
Pecas vazia = new Pecas(null, null);
array.add(22, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l23 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca23.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l23 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca23.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l23 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca23.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l23 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca23.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l23 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca23.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l23 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca23.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l23 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca23.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas/verticais1///" + l23 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca23.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l23 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca23.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l23 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca23.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l23 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca23.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l23 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca23.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l23 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca23.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l23 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca23.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l23 + ".png"));
break;
case 15:
arrayH.add(p);
btnpeca23.setEnabled(false);
btnhumano8.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l23 + ".png"));
break;
case 16:
arrayH.add(p);
btnpeca23.setEnabled(false);
btnhumano9.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l23 + ".png"));
break;
case 17:
arrayH.add(p);
btnpeca23.setEnabled(false);
btnhumano10.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l23 + ".png"));
break;
case 18:
arrayH.add(p);
btnpeca23.setEnabled(false);
btnhumano11.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l23 + ".png"));
break;
case 19:
arrayH.add(p);
btnpeca23.setEnabled(false);
btnhumano12.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l23 + ".png"));
break;
case 20:
arrayH.add(p);
btnpeca23.setEnabled(false);
btnhumano13.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l23 + ".png"));
break;
case 21:
arrayH.add(p);
btnpeca23.setEnabled(false);
btnhumano14.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l23 + ".png"));
break;
case 22:
arrayH.add(p);
btnpeca23.setEnabled(false);
btnhumano15.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l23 + ".png"));
break;
case 23:
arrayH.add(p);
btnpeca23.setEnabled(false);
btnhumano16.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l23 + ".png"));
break;
case 24:
arrayH.add(p);
btnpeca23.setEnabled(false);
btnhumano17.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l23 + ".png"));
break;
case 25:
arrayH.add(p);
btnpeca23.setEnabled(false);
btnhumano18.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l23 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca24 = new JButton(pecavirada);
btnpeca24.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(23);
array.remove(23);
Pecas vazia = new Pecas(null, null);
array.add(23, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l24 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca24.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l24 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca24.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l24 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca24.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l24 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca24.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l24 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca24.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l24 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca24.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l24 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca24.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l24 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca24.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l24 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca24.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l24 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca24.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l24 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca24.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l24 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca24.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l24 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca24.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l24 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca24.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l24 + ".png"));
break;
case 15:
arrayH.add(p);
btnpeca24.setEnabled(false);
btnhumano8.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l24 + ".png"));
break;
case 16:
arrayH.add(p);
btnpeca24.setEnabled(false);
btnhumano9.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l24 + ".png"));
break;
case 17:
arrayH.add(p);
btnpeca24.setEnabled(false);
btnhumano10.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l24 + ".png"));
break;
case 18:
arrayH.add(p);
btnpeca24.setEnabled(false);
btnhumano11.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l24 + ".png"));
break;
case 19:
arrayH.add(p);
btnpeca24.setEnabled(false);
btnhumano12.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l24 + ".png"));
break;
case 20:
arrayH.add(p);
btnpeca24.setEnabled(false);
btnhumano13.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l24 + ".png"));
break;
case 21:
arrayH.add(p);
btnpeca24.setEnabled(false);
btnhumano14.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l24 + ".png"));
break;
case 22:
arrayH.add(p);
btnpeca24.setEnabled(false);
btnhumano15.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l24 + ".png"));
break;
case 23:
arrayH.add(p);
btnpeca24.setEnabled(false);
btnhumano16.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l24 + ".png"));
break;
case 24:
arrayH.add(p);
btnpeca24.setEnabled(false);
btnhumano17.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l24 + ".png"));
break;
case 25:
arrayH.add(p);
btnpeca24.setEnabled(false);
btnhumano18.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l24 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca25 = new JButton(pecavirada);
btnpeca25.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(24);
array.remove(24);
Pecas vazia = new Pecas(null, null);
array.add(24, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l25 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca25.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l25 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca25.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l25 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca25.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l25 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca25.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l25 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca25.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l25 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca25.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l25 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca25.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l25 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca25.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l25 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca25.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l25 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca25.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l25 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca25.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l25 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca25.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l25 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca25.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l25 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca25.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l25 + ".png"));
break;
case 15:
arrayH.add(p);
btnpeca25.setEnabled(false);
btnhumano8.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l25 + ".png"));
break;
case 16:
arrayH.add(p);
btnpeca25.setEnabled(false);
btnhumano9.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l25 + ".png"));
break;
case 17:
arrayH.add(p);
btnpeca25.setEnabled(false);
btnhumano10.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l25 + ".png"));
break;
case 18:
arrayH.add(p);
btnpeca25.setEnabled(false);
btnhumano11.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l25 + ".png"));
break;
case 19:
arrayH.add(p);
btnpeca25.setEnabled(false);
btnhumano12.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l25 + ".png"));
break;
case 20:
arrayH.add(p);
btnpeca25.setEnabled(false);
btnhumano13.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l25 + ".png"));
break;
case 21:
arrayH.add(p);
btnpeca25.setEnabled(false);
btnhumano14.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l25 + ".png"));
break;
case 22:
arrayH.add(p);
btnpeca25.setEnabled(false);
btnhumano15.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l25 + ".png"));
break;
case 23:
arrayH.add(p);
btnpeca25.setEnabled(false);
btnhumano16.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l25 + ".png"));
break;
case 24:
arrayH.add(p);
btnpeca25.setEnabled(false);
btnhumano17.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l25 + ".png"));
break;
case 25:
arrayH.add(p);
btnpeca25.setEnabled(false);
btnhumano18.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l25 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca26 = new JButton(pecavirada);
btnpeca26.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(25);
array.remove(25);
Pecas vazia = new Pecas(null, null);
array.add(25, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l26 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca26.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca26.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca26.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca26.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca26.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca26.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca26.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca26.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca26.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca26.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca26.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca26.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca26.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca26.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 15:
arrayH.add(p);
btnpeca26.setEnabled(false);
btnhumano8.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 16:
arrayH.add(p);
btnpeca26.setEnabled(false);
btnhumano9.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 17:
arrayH.add(p);
btnpeca26.setEnabled(false);
btnhumano10.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 18:
arrayH.add(p);
btnpeca26.setEnabled(false);
btnhumano11.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 19:
arrayH.add(p);
btnpeca26.setEnabled(false);
btnhumano12.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 20:
arrayH.add(p);
btnpeca26.setEnabled(false);
btnhumano13.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 21:
arrayH.add(p);
btnpeca26.setEnabled(false);
btnhumano14.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 22:
arrayH.add(p);
btnpeca26.setEnabled(false);
btnhumano15.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 23:
arrayH.add(p);
btnpeca26.setEnabled(false);
btnhumano16.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 24:
arrayH.add(p);
btnpeca26.setEnabled(false);
btnhumano17.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 25:
arrayH.add(p);
btnpeca26.setEnabled(false);
btnhumano18.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca27 = new JButton(pecavirada);
btnpeca27.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(26);
array.remove(26);
Pecas vazia = new Pecas(null, null);
array.add(26, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l27 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca27.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l27 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca27.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l27 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca27.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l27 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca27.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l27 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca27.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l27 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca27.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l27 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca27.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l27 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca27.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l27 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca27.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l27 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca27.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l27 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca27.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l27 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca27.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l27 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca27.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l27 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca27.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l27 + ".png"));
break;
case 15:
arrayH.add(p);
btnpeca27.setEnabled(false);
btnhumano8.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l27 + ".png"));
break;
case 16:
arrayH.add(p);
btnpeca27.setEnabled(false);
btnhumano9.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l27 + ".png"));
break;
case 17:
arrayH.add(p);
btnpeca27.setEnabled(false);
btnhumano10.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l27 + ".png"));
break;
case 18:
arrayH.add(p);
btnpeca27.setEnabled(false);
btnhumano11.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l27 + ".png"));
break;
case 19:
arrayH.add(p);
btnpeca27.setEnabled(false);
btnhumano12.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l27 + ".png"));
break;
case 20:
arrayH.add(p);
btnpeca27.setEnabled(false);
btnhumano13.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l27 + ".png"));
break;
case 21:
arrayH.add(p);
btnpeca27.setEnabled(false);
btnhumano14.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l27 + ".png"));
break;
case 22:
arrayH.add(p);
btnpeca27.setEnabled(false);
btnhumano15.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l27 + ".png"));
break;
case 23:
arrayH.add(p);
btnpeca27.setEnabled(false);
btnhumano16.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l27 + ".png"));
break;
case 24:
arrayH.add(p);
btnpeca27.setEnabled(false);
btnhumano17.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l27 + ".png"));
break;
case 25:
arrayH.add(p);
btnpeca27.setEnabled(false);
btnhumano18.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l27 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca28 = new JButton(pecavirada);
btnpeca28.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(27);
array.remove(27);
Pecas vazia = new Pecas(null, null);
array.add(27, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l28 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca28.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l28 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca28.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l28 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca28.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l28 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca28.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l28 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca28.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l28 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca28.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l28 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca28.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l28 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca28.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l28 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca28.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l28 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca28.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l28 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca28.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l28 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca28.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l28 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca28.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l28 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca28.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l28 + ".png"));
break;
case 15:
arrayH.add(p);
btnpeca28.setEnabled(false);
btnhumano8.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l28 + ".png"));
break;
case 16:
arrayH.add(p);
btnpeca28.setEnabled(false);
btnhumano9.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l28 + ".png"));
break;
case 17:
arrayH.add(p);
btnpeca28.setEnabled(false);
btnhumano10.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l28 + ".png"));
break;
case 18:
arrayH.add(p);
btnpeca28.setEnabled(false);
btnhumano11.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l28 + ".png"));
break;
case 19:
arrayH.add(p);
btnpeca28.setEnabled(false);
btnhumano12.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l28 + ".png"));
break;
case 20:
arrayH.add(p);
btnpeca28.setEnabled(false);
btnhumano13.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l28 + ".png"));
break;
case 21:
arrayH.add(p);
btnpeca28.setEnabled(false);
btnhumano14.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l28 + ".png"));
break;
case 22:
arrayH.add(p);
btnpeca28.setEnabled(false);
btnhumano15.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l28 + ".png"));
break;
case 23:
arrayH.add(p);
btnpeca28.setEnabled(false);
btnhumano16.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l28 + ".png"));
break;
case 24:
arrayH.add(p);
btnpeca28.setEnabled(false);
btnhumano17.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l28 + ".png"));
break;
case 25:
arrayH.add(p);
btnpeca28.setEnabled(false);
btnhumano18.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l28 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
panel_pecasAescolher.add(btnpeca1);
panel_pecasAescolher.add(btnpeca2);
panel_pecasAescolher.add(btnpeca3);
panel_pecasAescolher.add(btnpeca4);
panel_pecasAescolher.add(btnpeca5);
panel_pecasAescolher.add(btnpeca6);
panel_pecasAescolher.add(btnpeca7);
panel_pecasAescolher.add(btnpeca8);
panel_pecasAescolher.add(btnpeca9);
panel_pecasAescolher.add(btnpeca10);
panel_pecasAescolher.add(btnpeca11);
panel_pecasAescolher.add(btnpeca12);
panel_pecasAescolher.add(btnpeca13);
panel_pecasAescolher.add(btnpeca14);
panel_pecasAescolher.add(btnpeca15);
panel_pecasAescolher.add(btnpeca16);
panel_pecasAescolher.add(btnpeca17);
panel_pecasAescolher.add(btnpeca18);
panel_pecasAescolher.add(btnpeca19);
panel_pecasAescolher.add(btnpeca20);
panel_pecasAescolher.add(btnpeca21);
panel_pecasAescolher.add(btnpeca22);
panel_pecasAescolher.add(btnpeca23);
panel_pecasAescolher.add(btnpeca24);
panel_pecasAescolher.add(btnpeca25);
panel_pecasAescolher.add(btnpeca26);
panel_pecasAescolher.add(btnpeca27);
panel_pecasAescolher.add(btnpeca28);
JPanel panel_tabuleiro = new JPanel();
panel_tabuleiro.setBorder(new LineBorder(Color.RED, 1, true));
panel_tabuleiro.setBounds(361, 124, 979, 426);
getContentPane().add(panel_tabuleiro);
panel_tabuleiro.setLayout(null);
btn_14 = new JButton("");
btn_14.setEnabled(false);
btn_14.setBounds(37, 145, 35, 70);
panel_tabuleiro.add(btn_14);
btn_13 = new JButton("");
btn_13.setEnabled(false);
btn_13.setBounds(37, 76, 35, 70);
panel_tabuleiro.add(btn_13);
btn_15 = new JButton("");
btn_15.setEnabled(false);
btn_15.setBounds(37, 214, 35, 70);
panel_tabuleiro.add(btn_15);
btn_12 = new JButton("");
btn_12.setEnabled(false);
btn_12.setBounds(37, 42, 70, 35);
panel_tabuleiro.add(btn_12);
btn_16 = new JButton("");
btn_16.setEnabled(false);
btn_16.setBounds(37, 283, 35, 70);
panel_tabuleiro.add(btn_16);
btn_18 = new JButton("");
btn_18.setEnabled(false);
btn_18.setBounds(106, 352, 70, 35);
panel_tabuleiro.add(btn_18);
btn_11 = new JButton("");
btn_11.setEnabled(false);
btn_11.setBounds(106, 42, 70, 35);
panel_tabuleiro.add(btn_11);
btn_23 = new JButton("");
btn_23.setEnabled(false);
btn_23.setBounds(451, 352, 70, 35);
panel_tabuleiro.add(btn_23);
btn_10 = new JButton("");
btn_10.setEnabled(false);
btn_10.setBounds(175, 42, 70, 35);
panel_tabuleiro.add(btn_10);
btn_9 = new JButton("");
btn_9.setEnabled(false);
btn_9.setBounds(244, 42, 70, 35);
panel_tabuleiro.add(btn_9);
btn_8 = new JButton("");
btn_8.setEnabled(false);
btn_8.setBounds(313, 42, 70, 35);
panel_tabuleiro.add(btn_8);
btn_7 = new JButton("");
btn_7.setEnabled(false);
btn_7.setBounds(382, 42, 70, 35);
panel_tabuleiro.add(btn_7);
btn_6 = new JButton("");
btn_6.setEnabled(false);
btn_6.setBounds(451, 42, 70, 35);
panel_tabuleiro.add(btn_6);
btn_5 = new JButton("");
btn_5.setEnabled(false);
btn_5.setBounds(520, 42, 70, 35);
panel_tabuleiro.add(btn_5);
btn_17 = new JButton("");
btn_17.setEnabled(false);
btn_17.setBounds(37, 352, 70, 35);
panel_tabuleiro.add(btn_17);
btn_19 = new JButton("");
btn_19.setEnabled(false);
btn_19.setBounds(175, 352, 70, 35);
panel_tabuleiro.add(btn_19);
btn_20 = new JButton("");
btn_20.setEnabled(false);
btn_20.setBounds(244, 352, 70, 35);
panel_tabuleiro.add(btn_20);
btn_21 = new JButton("");
btn_21.setEnabled(false);
btn_21.setBounds(313, 352, 70, 35);
panel_tabuleiro.add(btn_21);
btn_22 = new JButton("");
btn_22.setEnabled(false);
btn_22.setBounds(382, 352, 70, 35);
panel_tabuleiro.add(btn_22);
btn_27 = new JButton("");
btn_27.setEnabled(false);
btn_27.setBounds(728, 352, 70, 35);
panel_tabuleiro.add(btn_27);
btn_24 = new JButton("");
btn_24.setEnabled(false);
btn_24.setBounds(521, 352, 70, 35);
panel_tabuleiro.add(btn_24);
btn_25 = new JButton("");
btn_25.setEnabled(false);
btn_25.setBounds(590, 352, 70, 35);
panel_tabuleiro.add(btn_25);
btn_26 = new JButton("");
btn_26.setEnabled(false);
btn_26.setBounds(659, 352, 70, 35);
panel_tabuleiro.add(btn_26);
btn_4 = new JButton("");
btn_4.setEnabled(false);
btn_4.setBounds(589, 42, 70, 35);
panel_tabuleiro.add(btn_4);
btn_3 = new JButton("");
btn_3.setEnabled(false);
btn_3.setBounds(658, 42, 70, 35);
panel_tabuleiro.add(btn_3);
btn_2 = new JButton("");
btn_2.setEnabled(false);
btn_2.setBounds(727, 42, 70, 35);
panel_tabuleiro.add(btn_2);
btn_1 = new JButton("");
btn_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btn_1.setEnabled(false);
btn_1.setBounds(796, 42, 70, 35);
panel_tabuleiro.add(btn_1);
btn_28 = new JButton("");
btn_28.setEnabled(false);
btn_28.setBounds(797, 352, 70, 35);
panel_tabuleiro.add(btn_28);
JLabel lblEscolhaSuasPecas = new JLabel("Escolha Suas Pecas");
lblEscolhaSuasPecas.setFont(new Font("Times New Roman", Font.BOLD, 18));
lblEscolhaSuasPecas.setBounds(79, 98, 160, 36);
getContentPane().add(lblEscolhaSuasPecas);
setSize(1366, 720);
setVisible(true);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
public static void main(String[] args) {
new TelaDoJogo();
}
}
|
src/br/com/domino/view/TelaDoJogo.java
|
package br.com.domino.view;
import java.awt.GridLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import br.com.domino.model.Actions;
import br.com.domino.model.Pecas;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.awt.event.ActionEvent;
import javax.swing.border.LineBorder;
import java.awt.Color;
public class TelaDoJogo extends JFrame {
String l1 = "", l2 = "", l3 = "", l4 = "", l5 = "", l6 = "", l7 = "", l8 = "", l9 = "", l10 = "", l11 = "",
l12 = "", l13 = "", l14 = "", l15 = "", l16 = "", l17 = "", l18 = "", l19 = "", l20 = "", l21 = "",
l22 = "", l23 = "", l24 = "", l25 = "", l26 = "", l27 = "", l28 = "";
JButton btnhumano1;
JButton btnhumano2;
JButton btnhumano3;
JButton btnhumano4;
JButton btnhumano5;
JButton btnhumano6;
JButton btnhumano7;
JButton btnhumano8;
JButton btnhumano9;
JButton btnhumano10;
JButton btnhumano11;
JButton btnhumano12;
JButton btnhumano13;
JButton btnhumano14;
JButton btnhumano15;
JButton btnhumano16;
JButton btnhumano17;
JButton btnhumano18;
JButton btnmaquina1;
JButton btnmaquina2;
JButton btnmaquina3;
JButton btnmaquina4;
JButton btnmaquina5;
JButton btnmaquina6;
JButton btnmaquina7;
JButton btnmaquina8;
JButton btnmaquina9;
JButton btnmaquina10;
JButton btnmaquina11;
JButton btnmaquina12;
JButton btnmaquina13;
JButton btnmaquina14;
JButton btnmaquina15;
JButton btnmaquina16;
JButton btnmaquina17;
JButton btnmaquina18;
JButton btn_1;
JButton btn_2;
JButton btn_3;
JButton btn_4;
JButton btn_5;
JButton btn_6;
JButton btn_7;
JButton btn_8;
JButton btn_9;
JButton btn_10;
JButton btn_11;
JButton btn_12;
JButton btn_13;
JButton btn_14;
JButton btn_15;
JButton btn_16;
JButton btn_17;
JButton btn_18;
JButton btn_19;
JButton btn_20;
JButton btn_21;
JButton btn_22;
JButton btn_23;
JButton btn_24;
JButton btn_25;
JButton btn_26;
JButton btn_27;
JButton btn_28;
public void desabilitaBotoesHumano() {
btnhumano1.setEnabled(false);
btnhumano2.setEnabled(false);
btnhumano3.setEnabled(false);
btnhumano4.setEnabled(false);
btnhumano5.setEnabled(false);
btnhumano6.setEnabled(false);
btnhumano7.setEnabled(false);
btnhumano8.setEnabled(false);
btnhumano9.setEnabled(false);
btnhumano10.setEnabled(false);
btnhumano11.setEnabled(false);
btnhumano12.setEnabled(false);
btnhumano13.setEnabled(false);
btnhumano14.setEnabled(false);
btnhumano15.setEnabled(false);
btnhumano16.setEnabled(false);
btnhumano17.setEnabled(false);
btnhumano18.setEnabled(false);
}
public void habilitaBotoesHumano() {
btnhumano1.setEnabled(true);
btnhumano2.setEnabled(true);
btnhumano3.setEnabled(true);
btnhumano4.setEnabled(true);
btnhumano5.setEnabled(true);
btnhumano6.setEnabled(true);
btnhumano7.setEnabled(true);
btnhumano8.setEnabled(true);
btnhumano9.setEnabled(true);
btnhumano10.setEnabled(true);
btnhumano11.setEnabled(true);
btnhumano12.setEnabled(true);
btnhumano13.setEnabled(true);
btnhumano14.setEnabled(true);
btnhumano15.setEnabled(true);
btnhumano16.setEnabled(true);
btnhumano17.setEnabled(true);
btnhumano18.setEnabled(true);
}
public void desabilitaBotoesMaquina() {
btnmaquina1.setEnabled(false);
btnmaquina2.setEnabled(false);
btnmaquina3.setEnabled(false);
btnmaquina4.setEnabled(false);
btnmaquina5.setEnabled(false);
btnmaquina6.setEnabled(false);
btnmaquina7.setEnabled(false);
btnmaquina8.setEnabled(false);
btnmaquina9.setEnabled(false);
btnmaquina10.setEnabled(false);
btnmaquina11.setEnabled(false);
btnmaquina12.setEnabled(false);
btnmaquina13.setEnabled(false);
btnmaquina14.setEnabled(false);
btnmaquina15.setEnabled(false);
btnmaquina16.setEnabled(false);
btnmaquina17.setEnabled(false);
btnmaquina18.setEnabled(false);
}
public void habilitaBotoesMaquina() {
btnmaquina1.setEnabled(true);
btnmaquina2.setEnabled(true);
btnmaquina3.setEnabled(true);
btnmaquina4.setEnabled(true);
btnmaquina5.setEnabled(true);
btnmaquina6.setEnabled(true);
btnmaquina7.setEnabled(true);
btnmaquina8.setEnabled(true);
btnmaquina9.setEnabled(true);
btnmaquina10.setEnabled(true);
btnmaquina11.setEnabled(true);
btnmaquina12.setEnabled(true);
btnmaquina13.setEnabled(true);
btnmaquina14.setEnabled(true);
btnmaquina15.setEnabled(true);
btnmaquina16.setEnabled(true);
btnmaquina17.setEnabled(true);
btnmaquina18.setEnabled(true);
}
int contadorCompraMaquina = 7;
public void insereImagenNoBotao(int contadorMaquina) {
++contadorMaquina;
switch (contadorMaquina) {
case 8:
btnmaquina8.setEnabled(true);
btnmaquina8.setIcon(new ImageIcon(".//resource//imagens//preta.png"));
break;
case 9:
btnmaquina9.setEnabled(true);
btnmaquina9.setIcon(new ImageIcon(".//resource//imagens//preta.png"));
break;
case 10:
btnmaquina10.setEnabled(true);
btnmaquina10.setIcon(new ImageIcon(".//resource//imagens//preta.png"));
break;
case 11:
btnmaquina11.setEnabled(true);
btnmaquina11.setIcon(new ImageIcon(".//resource//imagens//preta.png"));
break;
case 12:
btnmaquina12.setEnabled(true);
btnmaquina12.setIcon(new ImageIcon(".//resource//imagens//preta.png"));
break;
case 13:
btnmaquina13.setEnabled(true);
btnmaquina13.setIcon(new ImageIcon(".//resource//imagens//preta.png"));
break;
case 14:
btnmaquina14.setEnabled(true);
btnmaquina14.setIcon(new ImageIcon(".//resource//imagens//preta.png"));
break;
case 15:
btnmaquina15.setEnabled(true);
btnmaquina15.setIcon(new ImageIcon(".//resource//imagens//preta.png"));
break;
case 16:
btnmaquina16.setEnabled(true);
btnmaquina16.setIcon(new ImageIcon(".//resource//imagens//preta.png"));
break;
case 17:
btnmaquina17.setEnabled(true);
btnmaquina17.setIcon(new ImageIcon(".//resource//imagens//preta.png"));
break;
case 18:
btnmaquina18.setEnabled(true);
btnmaquina18.setIcon(new ImageIcon(".//resource//imagens//preta.png"));
break;
default:
break;
}
}
int aux = 0;
int aux2 = 0;
boolean pedraDiferente = false;
Actions al = new Actions();
ArrayList<Pecas> arrayH = new ArrayList<Pecas>();
ArrayList<Pecas> arrayM = new ArrayList<Pecas>();
Boolean vezDoJogo = true;
// recebe todas as pedras do caminho do jogo do domino
ArrayList<Pecas> arrayTabuleiro = new ArrayList<Pecas>();
private static final long serialVersionUID = 1L;
public TelaDoJogo() {
ArrayList<Pecas> array = new ArrayList<Pecas>();
for (Pecas pecas : al.embaralhaPedrasDomino()) {
array.add(pecas);
}
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu mnMenu = new JMenu("Menu");
menuBar.add(mnMenu);
JMenuItem mntmNovoJogo = new JMenuItem("Novo Jogo");
mnMenu.add(mntmNovoJogo);
JMenuItem mntmSalvarJogo = new JMenuItem("Salvar Jogo");
mnMenu.add(mntmSalvarJogo);
JMenuItem mntmInstrues = new JMenuItem("Instru\u00E7\u00F5es");
mntmInstrues.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new TelaInstrucoes().setVisible(true);
}
});
mnMenu.add(mntmInstrues);
JMenuItem mntmSair = new JMenuItem("Sair");
mntmSair.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
dispose();
}
});
mnMenu.add(mntmSair);
getContentPane().setLayout(null);
ImageIcon iconMaquina = new ImageIcon(".//resource//imagens//sasuke.png");
JLabel lblIconemaquina = new JLabel(iconMaquina);
lblIconemaquina.setBounds(0, 0, 73, 100);
getContentPane().add(lblIconemaquina);
JLabel lblNomemaquina = new JLabel("JoanesMachine dos Santos");
lblNomemaquina.setFont(new Font("Times New Roman", Font.BOLD, 14));
lblNomemaquina.setBounds(77, 32, 195, 25);
getContentPane().add(lblNomemaquina);
ImageIcon iconJogador = new ImageIcon(".//resource//imagens//naruto.png");
JLabel lblIconejogador = new JLabel(iconJogador);
lblIconejogador.setBounds(0, 561, 73, 100);
getContentPane().add(lblIconejogador);
JLabel lblNomejogador = new JLabel("Emerson Sousa Pereira");
lblNomejogador.setFont(new Font("Times New Roman", Font.BOLD, 14));
lblNomejogador.setBounds(77, 596, 217, 36);
getContentPane().add(lblNomejogador);
JPanel panel_pecasMaquina = new JPanel();
panel_pecasMaquina.setBounds(304, 0, 958, 81);
getContentPane().add(panel_pecasMaquina);
panel_pecasMaquina.setLayout(new GridLayout(1, 20, 0, 0));
btnmaquina1 = new JButton("");
btnmaquina1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnmaquina2 = new JButton("");
btnmaquina3 = new JButton("");
btnmaquina4 = new JButton("");
btnmaquina5 = new JButton("");
btnmaquina6 = new JButton("");
btnmaquina7 = new JButton("");
btnmaquina8 = new JButton("");
btnmaquina8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnmaquina9 = new JButton("");
btnmaquina10 = new JButton("");
btnmaquina11 = new JButton("");
btnmaquina12 = new JButton("");
btnmaquina13 = new JButton("");
btnmaquina14 = new JButton("");
btnmaquina15 = new JButton("");
btnmaquina16 = new JButton("");
btnmaquina17 = new JButton("");
btnmaquina18 = new JButton("");
panel_pecasMaquina.add(btnmaquina1);
panel_pecasMaquina.add(btnmaquina2);
panel_pecasMaquina.add(btnmaquina3);
panel_pecasMaquina.add(btnmaquina4);
panel_pecasMaquina.add(btnmaquina5);
panel_pecasMaquina.add(btnmaquina6);
panel_pecasMaquina.add(btnmaquina7);
panel_pecasMaquina.add(btnmaquina8);
panel_pecasMaquina.add(btnmaquina9);
panel_pecasMaquina.add(btnmaquina10);
panel_pecasMaquina.add(btnmaquina11);
panel_pecasMaquina.add(btnmaquina12);
panel_pecasMaquina.add(btnmaquina13);
panel_pecasMaquina.add(btnmaquina14);
panel_pecasMaquina.add(btnmaquina15);
panel_pecasMaquina.add(btnmaquina16);
panel_pecasMaquina.add(btnmaquina17);
panel_pecasMaquina.add(btnmaquina18);
JPanel panel_pecasJogador = new JPanel();
panel_pecasJogador.setBounds(304, 580, 958, 81);
getContentPane().add(panel_pecasJogador);
panel_pecasJogador.setLayout(new GridLayout(1, 20, 0, 0));
btnhumano1 = new JButton("");
btnhumano1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
++aux2;
Pecas p1 = arrayH.get(0);
String ladoa = p1.getLadoEsquerdo().toString();
String ladob = p1.getLadoDireito().toString();
System.out.println(l1 = ladoa + ladob);
switch (aux2) {
case 1:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_1.setEnabled(true);
btn_1.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 1) {
// obs: tem que inverter os valores antes de inserir
// no array.
Pecas novop = new Pecas(p1.getLadoDireito(), p1.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano1.setEnabled(false);
btn_1.setEnabled(true);
btn_1.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 2) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_1.setEnabled(true);
btn_1.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 2:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 1) {
Pecas novop = new Pecas(p1.getLadoDireito(), p1.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano1.setEnabled(false);
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 2) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 3:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 1) {
Pecas novop = new Pecas(p1.getLadoDireito(), p1.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano1.setEnabled(false);
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 2) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 4:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 1) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 2) {
Pecas novop = new Pecas(p1.getLadoDireito(), p1.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano1.setEnabled(false);
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 5:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 1) {
Pecas novop = new Pecas(p1.getLadoDireito(), p1.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano1.setEnabled(false);
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 2) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 6:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 1) {
Pecas novop = new Pecas(p1.getLadoDireito(), p1.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano1.setEnabled(false);
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 2) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 7:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 1) {
Pecas novop = new Pecas(p1.getLadoDireito(), p1.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano1.setEnabled(false);
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 2) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 8:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 1) {
Pecas novop = new Pecas(p1.getLadoDireito(), p1.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano1.setEnabled(false);
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 2) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 9:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 1) {
Pecas novop = new Pecas(p1.getLadoDireito(), p1.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano1.setEnabled(false);
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 2) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 10:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 1) {
Pecas novop = new Pecas(p1.getLadoDireito(), p1.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano1.setEnabled(false);
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 2) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 11:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 1) {
Pecas novop = new Pecas(p1.getLadoDireito(), p1.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano1.setEnabled(false);
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 2) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 12:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 1) {
Pecas novop = new Pecas(p1.getLadoDireito(), p1.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano1.setEnabled(false);
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) == 2) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l1 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 13:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//verticias2//" + l1 + ".png"));
} else {
if (al.verificaLadosPedraDireita(arrayTabuleiro, p1) == 1) {
// obs: tem que inverter os valores antes de inserir
// no array.
Pecas novop = new Pecas(p1.getLadoDireito(), p1.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano1.setEnabled(false);
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//verticais2//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraDireita(arrayTabuleiro, p1) == 2) {
arrayTabuleiro.add(p1);
btnhumano1.setEnabled(false);
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//verticais2//" + l1 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p1) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_14.setEnabled(true);
btn_14.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_14.setEnabled(true);
btn_14.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
default:
JOptionPane.showMessageDialog(null, "Peas esgotadas");
break;
}
}
});
btnhumano2 = new JButton("");
btnhumano2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
++aux2;
Pecas p2 = arrayH.get(1);
String ladoa = p2.getLadoEsquerdo().toString();
String ladob = p2.getLadoDireito().toString();
System.out.println(l2 = ladoa + ladob);
switch (aux2) {
case 1:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_1.setEnabled(true);
btn_1.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 1) {
Pecas novop = new Pecas(p2.getLadoDireito(), p2.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano2.setEnabled(false);
btn_1.setEnabled(true);
btn_1.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 2) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_1.setEnabled(true);
btn_1.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 2:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 1) {
Pecas novop = new Pecas(p2.getLadoDireito(), p2.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano2.setEnabled(false);
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 2) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 3:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 1) {
Pecas novop = new Pecas(p2.getLadoDireito(), p2.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano2.setEnabled(false);
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 2) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 4:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 1) {
Pecas novop = new Pecas(p2.getLadoDireito(), p2.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano2.setEnabled(false);
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 2) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 5:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 1) {
Pecas novop = new Pecas(p2.getLadoDireito(), p2.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano2.setEnabled(false);
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 2) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 6:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 1) {
Pecas novop = new Pecas(p2.getLadoDireito(), p2.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano2.setEnabled(false);
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 2) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 7:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 1) {
Pecas novop = new Pecas(p2.getLadoDireito(), p2.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano2.setEnabled(false);
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 2) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 8:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 1) {
Pecas novop = new Pecas(p2.getLadoDireito(), p2.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano2.setEnabled(false);
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 2) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 9:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 1) {
Pecas novop = new Pecas(p2.getLadoDireito(), p2.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano2.setEnabled(false);
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 2) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 10:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 1) {
Pecas novop = new Pecas(p2.getLadoDireito(), p2.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano2.setEnabled(false);
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 2) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 11:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 1) {
Pecas novop = new Pecas(p2.getLadoDireito(), p2.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano2.setEnabled(false);
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 2) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 12:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 1) {
Pecas novop = new Pecas(p2.getLadoDireito(), p2.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano2.setEnabled(false);
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) == 2) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l2 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 13:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//verticias2//" + l2 + ".png"));
} else {
if (al.verificaLadosPedraDireita(arrayTabuleiro, p2) == 1) {
// obs: tem que inverter os valores antes de inserir
// no array.
Pecas novop = new Pecas(p2.getLadoDireito(), p2.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano2.setEnabled(false);
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//verticais2//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraDireita(arrayTabuleiro, p2) == 2) {
arrayTabuleiro.add(p2);
btnhumano2.setEnabled(false);
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//verticais2//" + l2 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p2) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_14.setEnabled(true);
btn_14.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_14.setEnabled(true);
btn_14.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
default:
JOptionPane.showMessageDialog(null, "Peas esgotadas");
break;
}
}
});
btnhumano3 = new JButton("");
btnhumano3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux2;
Pecas p3 = arrayH.get(2);
String ladoa = p3.getLadoEsquerdo().toString();
String ladob = p3.getLadoDireito().toString();
System.out.println(l3 = ladoa + ladob);
switch (aux2) {
case 1:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_1.setEnabled(true);
btn_1.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 1) {
Pecas novop = new Pecas(p3.getLadoDireito(), p3.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano3.setEnabled(false);
btn_1.setEnabled(true);
btn_1.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 2) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_1.setEnabled(true);
btn_1.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 2:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 1) {
Pecas novop = new Pecas(p3.getLadoDireito(), p3.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano3.setEnabled(false);
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 2) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 3:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 1) {
Pecas novop = new Pecas(p3.getLadoDireito(), p3.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano3.setEnabled(false);
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 2) {
arrayTabuleiro.add(p3);
btnhumano2.setEnabled(false);
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 4:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 1) {
Pecas novop = new Pecas(p3.getLadoDireito(), p3.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano3.setEnabled(false);
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 2) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 5:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 1) {
Pecas novop = new Pecas(p3.getLadoDireito(), p3.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano2.setEnabled(false);
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 2) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 6:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 1) {
Pecas novop = new Pecas(p3.getLadoDireito(), p3.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano3.setEnabled(false);
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 2) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 7:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 1) {
Pecas novop = new Pecas(p3.getLadoDireito(), p3.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano3.setEnabled(false);
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 2) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 8:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 1) {
Pecas novop = new Pecas(p3.getLadoDireito(), p3.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano3.setEnabled(false);
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 2) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 9:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 1) {
Pecas novop = new Pecas(p3.getLadoDireito(), p3.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano3.setEnabled(false);
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 2) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 10:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 1) {
Pecas novop = new Pecas(p3.getLadoDireito(), p3.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano3.setEnabled(false);
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 2) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 11:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 1) {
Pecas novop = new Pecas(p3.getLadoDireito(), p3.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano3.setEnabled(false);
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 2) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 12:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 1) {
Pecas novop = new Pecas(p3.getLadoDireito(), p3.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano3.setEnabled(false);
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horintais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) == 2) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l3 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 13:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//verticias2//" + l3 + ".png"));
} else {
if (al.verificaLadosPedraDireita(arrayTabuleiro, p3) == 1) {
// obs: tem que inverter os valores antes de inserir
// no array.
Pecas novop = new Pecas(p3.getLadoDireito(), p3.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano3.setEnabled(false);
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//verticais2//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraDireita(arrayTabuleiro, p3) == 2) {
arrayTabuleiro.add(p3);
btnhumano3.setEnabled(false);
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//verticais2//" + l3 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p3) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_14.setEnabled(true);
btn_14.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_14.setEnabled(true);
btn_14.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
default:
JOptionPane.showMessageDialog(null, "Peas esgotadas");
break;
}
}
});
btnhumano4 = new JButton("");
btnhumano4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux2;
Pecas p4 = arrayH.get(3);
String ladoa = p4.getLadoEsquerdo().toString();
String ladob = p4.getLadoDireito().toString();
System.out.println(l4 = ladoa + ladob);
switch (aux2) {
case 1:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_1.setEnabled(true);
btn_1.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 1) {
Pecas novop = new Pecas(p4.getLadoDireito(), p4.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano4.setEnabled(false);
btn_1.setEnabled(true);
btn_1.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 2) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_1.setEnabled(true);
btn_1.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 2:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 1) {
Pecas novop = new Pecas(p4.getLadoDireito(), p4.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano4.setEnabled(false);
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 2) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 3:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 1) {
Pecas novop = new Pecas(p4.getLadoDireito(), p4.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano4.setEnabled(false);
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 2) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 4:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 1) {
Pecas novop = new Pecas(p4.getLadoDireito(), p4.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano4.setEnabled(false);
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 2) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 5:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 1) {
Pecas novop = new Pecas(p4.getLadoDireito(), p4.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano4.setEnabled(false);
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 2) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 6:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 1) {
Pecas novop = new Pecas(p4.getLadoDireito(), p4.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano4.setEnabled(false);
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 2) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 7:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 1) {
Pecas novop = new Pecas(p4.getLadoDireito(), p4.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano4.setEnabled(false);
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 2) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 8:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 1) {
Pecas novop = new Pecas(p4.getLadoDireito(), p4.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano4.setEnabled(false);
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 2) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 9:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 1) {
Pecas novop = new Pecas(p4.getLadoDireito(), p4.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano4.setEnabled(false);
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 2) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 10:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 1) {
Pecas novop = new Pecas(p4.getLadoDireito(), p4.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano4.setEnabled(false);
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 2) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 11:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 1) {
Pecas novop = new Pecas(p4.getLadoDireito(), p4.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano4.setEnabled(false);
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 2) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 12:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 1) {
Pecas novop = new Pecas(p4.getLadoDireito(), p4.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano4.setEnabled(false);
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) == 2) {
arrayTabuleiro.add(p4);
btnhumano4.setEnabled(false);
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l4 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 13:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p4);
btnhumano2.setEnabled(false);
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//verticias2//" + l4 + ".png"));
} else {
if (al.verificaLadosPedraDireita(arrayTabuleiro, p4) == 1) {
// obs: tem que inverter os valores antes de inserir
// no array.
Pecas novop = new Pecas(p4.getLadoDireito(), p4.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano2.setEnabled(false);
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//verticais2//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraDireita(arrayTabuleiro, p4) == 2) {
arrayTabuleiro.add(p4);
btnhumano2.setEnabled(false);
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//verticais2//" + l4 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p4) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_14.setEnabled(true);
btn_14.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_14.setEnabled(true);
btn_14.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
default:
JOptionPane.showMessageDialog(null, "Peas esgotadas");
break;
}
}
});
btnhumano5 = new JButton("");
btnhumano5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
++aux2;
Pecas p5 = arrayH.get(4);
String ladoa = p5.getLadoEsquerdo().toString();
String ladob = p5.getLadoDireito().toString();
System.out.println(l5 = ladoa + ladob);
switch (aux2) {
case 1:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_1.setEnabled(true);
btn_1.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 1) {
Pecas novop = new Pecas(p5.getLadoDireito(), p5.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano5.setEnabled(false);
btn_1.setEnabled(true);
btn_1.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 2) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_1.setEnabled(true);
btn_1.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 2:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 1) {
Pecas novop = new Pecas(p5.getLadoDireito(), p5.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano5.setEnabled(false);
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 2) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 3:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 1) {
Pecas novop = new Pecas(p5.getLadoDireito(), p5.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano5.setEnabled(false);
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 2) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 4:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 1) {
Pecas novop = new Pecas(p5.getLadoDireito(), p5.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano5.setEnabled(false);
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 2) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 5:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 1) {
Pecas novop = new Pecas(p5.getLadoDireito(), p5.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano5.setEnabled(false);
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 2) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 6:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 1) {
Pecas novop = new Pecas(p5.getLadoDireito(), p5.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano5.setEnabled(false);
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 2) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 7:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 1) {
Pecas novop = new Pecas(p5.getLadoDireito(), p5.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano5.setEnabled(false);
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 2) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 8:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 1) {
Pecas novop = new Pecas(p5.getLadoDireito(), p5.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano5.setEnabled(false);
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 2) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 9:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 1) {
Pecas novop = new Pecas(p5.getLadoDireito(), p5.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano5.setEnabled(false);
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 2) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 10:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 1) {
Pecas novop = new Pecas(p5.getLadoDireito(), p5.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano5.setEnabled(false);
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 2) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 11:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 1) {
Pecas novop = new Pecas(p5.getLadoDireito(), p5.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano5.setEnabled(false);
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 2) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 12:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 1) {
Pecas novop = new Pecas(p5.getLadoDireito(), p5.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano5.setEnabled(false);
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) == 2) {
arrayTabuleiro.add(p5);
btnhumano5.setEnabled(false);
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l5 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 13:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p5);
btnhumano2.setEnabled(false);
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//verticias2//" + l5 + ".png"));
} else {
if (al.verificaLadosPedraDireita(arrayTabuleiro, p5) == 1) {
// obs: tem que inverter os valores antes de inserir
// no array.
Pecas novop = new Pecas(p5.getLadoDireito(), p5.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano2.setEnabled(false);
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//verticais2//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraDireita(arrayTabuleiro, p5) == 2) {
arrayTabuleiro.add(p5);
btnhumano2.setEnabled(false);
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//verticais2//" + l5 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p5) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_14.setEnabled(true);
btn_14.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_14.setEnabled(true);
btn_14.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
default:
JOptionPane.showMessageDialog(null, "Peas esgotadas");
break;
}
}
});
btnhumano6 = new JButton("");
btnhumano6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux2;
Pecas p6 = arrayH.get(5);
String ladoa = p6.getLadoEsquerdo().toString();
String ladob = p6.getLadoDireito().toString();
System.out.println(l6 = ladoa + ladob);
switch (aux2) {
case 1:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_1.setEnabled(true);
btn_1.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 1) {
Pecas novop = new Pecas(p6.getLadoDireito(), p6.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano2.setEnabled(false);
btn_1.setEnabled(true);
btn_1.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 2) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_1.setEnabled(true);
btn_1.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 2:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 1) {
Pecas novop = new Pecas(p6.getLadoDireito(), p6.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano6.setEnabled(false);
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 2) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 3:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 1) {
Pecas novop = new Pecas(p6.getLadoDireito(), p6.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano6.setEnabled(false);
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 2) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 4:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 1) {
Pecas novop = new Pecas(p6.getLadoDireito(), p6.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano6.setEnabled(false);
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 2) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 5:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 1) {
Pecas novop = new Pecas(p6.getLadoDireito(), p6.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano6.setEnabled(false);
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 2) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 6:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 1) {
Pecas novop = new Pecas(p6.getLadoDireito(), p6.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano6.setEnabled(false);
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 2) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 7:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 1) {
Pecas novop = new Pecas(p6.getLadoDireito(), p6.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano6.setEnabled(false);
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 2) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 8:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 1) {
Pecas novop = new Pecas(p6.getLadoDireito(), p6.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano6.setEnabled(false);
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 2) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 9:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 1) {
Pecas novop = new Pecas(p6.getLadoDireito(), p6.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano6.setEnabled(false);
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 2) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 10:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 1) {
Pecas novop = new Pecas(p6.getLadoDireito(), p6.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano6.setEnabled(false);
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 2) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 11:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 1) {
Pecas novop = new Pecas(p6.getLadoDireito(), p6.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano6.setEnabled(false);
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 2) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 12:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 1) {
Pecas novop = new Pecas(p6.getLadoDireito(), p6.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano6.setEnabled(false);
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) == 2) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l6 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 13:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//verticias2//" + l6 + ".png"));
} else {
if (al.verificaLadosPedraDireita(arrayTabuleiro, p6) == 1) {
// obs: tem que inverter os valores antes de inserir
// no array.
Pecas novop = new Pecas(p6.getLadoDireito(), p6.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano6.setEnabled(false);
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//verticais2//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraDireita(arrayTabuleiro, p6) == 2) {
arrayTabuleiro.add(p6);
btnhumano6.setEnabled(false);
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//verticais2//" + l6 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p6) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_14.setEnabled(true);
btn_14.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_14.setEnabled(true);
btn_14.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
default:
JOptionPane.showMessageDialog(null, "Peas esgotadas");
break;
}
}
});
btnhumano7 = new JButton("");
btnhumano7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
++aux2;
Pecas p7 = arrayH.get(6);
String ladoa = p7.getLadoEsquerdo().toString();
String ladob = p7.getLadoDireito().toString();
System.out.println(l7 = ladoa + ladob);
switch (aux2) {
case 1:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_1.setEnabled(true);
btn_1.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 1) {
Pecas novop = new Pecas(p7.getLadoDireito(), p7.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano7.setEnabled(false);
btn_1.setEnabled(true);
btn_1.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 2) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_1.setEnabled(true);
btn_1.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 2:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 1) {
Pecas novop = new Pecas(p7.getLadoDireito(), p7.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano7.setEnabled(false);
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 2) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_2.setEnabled(true);
btn_2.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 3:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 1) {
Pecas novop = new Pecas(p7.getLadoDireito(), p7.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano7.setEnabled(false);
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 2) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_3.setEnabled(true);
btn_3.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 4:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 1) {
Pecas novop = new Pecas(p7.getLadoDireito(), p7.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano7.setEnabled(false);
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 2) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_4.setEnabled(true);
btn_4.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 5:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 1) {
Pecas novop = new Pecas(p7.getLadoDireito(), p7.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano7.setEnabled(false);
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 2) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_5.setEnabled(true);
btn_5.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 6:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 1) {
Pecas novop = new Pecas(p7.getLadoDireito(), p7.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano7.setEnabled(false);
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 2) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_6.setEnabled(true);
btn_6.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 7:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 1) {
Pecas novop = new Pecas(p7.getLadoDireito(), p7.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano7.setEnabled(false);
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 2) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_7.setEnabled(true);
btn_7.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 8:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 1) {
Pecas novop = new Pecas(p7.getLadoDireito(), p7.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano7.setEnabled(false);
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 2) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_8.setEnabled(true);
btn_8.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 9:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 1) {
Pecas novop = new Pecas(p7.getLadoDireito(), p7.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano7.setEnabled(false);
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 2) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_9.setEnabled(true);
btn_9.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 10:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 1) {
Pecas novop = new Pecas(p7.getLadoDireito(), p7.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano7.setEnabled(false);
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 2) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_10.setEnabled(true);
btn_10.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 11:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 1) {
Pecas novop = new Pecas(p7.getLadoDireito(), p7.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano7.setEnabled(false);
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 2) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_11.setEnabled(true);
btn_11.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 12:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 1) {
Pecas novop = new Pecas(p7.getLadoDireito(), p7.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano7.setEnabled(false);
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) == 2) {
arrayTabuleiro.add(p7);
btnhumano7.setEnabled(false);
btn_12.setEnabled(true);
btn_12.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + l7 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
if (valor == "") {
JOptionPane.showMessageDialog(null, "Maquina passa ou compra");
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//verticais2//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
case 13:
if (arrayTabuleiro.isEmpty()) {
arrayTabuleiro.add(p7);
btnhumano2.setEnabled(false);
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//verticias2//" + l7 + ".png"));
} else {
if (al.verificaLadosPedraDireita(arrayTabuleiro, p7) == 1) {
// obs: tem que inverter os valores antes de inserir
// no array.
Pecas novop = new Pecas(p7.getLadoDireito(), p7.getLadoEsquerdo());
arrayTabuleiro.add(novop);
btnhumano2.setEnabled(false);
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//verticais2//" + ladob + ladoa + ".png"));
} else {
if (al.verificaLadosPedraDireita(arrayTabuleiro, p7) == 2) {
arrayTabuleiro.add(p7);
btnhumano2.setEnabled(false);
btn_13.setEnabled(true);
btn_13.setIcon(new ImageIcon(".//resource//pecas//verticais2//" + l7 + ".png"));
} else {
JOptionPane.showMessageDialog(null, "Pedra diferente");
--aux2;
}
}
}
/** Inteligncia simples da maquina **/
if (al.verificaLadosPedraEsquerda(arrayTabuleiro, p7) != 0) {
String valor = al.escolhePedraMaquina(arrayTabuleiro, arrayM);
/** logica para a compra de peas do jogador maquina **/
if (valor == "") {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//possui um rando com 0 e 1, caso 0 a maquina passa, caso 1 ela faz uma compra no array
int i = al.maquinaCompraPassa();
if (i == 0) {
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
// escolhe a primeira pedra que encontrar no array e pega
al.escolhePecaAleatorio(array, arrayM);
// testa se a pedra comprada pode ser jogada no tabuleiro
String p = al.testaPedraCompraMaquina(arrayTabuleiro, arrayM);
if (p == "") {
/**
* caso a pedra comprada no possa ser
* jogada no tabuleiro a maquina passa a
* jogada
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Passa Jogada ");
} else {
/**
* caso a pedra comprada possa ser jogada no
* tabuleiro a maquina a insere no
* arrayTabuleiro
**/
JOptionPane.showMessageDialog(null, "Maquina: Compra");
/**
* INSERE A IMAGEM NO BOTO CORRESPONDENTE
**/
insereImagenNoBotao(contadorCompraMaquina);
JOptionPane.showMessageDialog(null, "Maquina: Joga");
btn_14.setEnabled(true);
btn_14.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + p + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Finaliza o codigo de compra de peas do jogador
* maquina
**/
} else {
JOptionPane.showMessageDialog(null, "Jogador da vez: CPU");
btn_14.setEnabled(true);
btn_14.setIcon(new ImageIcon(".//resource//pecas//horizontais//" + valor + ".png"));
++aux2;
JOptionPane.showMessageDialog(null, "Jogador da vez: Homen");
}
}
for (Pecas i : arrayTabuleiro) {
System.out.println("Array tabuliero: " + i.getLadoEsquerdo() + " " + i.getLadoDireito());
}
break;
default:
JOptionPane.showMessageDialog(null, "Peas esgotadas");
break;
}
}
});
btnhumano8 = new JButton("");
btnhumano8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnhumano9 = new JButton("");
btnhumano9.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnhumano10 = new JButton("");
btnhumano11 = new JButton("");
btnhumano12 = new JButton("");
btnhumano13 = new JButton("");
btnhumano14 = new JButton("");
btnhumano15 = new JButton("");
btnhumano16 = new JButton("");
btnhumano17 = new JButton("");
btnhumano18 = new JButton("");
btnhumano18.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
panel_pecasJogador.add(btnhumano1);
panel_pecasJogador.add(btnhumano2);
panel_pecasJogador.add(btnhumano3);
panel_pecasJogador.add(btnhumano4);
panel_pecasJogador.add(btnhumano5);
panel_pecasJogador.add(btnhumano6);
panel_pecasJogador.add(btnhumano7);
panel_pecasJogador.add(btnhumano8);
panel_pecasJogador.add(btnhumano9);
panel_pecasJogador.add(btnhumano10);
panel_pecasJogador.add(btnhumano11);
panel_pecasJogador.add(btnhumano12);
panel_pecasJogador.add(btnhumano13);
panel_pecasJogador.add(btnhumano14);
panel_pecasJogador.add(btnhumano15);
panel_pecasJogador.add(btnhumano16);
panel_pecasJogador.add(btnhumano17);
panel_pecasJogador.add(btnhumano18);
JPanel panel_pecasAescolher = new JPanel();
panel_pecasAescolher.setBounds(0, 145, 330, 405);
getContentPane().add(panel_pecasAescolher);
panel_pecasAescolher.setLayout(new GridLayout(5, 6, 5, 5));
ImageIcon pecavirada = new ImageIcon(".//resource//imagens//pecavirada.png");
JButton btnpeca1 = new JButton(pecavirada);
btnpeca1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(0);
array.remove(0);
Pecas vazia = new Pecas(null, null);
array.add(0, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l1 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca1.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l1 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca1.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l1 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca1.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l1 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca1.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l1 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca1.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l1 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca1.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l1 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca1.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l1 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca1.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l1 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca1.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l1 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca1.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l1 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca1.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l1 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca1.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l1 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca1.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l1 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca1.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l1 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca2 = new JButton(pecavirada);
btnpeca2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(1);
array.remove(1);
Pecas vazia = new Pecas(null, null);
array.add(1, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l2 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca2.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l2 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca2.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l2 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca2.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l2 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca2.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l2 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca2.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l2 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca2.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l2 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca2.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l2 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca2.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l2 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca2.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l2 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca2.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l2 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca2.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l2 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca2.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l2 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca2.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l2 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca2.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l2 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca3 = new JButton(pecavirada);
btnpeca3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(2);
array.remove(2);
Pecas vazia = new Pecas(null, null);
array.add(2, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l3 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca3.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l3 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca3.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l3 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca3.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l3 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca3.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l3 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca3.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l3 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca3.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas/verticais1///" + l3 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca3.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l3 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca3.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l3 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca3.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l3 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca3.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l3 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca3.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l3 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca3.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l3 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca3.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l3 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca3.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l3 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca4 = new JButton(pecavirada);
btnpeca4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(3);
array.remove(3);
Pecas vazia = new Pecas(null, null);
array.add(3, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l4 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca4.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l4 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca4.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l4 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca4.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l4 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca4.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l4 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca4.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l4 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca4.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l4 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca4.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l4 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca4.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l4 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca4.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l4 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca4.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l4 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca4.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l4 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca4.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l4 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca4.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l4 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca4.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l4 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca5 = new JButton(pecavirada);
btnpeca5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(4);
array.remove(4);
Pecas vazia = new Pecas(null, null);
array.add(4, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l5 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca5.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l5 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca5.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l5 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca5.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l5 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca5.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l5 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca5.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l5 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca5.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l5 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca5.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l5 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca5.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l5 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca5.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l5 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca5.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l5 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca5.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l5 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca5.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l5 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca5.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l5 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca5.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l5 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca6 = new JButton(pecavirada);
btnpeca6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(5);
array.remove(5);
Pecas vazia = new Pecas(null, null);
array.add(5, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l6 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca6.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l6 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca6.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l6 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca6.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l6 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca6.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l6 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca6.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l6 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca6.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l6 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca6.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l6 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca6.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l6 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca6.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l6 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca6.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l6 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca6.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l6 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca6.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l6 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca6.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l6 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca6.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l6 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca7 = new JButton(pecavirada);
btnpeca7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(6);
array.remove(6);
Pecas vazia = new Pecas(null, null);
array.add(6, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l7 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca7.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l7 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca7.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l7 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca7.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l7 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca7.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l7 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca7.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l7 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca7.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l7 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca7.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l7 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca7.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l7 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca7.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l7 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca7.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l7 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca7.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l7 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca7.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l7 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca7.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l7 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca7.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l7 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca8 = new JButton(pecavirada);
btnpeca8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(7);
array.remove(7);
Pecas vazia = new Pecas(null, null);
array.add(7, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l8 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca8.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l8 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca8.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l8 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca8.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l8 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca8.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l8 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca8.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l8 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca8.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l8 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca8.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l8 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca8.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l8 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca8.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l8 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca8.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l8 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca8.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l8 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca8.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l8 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca8.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l8 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca8.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l8 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca9 = new JButton(pecavirada);
btnpeca9.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(8);
array.remove(8);
Pecas vazia = new Pecas(null, null);
array.add(8, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l9 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca9.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l9 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca9.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l9 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca9.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l9 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca9.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l9 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca9.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l9 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca9.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l9 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca9.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l9 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca9.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l9 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca9.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l9 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca9.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l9 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca9.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l9 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca9.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l9 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca9.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l9 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca9.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l9 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca10 = new JButton(pecavirada);
btnpeca10.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(9);
array.remove(9);
Pecas vazia = new Pecas(null, null);
array.add(9, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l10 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca10.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l10 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca10.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l10 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca10.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l10 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca10.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l10 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca10.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l10 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca10.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l10 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca10.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l10 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca10.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l10 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca10.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l10 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca10.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l10 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca10.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l10 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca10.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l10 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca10.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l10 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca10.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l10 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca11 = new JButton(pecavirada);
btnpeca11.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(10);
array.remove(10);
Pecas vazia = new Pecas(null, null);
array.add(10, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l11 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca11.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l11 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca11.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l11 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca11.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l11 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca11.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l11 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca11.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l11 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca11.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l11 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca11.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l11 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca11.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l11 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca11.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l11 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca11.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l11 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca11.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l11 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca11.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l11 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca11.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l11 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca11.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l11 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca12 = new JButton(pecavirada);
btnpeca12.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(11);
array.remove(11);
Pecas vazia = new Pecas(null, null);
array.add(11, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l12 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca12.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l12 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca12.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l12 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca12.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l12 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca12.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l12 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca12.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l12 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca12.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l12 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca12.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l12 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca12.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l12 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca12.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l12 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca12.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l12 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca12.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l12 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca12.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l12 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca12.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l12 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca12.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l12 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca13 = new JButton(pecavirada);
btnpeca13.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(12);
array.remove(12);
Pecas vazia = new Pecas(null, null);
array.add(12, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l13 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca13.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l13 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca13.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l13 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca13.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l13 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca13.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l13 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca13.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l13 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca13.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l13 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca13.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l13 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca13.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l13 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca13.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l13 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca13.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l13 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca13.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l13 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca13.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l13 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca13.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l13 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca13.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l13 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca14 = new JButton(pecavirada);
btnpeca14.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(13);
array.remove(13);
Pecas vazia = new Pecas(null, null);
array.add(13, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l14 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca14.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l14 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca14.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l14 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca14.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l14 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca14.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l14 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca14.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l14 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca14.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l14 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca14.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l14 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca14.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l14 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca14.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l14 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca14.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l14 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca14.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l14 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca14.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l14 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca14.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l14 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca14.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l14 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca15 = new JButton(pecavirada);
btnpeca15.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(14);
array.remove(14);
Pecas vazia = new Pecas(null, null);
array.add(14, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l15 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca15.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l15 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca15.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l15 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca15.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l15 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca15.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l15 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca15.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l15 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca15.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l15 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca15.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l15 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca15.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l15 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca15.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l15 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca15.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l15 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca15.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l15 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca15.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l15 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca15.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l15 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca15.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l15 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca16 = new JButton(pecavirada);
btnpeca16.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(15);
array.remove(15);
Pecas vazia = new Pecas(null, null);
array.add(15, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l16 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca16.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l16 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca16.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l16 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca16.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l16 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca16.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l16 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca16.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l16 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca16.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l16 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca16.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l16 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca16.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l16 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca16.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l16 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca16.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l16 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca16.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l16 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca16.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l16 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca16.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l16 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca16.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l16 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca17 = new JButton(pecavirada);
btnpeca17.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(16);
array.remove(16);
Pecas vazia = new Pecas(null, null);
array.add(16, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l17 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca17.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l17 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca17.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l17 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca17.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l17 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca17.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l17 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca17.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l17 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca17.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l17 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca17.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l17 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca17.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l17 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca17.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l17 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca17.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l17 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca17.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l17 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca17.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l17 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca17.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l17 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca17.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l17 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca18 = new JButton(pecavirada);
btnpeca18.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(17);
array.remove(17);
Pecas vazia = new Pecas(null, null);
array.add(17, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l18 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca18.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l18 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca18.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l18 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca18.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l18 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca18.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l18 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca18.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l18 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca18.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l18 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca18.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l18 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca18.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l18 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca18.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l18 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca18.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l18 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca18.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l18 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca18.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l18 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca18.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l18 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca18.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l18 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca19 = new JButton(pecavirada);
btnpeca19.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(18);
array.remove(18);
Pecas vazia = new Pecas(null, null);
array.add(18, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l19 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca19.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l19 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca19.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l19 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca19.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l19 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca19.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l19 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca19.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l19 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca19.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l19 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca19.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l19 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca19.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l19 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca19.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l19 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca19.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l19 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca19.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l19 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca19.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l19 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca19.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l19 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca19.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l19 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca20 = new JButton(pecavirada);
btnpeca20.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(19);
array.remove(19);
Pecas vazia = new Pecas(null, null);
array.add(19, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l20 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca20.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l20 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca20.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l20 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca20.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l20 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca20.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l20 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca20.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l20 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca20.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l20 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca20.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l20 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca20.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l20 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca20.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l20 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca20.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l20 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca20.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l20 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca20.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l20 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca20.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l20 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca20.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l20 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca21 = new JButton(pecavirada);
btnpeca21.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(20);
array.remove(20);
Pecas vazia = new Pecas(null, null);
array.add(20, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l21 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca21.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l21 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca21.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l21 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca21.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l21 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca21.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l21 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca21.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l21 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca21.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l21 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca21.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l21 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca21.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l21 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca21.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l21 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca21.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l21 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca21.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l21 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca21.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l21 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca21.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l21 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca21.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l21 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca22 = new JButton(pecavirada);
btnpeca22.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(21);
array.remove(21);
Pecas vazia = new Pecas(null, null);
array.add(21, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l22 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca22.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l22 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca22.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l22 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca22.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l22 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca22.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l22 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca22.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l22 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca22.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l22 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca22.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l22 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca22.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l22 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca22.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l22 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca22.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l22 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca22.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l22 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca22.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l22 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca22.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l22 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca22.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l22 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
}
break;
}
}
});
JButton btnpeca23 = new JButton(pecavirada);
btnpeca23.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(22);
array.remove(22);
Pecas vazia = new Pecas(null, null);
array.add(22, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l23 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca23.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l23 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca23.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l23 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca23.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l23 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca23.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l23 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca23.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l23 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca23.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l23 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca23.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas/verticais1///" + l23 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca23.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l23 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca23.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l23 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca23.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l23 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca23.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l23 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca23.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l23 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca23.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l23 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca23.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l23 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
} break;
}
}
});
JButton btnpeca24 = new JButton(pecavirada);
btnpeca24.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(23);
array.remove(23);
Pecas vazia = new Pecas(null, null);
array.add(23, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l24 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca24.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l24 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca24.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l24 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca24.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l24 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca24.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l24 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca24.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l24 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca24.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l24 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca24.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l24 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca24.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l24 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca24.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l24 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca24.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l24 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca24.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l24 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca24.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l24 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca24.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l24 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca24.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l24 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
} break;
}
}
});
JButton btnpeca25 = new JButton(pecavirada);
btnpeca25.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(24);
array.remove(24);
Pecas vazia = new Pecas(null, null);
array.add(24, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l25 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca25.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l25 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca25.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l25 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca25.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l25 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca25.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l25 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca25.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l25 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca25.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l25 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca25.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l25 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca25.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l25 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca25.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l25 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca25.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l25 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca25.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l25 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca25.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l25 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca25.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l25 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca25.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l25 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
} break;
}
}
});
JButton btnpeca26 = new JButton(pecavirada);
btnpeca26.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(25);
array.remove(25);
Pecas vazia = new Pecas(null, null);
array.add(25, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l26 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca26.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca26.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca26.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca26.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca26.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca26.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca26.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca26.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca26.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca26.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca26.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca26.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca26.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca26.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l26 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
} break;
}
}
});
JButton btnpeca27 = new JButton(pecavirada);
btnpeca27.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(26);
array.remove(26);
Pecas vazia = new Pecas(null, null);
array.add(26, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l27 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca27.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l27 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca27.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l27 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca27.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l27 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca27.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l27 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca27.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l27 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca27.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l27 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca27.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l27 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca27.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l27 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca27.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l27 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca27.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l27 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca27.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l27 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca27.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l27 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca27.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l27 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca27.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l27 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
} break;
}
}
});
JButton btnpeca28 = new JButton(pecavirada);
btnpeca28.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
++aux;
Pecas p = array.get(27);
array.remove(27);
Pecas vazia = new Pecas(null, null);
array.add(27, vazia);
String ladoa = p.getLadoEsquerdo().toString();
String ladob = p.getLadoDireito().toString();
l28 = ladoa + ladob;
switch (aux) {
case 1:
arrayH.add(p);
btnpeca28.setEnabled(false);
btnhumano1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l28 + ".png"));
break;
case 2:
arrayH.add(p);
btnpeca28.setEnabled(false);
btnhumano2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l28 + ".png"));
break;
case 3:
arrayH.add(p);
btnpeca28.setEnabled(false);
btnhumano3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l28 + ".png"));
break;
case 4:
arrayH.add(p);
btnpeca28.setEnabled(false);
btnhumano4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l28 + ".png"));
break;
case 5:
arrayH.add(p);
btnpeca28.setEnabled(false);
btnhumano5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l28 + ".png"));
break;
case 6:
arrayH.add(p);
btnpeca28.setEnabled(false);
btnhumano6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l28 + ".png"));
break;
case 7:
arrayH.add(p);
btnpeca28.setEnabled(false);
btnhumano7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l28 + ".png"));
break;
case 8:
arrayM.add(p);
btnpeca28.setEnabled(false);
btnmaquina1.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l28 + ".png"));
break;
case 9:
arrayM.add(p);
btnpeca28.setEnabled(false);
btnmaquina2.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l28 + ".png"));
break;
case 10:
arrayM.add(p);
btnpeca28.setEnabled(false);
btnmaquina3.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l28 + ".png"));
break;
case 11:
arrayM.add(p);
btnpeca28.setEnabled(false);
btnmaquina4.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l28 + ".png"));
break;
case 12:
arrayM.add(p);
btnpeca28.setEnabled(false);
btnmaquina5.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l28 + ".png"));
break;
case 13:
arrayM.add(p);
btnpeca28.setEnabled(false);
btnmaquina6.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l28 + ".png"));
break;
case 14:
arrayM.add(p);
btnpeca28.setEnabled(false);
btnmaquina7.setIcon(new ImageIcon(".//resource//Pecas//verticais1//" + l28 + ".png"));
break;
default:
if (arrayM.size() == 7 && arrayTabuleiro.size() == 0) {
JOptionPane.showMessageDialog(null, "Peas esgotadas");
} break;
}
}
});
panel_pecasAescolher.add(btnpeca1);
panel_pecasAescolher.add(btnpeca2);
panel_pecasAescolher.add(btnpeca3);
panel_pecasAescolher.add(btnpeca4);
panel_pecasAescolher.add(btnpeca5);
panel_pecasAescolher.add(btnpeca6);
panel_pecasAescolher.add(btnpeca7);
panel_pecasAescolher.add(btnpeca8);
panel_pecasAescolher.add(btnpeca9);
panel_pecasAescolher.add(btnpeca10);
panel_pecasAescolher.add(btnpeca11);
panel_pecasAescolher.add(btnpeca12);
panel_pecasAescolher.add(btnpeca13);
panel_pecasAescolher.add(btnpeca14);
panel_pecasAescolher.add(btnpeca15);
panel_pecasAescolher.add(btnpeca16);
panel_pecasAescolher.add(btnpeca17);
panel_pecasAescolher.add(btnpeca18);
panel_pecasAescolher.add(btnpeca19);
panel_pecasAescolher.add(btnpeca20);
panel_pecasAescolher.add(btnpeca21);
panel_pecasAescolher.add(btnpeca22);
panel_pecasAescolher.add(btnpeca23);
panel_pecasAescolher.add(btnpeca24);
panel_pecasAescolher.add(btnpeca25);
panel_pecasAescolher.add(btnpeca26);
panel_pecasAescolher.add(btnpeca27);
panel_pecasAescolher.add(btnpeca28);
JPanel panel_tabuleiro = new JPanel();
panel_tabuleiro.setBorder(new LineBorder(Color.RED, 1, true));
panel_tabuleiro.setBounds(361, 124, 979, 426);
getContentPane().add(panel_tabuleiro);
panel_tabuleiro.setLayout(null);
btn_14 = new JButton("");
btn_14.setEnabled(false);
btn_14.setBounds(37, 145, 35, 70);
panel_tabuleiro.add(btn_14);
btn_13 = new JButton("");
btn_13.setEnabled(false);
btn_13.setBounds(37, 76, 35, 70);
panel_tabuleiro.add(btn_13);
btn_15 = new JButton("");
btn_15.setEnabled(false);
btn_15.setBounds(37, 214, 35, 70);
panel_tabuleiro.add(btn_15);
btn_12 = new JButton("");
btn_12.setEnabled(false);
btn_12.setBounds(37, 42, 70, 35);
panel_tabuleiro.add(btn_12);
btn_16 = new JButton("");
btn_16.setEnabled(false);
btn_16.setBounds(37, 283, 35, 70);
panel_tabuleiro.add(btn_16);
btn_18 = new JButton("");
btn_18.setEnabled(false);
btn_18.setBounds(106, 352, 70, 35);
panel_tabuleiro.add(btn_18);
btn_11 = new JButton("");
btn_11.setEnabled(false);
btn_11.setBounds(106, 42, 70, 35);
panel_tabuleiro.add(btn_11);
btn_23 = new JButton("");
btn_23.setEnabled(false);
btn_23.setBounds(451, 352, 70, 35);
panel_tabuleiro.add(btn_23);
btn_10 = new JButton("");
btn_10.setEnabled(false);
btn_10.setBounds(175, 42, 70, 35);
panel_tabuleiro.add(btn_10);
btn_9 = new JButton("");
btn_9.setEnabled(false);
btn_9.setBounds(244, 42, 70, 35);
panel_tabuleiro.add(btn_9);
btn_8 = new JButton("");
btn_8.setEnabled(false);
btn_8.setBounds(313, 42, 70, 35);
panel_tabuleiro.add(btn_8);
btn_7 = new JButton("");
btn_7.setEnabled(false);
btn_7.setBounds(382, 42, 70, 35);
panel_tabuleiro.add(btn_7);
btn_6 = new JButton("");
btn_6.setEnabled(false);
btn_6.setBounds(451, 42, 70, 35);
panel_tabuleiro.add(btn_6);
btn_5 = new JButton("");
btn_5.setEnabled(false);
btn_5.setBounds(520, 42, 70, 35);
panel_tabuleiro.add(btn_5);
btn_17 = new JButton("");
btn_17.setEnabled(false);
btn_17.setBounds(37, 352, 70, 35);
panel_tabuleiro.add(btn_17);
btn_19 = new JButton("");
btn_19.setEnabled(false);
btn_19.setBounds(175, 352, 70, 35);
panel_tabuleiro.add(btn_19);
btn_20 = new JButton("");
btn_20.setEnabled(false);
btn_20.setBounds(244, 352, 70, 35);
panel_tabuleiro.add(btn_20);
btn_21 = new JButton("");
btn_21.setEnabled(false);
btn_21.setBounds(313, 352, 70, 35);
panel_tabuleiro.add(btn_21);
btn_22 = new JButton("");
btn_22.setEnabled(false);
btn_22.setBounds(382, 352, 70, 35);
panel_tabuleiro.add(btn_22);
btn_27 = new JButton("");
btn_27.setEnabled(false);
btn_27.setBounds(728, 352, 70, 35);
panel_tabuleiro.add(btn_27);
btn_24 = new JButton("");
btn_24.setEnabled(false);
btn_24.setBounds(521, 352, 70, 35);
panel_tabuleiro.add(btn_24);
btn_25 = new JButton("");
btn_25.setEnabled(false);
btn_25.setBounds(590, 352, 70, 35);
panel_tabuleiro.add(btn_25);
btn_26 = new JButton("");
btn_26.setEnabled(false);
btn_26.setBounds(659, 352, 70, 35);
panel_tabuleiro.add(btn_26);
btn_4 = new JButton("");
btn_4.setEnabled(false);
btn_4.setBounds(589, 42, 70, 35);
panel_tabuleiro.add(btn_4);
btn_3 = new JButton("");
btn_3.setEnabled(false);
btn_3.setBounds(658, 42, 70, 35);
panel_tabuleiro.add(btn_3);
btn_2 = new JButton("");
btn_2.setEnabled(false);
btn_2.setBounds(727, 42, 70, 35);
panel_tabuleiro.add(btn_2);
btn_1 = new JButton("");
btn_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btn_1.setEnabled(false);
btn_1.setBounds(796, 42, 70, 35);
panel_tabuleiro.add(btn_1);
btn_28 = new JButton("");
btn_28.setEnabled(false);
btn_28.setBounds(797, 352, 70, 35);
panel_tabuleiro.add(btn_28);
JLabel lblEscolhaSuasPecas = new JLabel("Escolha Suas Pecas");
lblEscolhaSuasPecas.setFont(new Font("Times New Roman", Font.BOLD, 18));
lblEscolhaSuasPecas.setBounds(79, 98, 160, 36);
getContentPane().add(lblEscolhaSuasPecas);
setSize(1366, 720);
setVisible(true);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
public static void main(String[] args) {
new TelaDoJogo();
}
}
|
Colocado as imagens comparadas para os botões do humano...
|
src/br/com/domino/view/TelaDoJogo.java
|
Colocado as imagens comparadas para os botões do humano...
|
|
Java
|
epl-1.0
|
342597fc833d7124c0e49e8c801e6966f48b453b
| 0
|
opendaylight/yangtools,opendaylight/yangtools
|
/*
* Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.yangtools.yang.common;
import static org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil.getRevisionFormat;
import com.google.common.base.Preconditions;
import java.io.Serializable;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.util.Date;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.opendaylight.yangtools.concepts.Immutable;
import org.opendaylight.yangtools.objcache.ObjectCache;
import org.opendaylight.yangtools.objcache.ObjectCacheFactory;
/**
* The QName from XML consists of local name of element and XML namespace, but
* for our use, we added module revision to it.
*
* In YANG context QName is full name of defined node, type, procedure or
* notification. QName consists of XML namespace, YANG model revision and local
* name of defined type. It is used to prevent name clashes between nodes with
* same local name, but from different schemas.
*
* <ul>
* <li><b>XMLNamespace</b> - {@link #getNamespace()} - the namespace assigned to the YANG module which
* defined element, type, procedure or notification.</li>
* <li><b>Revision</b> - {@link #getRevision()} - the revision of the YANG module which describes the
* element</li>
* <li><b>LocalName</b> - {@link #getLocalName()} - the YANG schema identifier which were defined for this
* node in the YANG module</li>
* </ul>
*
* QName may also have <code>prefix</code> assigned, but prefix does not
* affect equality and identity of two QNames and carry only information
* which may be useful for serializers / deserializers.
*
*
*/
public final class QName implements Immutable, Serializable, Comparable<QName> {
private static final ObjectCache CACHE = ObjectCacheFactory.getObjectCache(QName.class);
private static final long serialVersionUID = 5398411242927766414L;
static final String QNAME_REVISION_DELIMITER = "?revision=";
static final String QNAME_LEFT_PARENTHESIS = "(";
static final String QNAME_RIGHT_PARENTHESIS = ")";
private static final Pattern QNAME_PATTERN_FULL = Pattern.compile("^\\((.+)\\" + QNAME_REVISION_DELIMITER
+ "(.+)\\)(.+)$");
private static final Pattern QNAME_PATTERN_NO_REVISION = Pattern.compile("^\\((.+)\\)(.+)$");
private static final Pattern QNAME_PATTERN_NO_NAMESPACE_NO_REVISION = Pattern.compile("^(.+)$");
private static final char[] ILLEGAL_CHARACTERS = new char[] { '?', '(', ')', '&' };
// Mandatory
private final QNameModule module;
// Mandatory
private final String localName;
private QName(final QNameModule module, final String localName) {
this.localName = checkLocalName(localName);
this.module = module;
}
/**
* Look up specified QName in the global cache and return a shared reference.
*
* @param qname QName instance
* @return Cached instance, according to {@link ObjectCache} policy.
*/
public static QName cachedReference(final QName qname) {
// We also want to make sure we keep the QNameModule cached
final QNameModule myMod = qname.getModule();
final QNameModule cacheMod = QNameModule.cachedReference(myMod);
final QName what;
if (cacheMod.equals(myMod)) {
what = qname;
} else {
what = QName.create(cacheMod, qname.localName);
}
return CACHE.getReference(what);
}
/**
* QName Constructor.
*
* @param namespace
* the namespace assigned to the YANG module
* @param localName
* YANG schema identifier
*/
public QName(final URI namespace, final String localName) {
this(QNameModule.create(namespace, null), localName);
}
private static String checkLocalName(final String localName) {
if (localName == null) {
throw new IllegalArgumentException("Parameter 'localName' may not be null.");
}
if (localName.length() == 0) {
throw new IllegalArgumentException("Parameter 'localName' must be a non-empty string.");
}
for (final char c : ILLEGAL_CHARACTERS) {
if (localName.indexOf(c) != -1) {
throw new IllegalArgumentException(String.format(
"Parameter 'localName':'%s' contains illegal character '%s'", localName, c));
}
}
return localName;
}
public static QName create(final String input) {
Matcher matcher = QNAME_PATTERN_FULL.matcher(input);
if (matcher.matches()) {
final String namespace = matcher.group(1);
final String revision = matcher.group(2);
final String localName = matcher.group(3);
return create(namespace, revision, localName);
}
matcher = QNAME_PATTERN_NO_REVISION.matcher(input);
if (matcher.matches()) {
final URI namespace = URI.create(matcher.group(1));
final String localName = matcher.group(2);
return new QName(namespace, localName);
}
matcher = QNAME_PATTERN_NO_NAMESPACE_NO_REVISION.matcher(input);
if (matcher.matches()) {
final String localName = matcher.group(1);
return new QName((URI) null, localName);
}
throw new IllegalArgumentException("Invalid input:" + input);
}
/**
* Get the module component of the QName.
*
* @return Module component
*/
public QNameModule getModule() {
return module;
}
/**
* Returns XMLNamespace assigned to the YANG module.
*
* @return XMLNamespace assigned to the YANG module.
*/
public URI getNamespace() {
return module.getNamespace();
}
/**
* Returns YANG schema identifier which were defined for this node in the
* YANG module
*
* @return YANG schema identifier which were defined for this node in the
* YANG module
*/
public String getLocalName() {
return localName;
}
/**
* Returns revision of the YANG module if the module has defined revision,
* otherwise returns <code>null</code>
*
* @return revision of the YANG module if the module has defined revision,
* otherwise returns <code>null</code>
*/
public Date getRevision() {
return module.getRevision();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Objects.hashCode(localName);
result = prime * result + module.hashCode();
return result;
}
/**
*
* Compares the specified object with this list for equality. Returns
* <tt>true</tt> if and only if the specified object is also instance of
* {@link QName} and its {@link #getLocalName()}, {@link #getNamespace()} and
* {@link #getRevision()} are equals to same properties of this instance.
*
* @param obj the object to be compared for equality with this QName
* @return <tt>true</tt> if the specified object is equal to this QName
*
*/
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof QName)) {
return false;
}
final QName other = (QName) obj;
return Objects.equals(localName, other.localName) && module.equals(other.module);
}
public static QName create(final QName base, final String localName) {
return create(base.getModule(), localName);
}
/**
* Creates new QName.
*
* @param qnameModule
* Namespace and revision enclosed as a QNameModule
* @param localName
* Local name part of QName. MUST NOT BE null.
* @return Instance of QName
*/
public static QName create(final QNameModule qnameModule, final String localName) {
return new QName(Preconditions.checkNotNull(qnameModule,"module may not be null"), localName);
}
/**
* Creates new QName.
*
* @param namespace
* Namespace of QName or null if namespace is undefined.
* @param revision
* Revision of namespace or null if revision is unspecified.
* @param localName
* Local name part of QName. MUST NOT BE null.
* @return Instance of QName
*/
public static QName create(final URI namespace, final Date revision, final String localName) {
return create(QNameModule.create(namespace, revision), localName);
}
/**
*
* Creates new QName.
*
* @param namespace
* Namespace of QName, MUST NOT BE Null.
* @param revision
* Revision of namespace / YANG module. MUST NOT BE null, MUST BE
* in format <code>YYYY-mm-dd</code>.
* @param localName
* Local name part of QName. MUST NOT BE null.
* @return
* @throws NullPointerException
* If any of parameters is null.
* @throws IllegalArgumentException
* If <code>namespace</code> is not valid URI or
* <code>revision</code> is not according to format
* <code>YYYY-mm-dd</code>.
*/
public static QName create(final String namespace, final String revision, final String localName) {
final URI namespaceUri = parseNamespace(namespace);
final Date revisionDate = parseRevision(revision);
return create(namespaceUri, revisionDate, localName);
}
private static URI parseNamespace(final String namespace) {
try {
return new URI(namespace);
} catch (final URISyntaxException ue) {
throw new IllegalArgumentException(String.format("Namespace '%s' is not a valid URI", namespace), ue);
}
}
/**
* Creates new QName.
*
* @param namespace
* Namespace of QName, MUST NOT BE Null.
* @param localName
* Local name part of QName. MUST NOT BE null.
* @return
* @throws NullPointerException
* If any of parameters is null.
* @throws IllegalArgumentException
* If <code>namespace</code> is not valid URI.
*/
public static QName create(final String namespace, final String localName) {
return create(parseNamespace(namespace), null, localName);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
if (getNamespace() != null) {
sb.append(QNAME_LEFT_PARENTHESIS + getNamespace());
if (getFormattedRevision() != null) {
sb.append(QNAME_REVISION_DELIMITER + getFormattedRevision());
}
sb.append(QNAME_RIGHT_PARENTHESIS);
}
sb.append(localName);
return sb.toString();
}
/**
* Return string representation of revision in format
* <code>YYYY-mm-dd</code>
*
* YANG Specification defines format for <code>revision</code> as
* YYYY-mm-dd. This format for revision is reused accross multiple places
* such as capabilities URI, YANG modules, etc.
*
* @return String representation of revision or null, if revision is not
* set.
*/
public String getFormattedRevision() {
return module.getFormattedRevision();
}
/**
* Creates copy of this with revision and prefix unset.
*
* @return copy of this QName with revision and prefix unset.
*/
public QName withoutRevision() {
return create(getNamespace(), null, localName);
}
public static Date parseRevision(final String formatedDate) {
try {
return getRevisionFormat().parse(formatedDate);
} catch (ParseException | RuntimeException e) {
throw new IllegalArgumentException(
String.format("Revision '%s'is not in a supported format", formatedDate), e);
}
}
/**
* Formats {@link Date} representing revision to format
* <code>YYYY-mm-dd</code>
*
* YANG Specification defines format for <code>revision</code> as
* YYYY-mm-dd. This format for revision is reused accross multiple places
* such as capabilities URI, YANG modules, etc.
*
* @param revision
* Date object to format or null
* @return String representation or null if the input was null.
*/
public static String formattedRevision(final Date revision) {
if (revision == null) {
return null;
}
return getRevisionFormat().format(revision);
}
/**
*
* Compares this QName to other, without comparing revision.
*
* Compares instance of this to other instance of QName and returns true if
* both instances have equal <code>localName</code> ({@link #getLocalName()}
* ) and <code>namespace</code> ({@link #getNamespace()}).
*
* @param other
* Other QName. Must not be null.
* @return true if this instance and other have equals localName and
* namespace.
* @throws NullPointerException
* if <code>other</code> is null.
*/
public boolean isEqualWithoutRevision(final QName other) {
return localName.equals(other.getLocalName()) && Objects.equals(getNamespace(), other.getNamespace());
}
@Override
public int compareTo(final QName other) {
// compare mandatory localName parameter
int result = localName.compareTo(other.localName);
if (result != 0) {
return result;
}
// compare nullable namespace parameter
if (getNamespace() == null) {
if (other.getNamespace() != null) {
return -1;
}
} else {
if (other.getNamespace() == null) {
return 1;
}
result = getNamespace().compareTo(other.getNamespace());
if (result != 0) {
return result;
}
}
// compare nullable revision parameter
if (getRevision() == null) {
if (other.getRevision() != null) {
return -1;
}
} else {
if (other.getRevision() == null) {
return 1;
}
result = getRevision().compareTo(other.getRevision());
if (result != 0) {
return result;
}
}
return result;
}
}
|
yang/yang-common/src/main/java/org/opendaylight/yangtools/yang/common/QName.java
|
/*
* Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.yangtools.yang.common;
import static org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil.getRevisionFormat;
import com.google.common.base.Preconditions;
import java.io.Serializable;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.util.Date;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.opendaylight.yangtools.concepts.Immutable;
import org.opendaylight.yangtools.objcache.ObjectCache;
import org.opendaylight.yangtools.objcache.ObjectCacheFactory;
/**
* The QName from XML consists of local name of element and XML namespace, but
* for our use, we added module revision to it.
*
* In YANG context QName is full name of defined node, type, procedure or
* notification. QName consists of XML namespace, YANG model revision and local
* name of defined type. It is used to prevent name clashes between nodes with
* same local name, but from different schemas.
*
* <ul>
* <li><b>XMLNamespace</b> - {@link #getNamespace()} - the namespace assigned to the YANG module which
* defined element, type, procedure or notification.</li>
* <li><b>Revision</b> - {@link #getRevision()} - the revision of the YANG module which describes the
* element</li>
* <li><b>LocalName</b> - {@link #getLocalName()} - the YANG schema identifier which were defined for this
* node in the YANG module</li>
* </ul>
*
* QName may also have <code>prefix</code> assigned, but prefix does not
* affect equality and identity of two QNames and carry only information
* which may be useful for serializers / deserializers.
*
*
*/
public final class QName implements Immutable, Serializable, Comparable<QName> {
private static final ObjectCache CACHE = ObjectCacheFactory.getObjectCache(QName.class);
private static final long serialVersionUID = 5398411242927766414L;
static final String QNAME_REVISION_DELIMITER = "?revision=";
static final String QNAME_LEFT_PARENTHESIS = "(";
static final String QNAME_RIGHT_PARENTHESIS = ")";
private static final Pattern QNAME_PATTERN_FULL = Pattern.compile("^\\((.+)\\" + QNAME_REVISION_DELIMITER
+ "(.+)\\)(.+)$");
private static final Pattern QNAME_PATTERN_NO_REVISION = Pattern.compile("^\\((.+)\\)(.+)$");
private static final Pattern QNAME_PATTERN_NO_NAMESPACE_NO_REVISION = Pattern.compile("^(.+)$");
private static final char[] ILLEGAL_CHARACTERS = new char[] { '?', '(', ')', '&' };
// Mandatory
private final QNameModule module;
// Mandatory
private final String localName;
private QName(final QNameModule module, final String localName) {
this.localName = checkLocalName(localName);
this.module = module;
}
/**
* Look up specified QName in the global cache and return a shared reference.
*
* @param qname QName instance
* @return Cached instance, according to {@link ObjectCache} policy.
*/
public static QName cachedReference(final QName qname) {
// We also want to make sure we keep the QNameModule cached
final QNameModule myMod = qname.getModule();
final QNameModule cacheMod = QNameModule.cachedReference(myMod);
final QName what;
if (cacheMod.equals(myMod)) {
what = qname;
} else {
what = QName.create(cacheMod, qname.localName);
}
return CACHE.getReference(what);
}
/**
* QName Constructor.
*
* @param namespace
* the namespace assigned to the YANG module
* @param localName
* YANG schema identifier
*/
public QName(final URI namespace, final String localName) {
this(QNameModule.create(namespace, null), localName);
}
private static String checkLocalName(final String localName) {
if (localName == null) {
throw new IllegalArgumentException("Parameter 'localName' may not be null.");
}
if (localName.length() == 0) {
throw new IllegalArgumentException("Parameter 'localName' must be a non-empty string.");
}
for (final char c : ILLEGAL_CHARACTERS) {
if (localName.indexOf(c) != -1) {
throw new IllegalArgumentException(String.format(
"Parameter 'localName':'%s' contains illegal character '%s'", localName, c));
}
}
return localName;
}
public static QName create(final String input) {
Matcher matcher = QNAME_PATTERN_FULL.matcher(input);
if (matcher.matches()) {
final String namespace = matcher.group(1);
final String revision = matcher.group(2);
final String localName = matcher.group(3);
return create(namespace, revision, localName);
}
matcher = QNAME_PATTERN_NO_REVISION.matcher(input);
if (matcher.matches()) {
final URI namespace = URI.create(matcher.group(1));
final String localName = matcher.group(2);
return new QName(namespace, localName);
}
matcher = QNAME_PATTERN_NO_NAMESPACE_NO_REVISION.matcher(input);
if (matcher.matches()) {
final String localName = matcher.group(1);
return new QName((URI) null, localName);
}
throw new IllegalArgumentException("Invalid input:" + input);
}
/**
* Get the module component of the QName.
*
* @return Module component
*/
public QNameModule getModule() {
return module;
}
/**
* Returns XMLNamespace assigned to the YANG module.
*
* @return XMLNamespace assigned to the YANG module.
*/
public URI getNamespace() {
return module.getNamespace();
}
/**
* Returns YANG schema identifier which were defined for this node in the
* YANG module
*
* @return YANG schema identifier which were defined for this node in the
* YANG module
*/
public String getLocalName() {
return localName;
}
/**
* Returns revision of the YANG module if the module has defined revision,
* otherwise returns <code>null</code>
*
* @return revision of the YANG module if the module has defined revision,
* otherwise returns <code>null</code>
*/
public Date getRevision() {
return module.getRevision();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Objects.hashCode(localName);
result = prime * result + module.hashCode();
return result;
}
/**
*
* Compares the specified object with this list for equality. Returns
* <tt>true</tt> if and only if the specified object is also instance of
* {@link QName} and its {@link #getLocalName()}, {@link #getNamespace()} and
* {@link #getRevision()} are equals to same properties of this instance.
*
* @param obj the object to be compared for equality with this QName
* @return <tt>true</tt> if the specified object is equal to this QName
*
*/
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof QName)) {
return false;
}
final QName other = (QName) obj;
if (localName == null) {
if (other.localName != null) {
return false;
}
} else if (!localName.equals(other.localName)) {
return false;
}
return module.equals(other.module);
}
public static QName create(final QName base, final String localName) {
return create(base.getModule(), localName);
}
/**
* Creates new QName.
*
* @param qnameModule
* Namespace and revision enclosed as a QNameModule
* @param localName
* Local name part of QName. MUST NOT BE null.
* @return Instance of QName
*/
public static QName create(final QNameModule qnameModule, final String localName) {
return new QName(Preconditions.checkNotNull(qnameModule,"module may not be null"), localName);
}
/**
* Creates new QName.
*
* @param namespace
* Namespace of QName or null if namespace is undefined.
* @param revision
* Revision of namespace or null if revision is unspecified.
* @param localName
* Local name part of QName. MUST NOT BE null.
* @return Instance of QName
*/
public static QName create(final URI namespace, final Date revision, final String localName) {
return create(QNameModule.create(namespace, revision), localName);
}
/**
*
* Creates new QName.
*
* @param namespace
* Namespace of QName, MUST NOT BE Null.
* @param revision
* Revision of namespace / YANG module. MUST NOT BE null, MUST BE
* in format <code>YYYY-mm-dd</code>.
* @param localName
* Local name part of QName. MUST NOT BE null.
* @return
* @throws NullPointerException
* If any of parameters is null.
* @throws IllegalArgumentException
* If <code>namespace</code> is not valid URI or
* <code>revision</code> is not according to format
* <code>YYYY-mm-dd</code>.
*/
public static QName create(final String namespace, final String revision, final String localName) {
final URI namespaceUri = parseNamespace(namespace);
final Date revisionDate = parseRevision(revision);
return create(namespaceUri, revisionDate, localName);
}
private static URI parseNamespace(final String namespace) {
try {
return new URI(namespace);
} catch (final URISyntaxException ue) {
throw new IllegalArgumentException(String.format("Namespace '%s' is not a valid URI", namespace), ue);
}
}
/**
* Creates new QName.
*
* @param namespace
* Namespace of QName, MUST NOT BE Null.
* @param localName
* Local name part of QName. MUST NOT BE null.
* @return
* @throws NullPointerException
* If any of parameters is null.
* @throws IllegalArgumentException
* If <code>namespace</code> is not valid URI.
*/
public static QName create(final String namespace, final String localName) {
return create(parseNamespace(namespace), null, localName);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
if (getNamespace() != null) {
sb.append(QNAME_LEFT_PARENTHESIS + getNamespace());
if (getFormattedRevision() != null) {
sb.append(QNAME_REVISION_DELIMITER + getFormattedRevision());
}
sb.append(QNAME_RIGHT_PARENTHESIS);
}
sb.append(localName);
return sb.toString();
}
/**
* Return string representation of revision in format
* <code>YYYY-mm-dd</code>
*
* YANG Specification defines format for <code>revision</code> as
* YYYY-mm-dd. This format for revision is reused accross multiple places
* such as capabilities URI, YANG modules, etc.
*
* @return String representation of revision or null, if revision is not
* set.
*/
public String getFormattedRevision() {
return module.getFormattedRevision();
}
/**
* Creates copy of this with revision and prefix unset.
*
* @return copy of this QName with revision and prefix unset.
*/
public QName withoutRevision() {
return create(getNamespace(), null, localName);
}
public static Date parseRevision(final String formatedDate) {
try {
return getRevisionFormat().parse(formatedDate);
} catch (ParseException | RuntimeException e) {
throw new IllegalArgumentException(
String.format("Revision '%s'is not in a supported format", formatedDate), e);
}
}
/**
* Formats {@link Date} representing revision to format
* <code>YYYY-mm-dd</code>
*
* YANG Specification defines format for <code>revision</code> as
* YYYY-mm-dd. This format for revision is reused accross multiple places
* such as capabilities URI, YANG modules, etc.
*
* @param revision
* Date object to format or null
* @return String representation or null if the input was null.
*/
public static String formattedRevision(final Date revision) {
if (revision == null) {
return null;
}
return getRevisionFormat().format(revision);
}
/**
*
* Compares this QName to other, without comparing revision.
*
* Compares instance of this to other instance of QName and returns true if
* both instances have equal <code>localName</code> ({@link #getLocalName()}
* ) and <code>namespace</code> ({@link #getNamespace()}).
*
* @param other
* Other QName. Must not be null.
* @return true if this instance and other have equals localName and
* namespace.
* @throws NullPointerException
* if <code>other</code> is null.
*/
public boolean isEqualWithoutRevision(final QName other) {
return localName.equals(other.getLocalName()) && Objects.equals(getNamespace(), other.getNamespace());
}
@Override
public int compareTo(final QName other) {
// compare mandatory localName parameter
int result = localName.compareTo(other.localName);
if (result != 0) {
return result;
}
// compare nullable namespace parameter
if (getNamespace() == null) {
if (other.getNamespace() != null) {
return -1;
}
} else {
if (other.getNamespace() == null) {
return 1;
}
result = getNamespace().compareTo(other.getNamespace());
if (result != 0) {
return result;
}
}
// compare nullable revision parameter
if (getRevision() == null) {
if (other.getRevision() != null) {
return -1;
}
} else {
if (other.getRevision() == null) {
return 1;
}
result = getRevision().compareTo(other.getRevision());
if (result != 0) {
return result;
}
}
return result;
}
}
|
Use Objects.equals() in QName.equals()
Simplifies the code.
Change-Id: Ibac465c5bbc5a5ab8b5b3b40b5c57a042c93d095
Signed-off-by: Robert Varga <b8bd3df785fdc0ff42dd1710c5d91998513c57ef@cisco.com>
|
yang/yang-common/src/main/java/org/opendaylight/yangtools/yang/common/QName.java
|
Use Objects.equals() in QName.equals()
|
|
Java
|
epl-1.0
|
c1caea590272cbc5a606c886ef1f790d794b45a5
| 0
|
pedrofvteixeira/mondrian,mdamour1976/mondrian,OSBI/mondrian,openedbox/mondrian,preisanalytics/mondrian,mdamour1976/mondrian,ivanpogodin/mondrian,nextelBIS/mondrian,wetet2/mondrian,mustangore/mondrian,stiberger/mondrian,cesarmarinhorj/mondrian,wetet2/mondrian,stiberger/mondrian,pedrofvteixeira/mondrian,pedrofvteixeira/mondrian,mustangore/mondrian,mustangore/mondrian,truvenganong/mondrian,Seiferxx/mondrian,nextelBIS/mondrian,julianhyde/mondrian,dkincade/mondrian,dkincade/mondrian,preisanalytics/mondrian,bmorrise/mondrian,sayanh/mondrian,syncron/mondrian,OSBI/mondrian,syncron/mondrian,sayanh/mondrian,cocosli/mondrian,ivanpogodin/mondrian,lgrill-pentaho/mondrian,truvenganong/mondrian,lgrill-pentaho/mondrian,nextelBIS/mondrian,AvinashPD/mondrian,cocosli/mondrian,lgrill-pentaho/mondrian,AvinashPD/mondrian,Seiferxx/mondrian,openedbox/mondrian,mdamour1976/mondrian,cocosli/mondrian,ivanpogodin/mondrian,syncron/mondrian,openedbox/mondrian,AvinashPD/mondrian,pentaho/mondrian,pentaho/mondrian,sayanh/mondrian,cesarmarinhorj/mondrian,cesarmarinhorj/mondrian,julianhyde/mondrian,truvenganong/mondrian,stiberger/mondrian,bmorrise/mondrian,wetet2/mondrian,Seiferxx/mondrian,OSBI/mondrian,pentaho/mondrian,bmorrise/mondrian,dkincade/mondrian,preisanalytics/mondrian
|
/*
// This software is subject to the terms of the Eclipse Public License v1.0
// Agreement, available at the following URL:
// http://www.eclipse.org/legal/epl-v10.html.
// You must accept the terms of that agreement to use this software.
//
// Copyright (C) 2003-2005 Julian Hyde
// Copyright (C) 2005-2013 Pentaho
// All Rights Reserved.
*/
package mondrian.test;
import mondrian.olap.*;
import mondrian.olap.Role.HierarchyAccess;
import junit.framework.Assert;
import org.olap4j.mdx.IdentifierNode;
import java.util.List;
/**
* <code>AccessControlTest</code> is a set of unit-tests for access-control.
* For these tests, all of the roles are of type RoleImpl.
*
* @see Role
*
* @author jhyde
* @since Feb 21, 2003
*/
public class AccessControlTest extends FoodMartTestCase {
private static final String BiServer1574Role1 =
"<Role name=\"role1\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Warehouse\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Store Size in SQFT]\" access=\"custom\" rollupPolicy=\"partial\">\n"
+ " <MemberGrant member=\"[Store Size in SQFT].[20319]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store Size in SQFT].[21215]\" access=\"none\"/>\n"
+ " </HierarchyGrant>\n"
+ " <HierarchyGrant hierarchy=\"[Store Type]\" access=\"custom\" rollupPolicy=\"partial\">\n"
+ " <MemberGrant member=\"[Store Type].[Supermarket]\" access=\"all\"/>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>";
public AccessControlTest(String name) {
super(name);
}
public void testSchemaReader() {
final TestContext testContext = getTestContext();
final Connection connection = testContext.getConnection();
Schema schema = connection.getSchema();
final boolean fail = true;
Cube cube = schema.lookupCube("Sales", fail);
final SchemaReader schemaReader =
cube.getSchemaReader(connection.getRole());
final SchemaReader schemaReader1 = schemaReader.withoutAccessControl();
assertNotNull(schemaReader1);
final SchemaReader schemaReader2 = schemaReader1.withoutAccessControl();
assertNotNull(schemaReader2);
}
public void testGrantDimensionNone() {
final TestContext context = getTestContext().withFreshConnection();
final Connection connection = context.getConnection();
RoleImpl role = ((RoleImpl) connection.getRole()).makeMutableClone();
Schema schema = connection.getSchema();
Cube salesCube = schema.lookupCube("Sales", true);
// todo: add Schema.lookupDimension
final SchemaReader schemaReader = salesCube.getSchemaReader(role);
Dimension genderDimension =
(Dimension) schemaReader.lookupCompound(
salesCube, Id.Segment.toList("Gender"), true,
Category.Dimension);
role.grant(genderDimension, Access.NONE);
role.makeImmutable();
connection.setRole(role);
context.assertAxisThrows(
"[Gender].children",
"MDX object '[Gender]' not found in cube 'Sales'");
}
public void testRestrictMeasures() {
final TestContext testContext = TestContext.instance().create(
null, null, null, null, null,
"<Role name=\"Role1\">\n"
+ " <SchemaGrant access=\"all\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Measures]\" access=\"all\">\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>"
+ "<Role name=\"Role2\">\n"
+ " <SchemaGrant access=\"all\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Measures]\" access=\"custom\">\n"
+ " <MemberGrant member=\"[Measures].[Unit Sales]\" access=\"all\"/>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>");
final TestContext role1 = testContext.withRole("Role1");
final TestContext role2 = testContext.withRole("Role2");
role1.assertQueryReturns(
"SELECT {[Measures].Members} ON COLUMNS FROM [SALES]",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "{[Measures].[Store Cost]}\n"
+ "{[Measures].[Store Sales]}\n"
+ "{[Measures].[Sales Count]}\n"
+ "{[Measures].[Customer Count]}\n"
+ "{[Measures].[Promotion Sales]}\n"
+ "Row #0: 266,773\n"
+ "Row #0: 225,627.23\n"
+ "Row #0: 565,238.13\n"
+ "Row #0: 86,837\n"
+ "Row #0: 5,581\n"
+ "Row #0: 151,211.21\n");
role2.assertQueryReturns(
"SELECT {[Measures].Members} ON COLUMNS FROM [SALES]",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Row #0: 266,773\n");
}
public void testRoleMemberAccessNonExistentMemberFails() {
final TestContext testContext = TestContext.instance().create(
null, null, null, null, null,
"<Role name=\"Role1\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Store]\" access=\"custom\" rollupPolicy=\"partial\">\n"
+ " <MemberGrant member=\"[Store].[USA].[Non Existent]\" access=\"all\"/>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>")
.withRole("Role1");
testContext.assertQueryThrows(
"select {[Store].Children} on 0 from [Sales]",
"Member '[Store].[USA].[Non Existent]' not found");
}
public void testRoleMemberAccess() {
final Connection connection = getRestrictedConnection();
// because CA has access
assertMemberAccess(connection, Access.CUSTOM, "[Store].[USA]");
assertMemberAccess(connection, Access.CUSTOM, "[Store].[Mexico]");
assertMemberAccess(connection, Access.NONE, "[Store].[Mexico].[DF]");
assertMemberAccess(
connection, Access.NONE, "[Store].[Mexico].[DF].[Mexico City]");
assertMemberAccess(connection, Access.NONE, "[Store].[Canada]");
assertMemberAccess(
connection, Access.NONE, "[Store].[Canada].[BC].[Vancouver]");
assertMemberAccess(
connection, Access.ALL, "[Store].[USA].[CA].[Los Angeles]");
assertMemberAccess(
connection, Access.NONE, "[Store].[USA].[CA].[San Diego]");
// USA deny supercedes OR grant
assertMemberAccess(
connection, Access.NONE, "[Store].[USA].[OR].[Portland]");
assertMemberAccess(
connection, Access.NONE, "[Store].[USA].[WA].[Seattle]");
assertMemberAccess(connection, Access.NONE, "[Store].[USA].[WA]");
// above top level
assertMemberAccess(connection, Access.NONE, "[Store].[All Stores]");
}
private void assertMemberAccess(
final Connection connection,
Access expectedAccess,
String memberName)
{
final Role role = connection.getRole(); // restricted
Schema schema = connection.getSchema();
final boolean fail = true;
Cube salesCube = schema.lookupCube("Sales", fail);
final SchemaReader schemaReader =
salesCube.getSchemaReader(null).withLocus();
final Member member =
schemaReader.getMemberByUniqueName(
Util.parseIdentifier(memberName), true);
final Access actualAccess = role.getAccess(member);
Assert.assertEquals(memberName, expectedAccess, actualAccess);
}
private void assertCubeAccess(
final Connection connection,
Access expectedAccess,
String cubeName)
{
final Role role = connection.getRole();
Schema schema = connection.getSchema();
final boolean fail = true;
Cube cube = schema.lookupCube(cubeName, fail);
final Access actualAccess = role.getAccess(cube);
Assert.assertEquals(cubeName, expectedAccess, actualAccess);
}
private void assertHierarchyAccess(
final Connection connection,
Access expectedAccess,
String cubeName,
String hierarchyName)
{
final Role role = connection.getRole();
Schema schema = connection.getSchema();
final boolean fail = true;
Cube cube = schema.lookupCube(cubeName, fail);
final SchemaReader schemaReader =
cube.getSchemaReader(null); // unrestricted
final Hierarchy hierarchy =
(Hierarchy) schemaReader.lookupCompound(
cube, Util.parseIdentifier(hierarchyName), fail,
Category.Hierarchy);
final Access actualAccess = role.getAccess(hierarchy);
Assert.assertEquals(cubeName, expectedAccess, actualAccess);
}
private Role.HierarchyAccess getHierarchyAccess(
final Connection connection,
String cubeName,
String hierarchyName)
{
final Role role = connection.getRole();
Schema schema = connection.getSchema();
final boolean fail = true;
Cube cube = schema.lookupCube(cubeName, fail);
final SchemaReader schemaReader =
cube.getSchemaReader(null); // unrestricted
final Hierarchy hierarchy =
(Hierarchy) schemaReader.lookupCompound(
cube, Util.parseIdentifier(hierarchyName), fail,
Category.Hierarchy);
return role.getAccessDetails(hierarchy);
}
public void testGrantHierarchy1a() {
// assert: can access Mexico (explicitly granted)
// assert: can not access Canada (explicitly denied)
// assert: can access USA (rule 3 - parent of allowed member San
// Francisco)
getRestrictedTestContext().assertAxisReturns(
"[Store].level.members",
"[Store].[Mexico]\n" + "[Store].[USA]");
}
public void testGrantHierarchy1aAllMembers() {
// assert: can access Mexico (explicitly granted)
// assert: can not access Canada (explicitly denied)
// assert: can access USA (rule 3 - parent of allowed member San
// Francisco)
getRestrictedTestContext().assertAxisReturns(
"[Store].level.allmembers",
"[Store].[Mexico]\n" + "[Store].[USA]");
}
public void testGrantHierarchy1b() {
// can access Mexico (explicitly granted) which is the first accessible
// one
getRestrictedTestContext().assertAxisReturns(
"[Store].defaultMember",
"[Store].[Mexico]");
}
public void testGrantHierarchy1c() {
// the root element is All Customers
getRestrictedTestContext().assertAxisReturns(
"[Customers].defaultMember",
"[Customers].[Canada].[BC]");
}
public void testGrantHierarchy2() {
// assert: can access California (parent of allowed member)
final TestContext testContext = getRestrictedTestContext();
testContext.assertAxisReturns(
"[Store].[USA].children",
"[Store].[USA].[CA]");
testContext.assertAxisReturns(
"[Store].[USA].children",
"[Store].[USA].[CA]");
testContext.assertAxisReturns(
"[Store].[USA].[CA].children",
"[Store].[USA].[CA].[Los Angeles]\n"
+ "[Store].[USA].[CA].[San Francisco]");
}
public void testGrantHierarchy3() {
// assert: can not access Washington (child of denied member)
final TestContext testContext = getRestrictedTestContext();
testContext.assertAxisThrows("[Store].[USA].[WA]", "not found");
}
private TestContext getRestrictedTestContext() {
return new DelegatingTestContext(getTestContext()) {
public Connection getConnection() {
return getRestrictedConnection();
}
};
}
public void testGrantHierarchy4() {
// assert: can not access Oregon (rule 1 - order matters)
final TestContext testContext = getRestrictedTestContext();
testContext.assertAxisThrows(
"[Store].[USA].[OR].children", "not found");
}
public void testGrantHierarchy5() {
// assert: can not access All (above top level)
final TestContext testContext = getRestrictedTestContext();
testContext.assertAxisThrows("[Store].[All Stores]", "not found");
testContext.assertAxisReturns(
"[Store].members",
// note:
// no: [All Stores] -- above top level
// no: [Canada] -- not explicitly allowed
// yes: [Mexico] -- explicitly allowed -- and all its children
// except [DF]
// no: [Mexico].[DF]
// yes: [USA] -- implicitly allowed
// yes: [CA] -- implicitly allowed
// no: [OR], [WA]
// yes: [San Francisco] -- explicitly allowed
// no: [San Diego]
"[Store].[Mexico]\n"
+ "[Store].[Mexico].[Guerrero]\n"
+ "[Store].[Mexico].[Guerrero].[Acapulco]\n"
+ "[Store].[Mexico].[Guerrero].[Acapulco].[Store 1]\n"
+ "[Store].[Mexico].[Jalisco]\n"
+ "[Store].[Mexico].[Jalisco].[Guadalajara]\n"
+ "[Store].[Mexico].[Jalisco].[Guadalajara].[Store 5]\n"
+ "[Store].[Mexico].[Veracruz]\n"
+ "[Store].[Mexico].[Veracruz].[Orizaba]\n"
+ "[Store].[Mexico].[Veracruz].[Orizaba].[Store 10]\n"
+ "[Store].[Mexico].[Yucatan]\n"
+ "[Store].[Mexico].[Yucatan].[Merida]\n"
+ "[Store].[Mexico].[Yucatan].[Merida].[Store 8]\n"
+ "[Store].[Mexico].[Zacatecas]\n"
+ "[Store].[Mexico].[Zacatecas].[Camacho]\n"
+ "[Store].[Mexico].[Zacatecas].[Camacho].[Store 4]\n"
+ "[Store].[Mexico].[Zacatecas].[Hidalgo]\n"
+ "[Store].[Mexico].[Zacatecas].[Hidalgo].[Store 12]\n"
+ "[Store].[Mexico].[Zacatecas].[Hidalgo].[Store 18]\n"
+ "[Store].[USA]\n"
+ "[Store].[USA].[CA]\n"
+ "[Store].[USA].[CA].[Los Angeles]\n"
+ "[Store].[USA].[CA].[Los Angeles].[Store 7]\n"
+ "[Store].[USA].[CA].[San Francisco]\n"
+ "[Store].[USA].[CA].[San Francisco].[Store 14]");
}
public void testGrantHierarchy6() {
// assert: parent if at top level is null
getRestrictedTestContext().assertAxisReturns(
"[Customers].[USA].[CA].parent",
"");
}
public void testGrantHierarchy7() {
// assert: members above top level do not exist
final TestContext testContext = getRestrictedTestContext();
testContext.assertAxisThrows(
"[Customers].[Canada].children",
"MDX object '[Customers].[Canada]' not found in cube 'Sales'");
}
public void testGrantHierarchy8() {
// assert: can not access Catherine Abel in San Francisco (below bottom
// level)
final TestContext testContext = getRestrictedTestContext();
testContext.assertAxisThrows(
"[Customers].[USA].[CA].[San Francisco].[Catherine Abel]",
"not found");
testContext.assertAxisReturns(
"[Customers].[USA].[CA].[San Francisco].children",
"");
Axis axis = testContext.executeAxis("[Customers].members");
// 13 states, 109 cities
Assert.assertEquals(122, axis.getPositions().size());
}
public void testGrantHierarchy8AllMembers() {
// assert: can not access Catherine Abel in San Francisco (below bottom
// level)
final TestContext testContext = getRestrictedTestContext();
testContext.assertAxisThrows(
"[Customers].[USA].[CA].[San Francisco].[Catherine Abel]",
"not found");
testContext.assertAxisReturns(
"[Customers].[USA].[CA].[San Francisco].children",
"");
Axis axis = testContext.executeAxis("[Customers].allmembers");
// 13 states, 109 cities
Assert.assertEquals(122, axis.getPositions().size());
}
/**
* Tests for Mondrian BUG 1201 - Native Rollups did not handle
* access-control with more than one member where granted access=all
*/
public void testBugMondrian_1201_MultipleMembersInRoleAccessControl() {
String test_1201_Roles =
"<Role name=\"Role1\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Store]\" access=\"custom\" rollupPolicy=\"partial\">\n"
+ " <MemberGrant member=\"[Store].[USA].[WA]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[USA].[OR]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[USA].[CA].[San Francisco]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[USA].[CA].[Los Angeles]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[Mexico]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[Mexico].[DF]\" access=\"none\"/>\n"
+ " <MemberGrant member=\"[Store].[Canada]\" access=\"none\"/>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>\n"
+ "<Role name=\"Role2\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Store]\" access=\"custom\" rollupPolicy=\"full\">\n"
+ " <MemberGrant member=\"[Store].[USA].[WA]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[USA].[OR]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[USA].[CA].[San Francisco]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[USA].[CA].[Los Angeles]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[Mexico]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[Mexico].[DF]\" access=\"none\"/>\n"
+ " <MemberGrant member=\"[Store].[Canada]\" access=\"none\"/>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>";
final TestContext partialRollupTestContext =
TestContext.instance().create(
null, null, null, null, null, test_1201_Roles)
.withRole("Role1");
final TestContext fullRollupTestContext =
TestContext.instance().create(
null, null, null, null, null, test_1201_Roles)
.withRole("Role2");
// Must return only 2 [USA].[CA] stores
partialRollupTestContext.assertQueryReturns(
"select NON EMPTY {[Measures].[Unit Sales]} ON COLUMNS, \n"
+ " Filter( [Store].[USA].[CA].children,"
+ " [Measures].[Unit Sales]>0) ON ROWS \n"
+ "from [Sales] \n"
+ "where ([Time].[1997].[Q1].[2])",
"Axis #0:\n"
+ "{[Time].[1997].[Q1].[2]}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Store].[USA].[CA].[Los Angeles]}\n"
+ "{[Store].[USA].[CA].[San Francisco]}\n"
+ "Row #0: 2,614\n"
+ "Row #1: 187\n");
// Must return only 2 [USA].[CA] stores
partialRollupTestContext.assertQueryReturns(
"select NON EMPTY {[Measures].[Unit Sales]} ON COLUMNS, \n"
+ " TopCount( [Store].[USA].[CA].children, 20,"
+ " [Measures].[Unit Sales]) ON ROWS \n"
+ "from [Sales] \n"
+ "where ([Time].[1997].[Q1].[2])",
"Axis #0:\n"
+ "{[Time].[1997].[Q1].[2]}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Store].[USA].[CA].[Los Angeles]}\n"
+ "{[Store].[USA].[CA].[San Francisco]}\n"
+ "Row #0: 2,614\n"
+ "Row #1: 187\n");
// Partial Rollup: [USA].[CA] rolls up only up to 2.801
partialRollupTestContext.assertQueryReturns(
"select NON EMPTY {[Measures].[Unit Sales]} ON COLUMNS, \n"
+ " Filter( [Store].[Store State].Members,"
+ " [Measures].[Unit Sales]>4000) ON ROWS \n"
+ "from [Sales] \n"
+ "where ([Time].[1997].[Q1].[2])",
"Axis #0:\n"
+ "{[Time].[1997].[Q1].[2]}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Store].[USA].[OR]}\n"
+ "{[Store].[USA].[WA]}\n"
+ "Row #0: 4,617\n"
+ "Row #1: 10,319\n");
// Full Rollup: [USA].[CA] rolls up to 6.021
fullRollupTestContext.assertQueryReturns(
"select NON EMPTY {[Measures].[Unit Sales]} ON COLUMNS, \n"
+ " Filter( [Store].[Store State].Members,"
+ " [Measures].[Unit Sales]>4000) ON ROWS \n"
+ "from [Sales] \n"
+ "where ([Time].[1997].[Q1].[2])",
"Axis #0:\n"
+ "{[Time].[1997].[Q1].[2]}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Store].[USA].[CA]}\n"
+ "{[Store].[USA].[OR]}\n"
+ "{[Store].[USA].[WA]}\n"
+ "Row #0: 6,021\n"
+ "Row #1: 4,617\n"
+ "Row #2: 10,319\n");
}
public void testBugMondrian_1201_CacheAwareOfRoleAccessControl() {
String test_1201_Roles =
"<Role name=\"Role1\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Store]\" access=\"custom\" rollupPolicy=\"partial\">\n"
+ " <MemberGrant member=\"[Store].[USA].[WA]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[USA].[OR]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[USA].[CA].[San Francisco]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[USA].[CA].[Los Angeles]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[Mexico]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[Mexico].[DF]\" access=\"none\"/>\n"
+ " <MemberGrant member=\"[Store].[Canada]\" access=\"none\"/>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>\n"
+ "<Role name=\"Role2\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Store]\" access=\"custom\" rollupPolicy=\"partial\">\n"
+ " <MemberGrant member=\"[Store].[USA].[WA]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[USA].[OR]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[USA].[CA].[San Francisco]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[Mexico]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[Mexico].[DF]\" access=\"none\"/>\n"
+ " <MemberGrant member=\"[Store].[Canada]\" access=\"none\"/>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>";
final TestContext partialRollupTestContext1 =
TestContext.instance().create(
null, null, null, null, null, test_1201_Roles)
.withRole("Role1");
final TestContext partialRollupTestContext2 =
TestContext.instance().create(
null, null, null, null, null, test_1201_Roles)
.withRole("Role2");
// Put query into cache
partialRollupTestContext1.assertQueryReturns(
"select NON EMPTY {[Measures].[Unit Sales]} ON COLUMNS, \n"
+ " Filter( [Store].[USA].[CA].children,"
+ " [Measures].[Unit Sales]>0) ON ROWS \n"
+ "from [Sales] \n"
+ "where ([Time].[1997].[Q1].[2])",
"Axis #0:\n"
+ "{[Time].[1997].[Q1].[2]}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Store].[USA].[CA].[Los Angeles]}\n"
+ "{[Store].[USA].[CA].[San Francisco]}\n"
+ "Row #0: 2,614\n"
+ "Row #1: 187\n");
// Run same query using another role with different access controls
partialRollupTestContext2.assertQueryReturns(
"select NON EMPTY {[Measures].[Unit Sales]} ON COLUMNS, \n"
+ " TopCount( [Store].[USA].[CA].children, 20,"
+ " [Measures].[Unit Sales]) ON ROWS \n"
+ "from [Sales] \n"
+ "where ([Time].[1997].[Q1].[2])",
"Axis #0:\n"
+ "{[Time].[1997].[Q1].[2]}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Store].[USA].[CA].[San Francisco]}\n"
+ "Row #0: 187\n");
}
/**
* Tests for Mondrian BUG 1127 - Native Top Count was not taking into
* account user roles
*/
public void testBugMondrian1127OneSlicerOnly() {
final TestContext testContext = getRestrictedTestContext();
testContext.assertQueryReturns(
"select NON EMPTY {[Measures].[Unit Sales]} ON COLUMNS, \n"
+ " TopCount([Store].[USA].[CA].Children, 10,"
+ " [Measures].[Unit Sales]) ON ROWS \n"
+ "from [Sales] \n"
+ "where ([Time].[1997].[Q1].[2])",
"Axis #0:\n"
+ "{[Time].[1997].[Q1].[2]}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Store].[USA].[CA].[Los Angeles]}\n"
+ "{[Store].[USA].[CA].[San Francisco]}\n"
+ "Row #0: 2,614\n"
+ "Row #1: 187\n");
final TestContext unrestrictedTestContext = getTestContext();
unrestrictedTestContext.assertQueryReturns(
"select NON EMPTY {[Measures].[Unit Sales]} ON COLUMNS, \n"
+ " TopCount([Store].[USA].[CA].Children, 10, "
+ " [Measures].[Unit Sales]) ON ROWS \n"
+ "from [Sales] \n"
+ "where ([Time].[1997].[Q1].[2])",
"Axis #0:\n"
+ "{[Time].[1997].[Q1].[2]}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Store].[USA].[CA].[Los Angeles]}\n"
+ "{[Store].[USA].[CA].[San Diego]}\n"
+ "{[Store].[USA].[CA].[Beverly Hills]}\n"
+ "{[Store].[USA].[CA].[San Francisco]}\n"
+ "Row #0: 2,614\n"
+ "Row #1: 1,879\n"
+ "Row #2: 1,341\n"
+ "Row #3: 187\n");
}
public void testBugMondrian1127MultipleSlicers() {
final TestContext testContext = getRestrictedTestContext();
testContext.assertQueryReturns(
"select NON EMPTY {[Measures].[Unit Sales]} ON COLUMNS, \n"
+ " TopCount([Store].[USA].[CA].Children, 10,"
+ " [Measures].[Unit Sales]) ON ROWS \n"
+ "from [Sales] \n"
+ "where ([Time].[1997].[Q1].[2] : [Time].[1997].[Q1].[3])",
"Axis #0:\n"
+ "{[Time].[1997].[Q1].[2]}\n"
+ "{[Time].[1997].[Q1].[3]}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Store].[USA].[CA].[Los Angeles]}\n"
+ "{[Store].[USA].[CA].[San Francisco]}\n"
+ "Row #0: 4,497\n"
+ "Row #1: 337\n");
final TestContext unrestrictedTestContext = getTestContext();
unrestrictedTestContext.assertQueryReturns(
"select NON EMPTY {[Measures].[Unit Sales]} ON COLUMNS, \n"
+ " TopCount([Store].[USA].[CA].Children, 10, "
+ " [Measures].[Unit Sales]) ON ROWS \n"
+ "from [Sales] \n"
+ "where ([Time].[1997].[Q1].[2] : [Time].[1997].[Q1].[3])",
"Axis #0:\n"
+ "{[Time].[1997].[Q1].[2]}\n"
+ "{[Time].[1997].[Q1].[3]}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Store].[USA].[CA].[Los Angeles]}\n"
+ "{[Store].[USA].[CA].[San Diego]}\n"
+ "{[Store].[USA].[CA].[Beverly Hills]}\n"
+ "{[Store].[USA].[CA].[San Francisco]}\n"
+ "Row #0: 4,497\n"
+ "Row #1: 4,094\n"
+ "Row #2: 2,585\n"
+ "Row #3: 337\n");
}
/**
* Tests that we only aggregate over SF, LA, even when called from
* functions.
*/
public void testGrantHierarchy9() {
// Analysis services doesn't allow aggregation within calculated
// measures, so use the following query to generate the results:
//
// with member [Store].[SF LA] as
// 'Aggregate({[USA].[CA].[San Francisco], [Store].[USA].[CA].[Los
// Angeles]})'
// select {[Measures].[Unit Sales]} on columns,
// {[Gender].children} on rows
// from Sales
// where ([Marital Status].[S], [Store].[SF LA])
final TestContext tc = new RestrictedTestContext();
tc.assertQueryReturns(
"with member [Measures].[California Unit Sales] as "
+ " 'Aggregate({[Store].[USA].[CA].children}, [Measures].[Unit Sales])'\n"
+ "select {[Measures].[California Unit Sales]} on columns,\n"
+ " {[Gender].children} on rows\n"
+ "from Sales\n"
+ "where ([Marital Status].[S])",
"Axis #0:\n"
+ "{[Marital Status].[S]}\n"
+ "Axis #1:\n"
+ "{[Measures].[California Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Gender].[F]}\n"
+ "{[Gender].[M]}\n"
+ "Row #0: 6,636\n"
+ "Row #1: 7,329\n");
}
public void testGrantHierarchyA() {
final TestContext tc = new RestrictedTestContext();
// assert: totals for USA include missing cells
tc.assertQueryReturns(
"select {[Unit Sales]} on columns,\n"
+ "{[Store].[USA], [Store].[USA].children} on rows\n"
+ "from [Sales]",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Store].[USA]}\n"
+ "{[Store].[USA].[CA]}\n"
+ "Row #0: 266,773\n"
+ "Row #1: 74,748\n");
}
public void _testSharedObjectsInGrantMappingsBug() {
final TestContext testContext = new TestContext() {
public Connection getConnection() {
boolean mustGet = true;
Connection connection = super.getConnection();
Schema schema = connection.getSchema();
Cube salesCube = schema.lookupCube("Sales", mustGet);
Cube warehouseCube = schema.lookupCube("Warehouse", mustGet);
Hierarchy measuresInSales = salesCube.lookupHierarchy(
new Id.NameSegment("Measures", Id.Quoting.UNQUOTED), false);
Hierarchy storeInWarehouse = warehouseCube.lookupHierarchy(
new Id.NameSegment("Store", Id.Quoting.UNQUOTED), false);
RoleImpl role = new RoleImpl();
role.grant(schema, Access.NONE);
role.grant(salesCube, Access.NONE);
// For using hierarchy Measures in #assertExprThrows
Role.RollupPolicy rollupPolicy = Role.RollupPolicy.FULL;
role.grant(
measuresInSales, Access.ALL, null, null, rollupPolicy);
role.grant(warehouseCube, Access.NONE);
role.grant(storeInWarehouse.getDimension(), Access.ALL);
role.makeImmutable();
connection.setRole(role);
return connection;
}
};
// Looking up default member on dimension Store in cube Sales should
// fail.
testContext.assertExprThrows(
"[Store].DefaultMember",
"'[Store]' not found in cube 'Sales'");
}
public void testNoAccessToCube() {
final TestContext tc = new RestrictedTestContext();
tc.assertQueryThrows("select from [HR]", "MDX cube 'HR' not found");
}
private Connection getRestrictedConnection() {
return getRestrictedConnection(true);
}
/**
* Returns a connection with limited access to the schema.
*
* @param restrictCustomers true to restrict access to the customers
* dimension. This will change the defaultMember of the dimension,
* all cell values will be null because there are no sales data
* for Canada
*
* @return restricted connection
*/
private Connection getRestrictedConnection(boolean restrictCustomers) {
Connection connection =
getTestContext().withSchemaPool(false).getConnection();
RoleImpl role = new RoleImpl();
Schema schema = connection.getSchema();
final boolean fail = true;
Cube salesCube = schema.lookupCube("Sales", fail);
final SchemaReader schemaReader =
salesCube.getSchemaReader(null).withLocus();
Hierarchy storeHierarchy = salesCube.lookupHierarchy(
new Id.NameSegment("Store", Id.Quoting.UNQUOTED), false);
role.grant(schema, Access.ALL_DIMENSIONS);
role.grant(salesCube, Access.ALL);
Level nationLevel =
Util.lookupHierarchyLevel(storeHierarchy, "Store Country");
Role.RollupPolicy rollupPolicy = Role.RollupPolicy.FULL;
role.grant(
storeHierarchy, Access.CUSTOM, nationLevel, null, rollupPolicy);
role.grant(
schemaReader.getMemberByUniqueName(
Util.parseIdentifier("[Store].[All Stores].[USA].[OR]"), fail),
Access.ALL);
role.grant(
schemaReader.getMemberByUniqueName(
Util.parseIdentifier("[Store].[All Stores].[USA]"), fail),
Access.CUSTOM);
role.grant(
schemaReader.getMemberByUniqueName(
Util.parseIdentifier(
"[Store].[All Stores].[USA].[CA].[San Francisco]"), fail),
Access.ALL);
role.grant(
schemaReader.getMemberByUniqueName(
Util.parseIdentifier(
"[Store].[All Stores].[USA].[CA].[Los Angeles]"), fail),
Access.ALL);
role.grant(
schemaReader.getMemberByUniqueName(
Util.parseIdentifier(
"[Store].[All Stores].[Mexico]"), fail),
Access.ALL);
role.grant(
schemaReader.getMemberByUniqueName(
Util.parseIdentifier(
"[Store].[All Stores].[Mexico].[DF]"), fail),
Access.NONE);
role.grant(
schemaReader.getMemberByUniqueName(
Util.parseIdentifier(
"[Store].[All Stores].[Canada]"), fail),
Access.NONE);
if (restrictCustomers) {
Hierarchy customersHierarchy =
salesCube.lookupHierarchy(
new Id.NameSegment("Customers", Id.Quoting.UNQUOTED),
false);
Level stateProvinceLevel =
Util.lookupHierarchyLevel(customersHierarchy, "State Province");
Level customersCityLevel =
Util.lookupHierarchyLevel(customersHierarchy, "City");
role.grant(
customersHierarchy,
Access.CUSTOM,
stateProvinceLevel,
customersCityLevel,
rollupPolicy);
}
// No access to HR cube.
Cube hrCube = schema.lookupCube("HR", fail);
role.grant(hrCube, Access.NONE);
role.makeImmutable();
connection.setRole(role);
return connection;
}
// todo: test that access to restricted measure fails
// (will not work -- have not fixed Cube.getMeasures)
private class RestrictedTestContext extends TestContext {
public synchronized Connection getConnection() {
return getRestrictedConnection(false);
}
}
/**
* Test context where the [Store] hierarchy has restricted access
* and cell values are rolled up with 'partial' policy.
*/
private TestContext getRollupTestContext() {
return getTestContext().create(
null, null, null, null, null,
"<Role name=\"Role1\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"custom\">\n"
+ " <DimensionGrant dimension=\"[Measures]\" access=\"all\"/>\n"
+ " <DimensionGrant dimension=\"[Gender]\" access=\"all\"/>\n"
+ " <HierarchyGrant hierarchy=\"[Store]\" access=\"custom\" rollupPolicy=\"partial\">\n"
+ " <MemberGrant member=\"[Store].[USA]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[USA].[CA]\" access=\"none\"/>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>")
.withRole("Role1");
}
/**
* Basic test of partial rollup policy. [USA] = [OR] + [WA], not
* the usual [CA] + [OR] + [WA].
*/
public void testRollupPolicyBasic() {
getRollupTestContext().assertQueryReturns(
"select {[Store].[USA], [Store].[USA].Children} on 0\n"
+ "from [Sales]",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Store].[USA]}\n"
+ "{[Store].[USA].[OR]}\n"
+ "{[Store].[USA].[WA]}\n"
+ "Row #0: 192,025\n"
+ "Row #0: 67,659\n"
+ "Row #0: 124,366\n");
}
/**
* The total for [Store].[All Stores] is similarly reduced. All
* children of [All Stores] are visible, but one grandchild is not.
* Normally the total is 266,773.
*/
public void testRollupPolicyAll() {
getRollupTestContext().assertExprReturns(
"([Store].[All Stores])",
"192,025");
}
/**
* Access [Store].[All Stores] implicitly as it is the default member
* of the [Stores] hierarchy.
*/
public void testRollupPolicyAllAsDefault() {
getRollupTestContext().assertExprReturns(
"([Store])",
"192,025");
}
/**
* Access [Store].[All Stores] via the Parent relationship (to check
* that this doesn't circumvent access control).
*/
public void testRollupPolicyAllAsParent() {
getRollupTestContext().assertExprReturns(
"([Store].[USA].Parent)",
"192,025");
}
/**
* Tests that an access-controlled dimension affects results even if not
* used in the query. Unit test for
* <a href="http://jira.pentaho.com/browse/mondrian-1283">MONDRIAN-1283,
* "Mondrian doesn't restrict dimension members when dimension isn't
* included"</a>.
*/
public void testUnusedAccessControlledDimension() {
getRollupTestContext().assertQueryReturns(
"select [Gender].Children on 0 from [Sales]",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Gender].[F]}\n"
+ "{[Gender].[M]}\n"
+ "Row #0: 94,799\n"
+ "Row #0: 97,226\n");
getTestContext().assertQueryReturns(
"select [Gender].Children on 0 from [Sales]",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Gender].[F]}\n"
+ "{[Gender].[M]}\n"
+ "Row #0: 131,558\n"
+ "Row #0: 135,215\n");
}
/**
* Tests that members below bottom level are regarded as visible.
*/
public void testRollupBottomLevel() {
rollupPolicyBottom(
Role.RollupPolicy.FULL, "74,748", "36,759", "266,773");
rollupPolicyBottom(
Role.RollupPolicy.PARTIAL, "72,739", "35,775", "264,764");
rollupPolicyBottom(Role.RollupPolicy.HIDDEN, "", "", "");
}
private void rollupPolicyBottom(
Role.RollupPolicy rollupPolicy,
String v1,
String v2,
String v3)
{
final TestContext testContext =
TestContext.instance().create(
null, null, null, null, null,
"<Role name=\"Role1\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Customers]\" access=\"custom\" rollupPolicy=\""
+ rollupPolicy
+ "\" bottomLevel=\"[Customers].[City]\">\n"
+ " <MemberGrant member=\"[Customers].[USA]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Customers].[USA].[CA]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Customers].[USA].[CA].[Los Angeles]\" access=\"none\"/>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>")
.withRole("Role1");
// All of the children of [San Francisco] are invisible, because [City]
// is the bottom level, but that shouldn't affect the total.
testContext.assertExprReturns(
"([Customers].[USA].[CA].[San Francisco])", "88");
testContext.assertExprThrows(
"([Customers].[USA].[CA].[Los Angeles])",
"MDX object '[Customers].[USA].[CA].[Los Angeles]' not found in cube 'Sales'");
testContext.assertExprReturns("([Customers].[USA].[CA])", v1);
testContext.assertExprReturns(
"([Customers].[USA].[CA], [Gender].[F])", v2);
testContext.assertExprReturns("([Customers].[USA])", v3);
checkQuery(
testContext,
"select [Customers].Children on 0, "
+ "[Gender].Members on 1 from [Sales]");
}
/**
* Calls various {@link SchemaReader} methods on the members returned in
* a result set.
*
* @param testContext Test context
* @param mdx MDX query
*/
private void checkQuery(TestContext testContext, String mdx) {
Result result = testContext.executeQuery(mdx);
final SchemaReader schemaReader =
testContext.getConnection().getSchemaReader().withLocus();
for (Axis axis : result.getAxes()) {
for (Position position : axis.getPositions()) {
for (Member member : position) {
final Member accessControlledParent =
schemaReader.getMemberParent(member);
if (member.getParentMember() == null) {
assertNull(accessControlledParent);
}
final List<Member> accessControlledChildren =
schemaReader.getMemberChildren(member);
assertNotNull(accessControlledChildren);
}
}
}
}
/**
* Tests that a bad value for the rollupPolicy attribute gives the
* appropriate error.
*/
public void testRollupPolicyNegative() {
final TestContext testContext =
TestContext.instance().create(
null, null, null, null, null,
"<Role name=\"Role1\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Customers]\" access=\"custom\" rollupPolicy=\"bad\" bottomLevel=\"[Customers].[City]\">\n"
+ " <MemberGrant member=\"[Customers].[USA]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Customers].[USA].[CA].[Los Angeles]\" access=\"none\"/>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>")
.withRole("Role1");
testContext.assertQueryThrows(
"select from [Sales]",
"Illegal rollupPolicy value 'bad'");
}
/**
* Tests where all children are visible but a grandchild is not.
*/
public void testRollupPolicyGreatGrandchildInvisible() {
rollupPolicyGreatGrandchildInvisible(
Role.RollupPolicy.FULL, "266,773", "74,748");
rollupPolicyGreatGrandchildInvisible(
Role.RollupPolicy.PARTIAL, "266,767", "74,742");
rollupPolicyGreatGrandchildInvisible(
Role.RollupPolicy.HIDDEN, "", "");
}
private void rollupPolicyGreatGrandchildInvisible(
Role.RollupPolicy policy,
String v1,
String v2)
{
final TestContext testContext =
TestContext.instance().create(
null, null, null, null, null,
"<Role name=\"Role1\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Customers]\" access=\"custom\" rollupPolicy=\""
+ policy
+ "\">\n"
+ " <MemberGrant member=\"[Customers].[USA]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Customers].[USA].[CA].[San Francisco].[Gladys Evans]\" access=\"none\"/>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>")
.withRole("Role1");
testContext.assertExprReturns("[Measures].[Unit Sales]", v1);
testContext.assertExprReturns(
"([Measures].[Unit Sales], [Customers].[USA])",
v1);
testContext.assertExprReturns(
"([Measures].[Unit Sales], [Customers].[USA].[CA])",
v2);
}
/**
* Tests where two hierarchies are simultaneously access-controlled.
*/
public void testRollupPolicySimultaneous() {
// note that v2 is different for full vs partial, v3 is the same
rollupPolicySimultaneous(
Role.RollupPolicy.FULL, "266,773", "74,748", "25,635");
rollupPolicySimultaneous(
Role.RollupPolicy.PARTIAL, "72,631", "72,631", "25,635");
rollupPolicySimultaneous(
Role.RollupPolicy.HIDDEN, "", "", "");
}
private void rollupPolicySimultaneous(
Role.RollupPolicy policy,
String v1,
String v2,
String v3)
{
final TestContext testContext =
TestContext.instance().create(
null, null, null, null, null,
"<Role name=\"Role1\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Customers]\" access=\"custom\" rollupPolicy=\""
+ policy
+ "\">\n"
+ " <MemberGrant member=\"[Customers].[USA]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Customers].[USA].[CA].[San Francisco].[Gladys Evans]\" access=\"none\"/>\n"
+ " </HierarchyGrant>\n"
+ " <HierarchyGrant hierarchy=\"[Store]\" access=\"custom\" rollupPolicy=\""
+ policy
+ "\">\n"
+ " <MemberGrant member=\"[Store].[USA].[CA]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[USA].[CA].[San Francisco].[Store 14]\" access=\"none\"/>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>")
.withRole("Role1");
testContext.assertExprReturns("[Measures].[Unit Sales]", v1);
testContext.assertExprReturns(
"([Measures].[Unit Sales], [Customers].[USA])",
v1);
testContext.assertExprReturns(
"([Measures].[Unit Sales], [Customers].[USA].[CA])",
v2);
testContext.assertExprReturns(
"([Measures].[Unit Sales], "
+ "[Customers].[USA].[CA], [Store].[USA].[CA])",
v2);
testContext.assertExprReturns(
"([Measures].[Unit Sales], "
+ "[Customers].[USA].[CA], "
+ "[Store].[USA].[CA].[San Diego])",
v3);
}
// todo: performance test where 1 of 1000 children is not visible
public void testUnionRole() {
final TestContext testContext =
TestContext.instance().create(
null, null, null, null, null,
"<Role name=\"Role1\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Customers]\" access=\"custom\" rollupPolicy=\"Partial\">\n"
+ " <MemberGrant member=\"[Customers].[USA].[CA]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Customers].[USA].[CA].[San Francisco].[Gladys Evans]\" access=\"none\"/>\n"
+ " </HierarchyGrant>\n"
+ " <HierarchyGrant hierarchy=\"[Promotion Media]\" access=\"all\"/>\n"
+ " <HierarchyGrant hierarchy=\"[Marital Status]\" access=\"none\"/>\n"
+ " <HierarchyGrant hierarchy=\"[Gender]\" access=\"none\"/>\n"
+ " <HierarchyGrant hierarchy=\"[Store]\" access=\"custom\" rollupPolicy=\"Partial\" topLevel=\"[Store].[Store State]\"/>\n"
+ " </CubeGrant>\n"
+ " <CubeGrant cube=\"Warehouse\" access=\"all\"/>\n"
+ " </SchemaGrant>\n"
+ "</Role>\n"
+ "<Role name=\"Role2\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"none\">\n"
+ " <HierarchyGrant hierarchy=\"[Customers]\" access=\"custom\" rollupPolicy=\"Hidden\">\n"
+ " <MemberGrant member=\"[Customers].[USA]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Customers].[USA].[CA]\" access=\"none\"/>\n"
+ " <MemberGrant member=\"[Customers].[USA].[OR]\" access=\"none\"/>\n"
+ " <MemberGrant member=\"[Customers].[USA].[OR].[Portland]\" access=\"all\"/>\n"
+ " </HierarchyGrant>\n"
+ " <HierarchyGrant hierarchy=\"[Store]\" access=\"all\" rollupPolicy=\"Hidden\"/>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>\n");
Connection connection;
try {
connection = testContext.withRole("Role3,Role2").getConnection();
fail("expected exception, got " + connection);
} catch (RuntimeException e) {
final String message = e.getMessage();
assertTrue(message, message.indexOf("Role 'Role3' not found") >= 0);
}
try {
connection = testContext.withRole("Role1,Role3").getConnection();
fail("expected exception, got " + connection);
} catch (RuntimeException e) {
final String message = e.getMessage();
assertTrue(message, message.indexOf("Role 'Role3' not found") >= 0);
}
connection = testContext.withRole("Role1,Role2").getConnection();
// Cube access:
// Both can see [Sales]
// Role1 only see [Warehouse]
// Neither can see [Warehouse and Sales]
assertCubeAccess(connection, Access.ALL, "Sales");
assertCubeAccess(connection, Access.ALL, "Warehouse");
assertCubeAccess(connection, Access.NONE, "Warehouse and Sales");
// Hierarchy access:
// Both can see [Customers] with Custom access
// Both can see [Store], Role1 with Custom access, Role2 with All access
// Role1 can see [Promotion Media], Role2 cannot
// Neither can see [Marital Status]
assertHierarchyAccess(
connection, Access.CUSTOM, "Sales", "[Customers]");
assertHierarchyAccess(
connection, Access.ALL, "Sales", "[Store]");
assertHierarchyAccess(
connection, Access.ALL, "Sales", "[Promotion Media]");
assertHierarchyAccess(
connection, Access.NONE, "Sales", "[Marital Status]");
// Rollup policy is the greater of Role1's partian and Role2's hidden
final Role.HierarchyAccess hierarchyAccess =
getHierarchyAccess(connection, "Sales", "[Store]");
assertEquals(
Role.RollupPolicy.PARTIAL,
hierarchyAccess.getRollupPolicy());
// One of the roles is restricting the levels, so we
// expect only the levels from 2 to 4 to be available.
assertEquals(2, hierarchyAccess.getTopLevelDepth());
assertEquals(4, hierarchyAccess.getBottomLevelDepth());
// Member access:
// both can see [USA]
assertMemberAccess(connection, Access.CUSTOM, "[Customers].[USA]");
// Role1 can see [CA], Role2 cannot
assertMemberAccess(connection, Access.CUSTOM, "[Customers].[USA].[CA]");
// Role1 cannoy see [USA].[OR].[Portland], Role2 can
assertMemberAccess(
connection, Access.ALL, "[Customers].[USA].[OR].[Portland]");
// Role1 cannot see [USA].[OR], Role2 can see it by virtue of [Portland]
assertMemberAccess(
connection, Access.CUSTOM, "[Customers].[USA].[OR]");
// Neither can see Beaverton
assertMemberAccess(
connection, Access.NONE, "[Customers].[USA].[OR].[Beaverton]");
// Rollup policy
String mdx = "select Hierarchize(\n"
+ "{[Customers].[USA].Children,\n"
+ " [Customers].[USA].[OR].Children}) on 0\n"
+ "from [Sales]";
testContext.assertQueryReturns(
mdx,
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Customers].[USA].[CA]}\n"
+ "{[Customers].[USA].[OR]}\n"
+ "{[Customers].[USA].[OR].[Albany]}\n"
+ "{[Customers].[USA].[OR].[Beaverton]}\n"
+ "{[Customers].[USA].[OR].[Corvallis]}\n"
+ "{[Customers].[USA].[OR].[Lake Oswego]}\n"
+ "{[Customers].[USA].[OR].[Lebanon]}\n"
+ "{[Customers].[USA].[OR].[Milwaukie]}\n"
+ "{[Customers].[USA].[OR].[Oregon City]}\n"
+ "{[Customers].[USA].[OR].[Portland]}\n"
+ "{[Customers].[USA].[OR].[Salem]}\n"
+ "{[Customers].[USA].[OR].[W. Linn]}\n"
+ "{[Customers].[USA].[OR].[Woodburn]}\n"
+ "{[Customers].[USA].[WA]}\n"
+ "Row #0: 74,748\n"
+ "Row #0: 67,659\n"
+ "Row #0: 6,806\n"
+ "Row #0: 4,558\n"
+ "Row #0: 9,539\n"
+ "Row #0: 4,910\n"
+ "Row #0: 9,596\n"
+ "Row #0: 5,145\n"
+ "Row #0: 3,708\n"
+ "Row #0: 3,583\n"
+ "Row #0: 7,678\n"
+ "Row #0: 4,175\n"
+ "Row #0: 7,961\n"
+ "Row #0: 124,366\n");
testContext.withRole("Role1").assertQueryThrows(
mdx,
"MDX object '[Customers].[USA].[OR]' not found in cube 'Sales'");
testContext.withRole("Role2").assertQueryThrows(
mdx,
"MDX cube 'Sales' not found");
// Compared to above:
// a. cities in Oregon are missing besides Portland
// b. total for Oregon = total for Portland
testContext.withRole("Role1,Role2").assertQueryReturns(
mdx,
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Customers].[USA].[CA]}\n"
+ "{[Customers].[USA].[OR]}\n"
+ "{[Customers].[USA].[OR].[Portland]}\n"
+ "{[Customers].[USA].[WA]}\n"
+ "Row #0: 74,742\n"
+ "Row #0: 3,583\n"
+ "Row #0: 3,583\n"
+ "Row #0: 124,366\n");
checkQuery(testContext.withRole("Role1,Role2"), mdx);
}
/**
* This is a test for
* <a href="http://jira.pentaho.com/browse/MONDRIAN-1384">MONDRIAN-1384</a>
*/
public void testUnionRoleHasInaccessibleDescendants() throws Exception {
final TestContext testContext =
TestContext.instance().create(
null, null, null, null, null,
"<Role name=\"Role1\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " </SchemaGrant>\n"
+ "</Role>\n"
+ "<Role name=\"Role2\">\n"
+ " <SchemaGrant access=\"all\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Customers]\" access=\"custom\" rollupPolicy=\"partial\">\n"
+ " <MemberGrant member=\"[Customers].[USA].[OR]\" access=\"all\"/>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>\n");
final Connection connection =
testContext.withRole("Role1,Role2").getConnection();
final Cube cube =
connection.getSchema()
.lookupCube("Sales", true);
final HierarchyAccess accessDetails =
connection.getRole().getAccessDetails(
cube.lookupHierarchy(
new Id.NameSegment("Customers", Id.Quoting.UNQUOTED),
false));
final SchemaReader scr =
cube.getSchemaReader(null).withLocus();
assertEquals(
true,
accessDetails.hasInaccessibleDescendants(
scr.getMemberByUniqueName(
Util.parseIdentifier("[Customers].[USA]"),
true)));
}
/**
* This is a test for
* <a href="http://jira.pentaho.com/browse/MONDRIAN-1168">MONDRIAN-1168</a>
* Union of roles would sometimes return levels which should be restricted
* by ACL.
*/
public void testRoleUnionWithLevelRestrictions() throws Exception {
final TestContext testContext =
TestContext.instance().create(
null, null, null, null, null,
"<Role name=\"Role1\">\n"
+ " <SchemaGrant access=\"all\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Customers]\" access=\"custom\" rollupPolicy=\"Partial\" topLevel=\"[Customers].[State Province]\" bottomLevel=\"[Customers].[State Province]\">\n"
+ " <MemberGrant member=\"[Customers].[USA].[CA]\" access=\"all\"/>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>\n"
+ "<Role name=\"Role2\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " </SchemaGrant>\n"
+ "</Role>\n").withRole("Role1,Role2");
testContext.assertQueryReturns(
"select {[Customers].[State Province].Members} on columns from [Sales]",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Customers].[USA].[CA]}\n"
+ "Row #0: 74,748\n");
testContext.assertQueryReturns(
"select {[Customers].[Country].Members} on columns from [Sales]",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n");
SchemaReader reader =
testContext.getConnection().getSchemaReader().withLocus();
Cube cube = null;
for (Cube c : reader.getCubes()) {
if (c.getName().equals("Sales")) {
cube = c;
}
}
assertNotNull(cube);
reader =
cube.getSchemaReader(testContext.getConnection().getRole());
final List<Dimension> dimensions =
reader.getCubeDimensions(cube);
Dimension dimension = null;
for (Dimension dim : dimensions) {
if (dim.getName().equals("Customers")) {
dimension = dim;
}
}
assertNotNull(dimension);
Hierarchy hierarchy =
reader.getDimensionHierarchies(dimension).get(0);
assertNotNull(hierarchy);
final List<Level> levels =
reader.getHierarchyLevels(hierarchy);
// Do some tests
assertEquals(1, levels.size());
assertEquals(
2,
testContext.getConnection()
.getRole().getAccessDetails(hierarchy)
.getBottomLevelDepth());
assertEquals(
2,
testContext.getConnection()
.getRole().getAccessDetails(hierarchy)
.getTopLevelDepth());
}
/**
* Test to verify that non empty crossjoins enforce role access.
* Testcase for bug <a href="http://jira.pentaho.com/browse/MONDRIAN-369">
* MONDRIAN-369, "Non Empty Crossjoin fails to enforce role access".
*/
public void testNonEmptyAccess() {
final TestContext testContext =
TestContext.instance().create(
null, null, null, null, null,
"<Role name=\"Role1\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Product]\" access=\"custom\">\n"
+ " <MemberGrant member=\"[Product].[Drink]\" access=\"all\"/>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>")
.withRole("Role1");
// regular crossjoin returns the correct list of product children
final String expected =
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Gender].[All Gender], [Product].[Drink]}\n"
+ "Row #0: 24,597\n";
final String mdx =
"select {[Measures].[Unit Sales]} ON COLUMNS, "
+ " Crossjoin({[Gender].[All Gender]}, "
+ "[Product].Children) ON ROWS "
+ "from [Sales]";
testContext.assertQueryReturns(mdx, expected);
checkQuery(testContext, mdx);
// with bug MONDRIAN-397, non empty crossjoin did not return the correct
// list
final String mdx2 =
"select {[Measures].[Unit Sales]} ON COLUMNS, "
+ "NON EMPTY Crossjoin({[Gender].[All Gender]}, "
+ "[Product].[All Products].Children) ON ROWS "
+ "from [Sales]";
testContext.assertQueryReturns(mdx2, expected);
checkQuery(testContext, mdx2);
}
public void testNonEmptyAccessLevelMembers() {
final TestContext testContext = TestContext.instance().create(
null,
null,
null,
null,
null,
"<Role name=\"Role1\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Product]\" access=\"custom\">\n"
+ " <MemberGrant member=\"[Product].[Drink]\" access=\"all\"/>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>").withRole("Role1");
// <Level>.members inside regular crossjoin returns the correct list of
// product members
final String expected =
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Gender].[All Gender], [Product].[Drink]}\n"
+ "Row #0: 24,597\n";
final String mdx =
"select {[Measures].[Unit Sales]} ON COLUMNS, "
+ " Crossjoin({[Gender].[All Gender]}, "
+ "[Product].[Product Family].Members) ON ROWS "
+ "from [Sales]";
testContext.assertQueryReturns(mdx, expected);
checkQuery(testContext, mdx);
// with bug MONDRIAN-397, <Level>.members inside non empty crossjoin did
// not return the correct list
final String mdx2 =
"select {[Measures].[Unit Sales]} ON COLUMNS, "
+ "NON EMPTY Crossjoin({[Gender].[All Gender]}, "
+ "[Product].[Product Family].Members) ON ROWS "
+ "from [Sales]";
testContext.assertQueryReturns(mdx2, expected);
checkQuery(testContext, mdx2);
}
/**
* Testcase for bug <a href="http://jira.pentaho.com/browse/MONDRIAN-406">
* MONDRIAN-406, "Rollup policy doesn't work for members
* that are implicitly visible"</a>.
*/
public void testGoodman() {
final String query = "select {[Measures].[Unit Sales]} ON COLUMNS,\n"
+ "Hierarchize(Union(Union(Union({[Store].[All Stores]},"
+ " [Store].[All Stores].Children),"
+ " [Store].[All Stores].[USA].Children),"
+ " [Store].[All Stores].[USA].[CA].Children)) ON ROWS\n"
+ "from [Sales]\n"
+ "where [Time].[1997]";
// Note that total for [Store].[All Stores] and [Store].[USA] is sum
// of visible children [Store].[CA] and [Store].[OR].[Portland].
final TestContext testContext =
goodmanContext(Role.RollupPolicy.PARTIAL);
testContext.assertQueryReturns(
query,
"Axis #0:\n"
+ "{[Time].[1997]}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Store].[All Stores]}\n"
+ "{[Store].[USA]}\n"
+ "{[Store].[USA].[CA]}\n"
+ "{[Store].[USA].[CA].[Alameda]}\n"
+ "{[Store].[USA].[CA].[Beverly Hills]}\n"
+ "{[Store].[USA].[CA].[Los Angeles]}\n"
+ "{[Store].[USA].[CA].[San Diego]}\n"
+ "{[Store].[USA].[CA].[San Francisco]}\n"
+ "{[Store].[USA].[OR]}\n"
+ "Row #0: 100,827\n"
+ "Row #1: 100,827\n"
+ "Row #2: 74,748\n"
+ "Row #3: \n"
+ "Row #4: 21,333\n"
+ "Row #5: 25,663\n"
+ "Row #6: 25,635\n"
+ "Row #7: 2,117\n"
+ "Row #8: 26,079\n");
goodmanContext(Role.RollupPolicy.FULL).assertQueryReturns(
query,
"Axis #0:\n"
+ "{[Time].[1997]}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Store].[All Stores]}\n"
+ "{[Store].[USA]}\n"
+ "{[Store].[USA].[CA]}\n"
+ "{[Store].[USA].[CA].[Alameda]}\n"
+ "{[Store].[USA].[CA].[Beverly Hills]}\n"
+ "{[Store].[USA].[CA].[Los Angeles]}\n"
+ "{[Store].[USA].[CA].[San Diego]}\n"
+ "{[Store].[USA].[CA].[San Francisco]}\n"
+ "{[Store].[USA].[OR]}\n"
+ "Row #0: 266,773\n"
+ "Row #1: 266,773\n"
+ "Row #2: 74,748\n"
+ "Row #3: \n"
+ "Row #4: 21,333\n"
+ "Row #5: 25,663\n"
+ "Row #6: 25,635\n"
+ "Row #7: 2,117\n"
+ "Row #8: 67,659\n");
goodmanContext(Role.RollupPolicy.HIDDEN).assertQueryReturns(
query,
"Axis #0:\n"
+ "{[Time].[1997]}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Store].[All Stores]}\n"
+ "{[Store].[USA]}\n"
+ "{[Store].[USA].[CA]}\n"
+ "{[Store].[USA].[CA].[Alameda]}\n"
+ "{[Store].[USA].[CA].[Beverly Hills]}\n"
+ "{[Store].[USA].[CA].[Los Angeles]}\n"
+ "{[Store].[USA].[CA].[San Diego]}\n"
+ "{[Store].[USA].[CA].[San Francisco]}\n"
+ "{[Store].[USA].[OR]}\n"
+ "Row #0: \n"
+ "Row #1: \n"
+ "Row #2: 74,748\n"
+ "Row #3: \n"
+ "Row #4: 21,333\n"
+ "Row #5: 25,663\n"
+ "Row #6: 25,635\n"
+ "Row #7: 2,117\n"
+ "Row #8: \n");
checkQuery(testContext, query);
}
private static TestContext goodmanContext(final Role.RollupPolicy policy) {
return
TestContext.instance().create(
null, null, null, null, null,
"<Role name=\"California manager\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Store]\" rollupPolicy=\""
+ policy.name().toLowerCase()
+ "\" access=\"custom\">\n"
+ " <MemberGrant member=\"[Store].[USA].[CA]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[USA].[OR].[Portland]\" access=\"all\"/>\n"
+ " </HierarchyGrant>"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>")
.withRole("California manager");
}
/**
* Test case for bug <a href="http://jira.pentaho.com/browse/MONDRIAN-402">
* MONDRIAN-402, "Bug in RolapCubeHierarchy.hashCode() ?"</a>.
* Access-control elements for hierarchies with
* same name in different cubes could not be distinguished.
*/
public void testBugMondrian402() {
final TestContext testContext =
TestContext.instance().create(
null, null, null, null, null,
"<Role name=\"California manager\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Store]\" access=\"none\" />\n"
+ " </CubeGrant>\n"
+ " <CubeGrant cube=\"Sales Ragged\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Store]\" access=\"custom\" />\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>")
.withRole("California manager");
assertHierarchyAccess(
testContext.getConnection(), Access.NONE, "Sales", "Store");
assertHierarchyAccess(
testContext.getConnection(),
Access.CUSTOM,
"Sales Ragged",
"Store");
}
public void testPartialRollupParentChildHierarchy() {
final TestContext testContext = TestContext.instance().create(
null, null, null, null, null,
"<Role name=\"Buggy Role\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"HR\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Employees]\" access=\"custom\"\n"
+ " rollupPolicy=\"partial\">\n"
+ " <MemberGrant\n"
+ " member=\"[Employees].[All Employees].[Sheri Nowmer].[Darren Stanz]\"\n"
+ " access=\"all\"/>\n"
+ " </HierarchyGrant>\n"
+ " <HierarchyGrant hierarchy=\"[Store]\" access=\"custom\"\n"
+ " rollupPolicy=\"partial\">\n"
+ " <MemberGrant member=\"[Store].[All Stores].[USA].[CA]\" access=\"all\"/>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>")
.withRole("Buggy Role");
final String mdx = "select\n"
+ " {[Measures].[Number of Employees]} on columns,\n"
+ " {[Store]} on rows\n"
+ "from HR";
testContext.assertQueryReturns(
mdx,
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[Number of Employees]}\n"
+ "Axis #2:\n"
+ "{[Store].[All Stores]}\n"
+ "Row #0: 1\n");
checkQuery(testContext, mdx);
final String mdx2 = "select\n"
+ " {[Measures].[Number of Employees]} on columns,\n"
+ " {[Employees]} on rows\n"
+ "from HR";
testContext.assertQueryReturns(
mdx2,
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[Number of Employees]}\n"
+ "Axis #2:\n"
+ "{[Employees].[All Employees]}\n"
+ "Row #0: 1\n");
checkQuery(testContext, mdx2);
}
public void testParentChildUserDefinedRole()
{
TestContext testContext = getTestContext().withCube("HR");
final Connection connection = testContext.getConnection();
final Role savedRole = connection.getRole();
try {
// Run queries as top-level employee.
connection.setRole(
new PeopleRole(
savedRole, connection.getSchema(), "Sheri Nowmer"));
testContext.assertExprReturns(
"[Employees].Members.Count",
"1,156");
// Level 2 employee
connection.setRole(
new PeopleRole(
savedRole, connection.getSchema(), "Derrick Whelply"));
testContext.assertExprReturns(
"[Employees].Members.Count",
"605");
testContext.assertAxisReturns(
"Head([Employees].Members, 4),"
+ "Tail([Employees].Members, 2)",
"[Employees].[All Employees]\n"
+ "[Employees].[Sheri Nowmer]\n"
+ "[Employees].[Sheri Nowmer].[Derrick Whelply]\n"
+ "[Employees].[Sheri Nowmer].[Derrick Whelply].[Beverly Baker]\n"
+ "[Employees].[Sheri Nowmer].[Derrick Whelply].[Laurie Borges].[Ed Young].[Gregory Whiting].[Merrill Steel]\n"
+ "[Employees].[Sheri Nowmer].[Derrick Whelply].[Laurie Borges].[Ed Young].[Gregory Whiting].[Melissa Marple]");
// Leaf employee
connection.setRole(
new PeopleRole(
savedRole, connection.getSchema(), "Ann Weyerhaeuser"));
testContext.assertExprReturns(
"[Employees].Members.Count",
"7");
testContext.assertAxisReturns(
"[Employees].Members",
"[Employees].[All Employees]\n"
+ "[Employees].[Sheri Nowmer]\n"
+ "[Employees].[Sheri Nowmer].[Derrick Whelply]\n"
+ "[Employees].[Sheri Nowmer].[Derrick Whelply].[Laurie Borges]\n"
+ "[Employees].[Sheri Nowmer].[Derrick Whelply].[Laurie Borges].[Cody Goldey]\n"
+ "[Employees].[Sheri Nowmer].[Derrick Whelply].[Laurie Borges].[Cody Goldey].[Shanay Steelman]\n"
+ "[Employees].[Sheri Nowmer].[Derrick Whelply].[Laurie Borges].[Cody Goldey].[Shanay Steelman].[Ann Weyerhaeuser]");
} finally {
connection.setRole(savedRole);
}
}
/**
* Test case for
* <a href="http://jira.pentaho.com/browse/BISERVER-1574">BISERVER-1574,
* "Cube role rollupPolicy='partial' failure"</a>. The problem was a
* NullPointerException in
* {@link SchemaReader#getMemberParent(mondrian.olap.Member)} when called
* on a members returned in a result set. JPivot calls that method but
* Mondrian normally does not.
*/
public void testBugBiserver1574() {
final TestContext testContext =
TestContext.instance().create(
null, null, null, null, null, BiServer1574Role1)
.withRole("role1");
final String mdx =
"select {([Measures].[Store Invoice], [Store Size in SQFT].[All Store Size in SQFTs])} ON COLUMNS,\n"
+ " {[Warehouse].[All Warehouses]} ON ROWS\n"
+ "from [Warehouse]";
checkQuery(testContext, mdx);
testContext.assertQueryReturns(
mdx,
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[Store Invoice], [Store Size in SQFT].[All Store Size in SQFTs]}\n"
+ "Axis #2:\n"
+ "{[Warehouse].[All Warehouses]}\n"
+ "Row #0: 4,042.96\n");
}
/**
* Testcase for bug <a href="http://jira.pentaho.com/browse/MONDRIAN-435">
* MONDRIAN-435, "Internal error in HierarchizeArrayComparator"</a>. Occurs
* when apply Hierarchize function to tuples on a hierarchy with
* partial-rollup.
*/
public void testBugMondrian435() {
final TestContext testContext =
TestContext.instance().create(
null, null, null, null, null, BiServer1574Role1)
.withRole("role1");
// minimal testcase
testContext.assertQueryReturns(
"select hierarchize("
+ " crossjoin({[Store Size in SQFT], [Store Size in SQFT].Children}, {[Product]})"
+ ") on 0,"
+ "[Store Type].Members on 1 from [Warehouse]",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Store Size in SQFT].[All Store Size in SQFTs], [Product].[All Products]}\n"
+ "{[Store Size in SQFT].[20319], [Product].[All Products]}\n"
+ "Axis #2:\n"
+ "{[Store Type].[All Store Types]}\n"
+ "{[Store Type].[Supermarket]}\n"
+ "Row #0: 4,042.96\n"
+ "Row #0: 4,042.96\n"
+ "Row #1: 4,042.96\n"
+ "Row #1: 4,042.96\n");
// explicit tuples, not crossjoin
testContext.assertQueryReturns(
"select hierarchize("
+ " { ([Store Size in SQFT], [Product]),\n"
+ " ([Store Size in SQFT].[20319], [Product].[Food]),\n"
+ " ([Store Size in SQFT], [Product].[Drink].[Dairy]),\n"
+ " ([Store Size in SQFT].[20319], [Product]) }\n"
+ ") on 0,"
+ "[Store Type].Members on 1 from [Warehouse]",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Store Size in SQFT].[All Store Size in SQFTs], [Product].[All Products]}\n"
+ "{[Store Size in SQFT].[All Store Size in SQFTs], [Product].[Drink].[Dairy]}\n"
+ "{[Store Size in SQFT].[20319], [Product].[All Products]}\n"
+ "{[Store Size in SQFT].[20319], [Product].[Food]}\n"
+ "Axis #2:\n"
+ "{[Store Type].[All Store Types]}\n"
+ "{[Store Type].[Supermarket]}\n"
+ "Row #0: 4,042.96\n"
+ "Row #0: 82.454\n"
+ "Row #0: 4,042.96\n"
+ "Row #0: 2,696.758\n"
+ "Row #1: 4,042.96\n"
+ "Row #1: 82.454\n"
+ "Row #1: 4,042.96\n"
+ "Row #1: 2,696.758\n");
// extended testcase; note that [Store Size in SQFT].Parent is null,
// so disappears
testContext.assertQueryReturns(
"select non empty hierarchize("
+ "union("
+ " union("
+ " crossjoin({[Store Size in SQFT]}, {[Product]}),"
+ " crossjoin({[Store Size in SQFT], [Store Size in SQFT].Children}, {[Product]}),"
+ " all),"
+ " union("
+ " crossjoin({[Store Size in SQFT].Parent}, {[Product].[Drink]}),"
+ " crossjoin({[Store Size in SQFT].Children}, {[Product].[Food]}),"
+ " all),"
+ " all)) on 0,"
+ "[Store Type].Members on 1 from [Warehouse]",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Store Size in SQFT].[All Store Size in SQFTs], [Product].[All Products]}\n"
+ "{[Store Size in SQFT].[All Store Size in SQFTs], [Product].[All Products]}\n"
+ "{[Store Size in SQFT].[20319], [Product].[All Products]}\n"
+ "{[Store Size in SQFT].[20319], [Product].[Food]}\n"
+ "Axis #2:\n"
+ "{[Store Type].[All Store Types]}\n"
+ "{[Store Type].[Supermarket]}\n"
+ "Row #0: 4,042.96\n"
+ "Row #0: 4,042.96\n"
+ "Row #0: 4,042.96\n"
+ "Row #0: 2,696.758\n"
+ "Row #1: 4,042.96\n"
+ "Row #1: 4,042.96\n"
+ "Row #1: 4,042.96\n"
+ "Row #1: 2,696.758\n");
testContext.assertQueryReturns(
"select Hierarchize(\n"
+ " CrossJoin\n("
+ " CrossJoin(\n"
+ " {[Product].[All Products], "
+ " [Product].[Food],\n"
+ " [Product].[Food].[Eggs],\n"
+ " [Product].[Drink].[Dairy]},\n"
+ " [Store Type].MEMBERS),\n"
+ " [Store Size in SQFT].MEMBERS),\n"
+ " PRE) on 0\n"
+ "from [Warehouse]",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Product].[All Products], [Store Type].[All Store Types], [Store Size in SQFT].[All Store Size in SQFTs]}\n"
+ "{[Product].[All Products], [Store Type].[All Store Types], [Store Size in SQFT].[20319]}\n"
+ "{[Product].[All Products], [Store Type].[Supermarket], [Store Size in SQFT].[All Store Size in SQFTs]}\n"
+ "{[Product].[All Products], [Store Type].[Supermarket], [Store Size in SQFT].[20319]}\n"
+ "{[Product].[Drink].[Dairy], [Store Type].[All Store Types], [Store Size in SQFT].[All Store Size in SQFTs]}\n"
+ "{[Product].[Drink].[Dairy], [Store Type].[All Store Types], [Store Size in SQFT].[20319]}\n"
+ "{[Product].[Drink].[Dairy], [Store Type].[Supermarket], [Store Size in SQFT].[All Store Size in SQFTs]}\n"
+ "{[Product].[Drink].[Dairy], [Store Type].[Supermarket], [Store Size in SQFT].[20319]}\n"
+ "{[Product].[Food], [Store Type].[All Store Types], [Store Size in SQFT].[All Store Size in SQFTs]}\n"
+ "{[Product].[Food], [Store Type].[All Store Types], [Store Size in SQFT].[20319]}\n"
+ "{[Product].[Food], [Store Type].[Supermarket], [Store Size in SQFT].[All Store Size in SQFTs]}\n"
+ "{[Product].[Food], [Store Type].[Supermarket], [Store Size in SQFT].[20319]}\n"
+ "{[Product].[Food].[Eggs], [Store Type].[All Store Types], [Store Size in SQFT].[All Store Size in SQFTs]}\n"
+ "{[Product].[Food].[Eggs], [Store Type].[All Store Types], [Store Size in SQFT].[20319]}\n"
+ "{[Product].[Food].[Eggs], [Store Type].[Supermarket], [Store Size in SQFT].[All Store Size in SQFTs]}\n"
+ "{[Product].[Food].[Eggs], [Store Type].[Supermarket], [Store Size in SQFT].[20319]}\n"
+ "Row #0: 4,042.96\n"
+ "Row #0: 4,042.96\n"
+ "Row #0: 4,042.96\n"
+ "Row #0: 4,042.96\n"
+ "Row #0: 82.454\n"
+ "Row #0: 82.454\n"
+ "Row #0: 82.454\n"
+ "Row #0: 82.454\n"
+ "Row #0: 2,696.758\n"
+ "Row #0: 2,696.758\n"
+ "Row #0: 2,696.758\n"
+ "Row #0: 2,696.758\n"
+ "Row #0: \n"
+ "Row #0: \n"
+ "Row #0: \n"
+ "Row #0: \n");
}
/**
* Testcase for bug <a href="http://jira.pentaho.com/browse/MONDRIAN-436">
* MONDRIAN-436, "SubstitutingMemberReader.getMemberBuilder gives
* UnsupportedOperationException"</a>.
*/
public void testBugMondrian436() {
propSaver.set(propSaver.properties.EnableNativeCrossJoin, true);
propSaver.set(propSaver.properties.EnableNativeFilter, true);
propSaver.set(propSaver.properties.EnableNativeNonEmpty, true);
propSaver.set(propSaver.properties.EnableNativeTopCount, true);
propSaver.set(propSaver.properties.ExpandNonNative, true);
// Run with native enabled, then with whatever properties are set for
// this test run.
checkBugMondrian436();
propSaver.reset();
checkBugMondrian436();
}
private void checkBugMondrian436() {
final TestContext testContext =
TestContext.instance().create(
null, null, null, null, null, BiServer1574Role1)
.withRole("role1");
testContext.assertQueryReturns(
"select non empty {[Measures].[Units Ordered],\n"
+ " [Measures].[Units Shipped]} on 0,\n"
+ "non empty hierarchize(\n"
+ " union(\n"
+ " crossjoin(\n"
+ " {[Store Size in SQFT]},\n"
+ " {[Product].[Drink],\n"
+ " [Product].[Food],\n"
+ " [Product].[Drink].[Dairy]}),\n"
+ " crossjoin(\n"
+ " {[Store Size in SQFT].[20319]},\n"
+ " {[Product].Children}))) on 1\n"
+ "from [Warehouse]",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[Units Ordered]}\n"
+ "{[Measures].[Units Shipped]}\n"
+ "Axis #2:\n"
+ "{[Store Size in SQFT].[All Store Size in SQFTs], [Product].[Drink]}\n"
+ "{[Store Size in SQFT].[All Store Size in SQFTs], [Product].[Drink].[Dairy]}\n"
+ "{[Store Size in SQFT].[All Store Size in SQFTs], [Product].[Food]}\n"
+ "{[Store Size in SQFT].[20319], [Product].[Drink]}\n"
+ "{[Store Size in SQFT].[20319], [Product].[Food]}\n"
+ "{[Store Size in SQFT].[20319], [Product].[Non-Consumable]}\n"
+ "Row #0: 865.0\n"
+ "Row #0: 767.0\n"
+ "Row #1: 195.0\n"
+ "Row #1: 182.0\n"
+ "Row #2: 6065.0\n"
+ "Row #2: 5723.0\n"
+ "Row #3: 865.0\n"
+ "Row #3: 767.0\n"
+ "Row #4: 6065.0\n"
+ "Row #4: 5723.0\n"
+ "Row #5: 2179.0\n"
+ "Row #5: 2025.0\n");
}
/**
* Tests that hierarchy-level access control works on a virtual cube.
* See bug
* <a href="http://jira.pentaho.com/browse/MONDRIAN-456">
* MONDRIAN-456, "Roles and virtual cubes"</a>.
*/
public void testVirtualCube() {
TestContext testContext = TestContext.instance().create(
null, null, null, null, null,
"<Role name=\"VCRole\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Warehouse and Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Store]\" access=\"custom\">\n"
+ " <MemberGrant member=\"[Store].[USA].[CA]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[USA].[CA].[Los Angeles]\" access=\"none\"/>\n"
+ " </HierarchyGrant>\n"
+ " <HierarchyGrant hierarchy=\"[Customers]\" access=\"custom\"\n"
+ " topLevel=\"[Customers].[State Province]\" bottomLevel=\"[Customers].[City]\">\n"
+ " <MemberGrant member=\"[Customers].[USA].[CA]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Customers].[USA].[CA].[Los Angeles]\" access=\"none\"/>\n"
+ " </HierarchyGrant>\n"
+ " <HierarchyGrant hierarchy=\"[Gender]\" access=\"none\"/>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>").withRole("VCRole");
testContext.assertQueryReturns(
"select [Store].Members on 0 from [Warehouse and Sales]",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Store].[All Stores]}\n"
+ "{[Store].[USA]}\n"
+ "{[Store].[USA].[CA]}\n"
+ "{[Store].[USA].[CA].[Alameda]}\n"
+ "{[Store].[USA].[CA].[Alameda].[HQ]}\n"
+ "{[Store].[USA].[CA].[Beverly Hills]}\n"
+ "{[Store].[USA].[CA].[Beverly Hills].[Store 6]}\n"
+ "{[Store].[USA].[CA].[San Diego]}\n"
+ "{[Store].[USA].[CA].[San Diego].[Store 24]}\n"
+ "{[Store].[USA].[CA].[San Francisco]}\n"
+ "{[Store].[USA].[CA].[San Francisco].[Store 14]}\n"
+ "Row #0: 159,167.84\n"
+ "Row #0: 159,167.84\n"
+ "Row #0: 159,167.84\n"
+ "Row #0: \n"
+ "Row #0: \n"
+ "Row #0: 45,750.24\n"
+ "Row #0: 45,750.24\n"
+ "Row #0: 54,431.14\n"
+ "Row #0: 54,431.14\n"
+ "Row #0: 4,441.18\n"
+ "Row #0: 4,441.18\n");
}
/**
* this tests the fix for
* http://jira.pentaho.com/browse/BISERVER-2491
* rollupPolicy=partial and queries to upper members don't work
*/
public void testBugBiserver2491() {
final String BiServer2491Role2 =
"<Role name=\"role2\">"
+ " <SchemaGrant access=\"none\">"
+ " <CubeGrant cube=\"Sales\" access=\"all\">"
+ " <HierarchyGrant hierarchy=\"[Store]\" access=\"custom\" rollupPolicy=\"partial\">"
+ " <MemberGrant member=\"[Store].[USA].[CA]\" access=\"all\"/>"
+ " <MemberGrant member=\"[Store].[USA].[CA].[Los Angeles]\" access=\"none\"/>"
+ " </HierarchyGrant>"
+ " </CubeGrant>"
+ " </SchemaGrant>"
+ "</Role>";
final TestContext testContext =
TestContext.instance().create(
null, null, null, null, null, BiServer2491Role2)
.withRole("role2");
final String firstBrokenMdx =
"select [Measures].[Unit Sales] ON COLUMNS, {[Store].[Store Country].Members} ON ROWS from [Sales]";
checkQuery(testContext, firstBrokenMdx);
testContext.assertQueryReturns(
firstBrokenMdx,
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Store].[USA]}\n"
+ "Row #0: 49,085\n");
final String secondBrokenMdx =
"select [Measures].[Unit Sales] ON COLUMNS, "
+ "Descendants([Store],[Store].[Store Name]) ON ROWS from [Sales]";
checkQuery(testContext, secondBrokenMdx);
testContext.assertQueryReturns(
secondBrokenMdx,
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Store].[USA].[CA].[Alameda].[HQ]}\n"
+ "{[Store].[USA].[CA].[Beverly Hills].[Store 6]}\n"
+ "{[Store].[USA].[CA].[San Diego].[Store 24]}\n"
+ "{[Store].[USA].[CA].[San Francisco].[Store 14]}\n"
+ "Row #0: \n"
+ "Row #1: 21,333\n"
+ "Row #2: 25,635\n"
+ "Row #3: 2,117\n");
}
/**
* Test case for bug
* <a href="http://jira.pentaho.com/browse/MONDRIAN-622">MONDRIAN-622,
* "Poor performance with large union role"</a>.
*/
public void testBugMondrian622() {
StringBuilder buf = new StringBuilder();
StringBuilder buf2 = new StringBuilder();
final String cubeName = "Sales with multiple customers";
final Result result = TestContext.instance().executeQuery(
"select [Customers].[City].Members on 0 from [Sales]");
for (Position position : result.getAxes()[0].getPositions()) {
Member member = position.get(0);
String name = member.getParentMember().getName()
+ "."
+ member.getName(); // e.g. "BC.Burnaby"
// e.g. "[Customers].[State Province].[BC].[Burnaby]"
String uniqueName =
Util.replace(member.getUniqueName(), ".[All Customers]", "");
// e.g. "[Customers2].[State Province].[BC].[Burnaby]"
String uniqueName2 =
Util.replace(uniqueName, "Customers", "Customers2");
// e.g. "[Customers3].[State Province].[BC].[Burnaby]"
String uniqueName3 =
Util.replace(uniqueName, "Customers", "Customers3");
buf.append(
" <Role name=\"" + name + "\"> \n"
+ " <SchemaGrant access=\"none\"> \n"
+ " <CubeGrant access=\"all\" cube=\"" + cubeName
+ "\"> \n"
+ " <HierarchyGrant access=\"custom\" hierarchy=\"[Customers]\" rollupPolicy=\"partial\"> \n"
+ " <MemberGrant access=\"all\" member=\""
+ uniqueName + "\"/> \n"
+ " </HierarchyGrant> \n"
+ " <HierarchyGrant access=\"custom\" hierarchy=\"[Customers2]\" rollupPolicy=\"partial\"> \n"
+ " <MemberGrant access=\"all\" member=\""
+ uniqueName2 + "\"/> \n"
+ " </HierarchyGrant> \n"
+ " <HierarchyGrant access=\"custom\" hierarchy=\"[Customers3]\" rollupPolicy=\"partial\"> \n"
+ " <MemberGrant access=\"all\" member=\""
+ uniqueName3 + "\"/> \n"
+ " </HierarchyGrant> \n"
+ " </CubeGrant> \n"
+ " </SchemaGrant> \n"
+ " </Role> \n");
buf2.append(" <RoleUsage roleName=\"" + name + "\"/>\n");
}
final TestContext testContext = TestContext.instance().create(
" <Dimension name=\"Customers\"> \n"
+ " <Hierarchy hasAll=\"true\" primaryKey=\"customer_id\"> \n"
+ " <Table name=\"customer\"/> \n"
+ " <Level name=\"Country\" column=\"country\" uniqueMembers=\"true\"/> \n"
+ " <Level name=\"State Province\" column=\"state_province\" uniqueMembers=\"true\"/> \n"
+ " <Level name=\"City\" column=\"city\" uniqueMembers=\"false\"/> \n"
+ " <Level name=\"Name\" column=\"customer_id\" type=\"Numeric\" uniqueMembers=\"true\"/> \n"
+ " </Hierarchy> \n"
+ " </Dimension> ",
" <Cube name=\"" + cubeName + "\"> \n"
+ " <Table name=\"sales_fact_1997\"/> \n"
+ " <DimensionUsage name=\"Time\" source=\"Time\" foreignKey=\"time_id\"/> \n"
+ " <DimensionUsage name=\"Product\" source=\"Product\" foreignKey=\"product_id\"/> \n"
+ " <DimensionUsage name=\"Customers\" source=\"Customers\" foreignKey=\"customer_id\"/> \n"
+ " <DimensionUsage name=\"Customers2\" source=\"Customers\" foreignKey=\"customer_id\"/> \n"
+ " <DimensionUsage name=\"Customers3\" source=\"Customers\" foreignKey=\"customer_id\"/> \n"
+ " <Measure name=\"Unit Sales\" column=\"unit_sales\" aggregator=\"sum\" formatString=\"Standard\"/> \n"
+ " </Cube> \n",
null, null, null,
buf.toString()
+ " <Role name=\"Test\"> \n"
+ " <Union>\n"
+ buf2.toString()
+ " </Union>\n"
+ " </Role>\n");
final long t0 = System.currentTimeMillis();
final TestContext testContext1 = testContext.withRole("Test");
testContext1.executeQuery("select from [" + cubeName + "]");
final long t1 = System.currentTimeMillis();
// System.out.println("Elapsed=" + (t1 - t0) + " millis");
// System.out.println(
// "RoleImpl.accessCount=" + RoleImpl.accessCallCount);
// testContext1.executeQuery(
// "select from [Sales with multiple customers]");
// final long t2 = System.currentTimeMillis();
// System.out.println("Elapsed=" + (t2 - t1) + " millis");
// System.out.println("RoleImpl.accessCount=" + RoleImpl.accessCallCount);
}
/**
* Test case for bug
* <a href="http://jira.pentaho.com/browse/MONDRIAN-694">MONDRIAN-694,
* "Incorrect handling of child/parent relationship with hierarchy
* grants"</a>.
*/
public void testBugMondrian694() {
final TestContext testContext =
TestContext.instance().create(
null, null, null, null, null,
"<Role name=\"REG1\"> \n"
+ " <SchemaGrant access=\"none\"> \n"
+ " <CubeGrant cube=\"HR\" access=\"all\"> \n"
+ " <HierarchyGrant hierarchy=\"Employees\" access=\"custom\" rollupPolicy=\"partial\"> \n"
+ " <MemberGrant member=\"[Employees].[All Employees]\" access=\"none\"/>\n"
+ " <MemberGrant member=\"[Employees].[Sheri Nowmer].[Derrick Whelply].[Laurie Borges].[Cody Goldey].[Shanay Steelman].[Steven Betsekas]\" access=\"all\"/> \n"
+ " <MemberGrant member=\"[Employees].[Sheri Nowmer].[Derrick Whelply].[Laurie Borges].[Cody Goldey].[Shanay Steelman].[Arvid Ziegler]\" access=\"all\"/> \n"
+ " <MemberGrant member=\"[Employees].[Sheri Nowmer].[Derrick Whelply].[Laurie Borges].[Cody Goldey].[Shanay Steelman].[Ann Weyerhaeuser]\" access=\"all\"/> \n"
+ " </HierarchyGrant> \n"
+ " </CubeGrant> \n"
+ " </SchemaGrant> \n"
+ "</Role>")
.withRole("REG1");
// With bug MONDRIAN-694 returns 874.80, should return 79.20.
// Test case is minimal: doesn't happen without the Crossjoin, or
// without the NON EMPTY, or with [Employees] as opposed to
// [Employees].[All Employees], or with [Department].[All Departments].
testContext.assertQueryReturns(
"select NON EMPTY {[Measures].[Org Salary]} ON COLUMNS,\n"
+ "NON EMPTY Crossjoin({[Department].[14]}, {[Employees].[All Employees]}) ON ROWS\n"
+ "from [HR]",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[Org Salary]}\n"
+ "Axis #2:\n"
+ "{[Department].[14], [Employees].[All Employees]}\n"
+ "Row #0: $97.20\n");
// This query gave the right answer, even with MONDRIAN-694.
testContext.assertQueryReturns(
"select NON EMPTY {[Measures].[Org Salary]} ON COLUMNS, \n"
+ "NON EMPTY Hierarchize(Crossjoin({[Department].[14]}, {[Employees].[All Employees], [Employees].Children})) ON ROWS \n"
+ "from [HR] ",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[Org Salary]}\n"
+ "Axis #2:\n"
+ "{[Department].[14], [Employees].[All Employees]}\n"
+ "{[Department].[14], [Employees].[Sheri Nowmer]}\n"
+ "Row #0: $97.20\n"
+ "Row #1: $97.20\n");
// Original test case, not quite minimal. With MONDRIAN-694, returns
// $874.80 for [All Employees].
testContext.assertQueryReturns(
"select NON EMPTY {[Measures].[Org Salary]} ON COLUMNS, \n"
+ "NON EMPTY Hierarchize(Union(Crossjoin({[Department].[All Departments].[14]}, {[Employees].[All Employees]}), Crossjoin({[Department].[All Departments].[14]}, [Employees].[All Employees].Children))) ON ROWS \n"
+ "from [HR] ",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[Org Salary]}\n"
+ "Axis #2:\n"
+ "{[Department].[14], [Employees].[All Employees]}\n"
+ "{[Department].[14], [Employees].[Sheri Nowmer]}\n"
+ "Row #0: $97.20\n"
+ "Row #1: $97.20\n");
testContext.assertQueryReturns(
"select NON EMPTY {[Measures].[Org Salary]} ON COLUMNS, \n"
+ "NON EMPTY Crossjoin(Hierarchize(Union({[Employees].[All Employees]}, [Employees].[All Employees].Children)), {[Department].[14]}) ON ROWS \n"
+ "from [HR] ",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[Org Salary]}\n"
+ "Axis #2:\n"
+ "{[Employees].[All Employees], [Department].[14]}\n"
+ "{[Employees].[Sheri Nowmer], [Department].[14]}\n"
+ "Row #0: $97.20\n"
+ "Row #1: $97.20\n");
}
/**
* Test case for bug
* <a href="http://jira.pentaho.com/browse/MONDRIAN-722">MONDRIAN-722, "If
* ignoreInvalidMembers=true, should ignore grants with invalid
* members"</a>.
*/
public void testBugMondrian722() {
propSaver.set(
MondrianProperties.instance().IgnoreInvalidMembers,
true);
TestContext.instance().create(
null, null, null, null, null,
"<Role name=\"CTO\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Customers]\" access=\"custom\">\n"
+ " <MemberGrant member=\"[Customers].[USA].[XX]\" access=\"none\"/>\n"
+ " <MemberGrant member=\"[Customers].[USA].[XX].[Yyy Yyyyyyy]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Customers].[USA]\" access=\"none\"/>\n"
+ " <MemberGrant member=\"[Customers].[USA].[CA]\" access=\"none\"/>\n"
+ " <MemberGrant member=\"[Customers].[USA].[CA].[Los Angeles]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Customers].[USA].[CA].[Zzz Zzzz]\" access=\"none\"/>\n"
+ " <MemberGrant member=\"[Customers].[USA].[CA].[San Francisco]\" access=\"all\"/>\n"
+ " </HierarchyGrant>\n"
+ " <HierarchyGrant hierarchy=\"[Gender]\" access=\"none\"/>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>")
.withRole("CTO")
.assertQueryReturns(
"select [Measures] on 0,\n"
+ " Hierarchize(\n"
+ " {[Customers].[USA].Children,\n"
+ " [Customers].[USA].[CA].Children}) on 1\n"
+ "from [Sales]",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Customers].[USA].[CA]}\n"
+ "{[Customers].[USA].[CA].[Los Angeles]}\n"
+ "{[Customers].[USA].[CA].[San Francisco]}\n"
+ "Row #0: 74,748\n"
+ "Row #1: 2,009\n"
+ "Row #2: 88\n");
}
/**
* Test case for bug
* <a href="http://jira.pentaho.com/browse/MONDRIAN-746">MONDRIAN-746,
* "Report returns stack trace when turning on subtotals on a hierarchy with
* top level hidden"</a>.
*/
public void testCalcMemberLevel() {
checkCalcMemberLevel(getTestContext());
checkCalcMemberLevel(
TestContext.instance().create(
null, null, null, null, null,
"<Role name=\"Role1\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Store]\" access=\"custom\" rollupPolicy=\"Partial\" topLevel=\"[Store].[Store State]\">\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>\n")
.withRole("Role1"));
}
/**
* Test for bug MONDRIAN-568. Grants on OLAP elements are validated
* by name, thus granting implicit access to all cubes which have
* a dimension with the same name.
*/
public void testBugMondrian568() {
final TestContext testContext =
TestContext.instance().create(
null, null, null, null, null,
"<Role name=\"Role1\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"none\">\n"
+ " <HierarchyGrant hierarchy=\"[Measures]\" access=\"custom\">\n"
+ " <MemberGrant member=\"[Measures].[Unit Sales]\" access=\"all\"/>\n"
+ " </HierarchyGrant>"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>\n"
+ "<Role name=\"Role2\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales Ragged\" access=\"all\"/>\n"
+ " </SchemaGrant>\n"
+ "</Role>");
final TestContext testContextRole1 =
testContext
.withRole("Role1")
.withCube("Sales");
final TestContext testContextRole12 =
testContext
.withRole("Role1,Role2")
.withCube("Sales");
assertMemberAccess(
testContextRole1.getConnection(),
Access.NONE,
"[Measures].[Store Cost]");
assertMemberAccess(
testContextRole12.getConnection(),
Access.NONE,
"[Measures].[Store Cost]");
}
private void checkCalcMemberLevel(TestContext testContext) {
Result result = testContext.executeQuery(
"with member [Store].[USA].[CA].[Foo] as\n"
+ " 1\n"
+ "select {[Measures].[Unit Sales]} on columns,\n"
+ "{[Store].[USA].[CA],\n"
+ " [Store].[USA].[CA].[Los Angeles],\n"
+ " [Store].[USA].[CA].[Foo]} on rows\n"
+ "from [Sales]");
final List<Position> rowPos = result.getAxes()[1].getPositions();
final Member member0 = rowPos.get(0).get(0);
assertEquals("CA", member0.getName());
assertEquals("Store State", member0.getLevel().getName());
final Member member1 = rowPos.get(1).get(0);
assertEquals("Los Angeles", member1.getName());
assertEquals("Store City", member1.getLevel().getName());
final Member member2 = rowPos.get(2).get(0);
assertEquals("Foo", member2.getName());
assertEquals("Store City", member2.getLevel().getName());
}
/**
* Testcase for bug
* <a href="http://jira.pentaho.com/browse/MONDRIAN-935">MONDRIAN-935,
* "no results when some level members in a member grant have no data"</a>.
*/
public void testBugMondrian935() {
final TestContext testContext =
TestContext.instance().create(
null, null, null, null, null,
"<Role name='Role1'>\n"
+ " <SchemaGrant access='none'>\n"
+ " <CubeGrant cube='Sales' access='all'>\n"
+ " <HierarchyGrant hierarchy='[Store Type]' access='custom' rollupPolicy='partial'>\n"
+ " <MemberGrant member='[Store Type].[All Store Types]' access='none'/>\n"
+ " <MemberGrant member='[Store Type].[Supermarket]' access='all'/>\n"
+ " </HierarchyGrant>\n"
+ " <HierarchyGrant hierarchy='[Customers]' access='custom' rollupPolicy='partial' >\n"
+ " <MemberGrant member='[Customers].[All Customers]' access='none'/>\n"
+ " <MemberGrant member='[Customers].[USA].[WA]' access='all'/>\n"
+ " <MemberGrant member='[Customers].[USA].[CA]' access='none'/>\n"
+ " <MemberGrant member='[Customers].[USA].[CA].[Los Angeles]' access='all'/>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>\n");
testContext.withRole("Role1").assertQueryReturns(
"select [Measures] on 0,\n"
+ "[Customers].[USA].Children * [Store Type].Children on 1\n"
+ "from [Sales]",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Customers].[USA].[CA], [Store Type].[Supermarket]}\n"
+ "{[Customers].[USA].[WA], [Store Type].[Supermarket]}\n"
+ "Row #0: 1,118\n"
+ "Row #1: 73,178\n");
}
public void testDimensionGrant() throws Exception {
final TestContext context = TestContext.instance().create(
null, null, null, null, null,
"<Role name=\"Role1\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"custom\">\n"
+ " <DimensionGrant dimension=\"[Measures]\" access=\"all\" />\n"
+ " <DimensionGrant dimension=\"[Education Level]\" access=\"all\" />\n"
+ " <DimensionGrant dimension=\"[Gender]\" access=\"all\" />\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>\n"
+ "<Role name=\"Role2\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"custom\">\n"
+ " <DimensionGrant dimension=\"[Measures]\" access=\"all\" />\n"
+ " <DimensionGrant dimension=\"[Education Level]\" access=\"all\" />\n"
+ " <DimensionGrant dimension=\"[Customers]\" access=\"none\" />\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>\n"
+ "<Role name=\"Role3\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"custom\">\n"
+ " <DimensionGrant dimension=\"[Education Level]\" access=\"all\" />\n"
+ " <DimensionGrant dimension=\"[Measures]\" access=\"custom\" />\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>\n");
context.withRole("Role1").assertAxisReturns(
"[Education Level].Members",
"[Education Level].[All Education Levels]\n"
+ "[Education Level].[Bachelors Degree]\n"
+ "[Education Level].[Graduate Degree]\n"
+ "[Education Level].[High School Degree]\n"
+ "[Education Level].[Partial College]\n"
+ "[Education Level].[Partial High School]");
context.withRole("Role1").assertAxisThrows(
"[Customers].Members",
"Mondrian Error:Failed to parse query 'select {[Customers].Members} on columns from Sales'");
context.withRole("Role2").assertAxisThrows(
"[Customers].Members",
"Mondrian Error:Failed to parse query 'select {[Customers].Members} on columns from Sales'");
context.withRole("Role1").assertQueryReturns(
"select {[Education Level].Members} on columns, {[Measures].[Unit Sales]} on rows from Sales",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Education Level].[All Education Levels]}\n"
+ "{[Education Level].[Bachelors Degree]}\n"
+ "{[Education Level].[Graduate Degree]}\n"
+ "{[Education Level].[High School Degree]}\n"
+ "{[Education Level].[Partial College]}\n"
+ "{[Education Level].[Partial High School]}\n"
+ "Axis #2:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Row #0: 266,773\n"
+ "Row #0: 68,839\n"
+ "Row #0: 15,570\n"
+ "Row #0: 78,664\n"
+ "Row #0: 24,545\n"
+ "Row #0: 79,155\n");
context.withRole("Role3").assertQueryThrows(
"select {[Education Level].Members} on columns, {[Measures].[Unit Sales]} on rows from Sales",
"Mondrian Error:Failed to parse query 'select {[Education Level].Members} on columns, {[Measures].[Unit Sales]} on rows from Sales'");
}
// ~ Inner classes =========================================================
public static class PeopleRole extends DelegatingRole {
private final String repName;
public PeopleRole(Role role, Schema schema, String repName) {
super(((RoleImpl)role).makeMutableClone());
this.repName = repName;
defineGrantsForUser(schema);
}
private void defineGrantsForUser(Schema schema) {
RoleImpl role = (RoleImpl)this.role;
role.grant(schema, Access.NONE);
Cube cube = schema.lookupCube("HR", true);
role.grant(cube, Access.ALL);
Hierarchy hierarchy = cube.lookupHierarchy(
new Id.NameSegment("Employees"), false);
Level[] levels = hierarchy.getLevels();
Level topLevel = levels[1];
role.grant(hierarchy, Access.CUSTOM, null, null, RollupPolicy.FULL);
role.grant(hierarchy.getAllMember(), Access.NONE);
boolean foundMember = false;
List <Member> members =
schema.getSchemaReader().withLocus()
.getLevelMembers(topLevel, true);
for (Member member : members) {
if (member.getUniqueName().contains("[" + repName + "]")) {
foundMember = true;
role.grant(member, Access.ALL);
}
}
assertTrue(foundMember);
}
}
/**
* This is a test for MONDRIAN-1030. When the top level of a hierarchy
* is not accessible and a partial rollup policy is used, the results would
* be returned as those of the first member of those accessible only.
*
* <p>ie: If a union of roles give access to two two sibling root members
* and the level to which they belong is not included in a query, the
* returned cell data would be that of the first sibling and would exclude
* those of the second.
*
* <p>This is because the RolapEvaluator cannot represent default members
* as multiple members (only a single member is the default member) and
* because the default member is not the 'all member', it adds a constrain
* to the SQL for the first member only.
*
* <p>Currently, Mondrian disguises the root member in the evaluator as a
* RestrictedMemberReader.MultiCardinalityDefaultMember. Later,
* RolapHierarchy.LimitedRollupSubstitutingMemberReader will recognize it
* and use the correct rollup policy on the parent member to generate
* correct SQL.
*/
public void testMondrian1030() throws Exception {
final String mdx1 =
"With\n"
+ "Set [*NATIVE_CJ_SET] as 'NonEmptyCrossJoin([*BASE_MEMBERS_Customers],[*BASE_MEMBERS_Product])'\n"
+ "Set [*SORTED_ROW_AXIS] as 'Order([*CJ_ROW_AXIS],[Customers].CurrentMember.OrderKey,BASC,[Education Level].CurrentMember.OrderKey,BASC)'\n"
+ "Set [*BASE_MEMBERS_Customers] as '[Customers].[City].Members'\n"
+ "Set [*BASE_MEMBERS_Product] as '[Education Level].Members'\n"
+ "Set [*BASE_MEMBERS_Measures] as '{[Measures].[*FORMATTED_MEASURE_0]}'\n"
+ "Set [*CJ_ROW_AXIS] as 'Generate([*NATIVE_CJ_SET], {([Customers].currentMember,[Education Level].currentMember)})'\n"
+ "Set [*CJ_COL_AXIS] as '[*NATIVE_CJ_SET]'\n"
+ "Member [Measures].[*FORMATTED_MEASURE_0] as '[Measures].[Unit Sales]', FORMAT_STRING = '#,###', SOLVE_ORDER=400\n"
+ "Select\n"
+ "[*BASE_MEMBERS_Measures] on columns,\n"
+ "Non Empty [*SORTED_ROW_AXIS] on rows\n"
+ "From [Sales] \n";
final String mdx2 =
"With\n"
+ "Set [*BASE_MEMBERS_Product] as '[Education Level].Members'\n"
+ "Set [*BASE_MEMBERS_Measures] as '{[Measures].[*FORMATTED_MEASURE_0]}'\n"
+ "Member [Measures].[*FORMATTED_MEASURE_0] as '[Measures].[Unit Sales]', FORMAT_STRING = '#,###', SOLVE_ORDER=400\n"
+ "Select\n"
+ "[*BASE_MEMBERS_Measures] on columns,\n"
+ "Non Empty [*BASE_MEMBERS_Product] on rows\n"
+ "From [Sales] \n";
final TestContext context =
getTestContext().create(
null, null, null, null, null,
" <Role name=\"Role1\">\n"
+ " <SchemaGrant access=\"all\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Customers]\" access=\"custom\" topLevel=\"[Customers].[City]\" bottomLevel=\"[Customers].[City]\" rollupPolicy=\"partial\">\n"
+ " <MemberGrant member=\"[City].[Coronado]\" access=\"all\">\n"
+ " </MemberGrant>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ " </Role>\n"
+ " <Role name=\"Role2\">\n"
+ " <SchemaGrant access=\"all\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Customers]\" access=\"custom\" topLevel=\"[Customers].[City]\" bottomLevel=\"[Customers].[City]\" rollupPolicy=\"partial\">\n"
+ " <MemberGrant member=\"[City].[Burbank]\" access=\"all\">\n"
+ " </MemberGrant>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ " </Role>\n");
// Control tests
context.withRole("Role1").assertQueryReturns(
mdx1,
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[*FORMATTED_MEASURE_0]}\n"
+ "Axis #2:\n"
+ "{[Customers].[USA].[CA].[Coronado], [Education Level].[All Education Levels]}\n"
+ "{[Customers].[USA].[CA].[Coronado], [Education Level].[Bachelors Degree]}\n"
+ "{[Customers].[USA].[CA].[Coronado], [Education Level].[Graduate Degree]}\n"
+ "{[Customers].[USA].[CA].[Coronado], [Education Level].[High School Degree]}\n"
+ "{[Customers].[USA].[CA].[Coronado], [Education Level].[Partial College]}\n"
+ "{[Customers].[USA].[CA].[Coronado], [Education Level].[Partial High School]}\n"
+ "Row #0: 2,391\n"
+ "Row #1: 559\n"
+ "Row #2: 205\n"
+ "Row #3: 551\n"
+ "Row #4: 253\n"
+ "Row #5: 823\n");
context.withRole("Role2").assertQueryReturns(
mdx1,
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[*FORMATTED_MEASURE_0]}\n"
+ "Axis #2:\n"
+ "{[Customers].[USA].[CA].[Burbank], [Education Level].[All Education Levels]}\n"
+ "{[Customers].[USA].[CA].[Burbank], [Education Level].[Bachelors Degree]}\n"
+ "{[Customers].[USA].[CA].[Burbank], [Education Level].[Graduate Degree]}\n"
+ "{[Customers].[USA].[CA].[Burbank], [Education Level].[High School Degree]}\n"
+ "{[Customers].[USA].[CA].[Burbank], [Education Level].[Partial College]}\n"
+ "{[Customers].[USA].[CA].[Burbank], [Education Level].[Partial High School]}\n"
+ "Row #0: 3,086\n"
+ "Row #1: 914\n"
+ "Row #2: 126\n"
+ "Row #3: 1,029\n"
+ "Row #4: 286\n"
+ "Row #5: 731\n");
context.withRole("Role1,Role2").assertQueryReturns(
mdx1,
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[*FORMATTED_MEASURE_0]}\n"
+ "Axis #2:\n"
+ "{[Customers].[USA].[CA].[Burbank], [Education Level].[All Education Levels]}\n"
+ "{[Customers].[USA].[CA].[Burbank], [Education Level].[Bachelors Degree]}\n"
+ "{[Customers].[USA].[CA].[Burbank], [Education Level].[Graduate Degree]}\n"
+ "{[Customers].[USA].[CA].[Burbank], [Education Level].[High School Degree]}\n"
+ "{[Customers].[USA].[CA].[Burbank], [Education Level].[Partial College]}\n"
+ "{[Customers].[USA].[CA].[Burbank], [Education Level].[Partial High School]}\n"
+ "{[Customers].[USA].[CA].[Coronado], [Education Level].[All Education Levels]}\n"
+ "{[Customers].[USA].[CA].[Coronado], [Education Level].[Bachelors Degree]}\n"
+ "{[Customers].[USA].[CA].[Coronado], [Education Level].[Graduate Degree]}\n"
+ "{[Customers].[USA].[CA].[Coronado], [Education Level].[High School Degree]}\n"
+ "{[Customers].[USA].[CA].[Coronado], [Education Level].[Partial College]}\n"
+ "{[Customers].[USA].[CA].[Coronado], [Education Level].[Partial High School]}\n"
+ "Row #0: 3,086\n"
+ "Row #1: 914\n"
+ "Row #2: 126\n"
+ "Row #3: 1,029\n"
+ "Row #4: 286\n"
+ "Row #5: 731\n"
+ "Row #6: 2,391\n"
+ "Row #7: 559\n"
+ "Row #8: 205\n"
+ "Row #9: 551\n"
+ "Row #10: 253\n"
+ "Row #11: 823\n");
// Actual tests
context.withRole("Role1").assertQueryReturns(
mdx2,
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[*FORMATTED_MEASURE_0]}\n"
+ "Axis #2:\n"
+ "{[Education Level].[All Education Levels]}\n"
+ "{[Education Level].[Bachelors Degree]}\n"
+ "{[Education Level].[Graduate Degree]}\n"
+ "{[Education Level].[High School Degree]}\n"
+ "{[Education Level].[Partial College]}\n"
+ "{[Education Level].[Partial High School]}\n"
+ "Row #0: 2,391\n"
+ "Row #1: 559\n"
+ "Row #2: 205\n"
+ "Row #3: 551\n"
+ "Row #4: 253\n"
+ "Row #5: 823\n");
context.withRole("Role2").assertQueryReturns(
mdx2,
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[*FORMATTED_MEASURE_0]}\n"
+ "Axis #2:\n"
+ "{[Education Level].[All Education Levels]}\n"
+ "{[Education Level].[Bachelors Degree]}\n"
+ "{[Education Level].[Graduate Degree]}\n"
+ "{[Education Level].[High School Degree]}\n"
+ "{[Education Level].[Partial College]}\n"
+ "{[Education Level].[Partial High School]}\n"
+ "Row #0: 3,086\n"
+ "Row #1: 914\n"
+ "Row #2: 126\n"
+ "Row #3: 1,029\n"
+ "Row #4: 286\n"
+ "Row #5: 731\n");
context.withRole("Role1,Role2").assertQueryReturns(
mdx2,
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[*FORMATTED_MEASURE_0]}\n"
+ "Axis #2:\n"
+ "{[Education Level].[All Education Levels]}\n"
+ "{[Education Level].[Bachelors Degree]}\n"
+ "{[Education Level].[Graduate Degree]}\n"
+ "{[Education Level].[High School Degree]}\n"
+ "{[Education Level].[Partial College]}\n"
+ "{[Education Level].[Partial High School]}\n"
+ "Row #0: 5,477\n"
+ "Row #1: 1,473\n"
+ "Row #2: 331\n"
+ "Row #3: 1,580\n"
+ "Row #4: 539\n"
+ "Row #5: 1,554\n");
}
/**
* This is a test for
* <a href="http://jira.pentaho.com/browse/MONDRIAN-1030">MONDRIAN-1030</a>
* When a query is based on a level higher than one in the same hierarchy
* which has access controls, it would only constrain at the current level
* if the rollup policy of partial is used.
*
* <p>Example. A query on USA where only Los-Angeles is accessible would
* return the values for California instead of only LA.
*/
public void testBugMondrian1030_2() {
TestContext.instance().create(
null, null, null, null, null,
"<Role name=\"Bacon\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Customers]\" access=\"custom\" rollupPolicy=\"partial\">\n"
+ " <MemberGrant member=\"[Customers].[USA].[CA].[Los Angeles]\" access=\"all\"/>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>")
.withRole("Bacon")
.assertQueryReturns(
"select {[Measures].[Unit Sales]} on 0,\n"
+ " {[Customers].[USA]} on 1\n"
+ "from [Sales]",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Customers].[USA]}\n"
+ "Row #0: 2,009\n");
}
/**
* Test for
* <a href="http://jira.pentaho.com/browse/MONDRIAN-1091">MONDRIAN-1091</a>
* The RoleImpl would try to search for member grants by object identity
* rather than unique name. When using the partial rollup policy, the
* members are wrapped, so identity checks would fail.
*/
public void testMondrian1091() throws Exception {
final TestContext testContext = TestContext.instance().create(
null, null, null, null, null,
"<Role name=\"Role1\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Store]\" access=\"custom\" rollupPolicy=\"partial\">\n"
+ " <MemberGrant member=\"[Store].[USA].[CA]\" access=\"all\"/>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>")
.withRole("Role1");
testContext.assertQueryReturns(
"select {[Store].Members} on columns from [Sales]",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Store].[All Stores]}\n"
+ "{[Store].[USA]}\n"
+ "{[Store].[USA].[CA]}\n"
+ "{[Store].[USA].[CA].[Alameda]}\n"
+ "{[Store].[USA].[CA].[Alameda].[HQ]}\n"
+ "{[Store].[USA].[CA].[Beverly Hills]}\n"
+ "{[Store].[USA].[CA].[Beverly Hills].[Store 6]}\n"
+ "{[Store].[USA].[CA].[Los Angeles]}\n"
+ "{[Store].[USA].[CA].[Los Angeles].[Store 7]}\n"
+ "{[Store].[USA].[CA].[San Diego]}\n"
+ "{[Store].[USA].[CA].[San Diego].[Store 24]}\n"
+ "{[Store].[USA].[CA].[San Francisco]}\n"
+ "{[Store].[USA].[CA].[San Francisco].[Store 14]}\n"
+ "Row #0: 74,748\n"
+ "Row #0: 74,748\n"
+ "Row #0: 74,748\n"
+ "Row #0: \n"
+ "Row #0: \n"
+ "Row #0: 21,333\n"
+ "Row #0: 21,333\n"
+ "Row #0: 25,663\n"
+ "Row #0: 25,663\n"
+ "Row #0: 25,635\n"
+ "Row #0: 25,635\n"
+ "Row #0: 2,117\n"
+ "Row #0: 2,117\n");
org.olap4j.metadata.Cube cube =
testContext.getOlap4jConnection()
.getOlapSchema().getCubes().get("Sales");
org.olap4j.metadata.Member allMember =
cube.lookupMember(
IdentifierNode.parseIdentifier("[Store].[All Stores]")
.getSegmentList());
assertNotNull(allMember);
assertEquals(1, allMember.getHierarchy().getRootMembers().size());
assertEquals(
"[Store].[All Stores]",
allMember.getHierarchy().getRootMembers().get(0).getUniqueName());
}
/**
* Unit test for
* <a href="http://jira.pentaho.com/browse/mondrian-1259">MONDRIAN-1259,
* "Mondrian security: access leaks from one user to another"</a>.
*
* <p>Enhancements made to the SmartRestrictedMemberReader were causing
* security leaks between roles and potential class cast exceptions.
*/
public void testMondrian1259() throws Exception {
final String mdx =
"select non empty {[Store].Members} on columns from [Sales]";
final TestContext testContext = TestContext.instance().create(
null, null, null, null, null,
"<Role name=\"Role1\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Store]\" access=\"custom\" rollupPolicy=\"partial\">\n"
+ " <MemberGrant member=\"[Store].[USA].[CA]\" access=\"all\"/>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>"
+ "<Role name=\"Role2\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Store]\" access=\"custom\" rollupPolicy=\"partial\">\n"
+ " <MemberGrant member=\"[Store].[USA].[OR]\" access=\"all\"/>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>");
testContext.withRole("Role1").assertQueryReturns(
mdx,
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Store].[All Stores]}\n"
+ "{[Store].[USA]}\n"
+ "{[Store].[USA].[CA]}\n"
+ "{[Store].[USA].[CA].[Beverly Hills]}\n"
+ "{[Store].[USA].[CA].[Beverly Hills].[Store 6]}\n"
+ "{[Store].[USA].[CA].[Los Angeles]}\n"
+ "{[Store].[USA].[CA].[Los Angeles].[Store 7]}\n"
+ "{[Store].[USA].[CA].[San Diego]}\n"
+ "{[Store].[USA].[CA].[San Diego].[Store 24]}\n"
+ "{[Store].[USA].[CA].[San Francisco]}\n"
+ "{[Store].[USA].[CA].[San Francisco].[Store 14]}\n"
+ "Row #0: 74,748\n"
+ "Row #0: 74,748\n"
+ "Row #0: 74,748\n"
+ "Row #0: 21,333\n"
+ "Row #0: 21,333\n"
+ "Row #0: 25,663\n"
+ "Row #0: 25,663\n"
+ "Row #0: 25,635\n"
+ "Row #0: 25,635\n"
+ "Row #0: 2,117\n"
+ "Row #0: 2,117\n");
testContext.withRole("Role2").assertQueryReturns(
mdx,
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Store].[All Stores]}\n"
+ "{[Store].[USA]}\n"
+ "{[Store].[USA].[OR]}\n"
+ "{[Store].[USA].[OR].[Portland]}\n"
+ "{[Store].[USA].[OR].[Portland].[Store 11]}\n"
+ "{[Store].[USA].[OR].[Salem]}\n"
+ "{[Store].[USA].[OR].[Salem].[Store 13]}\n"
+ "Row #0: 67,659\n"
+ "Row #0: 67,659\n"
+ "Row #0: 67,659\n"
+ "Row #0: 26,079\n"
+ "Row #0: 26,079\n"
+ "Row #0: 41,580\n"
+ "Row #0: 41,580\n");
}
public void testMondrian1295() throws Exception {
final String mdx =
"With\n"
+ "Set [*NATIVE_CJ_SET] as 'NonEmptyCrossJoin([*BASE_MEMBERS_Time],[*BASE_MEMBERS_Product])'\n"
+ "Set [*SORTED_ROW_AXIS] as 'Order([*CJ_ROW_AXIS],Ancestor([Time].CurrentMember, [Time].[Year]).OrderKey,BASC,Ancestor([Time].CurrentMember, [Time].[Quarter]).OrderKey,BASC,[Time].CurrentMember.OrderKey,BASC,[Product].CurrentMember.OrderKey,BASC)'\n"
+ "Set [*BASE_MEMBERS_Product] as '{[Product].[All Products]}'\n"
+ "Set [*BASE_MEMBERS_Measures] as '{[Measures].[*FORMATTED_MEASURE_0]}'\n"
+ "Set [*CJ_ROW_AXIS] as 'Generate([*NATIVE_CJ_SET], {([Time].currentMember,[Product].currentMember)})'\n"
+ "Set [*BASE_MEMBERS_Time] as '[Time].[Year].Members'\n"
+ "Set [*CJ_COL_AXIS] as '[*NATIVE_CJ_SET]'\n"
+ "Member [Measures].[*FORMATTED_MEASURE_0] as '[Measures].[Unit Sales]', FORMAT_STRING = 'Standard', SOLVE_ORDER=400\n"
+ "Select\n"
+ "[*BASE_MEMBERS_Measures] on columns,\n"
+ "Non Empty [*SORTED_ROW_AXIS] on rows\n"
+ "From [Sales]\n";
final TestContext context =
getTestContext().create(
null, null, null, null, null,
"<Role name=\"Admin\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Store]\" rollupPolicy=\"partial\" access=\"custom\">\n"
+ " <MemberGrant member=\"[Store].[USA].[CA]\" access=\"all\">\n"
+ " </MemberGrant>\n"
+ " </HierarchyGrant>\n"
+ " <HierarchyGrant hierarchy=\"[Customers]\" rollupPolicy=\"partial\" access=\"custom\">\n"
+ " <MemberGrant member=\"[Customers].[USA].[CA]\" access=\"all\">\n"
+ " </MemberGrant>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role> \n");
// Control
context
.assertQueryReturns(
"select {[Measures].[Unit Sales]} on columns from [Sales]",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Row #0: 266,773\n");
context.withRole("Admin")
.assertQueryReturns(
"select {[Measures].[Unit Sales]} on columns from [Sales]",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Row #0: 74,748\n");
// Test
context.withRole("Admin")
.assertQueryReturns(
mdx,
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[*FORMATTED_MEASURE_0]}\n"
+ "Axis #2:\n"
+ "{[Time].[1997], [Product].[All Products]}\n"
+ "Row #0: 74,748\n");
}
public void testMondrian936() throws Exception {
final TestContext testContext = TestContext.instance().create(
null, null, null, null, null,
"<Role name=\"test\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Store]\" access=\"custom\"\n"
+ " topLevel=\"[Store].[Store Country]\" rollupPolicy=\"partial\">\n"
+ " <MemberGrant member=\"[Store].[All Stores]\" access=\"none\"/>\n"
+ " <MemberGrant member=\"[Store].[USA].[CA].[Los Angeles]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[USA].[CA].[Alameda]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[USA].[CA].[Beverly Hills]\"\n"
+ "access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[USA].[CA].[San Francisco]\"\n"
+ "access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[USA].[CA].[San Diego]\" access=\"all\"/>\n"
+ "\n"
+ " <MemberGrant member=\"[Store].[USA].[OR].[Portland]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[USA].[OR].[Salem]\" access=\"all\"/>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>");
testContext.withRole("test").assertQueryReturns(
"select {[Measures].[Unit Sales]} on columns, "
+ " {[Product].[Food].[Baked Goods].[Bread]} on rows "
+ " from [Sales] "
+ " where { [Store].[USA].[OR], [Store].[USA].[CA]} ", "Axis #0:\n"
+ "{[Store].[USA].[OR]}\n"
+ "{[Store].[USA].[CA]}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Product].[Food].[Baked Goods].[Bread]}\n"
+ "Row #0: 4,163\n");
// changing ordering of members in the slicer should not change
// result
testContext.withRole("test").assertQueryReturns(
"select {[Measures].[Unit Sales]} on columns, "
+ " {[Product].[Food].[Baked Goods].[Bread]} on rows "
+ " from [Sales] "
+ " where { [Store].[USA].[CA], [Store].[USA].[OR]} ", "Axis #0:\n"
+ "{[Store].[USA].[CA]}\n"
+ "{[Store].[USA].[OR]}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Product].[Food].[Baked Goods].[Bread]}\n"
+ "Row #0: 4,163\n");
Result result = testContext.withRole("test").executeQuery(
"with member store.aggCaliforniaOregon as "
+ "'aggregate({ [Store].[USA].[CA], [Store].[USA].[OR]})'"
+ " select store.aggCaliforniaOregon on 0 from sales");
String valueAggMember = result
.getCell(new int[] {0}).getFormattedValue();
result = testContext.withRole("test").executeQuery(
" select from sales where "
+ "{ [Store].[USA].[CA], [Store].[USA].[OR]}");
String valueSlicerAgg = result
.getCell(new int[] {}).getFormattedValue();
// aggregating CA & OR in a calc member should produce same result
// as aggregating in the slicer.
assertTrue(valueAggMember.equals(valueSlicerAgg));
}
public void testMondrian1434() {
String roleDef =
"<Role name=\"dev\">"
+ " <SchemaGrant access=\"all\">"
+ " <CubeGrant cube=\"Sales\" access=\"all\">"
+ " </CubeGrant>"
+ " <CubeGrant cube=\"HR\" access=\"all\">"
+ " </CubeGrant>"
+ " <CubeGrant cube=\"Warehouse and Sales\" access=\"all\">"
+ " <HierarchyGrant hierarchy=\"Measures\" access=\"custom\">"
+ " <MemberGrant member=\"[Measures].[Warehouse Sales]\" access=\"all\">"
+ " </MemberGrant>"
+ " </HierarchyGrant>"
+ " </CubeGrant>"
+ " </SchemaGrant>"
+ "</Role>";
TestContext testContext = TestContext.instance()
.create(null, null, null, null, null, roleDef).withRole("dev");
testContext.executeQuery(
" select from [Sales] where {[Measures].[Unit Sales]}");
roleDef =
"<Role name=\"dev\">"
+ " <SchemaGrant access=\"all\">"
+ " <CubeGrant cube=\"Sales\" access=\"all\">"
+ " <HierarchyGrant hierarchy=\"Measures\" access=\"custom\">"
+ " <MemberGrant member=\"[Measures].[Unit Sales]\" access=\"all\">"
+ " </MemberGrant>"
+ " </HierarchyGrant>"
+ " </CubeGrant>"
+ " <CubeGrant cube=\"HR\" access=\"all\">"
+ " </CubeGrant>"
+ " <CubeGrant cube=\"Warehouse and Sales\" access=\"all\">"
+ " </CubeGrant>"
+ " </SchemaGrant>"
+ "</Role>";
testContext = TestContext.instance()
.create(null, null, null, null, null, roleDef).withRole("dev");
testContext.executeQuery(
" select from [Warehouse and Sales] where {[Measures].[Store Sales]}");
// test is that there is no exception
}
}
// End AccessControlTest.java
|
testsrc/main/mondrian/test/AccessControlTest.java
|
/*
// This software is subject to the terms of the Eclipse Public License v1.0
// Agreement, available at the following URL:
// http://www.eclipse.org/legal/epl-v10.html.
// You must accept the terms of that agreement to use this software.
//
// Copyright (C) 2003-2005 Julian Hyde
// Copyright (C) 2005-2013 Pentaho
// All Rights Reserved.
*/
package mondrian.test;
import mondrian.olap.*;
import mondrian.olap.Role.HierarchyAccess;
import junit.framework.Assert;
import org.olap4j.mdx.IdentifierNode;
import java.util.List;
/**
* <code>AccessControlTest</code> is a set of unit-tests for access-control.
* For these tests, all of the roles are of type RoleImpl.
*
* @see Role
*
* @author jhyde
* @since Feb 21, 2003
*/
public class AccessControlTest extends FoodMartTestCase {
private static final String BiServer1574Role1 =
"<Role name=\"role1\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Warehouse\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Store Size in SQFT]\" access=\"custom\" rollupPolicy=\"partial\">\n"
+ " <MemberGrant member=\"[Store Size in SQFT].[20319]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store Size in SQFT].[21215]\" access=\"none\"/>\n"
+ " </HierarchyGrant>\n"
+ " <HierarchyGrant hierarchy=\"[Store Type]\" access=\"custom\" rollupPolicy=\"partial\">\n"
+ " <MemberGrant member=\"[Store Type].[Supermarket]\" access=\"all\"/>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>";
public AccessControlTest(String name) {
super(name);
}
public void testSchemaReader() {
final TestContext testContext = getTestContext();
final Connection connection = testContext.getConnection();
Schema schema = connection.getSchema();
final boolean fail = true;
Cube cube = schema.lookupCube("Sales", fail);
final SchemaReader schemaReader =
cube.getSchemaReader(connection.getRole());
final SchemaReader schemaReader1 = schemaReader.withoutAccessControl();
assertNotNull(schemaReader1);
final SchemaReader schemaReader2 = schemaReader1.withoutAccessControl();
assertNotNull(schemaReader2);
}
public void testGrantDimensionNone() {
final TestContext context = getTestContext().withFreshConnection();
final Connection connection = context.getConnection();
RoleImpl role = ((RoleImpl) connection.getRole()).makeMutableClone();
Schema schema = connection.getSchema();
Cube salesCube = schema.lookupCube("Sales", true);
// todo: add Schema.lookupDimension
final SchemaReader schemaReader = salesCube.getSchemaReader(role);
Dimension genderDimension =
(Dimension) schemaReader.lookupCompound(
salesCube, Id.Segment.toList("Gender"), true,
Category.Dimension);
role.grant(genderDimension, Access.NONE);
role.makeImmutable();
connection.setRole(role);
context.assertAxisThrows(
"[Gender].children",
"MDX object '[Gender]' not found in cube 'Sales'");
}
public void testRestrictMeasures() {
final TestContext testContext = TestContext.instance().create(
null, null, null, null, null,
"<Role name=\"Role1\">\n"
+ " <SchemaGrant access=\"all\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Measures]\" access=\"all\">\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>"
+ "<Role name=\"Role2\">\n"
+ " <SchemaGrant access=\"all\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Measures]\" access=\"custom\">\n"
+ " <MemberGrant member=\"[Measures].[Unit Sales]\" access=\"all\"/>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>");
final TestContext role1 = testContext.withRole("Role1");
final TestContext role2 = testContext.withRole("Role2");
role1.assertQueryReturns(
"SELECT {[Measures].Members} ON COLUMNS FROM [SALES]",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "{[Measures].[Store Cost]}\n"
+ "{[Measures].[Store Sales]}\n"
+ "{[Measures].[Sales Count]}\n"
+ "{[Measures].[Customer Count]}\n"
+ "{[Measures].[Promotion Sales]}\n"
+ "Row #0: 266,773\n"
+ "Row #0: 225,627.23\n"
+ "Row #0: 565,238.13\n"
+ "Row #0: 86,837\n"
+ "Row #0: 5,581\n"
+ "Row #0: 151,211.21\n");
role2.assertQueryReturns(
"SELECT {[Measures].Members} ON COLUMNS FROM [SALES]",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Row #0: 266,773\n");
}
public void testRoleMemberAccessNonExistentMemberFails() {
final TestContext testContext = TestContext.instance().create(
null, null, null, null, null,
"<Role name=\"Role1\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Store]\" access=\"custom\" rollupPolicy=\"partial\">\n"
+ " <MemberGrant member=\"[Store].[USA].[Non Existent]\" access=\"all\"/>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>")
.withRole("Role1");
testContext.assertQueryThrows(
"select {[Store].Children} on 0 from [Sales]",
"Member '[Store].[USA].[Non Existent]' not found");
}
public void testRoleMemberAccess() {
final Connection connection = getRestrictedConnection();
// because CA has access
assertMemberAccess(connection, Access.CUSTOM, "[Store].[USA]");
assertMemberAccess(connection, Access.CUSTOM, "[Store].[Mexico]");
assertMemberAccess(connection, Access.NONE, "[Store].[Mexico].[DF]");
assertMemberAccess(
connection, Access.NONE, "[Store].[Mexico].[DF].[Mexico City]");
assertMemberAccess(connection, Access.NONE, "[Store].[Canada]");
assertMemberAccess(
connection, Access.NONE, "[Store].[Canada].[BC].[Vancouver]");
assertMemberAccess(
connection, Access.ALL, "[Store].[USA].[CA].[Los Angeles]");
assertMemberAccess(
connection, Access.NONE, "[Store].[USA].[CA].[San Diego]");
// USA deny supercedes OR grant
assertMemberAccess(
connection, Access.NONE, "[Store].[USA].[OR].[Portland]");
assertMemberAccess(
connection, Access.NONE, "[Store].[USA].[WA].[Seattle]");
assertMemberAccess(connection, Access.NONE, "[Store].[USA].[WA]");
// above top level
assertMemberAccess(connection, Access.NONE, "[Store].[All Stores]");
}
private void assertMemberAccess(
final Connection connection,
Access expectedAccess,
String memberName)
{
final Role role = connection.getRole(); // restricted
Schema schema = connection.getSchema();
final boolean fail = true;
Cube salesCube = schema.lookupCube("Sales", fail);
final SchemaReader schemaReader =
salesCube.getSchemaReader(null).withLocus();
final Member member =
schemaReader.getMemberByUniqueName(
Util.parseIdentifier(memberName), true);
final Access actualAccess = role.getAccess(member);
Assert.assertEquals(memberName, expectedAccess, actualAccess);
}
private void assertCubeAccess(
final Connection connection,
Access expectedAccess,
String cubeName)
{
final Role role = connection.getRole();
Schema schema = connection.getSchema();
final boolean fail = true;
Cube cube = schema.lookupCube(cubeName, fail);
final Access actualAccess = role.getAccess(cube);
Assert.assertEquals(cubeName, expectedAccess, actualAccess);
}
private void assertHierarchyAccess(
final Connection connection,
Access expectedAccess,
String cubeName,
String hierarchyName)
{
final Role role = connection.getRole();
Schema schema = connection.getSchema();
final boolean fail = true;
Cube cube = schema.lookupCube(cubeName, fail);
final SchemaReader schemaReader =
cube.getSchemaReader(null); // unrestricted
final Hierarchy hierarchy =
(Hierarchy) schemaReader.lookupCompound(
cube, Util.parseIdentifier(hierarchyName), fail,
Category.Hierarchy);
final Access actualAccess = role.getAccess(hierarchy);
Assert.assertEquals(cubeName, expectedAccess, actualAccess);
}
private Role.HierarchyAccess getHierarchyAccess(
final Connection connection,
String cubeName,
String hierarchyName)
{
final Role role = connection.getRole();
Schema schema = connection.getSchema();
final boolean fail = true;
Cube cube = schema.lookupCube(cubeName, fail);
final SchemaReader schemaReader =
cube.getSchemaReader(null); // unrestricted
final Hierarchy hierarchy =
(Hierarchy) schemaReader.lookupCompound(
cube, Util.parseIdentifier(hierarchyName), fail,
Category.Hierarchy);
return role.getAccessDetails(hierarchy);
}
public void testGrantHierarchy1a() {
// assert: can access Mexico (explicitly granted)
// assert: can not access Canada (explicitly denied)
// assert: can access USA (rule 3 - parent of allowed member San
// Francisco)
getRestrictedTestContext().assertAxisReturns(
"[Store].level.members",
"[Store].[Mexico]\n" + "[Store].[USA]");
}
public void testGrantHierarchy1aAllMembers() {
// assert: can access Mexico (explicitly granted)
// assert: can not access Canada (explicitly denied)
// assert: can access USA (rule 3 - parent of allowed member San
// Francisco)
getRestrictedTestContext().assertAxisReturns(
"[Store].level.allmembers",
"[Store].[Mexico]\n" + "[Store].[USA]");
}
public void testGrantHierarchy1b() {
// can access Mexico (explicitly granted) which is the first accessible
// one
getRestrictedTestContext().assertAxisReturns(
"[Store].defaultMember",
"[Store].[Mexico]");
}
public void testGrantHierarchy1c() {
// the root element is All Customers
getRestrictedTestContext().assertAxisReturns(
"[Customers].defaultMember",
"[Customers].[Canada].[BC]");
}
public void testGrantHierarchy2() {
// assert: can access California (parent of allowed member)
final TestContext testContext = getRestrictedTestContext();
testContext.assertAxisReturns(
"[Store].[USA].children",
"[Store].[USA].[CA]");
testContext.assertAxisReturns(
"[Store].[USA].children",
"[Store].[USA].[CA]");
testContext.assertAxisReturns(
"[Store].[USA].[CA].children",
"[Store].[USA].[CA].[Los Angeles]\n"
+ "[Store].[USA].[CA].[San Francisco]");
}
public void testGrantHierarchy3() {
// assert: can not access Washington (child of denied member)
final TestContext testContext = getRestrictedTestContext();
testContext.assertAxisThrows("[Store].[USA].[WA]", "not found");
}
private TestContext getRestrictedTestContext() {
return new DelegatingTestContext(getTestContext()) {
public Connection getConnection() {
return getRestrictedConnection();
}
};
}
public void testGrantHierarchy4() {
// assert: can not access Oregon (rule 1 - order matters)
final TestContext testContext = getRestrictedTestContext();
testContext.assertAxisThrows(
"[Store].[USA].[OR].children", "not found");
}
public void testGrantHierarchy5() {
// assert: can not access All (above top level)
final TestContext testContext = getRestrictedTestContext();
testContext.assertAxisThrows("[Store].[All Stores]", "not found");
testContext.assertAxisReturns(
"[Store].members",
// note:
// no: [All Stores] -- above top level
// no: [Canada] -- not explicitly allowed
// yes: [Mexico] -- explicitly allowed -- and all its children
// except [DF]
// no: [Mexico].[DF]
// yes: [USA] -- implicitly allowed
// yes: [CA] -- implicitly allowed
// no: [OR], [WA]
// yes: [San Francisco] -- explicitly allowed
// no: [San Diego]
"[Store].[Mexico]\n"
+ "[Store].[Mexico].[Guerrero]\n"
+ "[Store].[Mexico].[Guerrero].[Acapulco]\n"
+ "[Store].[Mexico].[Guerrero].[Acapulco].[Store 1]\n"
+ "[Store].[Mexico].[Jalisco]\n"
+ "[Store].[Mexico].[Jalisco].[Guadalajara]\n"
+ "[Store].[Mexico].[Jalisco].[Guadalajara].[Store 5]\n"
+ "[Store].[Mexico].[Veracruz]\n"
+ "[Store].[Mexico].[Veracruz].[Orizaba]\n"
+ "[Store].[Mexico].[Veracruz].[Orizaba].[Store 10]\n"
+ "[Store].[Mexico].[Yucatan]\n"
+ "[Store].[Mexico].[Yucatan].[Merida]\n"
+ "[Store].[Mexico].[Yucatan].[Merida].[Store 8]\n"
+ "[Store].[Mexico].[Zacatecas]\n"
+ "[Store].[Mexico].[Zacatecas].[Camacho]\n"
+ "[Store].[Mexico].[Zacatecas].[Camacho].[Store 4]\n"
+ "[Store].[Mexico].[Zacatecas].[Hidalgo]\n"
+ "[Store].[Mexico].[Zacatecas].[Hidalgo].[Store 12]\n"
+ "[Store].[Mexico].[Zacatecas].[Hidalgo].[Store 18]\n"
+ "[Store].[USA]\n"
+ "[Store].[USA].[CA]\n"
+ "[Store].[USA].[CA].[Los Angeles]\n"
+ "[Store].[USA].[CA].[Los Angeles].[Store 7]\n"
+ "[Store].[USA].[CA].[San Francisco]\n"
+ "[Store].[USA].[CA].[San Francisco].[Store 14]");
}
public void testGrantHierarchy6() {
// assert: parent if at top level is null
getRestrictedTestContext().assertAxisReturns(
"[Customers].[USA].[CA].parent",
"");
}
public void testGrantHierarchy7() {
// assert: members above top level do not exist
final TestContext testContext = getRestrictedTestContext();
testContext.assertAxisThrows(
"[Customers].[Canada].children",
"MDX object '[Customers].[Canada]' not found in cube 'Sales'");
}
public void testGrantHierarchy8() {
// assert: can not access Catherine Abel in San Francisco (below bottom
// level)
final TestContext testContext = getRestrictedTestContext();
testContext.assertAxisThrows(
"[Customers].[USA].[CA].[San Francisco].[Catherine Abel]",
"not found");
testContext.assertAxisReturns(
"[Customers].[USA].[CA].[San Francisco].children",
"");
Axis axis = testContext.executeAxis("[Customers].members");
// 13 states, 109 cities
Assert.assertEquals(122, axis.getPositions().size());
}
public void testGrantHierarchy8AllMembers() {
// assert: can not access Catherine Abel in San Francisco (below bottom
// level)
final TestContext testContext = getRestrictedTestContext();
testContext.assertAxisThrows(
"[Customers].[USA].[CA].[San Francisco].[Catherine Abel]",
"not found");
testContext.assertAxisReturns(
"[Customers].[USA].[CA].[San Francisco].children",
"");
Axis axis = testContext.executeAxis("[Customers].allmembers");
// 13 states, 109 cities
Assert.assertEquals(122, axis.getPositions().size());
}
/**
* Tests for Mondrian BUG 1201 - Native Rollups did not handle
* access-control with more than one member where granted access=all
*/
public void testBugMondrian_1201_MultipleMembersInRoleAccessControl() {
String test_1201_Roles =
"<Role name=\"Role1\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Store]\" access=\"custom\" rollupPolicy=\"partial\">\n"
+ " <MemberGrant member=\"[Store].[USA].[WA]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[USA].[OR]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[USA].[CA].[San Francisco]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[USA].[CA].[Los Angeles]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[Mexico]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[Mexico].[DF]\" access=\"none\"/>\n"
+ " <MemberGrant member=\"[Store].[Canada]\" access=\"none\"/>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>\n"
+ "<Role name=\"Role2\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Store]\" access=\"custom\" rollupPolicy=\"full\">\n"
+ " <MemberGrant member=\"[Store].[USA].[WA]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[USA].[OR]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[USA].[CA].[San Francisco]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[USA].[CA].[Los Angeles]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[Mexico]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[Mexico].[DF]\" access=\"none\"/>\n"
+ " <MemberGrant member=\"[Store].[Canada]\" access=\"none\"/>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>";
final TestContext partialRollupTestContext =
TestContext.instance().create(
null, null, null, null, null, test_1201_Roles)
.withRole("Role1");
final TestContext fullRollupTestContext =
TestContext.instance().create(
null, null, null, null, null, test_1201_Roles)
.withRole("Role2");
// Must return only 2 [USA].[CA] stores
partialRollupTestContext.assertQueryReturns(
"select NON EMPTY {[Measures].[Unit Sales]} ON COLUMNS, \n"
+ " Filter( [Store].[USA].[CA].children,"
+ " [Measures].[Unit Sales]>0) ON ROWS \n"
+ "from [Sales] \n"
+ "where ([Time].[1997].[Q1].[2])",
"Axis #0:\n"
+ "{[Time].[1997].[Q1].[2]}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Store].[USA].[CA].[Los Angeles]}\n"
+ "{[Store].[USA].[CA].[San Francisco]}\n"
+ "Row #0: 2,614\n"
+ "Row #1: 187\n");
// Must return only 2 [USA].[CA] stores
partialRollupTestContext.assertQueryReturns(
"select NON EMPTY {[Measures].[Unit Sales]} ON COLUMNS, \n"
+ " TopCount( [Store].[USA].[CA].children, 20,"
+ " [Measures].[Unit Sales]) ON ROWS \n"
+ "from [Sales] \n"
+ "where ([Time].[1997].[Q1].[2])",
"Axis #0:\n"
+ "{[Time].[1997].[Q1].[2]}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Store].[USA].[CA].[Los Angeles]}\n"
+ "{[Store].[USA].[CA].[San Francisco]}\n"
+ "Row #0: 2,614\n"
+ "Row #1: 187\n");
// Partial Rollup: [USA].[CA] rolls up only up to 2.801
partialRollupTestContext.assertQueryReturns(
"select NON EMPTY {[Measures].[Unit Sales]} ON COLUMNS, \n"
+ " Filter( [Store].[Store State].Members,"
+ " [Measures].[Unit Sales]>4000) ON ROWS \n"
+ "from [Sales] \n"
+ "where ([Time].[1997].[Q1].[2])",
"Axis #0:\n"
+ "{[Time].[1997].[Q1].[2]}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Store].[USA].[OR]}\n"
+ "{[Store].[USA].[WA]}\n"
+ "Row #0: 4,617\n"
+ "Row #1: 10,319\n");
// Full Rollup: [USA].[CA] rolls up to 6.021
fullRollupTestContext.assertQueryReturns(
"select NON EMPTY {[Measures].[Unit Sales]} ON COLUMNS, \n"
+ " Filter( [Store].[Store State].Members,"
+ " [Measures].[Unit Sales]>4000) ON ROWS \n"
+ "from [Sales] \n"
+ "where ([Time].[1997].[Q1].[2])",
"Axis #0:\n"
+ "{[Time].[1997].[Q1].[2]}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Store].[USA].[CA]}\n"
+ "{[Store].[USA].[OR]}\n"
+ "{[Store].[USA].[WA]}\n"
+ "Row #0: 6,021\n"
+ "Row #1: 4,617\n"
+ "Row #2: 10,319\n");
}
public void testBugMondrian_1201_CacheAwareOfRoleAccessControl() {
String test_1201_Roles =
"<Role name=\"Role1\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Store]\" access=\"custom\" rollupPolicy=\"partial\">\n"
+ " <MemberGrant member=\"[Store].[USA].[WA]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[USA].[OR]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[USA].[CA].[San Francisco]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[USA].[CA].[Los Angeles]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[Mexico]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[Mexico].[DF]\" access=\"none\"/>\n"
+ " <MemberGrant member=\"[Store].[Canada]\" access=\"none\"/>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>\n"
+ "<Role name=\"Role2\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Store]\" access=\"custom\" rollupPolicy=\"partial\">\n"
+ " <MemberGrant member=\"[Store].[USA].[WA]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[USA].[OR]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[USA].[CA].[San Francisco]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[Mexico]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[Mexico].[DF]\" access=\"none\"/>\n"
+ " <MemberGrant member=\"[Store].[Canada]\" access=\"none\"/>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>";
final TestContext partialRollupTestContext1 =
TestContext.instance().create(
null, null, null, null, null, test_1201_Roles)
.withRole("Role1");
final TestContext partialRollupTestContext2 =
TestContext.instance().create(
null, null, null, null, null, test_1201_Roles)
.withRole("Role2");
// Put query into cache
partialRollupTestContext1.assertQueryReturns(
"select NON EMPTY {[Measures].[Unit Sales]} ON COLUMNS, \n"
+ " Filter( [Store].[USA].[CA].children,"
+ " [Measures].[Unit Sales]>0) ON ROWS \n"
+ "from [Sales] \n"
+ "where ([Time].[1997].[Q1].[2])",
"Axis #0:\n"
+ "{[Time].[1997].[Q1].[2]}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Store].[USA].[CA].[Los Angeles]}\n"
+ "{[Store].[USA].[CA].[San Francisco]}\n"
+ "Row #0: 2,614\n"
+ "Row #1: 187\n");
// Run same query using another role with different access controls
partialRollupTestContext2.assertQueryReturns(
"select NON EMPTY {[Measures].[Unit Sales]} ON COLUMNS, \n"
+ " TopCount( [Store].[USA].[CA].children, 20,"
+ " [Measures].[Unit Sales]) ON ROWS \n"
+ "from [Sales] \n"
+ "where ([Time].[1997].[Q1].[2])",
"Axis #0:\n"
+ "{[Time].[1997].[Q1].[2]}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Store].[USA].[CA].[San Francisco]}\n"
+ "Row #0: 187\n");
}
/**
* Tests for Mondrian BUG 1127 - Native Top Count was not taking into
* account user roles
*/
public void testBugMondrian1127OneSlicerOnly() {
final TestContext testContext = getRestrictedTestContext();
testContext.assertQueryReturns(
"select NON EMPTY {[Measures].[Unit Sales]} ON COLUMNS, \n"
+ " TopCount([Store].[USA].[CA].Children, 10,"
+ " [Measures].[Unit Sales]) ON ROWS \n"
+ "from [Sales] \n"
+ "where ([Time].[1997].[Q1].[2])",
"Axis #0:\n"
+ "{[Time].[1997].[Q1].[2]}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Store].[USA].[CA].[Los Angeles]}\n"
+ "{[Store].[USA].[CA].[San Francisco]}\n"
+ "Row #0: 2,614\n"
+ "Row #1: 187\n");
final TestContext unrestrictedTestContext = getTestContext();
unrestrictedTestContext.assertQueryReturns(
"select NON EMPTY {[Measures].[Unit Sales]} ON COLUMNS, \n"
+ " TopCount([Store].[USA].[CA].Children, 10, "
+ " [Measures].[Unit Sales]) ON ROWS \n"
+ "from [Sales] \n"
+ "where ([Time].[1997].[Q1].[2])",
"Axis #0:\n"
+ "{[Time].[1997].[Q1].[2]}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Store].[USA].[CA].[Los Angeles]}\n"
+ "{[Store].[USA].[CA].[San Diego]}\n"
+ "{[Store].[USA].[CA].[Beverly Hills]}\n"
+ "{[Store].[USA].[CA].[San Francisco]}\n"
+ "Row #0: 2,614\n"
+ "Row #1: 1,879\n"
+ "Row #2: 1,341\n"
+ "Row #3: 187\n");
}
public void testBugMondrian1127MultipleSlicers() {
final TestContext testContext = getRestrictedTestContext();
testContext.assertQueryReturns(
"select NON EMPTY {[Measures].[Unit Sales]} ON COLUMNS, \n"
+ " TopCount([Store].[USA].[CA].Children, 10,"
+ " [Measures].[Unit Sales]) ON ROWS \n"
+ "from [Sales] \n"
+ "where ([Time].[1997].[Q1].[2] : [Time].[1997].[Q1].[3])",
"Axis #0:\n"
+ "{[Time].[1997].[Q1].[2]}\n"
+ "{[Time].[1997].[Q1].[3]}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Store].[USA].[CA].[Los Angeles]}\n"
+ "{[Store].[USA].[CA].[San Francisco]}\n"
+ "Row #0: 4,497\n"
+ "Row #1: 337\n");
final TestContext unrestrictedTestContext = getTestContext();
unrestrictedTestContext.assertQueryReturns(
"select NON EMPTY {[Measures].[Unit Sales]} ON COLUMNS, \n"
+ " TopCount([Store].[USA].[CA].Children, 10, "
+ " [Measures].[Unit Sales]) ON ROWS \n"
+ "from [Sales] \n"
+ "where ([Time].[1997].[Q1].[2] : [Time].[1997].[Q1].[3])",
"Axis #0:\n"
+ "{[Time].[1997].[Q1].[2]}\n"
+ "{[Time].[1997].[Q1].[3]}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Store].[USA].[CA].[Los Angeles]}\n"
+ "{[Store].[USA].[CA].[San Diego]}\n"
+ "{[Store].[USA].[CA].[Beverly Hills]}\n"
+ "{[Store].[USA].[CA].[San Francisco]}\n"
+ "Row #0: 4,497\n"
+ "Row #1: 4,094\n"
+ "Row #2: 2,585\n"
+ "Row #3: 337\n");
}
/**
* Tests that we only aggregate over SF, LA, even when called from
* functions.
*/
public void testGrantHierarchy9() {
// Analysis services doesn't allow aggregation within calculated
// measures, so use the following query to generate the results:
//
// with member [Store].[SF LA] as
// 'Aggregate({[USA].[CA].[San Francisco], [Store].[USA].[CA].[Los
// Angeles]})'
// select {[Measures].[Unit Sales]} on columns,
// {[Gender].children} on rows
// from Sales
// where ([Marital Status].[S], [Store].[SF LA])
final TestContext tc = new RestrictedTestContext();
tc.assertQueryReturns(
"with member [Measures].[California Unit Sales] as "
+ " 'Aggregate({[Store].[USA].[CA].children}, [Measures].[Unit Sales])'\n"
+ "select {[Measures].[California Unit Sales]} on columns,\n"
+ " {[Gender].children} on rows\n"
+ "from Sales\n"
+ "where ([Marital Status].[S])",
"Axis #0:\n"
+ "{[Marital Status].[S]}\n"
+ "Axis #1:\n"
+ "{[Measures].[California Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Gender].[F]}\n"
+ "{[Gender].[M]}\n"
+ "Row #0: 6,636\n"
+ "Row #1: 7,329\n");
}
public void testGrantHierarchyA() {
final TestContext tc = new RestrictedTestContext();
// assert: totals for USA include missing cells
tc.assertQueryReturns(
"select {[Unit Sales]} on columns,\n"
+ "{[Store].[USA], [Store].[USA].children} on rows\n"
+ "from [Sales]",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Store].[USA]}\n"
+ "{[Store].[USA].[CA]}\n"
+ "Row #0: 266,773\n"
+ "Row #1: 74,748\n");
}
public void _testSharedObjectsInGrantMappingsBug() {
final TestContext testContext = new TestContext() {
public Connection getConnection() {
boolean mustGet = true;
Connection connection = super.getConnection();
Schema schema = connection.getSchema();
Cube salesCube = schema.lookupCube("Sales", mustGet);
Cube warehouseCube = schema.lookupCube("Warehouse", mustGet);
Hierarchy measuresInSales = salesCube.lookupHierarchy(
new Id.NameSegment("Measures", Id.Quoting.UNQUOTED), false);
Hierarchy storeInWarehouse = warehouseCube.lookupHierarchy(
new Id.NameSegment("Store", Id.Quoting.UNQUOTED), false);
RoleImpl role = new RoleImpl();
role.grant(schema, Access.NONE);
role.grant(salesCube, Access.NONE);
// For using hierarchy Measures in #assertExprThrows
Role.RollupPolicy rollupPolicy = Role.RollupPolicy.FULL;
role.grant(
measuresInSales, Access.ALL, null, null, rollupPolicy);
role.grant(warehouseCube, Access.NONE);
role.grant(storeInWarehouse.getDimension(), Access.ALL);
role.makeImmutable();
connection.setRole(role);
return connection;
}
};
// Looking up default member on dimension Store in cube Sales should
// fail.
testContext.assertExprThrows(
"[Store].DefaultMember",
"'[Store]' not found in cube 'Sales'");
}
public void testNoAccessToCube() {
final TestContext tc = new RestrictedTestContext();
tc.assertQueryThrows("select from [HR]", "MDX cube 'HR' not found");
}
private Connection getRestrictedConnection() {
return getRestrictedConnection(true);
}
/**
* Returns a connection with limited access to the schema.
*
* @param restrictCustomers true to restrict access to the customers
* dimension. This will change the defaultMember of the dimension,
* all cell values will be null because there are no sales data
* for Canada
*
* @return restricted connection
*/
private Connection getRestrictedConnection(boolean restrictCustomers) {
Connection connection =
getTestContext().withSchemaPool(false).getConnection();
RoleImpl role = new RoleImpl();
Schema schema = connection.getSchema();
final boolean fail = true;
Cube salesCube = schema.lookupCube("Sales", fail);
final SchemaReader schemaReader =
salesCube.getSchemaReader(null).withLocus();
Hierarchy storeHierarchy = salesCube.lookupHierarchy(
new Id.NameSegment("Store", Id.Quoting.UNQUOTED), false);
role.grant(schema, Access.ALL_DIMENSIONS);
role.grant(salesCube, Access.ALL);
Level nationLevel =
Util.lookupHierarchyLevel(storeHierarchy, "Store Country");
Role.RollupPolicy rollupPolicy = Role.RollupPolicy.FULL;
role.grant(
storeHierarchy, Access.CUSTOM, nationLevel, null, rollupPolicy);
role.grant(
schemaReader.getMemberByUniqueName(
Util.parseIdentifier("[Store].[All Stores].[USA].[OR]"), fail),
Access.ALL);
role.grant(
schemaReader.getMemberByUniqueName(
Util.parseIdentifier("[Store].[All Stores].[USA]"), fail),
Access.CUSTOM);
role.grant(
schemaReader.getMemberByUniqueName(
Util.parseIdentifier(
"[Store].[All Stores].[USA].[CA].[San Francisco]"), fail),
Access.ALL);
role.grant(
schemaReader.getMemberByUniqueName(
Util.parseIdentifier(
"[Store].[All Stores].[USA].[CA].[Los Angeles]"), fail),
Access.ALL);
role.grant(
schemaReader.getMemberByUniqueName(
Util.parseIdentifier(
"[Store].[All Stores].[Mexico]"), fail),
Access.ALL);
role.grant(
schemaReader.getMemberByUniqueName(
Util.parseIdentifier(
"[Store].[All Stores].[Mexico].[DF]"), fail),
Access.NONE);
role.grant(
schemaReader.getMemberByUniqueName(
Util.parseIdentifier(
"[Store].[All Stores].[Canada]"), fail),
Access.NONE);
if (restrictCustomers) {
Hierarchy customersHierarchy =
salesCube.lookupHierarchy(
new Id.NameSegment("Customers", Id.Quoting.UNQUOTED),
false);
Level stateProvinceLevel =
Util.lookupHierarchyLevel(customersHierarchy, "State Province");
Level customersCityLevel =
Util.lookupHierarchyLevel(customersHierarchy, "City");
role.grant(
customersHierarchy,
Access.CUSTOM,
stateProvinceLevel,
customersCityLevel,
rollupPolicy);
}
// No access to HR cube.
Cube hrCube = schema.lookupCube("HR", fail);
role.grant(hrCube, Access.NONE);
role.makeImmutable();
connection.setRole(role);
return connection;
}
// todo: test that access to restricted measure fails
// (will not work -- have not fixed Cube.getMeasures)
private class RestrictedTestContext extends TestContext {
public synchronized Connection getConnection() {
return getRestrictedConnection(false);
}
}
/**
* Test context where the [Store] hierarchy has restricted access
* and cell values are rolled up with 'partial' policy.
*/
private TestContext getRollupTestContext() {
return getTestContext().create(
null, null, null, null, null,
"<Role name=\"Role1\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"custom\">\n"
+ " <DimensionGrant dimension=\"[Measures]\" access=\"all\"/>\n"
+ " <DimensionGrant dimension=\"[Gender]\" access=\"all\"/>\n"
+ " <HierarchyGrant hierarchy=\"[Store]\" access=\"custom\" rollupPolicy=\"partial\">\n"
+ " <MemberGrant member=\"[Store].[USA]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[USA].[CA]\" access=\"none\"/>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>")
.withRole("Role1");
}
/**
* Basic test of partial rollup policy. [USA] = [OR] + [WA], not
* the usual [CA] + [OR] + [WA].
*/
public void testRollupPolicyBasic() {
getRollupTestContext().assertQueryReturns(
"select {[Store].[USA], [Store].[USA].Children} on 0\n"
+ "from [Sales]",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Store].[USA]}\n"
+ "{[Store].[USA].[OR]}\n"
+ "{[Store].[USA].[WA]}\n"
+ "Row #0: 192,025\n"
+ "Row #0: 67,659\n"
+ "Row #0: 124,366\n");
}
/**
* The total for [Store].[All Stores] is similarly reduced. All
* children of [All Stores] are visible, but one grandchild is not.
* Normally the total is 266,773.
*/
public void testRollupPolicyAll() {
getRollupTestContext().assertExprReturns(
"([Store].[All Stores])",
"192,025");
}
/**
* Access [Store].[All Stores] implicitly as it is the default member
* of the [Stores] hierarchy.
*/
public void testRollupPolicyAllAsDefault() {
getRollupTestContext().assertExprReturns(
"([Store])",
"192,025");
}
/**
* Access [Store].[All Stores] via the Parent relationship (to check
* that this doesn't circumvent access control).
*/
public void testRollupPolicyAllAsParent() {
getRollupTestContext().assertExprReturns(
"([Store].[USA].Parent)",
"192,025");
}
/**
* Tests that an access-controlled dimension affects results even if not
* used in the query. Unit test for
* <a href="http://jira.pentaho.com/browse/mondrian-1283">MONDRIAN-1283,
* "Mondrian doesn't restrict dimension members when dimension isn't
* included"</a>.
*/
public void testUnusedAccessControlledDimension() {
getRollupTestContext().assertQueryReturns(
"select [Gender].Children on 0 from [Sales]",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Gender].[F]}\n"
+ "{[Gender].[M]}\n"
+ "Row #0: 94,799\n"
+ "Row #0: 97,226\n");
getTestContext().assertQueryReturns(
"select [Gender].Children on 0 from [Sales]",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Gender].[F]}\n"
+ "{[Gender].[M]}\n"
+ "Row #0: 131,558\n"
+ "Row #0: 135,215\n");
}
/**
* Tests that members below bottom level are regarded as visible.
*/
public void testRollupBottomLevel() {
rollupPolicyBottom(
Role.RollupPolicy.FULL, "74,748", "36,759", "266,773");
rollupPolicyBottom(
Role.RollupPolicy.PARTIAL, "72,739", "35,775", "264,764");
rollupPolicyBottom(Role.RollupPolicy.HIDDEN, "", "", "");
}
private void rollupPolicyBottom(
Role.RollupPolicy rollupPolicy,
String v1,
String v2,
String v3)
{
final TestContext testContext =
TestContext.instance().create(
null, null, null, null, null,
"<Role name=\"Role1\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Customers]\" access=\"custom\" rollupPolicy=\""
+ rollupPolicy
+ "\" bottomLevel=\"[Customers].[City]\">\n"
+ " <MemberGrant member=\"[Customers].[USA]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Customers].[USA].[CA]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Customers].[USA].[CA].[Los Angeles]\" access=\"none\"/>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>")
.withRole("Role1");
// All of the children of [San Francisco] are invisible, because [City]
// is the bottom level, but that shouldn't affect the total.
testContext.assertExprReturns(
"([Customers].[USA].[CA].[San Francisco])", "88");
testContext.assertExprThrows(
"([Customers].[USA].[CA].[Los Angeles])",
"MDX object '[Customers].[USA].[CA].[Los Angeles]' not found in cube 'Sales'");
testContext.assertExprReturns("([Customers].[USA].[CA])", v1);
testContext.assertExprReturns(
"([Customers].[USA].[CA], [Gender].[F])", v2);
testContext.assertExprReturns("([Customers].[USA])", v3);
checkQuery(
testContext,
"select [Customers].Children on 0, "
+ "[Gender].Members on 1 from [Sales]");
}
/**
* Calls various {@link SchemaReader} methods on the members returned in
* a result set.
*
* @param testContext Test context
* @param mdx MDX query
*/
private void checkQuery(TestContext testContext, String mdx) {
Result result = testContext.executeQuery(mdx);
final SchemaReader schemaReader =
testContext.getConnection().getSchemaReader().withLocus();
for (Axis axis : result.getAxes()) {
for (Position position : axis.getPositions()) {
for (Member member : position) {
final Member accessControlledParent =
schemaReader.getMemberParent(member);
if (member.getParentMember() == null) {
assertNull(accessControlledParent);
}
final List<Member> accessControlledChildren =
schemaReader.getMemberChildren(member);
assertNotNull(accessControlledChildren);
}
}
}
}
/**
* Tests that a bad value for the rollupPolicy attribute gives the
* appropriate error.
*/
public void testRollupPolicyNegative() {
final TestContext testContext =
TestContext.instance().create(
null, null, null, null, null,
"<Role name=\"Role1\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Customers]\" access=\"custom\" rollupPolicy=\"bad\" bottomLevel=\"[Customers].[City]\">\n"
+ " <MemberGrant member=\"[Customers].[USA]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Customers].[USA].[CA].[Los Angeles]\" access=\"none\"/>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>")
.withRole("Role1");
testContext.assertQueryThrows(
"select from [Sales]",
"Illegal rollupPolicy value 'bad'");
}
/**
* Tests where all children are visible but a grandchild is not.
*/
public void testRollupPolicyGreatGrandchildInvisible() {
rollupPolicyGreatGrandchildInvisible(
Role.RollupPolicy.FULL, "266,773", "74,748");
rollupPolicyGreatGrandchildInvisible(
Role.RollupPolicy.PARTIAL, "266,767", "74,742");
rollupPolicyGreatGrandchildInvisible(
Role.RollupPolicy.HIDDEN, "", "");
}
private void rollupPolicyGreatGrandchildInvisible(
Role.RollupPolicy policy,
String v1,
String v2)
{
final TestContext testContext =
TestContext.instance().create(
null, null, null, null, null,
"<Role name=\"Role1\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Customers]\" access=\"custom\" rollupPolicy=\""
+ policy
+ "\">\n"
+ " <MemberGrant member=\"[Customers].[USA]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Customers].[USA].[CA].[San Francisco].[Gladys Evans]\" access=\"none\"/>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>")
.withRole("Role1");
testContext.assertExprReturns("[Measures].[Unit Sales]", v1);
testContext.assertExprReturns(
"([Measures].[Unit Sales], [Customers].[USA])",
v1);
testContext.assertExprReturns(
"([Measures].[Unit Sales], [Customers].[USA].[CA])",
v2);
}
/**
* Tests where two hierarchies are simultaneously access-controlled.
*/
public void testRollupPolicySimultaneous() {
// note that v2 is different for full vs partial, v3 is the same
rollupPolicySimultaneous(
Role.RollupPolicy.FULL, "266,773", "74,748", "25,635");
rollupPolicySimultaneous(
Role.RollupPolicy.PARTIAL, "72,631", "72,631", "25,635");
rollupPolicySimultaneous(
Role.RollupPolicy.HIDDEN, "", "", "");
}
private void rollupPolicySimultaneous(
Role.RollupPolicy policy,
String v1,
String v2,
String v3)
{
final TestContext testContext =
TestContext.instance().create(
null, null, null, null, null,
"<Role name=\"Role1\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Customers]\" access=\"custom\" rollupPolicy=\""
+ policy
+ "\">\n"
+ " <MemberGrant member=\"[Customers].[USA]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Customers].[USA].[CA].[San Francisco].[Gladys Evans]\" access=\"none\"/>\n"
+ " </HierarchyGrant>\n"
+ " <HierarchyGrant hierarchy=\"[Store]\" access=\"custom\" rollupPolicy=\""
+ policy
+ "\">\n"
+ " <MemberGrant member=\"[Store].[USA].[CA]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[USA].[CA].[San Francisco].[Store 14]\" access=\"none\"/>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>")
.withRole("Role1");
testContext.assertExprReturns("[Measures].[Unit Sales]", v1);
testContext.assertExprReturns(
"([Measures].[Unit Sales], [Customers].[USA])",
v1);
testContext.assertExprReturns(
"([Measures].[Unit Sales], [Customers].[USA].[CA])",
v2);
testContext.assertExprReturns(
"([Measures].[Unit Sales], "
+ "[Customers].[USA].[CA], [Store].[USA].[CA])",
v2);
testContext.assertExprReturns(
"([Measures].[Unit Sales], "
+ "[Customers].[USA].[CA], "
+ "[Store].[USA].[CA].[San Diego])",
v3);
}
// todo: performance test where 1 of 1000 children is not visible
public void testUnionRole() {
final TestContext testContext =
TestContext.instance().create(
null, null, null, null, null,
"<Role name=\"Role1\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Customers]\" access=\"custom\" rollupPolicy=\"Partial\">\n"
+ " <MemberGrant member=\"[Customers].[USA].[CA]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Customers].[USA].[CA].[San Francisco].[Gladys Evans]\" access=\"none\"/>\n"
+ " </HierarchyGrant>\n"
+ " <HierarchyGrant hierarchy=\"[Promotion Media]\" access=\"all\"/>\n"
+ " <HierarchyGrant hierarchy=\"[Marital Status]\" access=\"none\"/>\n"
+ " <HierarchyGrant hierarchy=\"[Gender]\" access=\"none\"/>\n"
+ " <HierarchyGrant hierarchy=\"[Store]\" access=\"custom\" rollupPolicy=\"Partial\" topLevel=\"[Store].[Store State]\"/>\n"
+ " </CubeGrant>\n"
+ " <CubeGrant cube=\"Warehouse\" access=\"all\"/>\n"
+ " </SchemaGrant>\n"
+ "</Role>\n"
+ "<Role name=\"Role2\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"none\">\n"
+ " <HierarchyGrant hierarchy=\"[Customers]\" access=\"custom\" rollupPolicy=\"Hidden\">\n"
+ " <MemberGrant member=\"[Customers].[USA]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Customers].[USA].[CA]\" access=\"none\"/>\n"
+ " <MemberGrant member=\"[Customers].[USA].[OR]\" access=\"none\"/>\n"
+ " <MemberGrant member=\"[Customers].[USA].[OR].[Portland]\" access=\"all\"/>\n"
+ " </HierarchyGrant>\n"
+ " <HierarchyGrant hierarchy=\"[Store]\" access=\"all\" rollupPolicy=\"Hidden\"/>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>\n");
Connection connection;
try {
connection = testContext.withRole("Role3,Role2").getConnection();
fail("expected exception, got " + connection);
} catch (RuntimeException e) {
final String message = e.getMessage();
assertTrue(message, message.indexOf("Role 'Role3' not found") >= 0);
}
try {
connection = testContext.withRole("Role1,Role3").getConnection();
fail("expected exception, got " + connection);
} catch (RuntimeException e) {
final String message = e.getMessage();
assertTrue(message, message.indexOf("Role 'Role3' not found") >= 0);
}
connection = testContext.withRole("Role1,Role2").getConnection();
// Cube access:
// Both can see [Sales]
// Role1 only see [Warehouse]
// Neither can see [Warehouse and Sales]
assertCubeAccess(connection, Access.ALL, "Sales");
assertCubeAccess(connection, Access.ALL, "Warehouse");
assertCubeAccess(connection, Access.NONE, "Warehouse and Sales");
// Hierarchy access:
// Both can see [Customers] with Custom access
// Both can see [Store], Role1 with Custom access, Role2 with All access
// Role1 can see [Promotion Media], Role2 cannot
// Neither can see [Marital Status]
assertHierarchyAccess(
connection, Access.CUSTOM, "Sales", "[Customers]");
assertHierarchyAccess(
connection, Access.ALL, "Sales", "[Store]");
assertHierarchyAccess(
connection, Access.ALL, "Sales", "[Promotion Media]");
assertHierarchyAccess(
connection, Access.NONE, "Sales", "[Marital Status]");
// Rollup policy is the greater of Role1's partian and Role2's hidden
final Role.HierarchyAccess hierarchyAccess =
getHierarchyAccess(connection, "Sales", "[Store]");
assertEquals(
Role.RollupPolicy.PARTIAL,
hierarchyAccess.getRollupPolicy());
// One of the roles is restricting the levels, so we
// expect only the levels from 2 to 4 to be available.
assertEquals(2, hierarchyAccess.getTopLevelDepth());
assertEquals(4, hierarchyAccess.getBottomLevelDepth());
// Member access:
// both can see [USA]
assertMemberAccess(connection, Access.CUSTOM, "[Customers].[USA]");
// Role1 can see [CA], Role2 cannot
assertMemberAccess(connection, Access.CUSTOM, "[Customers].[USA].[CA]");
// Role1 cannoy see [USA].[OR].[Portland], Role2 can
assertMemberAccess(
connection, Access.ALL, "[Customers].[USA].[OR].[Portland]");
// Role1 cannot see [USA].[OR], Role2 can see it by virtue of [Portland]
assertMemberAccess(
connection, Access.CUSTOM, "[Customers].[USA].[OR]");
// Neither can see Beaverton
assertMemberAccess(
connection, Access.NONE, "[Customers].[USA].[OR].[Beaverton]");
// Rollup policy
String mdx = "select Hierarchize(\n"
+ "{[Customers].[USA].Children,\n"
+ " [Customers].[USA].[OR].Children}) on 0\n"
+ "from [Sales]";
testContext.assertQueryReturns(
mdx,
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Customers].[USA].[CA]}\n"
+ "{[Customers].[USA].[OR]}\n"
+ "{[Customers].[USA].[OR].[Albany]}\n"
+ "{[Customers].[USA].[OR].[Beaverton]}\n"
+ "{[Customers].[USA].[OR].[Corvallis]}\n"
+ "{[Customers].[USA].[OR].[Lake Oswego]}\n"
+ "{[Customers].[USA].[OR].[Lebanon]}\n"
+ "{[Customers].[USA].[OR].[Milwaukie]}\n"
+ "{[Customers].[USA].[OR].[Oregon City]}\n"
+ "{[Customers].[USA].[OR].[Portland]}\n"
+ "{[Customers].[USA].[OR].[Salem]}\n"
+ "{[Customers].[USA].[OR].[W. Linn]}\n"
+ "{[Customers].[USA].[OR].[Woodburn]}\n"
+ "{[Customers].[USA].[WA]}\n"
+ "Row #0: 74,748\n"
+ "Row #0: 67,659\n"
+ "Row #0: 6,806\n"
+ "Row #0: 4,558\n"
+ "Row #0: 9,539\n"
+ "Row #0: 4,910\n"
+ "Row #0: 9,596\n"
+ "Row #0: 5,145\n"
+ "Row #0: 3,708\n"
+ "Row #0: 3,583\n"
+ "Row #0: 7,678\n"
+ "Row #0: 4,175\n"
+ "Row #0: 7,961\n"
+ "Row #0: 124,366\n");
testContext.withRole("Role1").assertQueryThrows(
mdx,
"MDX object '[Customers].[USA].[OR]' not found in cube 'Sales'");
testContext.withRole("Role2").assertQueryThrows(
mdx,
"MDX cube 'Sales' not found");
// Compared to above:
// a. cities in Oregon are missing besides Portland
// b. total for Oregon = total for Portland
testContext.withRole("Role1,Role2").assertQueryReturns(
mdx,
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Customers].[USA].[CA]}\n"
+ "{[Customers].[USA].[OR]}\n"
+ "{[Customers].[USA].[OR].[Portland]}\n"
+ "{[Customers].[USA].[WA]}\n"
+ "Row #0: 74,742\n"
+ "Row #0: 3,583\n"
+ "Row #0: 3,583\n"
+ "Row #0: 124,366\n");
checkQuery(testContext.withRole("Role1,Role2"), mdx);
}
/**
* This is a test for
* <a href="http://jira.pentaho.com/browse/MONDRIAN-1384">MONDRIAN-1384</a>
*/
public void testUnionRoleHasInaccessibleDescendants() throws Exception {
final TestContext testContext =
TestContext.instance().create(
null, null, null, null, null,
"<Role name=\"Role1\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " </SchemaGrant>\n"
+ "</Role>\n"
+ "<Role name=\"Role2\">\n"
+ " <SchemaGrant access=\"all\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Customers]\" access=\"custom\" rollupPolicy=\"partial\">\n"
+ " <MemberGrant member=\"[Customers].[USA].[OR]\" access=\"all\"/>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>\n");
final Connection connection =
testContext.withRole("Role1,Role2").getConnection();
final Cube cube =
connection.getSchema()
.lookupCube("Sales", true);
final HierarchyAccess accessDetails =
connection.getRole().getAccessDetails(
cube.lookupHierarchy(
new Id.NameSegment("Customers", Id.Quoting.UNQUOTED),
false));
final SchemaReader scr =
cube.getSchemaReader(null).withLocus();
assertEquals(
true,
accessDetails.hasInaccessibleDescendants(
scr.getMemberByUniqueName(
Util.parseIdentifier("[Customers].[USA]"),
true)));
}
/**
* This is a test for
* <a href="http://jira.pentaho.com/browse/MONDRIAN-1168">MONDRIAN-1168</a>
* Union of roles would sometimes return levels which should be restricted
* by ACL.
*/
public void testRoleUnionWithLevelRestrictions() throws Exception {
final TestContext testContext =
TestContext.instance().create(
null, null, null, null, null,
"<Role name=\"Role1\">\n"
+ " <SchemaGrant access=\"all\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Customers]\" access=\"custom\" rollupPolicy=\"Partial\" topLevel=\"[Customers].[State Province]\" bottomLevel=\"[Customers].[State Province]\">\n"
+ " <MemberGrant member=\"[Customers].[USA].[CA]\" access=\"all\"/>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>\n"
+ "<Role name=\"Role2\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " </SchemaGrant>\n"
+ "</Role>\n").withRole("Role1,Role2");
testContext.assertQueryReturns(
"select {[Customers].[State Province].Members} on columns from [Sales]",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Customers].[USA].[CA]}\n"
+ "Row #0: 74,748\n");
testContext.assertQueryReturns(
"select {[Customers].[Country].Members} on columns from [Sales]",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n");
SchemaReader reader =
testContext.getConnection().getSchemaReader().withLocus();
Cube cube = null;
for (Cube c : reader.getCubes()) {
if (c.getName().equals("Sales")) {
cube = c;
}
}
assertNotNull(cube);
reader =
cube.getSchemaReader(testContext.getConnection().getRole());
final List<Dimension> dimensions =
reader.getCubeDimensions(cube);
Dimension dimension = null;
for (Dimension dim : dimensions) {
if (dim.getName().equals("Customers")) {
dimension = dim;
}
}
assertNotNull(dimension);
Hierarchy hierarchy =
reader.getDimensionHierarchies(dimension).get(0);
assertNotNull(hierarchy);
final List<Level> levels =
reader.getHierarchyLevels(hierarchy);
// Do some tests
assertEquals(1, levels.size());
assertEquals(
2,
testContext.getConnection()
.getRole().getAccessDetails(hierarchy)
.getBottomLevelDepth());
assertEquals(
2,
testContext.getConnection()
.getRole().getAccessDetails(hierarchy)
.getTopLevelDepth());
}
/**
* Test to verify that non empty crossjoins enforce role access.
* Testcase for bug <a href="http://jira.pentaho.com/browse/MONDRIAN-369">
* MONDRIAN-369, "Non Empty Crossjoin fails to enforce role access".
*/
public void testNonEmptyAccess() {
final TestContext testContext =
TestContext.instance().create(
null, null, null, null, null,
"<Role name=\"Role1\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Product]\" access=\"custom\">\n"
+ " <MemberGrant member=\"[Product].[Drink]\" access=\"all\"/>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>")
.withRole("Role1");
// regular crossjoin returns the correct list of product children
final String expected =
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Gender].[All Gender], [Product].[Drink]}\n"
+ "Row #0: 24,597\n";
final String mdx =
"select {[Measures].[Unit Sales]} ON COLUMNS, "
+ " Crossjoin({[Gender].[All Gender]}, "
+ "[Product].Children) ON ROWS "
+ "from [Sales]";
testContext.assertQueryReturns(mdx, expected);
checkQuery(testContext, mdx);
// with bug MONDRIAN-397, non empty crossjoin did not return the correct
// list
final String mdx2 =
"select {[Measures].[Unit Sales]} ON COLUMNS, "
+ "NON EMPTY Crossjoin({[Gender].[All Gender]}, "
+ "[Product].[All Products].Children) ON ROWS "
+ "from [Sales]";
testContext.assertQueryReturns(mdx2, expected);
checkQuery(testContext, mdx2);
}
public void testNonEmptyAccessLevelMembers() {
final TestContext testContext = TestContext.instance().create(
null,
null,
null,
null,
null,
"<Role name=\"Role1\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Product]\" access=\"custom\">\n"
+ " <MemberGrant member=\"[Product].[Drink]\" access=\"all\"/>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>").withRole("Role1");
// <Level>.members inside regular crossjoin returns the correct list of
// product members
final String expected =
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Gender].[All Gender], [Product].[Drink]}\n"
+ "Row #0: 24,597\n";
final String mdx =
"select {[Measures].[Unit Sales]} ON COLUMNS, "
+ " Crossjoin({[Gender].[All Gender]}, "
+ "[Product].[Product Family].Members) ON ROWS "
+ "from [Sales]";
testContext.assertQueryReturns(mdx, expected);
checkQuery(testContext, mdx);
// with bug MONDRIAN-397, <Level>.members inside non empty crossjoin did
// not return the correct list
final String mdx2 =
"select {[Measures].[Unit Sales]} ON COLUMNS, "
+ "NON EMPTY Crossjoin({[Gender].[All Gender]}, "
+ "[Product].[Product Family].Members) ON ROWS "
+ "from [Sales]";
testContext.assertQueryReturns(mdx2, expected);
checkQuery(testContext, mdx2);
}
/**
* Testcase for bug <a href="http://jira.pentaho.com/browse/MONDRIAN-406">
* MONDRIAN-406, "Rollup policy doesn't work for members
* that are implicitly visible"</a>.
*/
public void testGoodman() {
final String query = "select {[Measures].[Unit Sales]} ON COLUMNS,\n"
+ "Hierarchize(Union(Union(Union({[Store].[All Stores]},"
+ " [Store].[All Stores].Children),"
+ " [Store].[All Stores].[USA].Children),"
+ " [Store].[All Stores].[USA].[CA].Children)) ON ROWS\n"
+ "from [Sales]\n"
+ "where [Time].[1997]";
// Note that total for [Store].[All Stores] and [Store].[USA] is sum
// of visible children [Store].[CA] and [Store].[OR].[Portland].
final TestContext testContext =
goodmanContext(Role.RollupPolicy.PARTIAL);
testContext.assertQueryReturns(
query,
"Axis #0:\n"
+ "{[Time].[1997]}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Store].[All Stores]}\n"
+ "{[Store].[USA]}\n"
+ "{[Store].[USA].[CA]}\n"
+ "{[Store].[USA].[CA].[Alameda]}\n"
+ "{[Store].[USA].[CA].[Beverly Hills]}\n"
+ "{[Store].[USA].[CA].[Los Angeles]}\n"
+ "{[Store].[USA].[CA].[San Diego]}\n"
+ "{[Store].[USA].[CA].[San Francisco]}\n"
+ "{[Store].[USA].[OR]}\n"
+ "Row #0: 100,827\n"
+ "Row #1: 100,827\n"
+ "Row #2: 74,748\n"
+ "Row #3: \n"
+ "Row #4: 21,333\n"
+ "Row #5: 25,663\n"
+ "Row #6: 25,635\n"
+ "Row #7: 2,117\n"
+ "Row #8: 26,079\n");
goodmanContext(Role.RollupPolicy.FULL).assertQueryReturns(
query,
"Axis #0:\n"
+ "{[Time].[1997]}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Store].[All Stores]}\n"
+ "{[Store].[USA]}\n"
+ "{[Store].[USA].[CA]}\n"
+ "{[Store].[USA].[CA].[Alameda]}\n"
+ "{[Store].[USA].[CA].[Beverly Hills]}\n"
+ "{[Store].[USA].[CA].[Los Angeles]}\n"
+ "{[Store].[USA].[CA].[San Diego]}\n"
+ "{[Store].[USA].[CA].[San Francisco]}\n"
+ "{[Store].[USA].[OR]}\n"
+ "Row #0: 266,773\n"
+ "Row #1: 266,773\n"
+ "Row #2: 74,748\n"
+ "Row #3: \n"
+ "Row #4: 21,333\n"
+ "Row #5: 25,663\n"
+ "Row #6: 25,635\n"
+ "Row #7: 2,117\n"
+ "Row #8: 67,659\n");
goodmanContext(Role.RollupPolicy.HIDDEN).assertQueryReturns(
query,
"Axis #0:\n"
+ "{[Time].[1997]}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Store].[All Stores]}\n"
+ "{[Store].[USA]}\n"
+ "{[Store].[USA].[CA]}\n"
+ "{[Store].[USA].[CA].[Alameda]}\n"
+ "{[Store].[USA].[CA].[Beverly Hills]}\n"
+ "{[Store].[USA].[CA].[Los Angeles]}\n"
+ "{[Store].[USA].[CA].[San Diego]}\n"
+ "{[Store].[USA].[CA].[San Francisco]}\n"
+ "{[Store].[USA].[OR]}\n"
+ "Row #0: \n"
+ "Row #1: \n"
+ "Row #2: 74,748\n"
+ "Row #3: \n"
+ "Row #4: 21,333\n"
+ "Row #5: 25,663\n"
+ "Row #6: 25,635\n"
+ "Row #7: 2,117\n"
+ "Row #8: \n");
checkQuery(testContext, query);
}
private static TestContext goodmanContext(final Role.RollupPolicy policy) {
return
TestContext.instance().create(
null, null, null, null, null,
"<Role name=\"California manager\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Store]\" rollupPolicy=\""
+ policy.name().toLowerCase()
+ "\" access=\"custom\">\n"
+ " <MemberGrant member=\"[Store].[USA].[CA]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[USA].[OR].[Portland]\" access=\"all\"/>\n"
+ " </HierarchyGrant>"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>")
.withRole("California manager");
}
/**
* Test case for bug <a href="http://jira.pentaho.com/browse/MONDRIAN-402">
* MONDRIAN-402, "Bug in RolapCubeHierarchy.hashCode() ?"</a>.
* Access-control elements for hierarchies with
* same name in different cubes could not be distinguished.
*/
public void testBugMondrian402() {
final TestContext testContext =
TestContext.instance().create(
null, null, null, null, null,
"<Role name=\"California manager\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Store]\" access=\"none\" />\n"
+ " </CubeGrant>\n"
+ " <CubeGrant cube=\"Sales Ragged\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Store]\" access=\"custom\" />\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>")
.withRole("California manager");
assertHierarchyAccess(
testContext.getConnection(), Access.NONE, "Sales", "Store");
assertHierarchyAccess(
testContext.getConnection(),
Access.CUSTOM,
"Sales Ragged",
"Store");
}
public void testPartialRollupParentChildHierarchy() {
final TestContext testContext = TestContext.instance().create(
null, null, null, null, null,
"<Role name=\"Buggy Role\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"HR\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Employees]\" access=\"custom\"\n"
+ " rollupPolicy=\"partial\">\n"
+ " <MemberGrant\n"
+ " member=\"[Employees].[All Employees].[Sheri Nowmer].[Darren Stanz]\"\n"
+ " access=\"all\"/>\n"
+ " </HierarchyGrant>\n"
+ " <HierarchyGrant hierarchy=\"[Store]\" access=\"custom\"\n"
+ " rollupPolicy=\"partial\">\n"
+ " <MemberGrant member=\"[Store].[All Stores].[USA].[CA]\" access=\"all\"/>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>")
.withRole("Buggy Role");
final String mdx = "select\n"
+ " {[Measures].[Number of Employees]} on columns,\n"
+ " {[Store]} on rows\n"
+ "from HR";
testContext.assertQueryReturns(
mdx,
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[Number of Employees]}\n"
+ "Axis #2:\n"
+ "{[Store].[All Stores]}\n"
+ "Row #0: 1\n");
checkQuery(testContext, mdx);
final String mdx2 = "select\n"
+ " {[Measures].[Number of Employees]} on columns,\n"
+ " {[Employees]} on rows\n"
+ "from HR";
testContext.assertQueryReturns(
mdx2,
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[Number of Employees]}\n"
+ "Axis #2:\n"
+ "{[Employees].[All Employees]}\n"
+ "Row #0: 1\n");
checkQuery(testContext, mdx2);
}
public void testParentChildUserDefinedRole()
{
TestContext testContext = getTestContext().withCube("HR");
final Connection connection = testContext.getConnection();
final Role savedRole = connection.getRole();
try {
// Run queries as top-level employee.
connection.setRole(
new PeopleRole(
savedRole, connection.getSchema(), "Sheri Nowmer"));
testContext.assertExprReturns(
"[Employees].Members.Count",
"1,156");
// Level 2 employee
connection.setRole(
new PeopleRole(
savedRole, connection.getSchema(), "Derrick Whelply"));
testContext.assertExprReturns(
"[Employees].Members.Count",
"605");
testContext.assertAxisReturns(
"Head([Employees].Members, 4),"
+ "Tail([Employees].Members, 2)",
"[Employees].[All Employees]\n"
+ "[Employees].[Sheri Nowmer]\n"
+ "[Employees].[Sheri Nowmer].[Derrick Whelply]\n"
+ "[Employees].[Sheri Nowmer].[Derrick Whelply].[Beverly Baker]\n"
+ "[Employees].[Sheri Nowmer].[Derrick Whelply].[Laurie Borges].[Ed Young].[Gregory Whiting].[Merrill Steel]\n"
+ "[Employees].[Sheri Nowmer].[Derrick Whelply].[Laurie Borges].[Ed Young].[Gregory Whiting].[Melissa Marple]");
// Leaf employee
connection.setRole(
new PeopleRole(
savedRole, connection.getSchema(), "Ann Weyerhaeuser"));
testContext.assertExprReturns(
"[Employees].Members.Count",
"7");
testContext.assertAxisReturns(
"[Employees].Members",
"[Employees].[All Employees]\n"
+ "[Employees].[Sheri Nowmer]\n"
+ "[Employees].[Sheri Nowmer].[Derrick Whelply]\n"
+ "[Employees].[Sheri Nowmer].[Derrick Whelply].[Laurie Borges]\n"
+ "[Employees].[Sheri Nowmer].[Derrick Whelply].[Laurie Borges].[Cody Goldey]\n"
+ "[Employees].[Sheri Nowmer].[Derrick Whelply].[Laurie Borges].[Cody Goldey].[Shanay Steelman]\n"
+ "[Employees].[Sheri Nowmer].[Derrick Whelply].[Laurie Borges].[Cody Goldey].[Shanay Steelman].[Ann Weyerhaeuser]");
} finally {
connection.setRole(savedRole);
}
}
/**
* Test case for
* <a href="http://jira.pentaho.com/browse/BISERVER-1574">BISERVER-1574,
* "Cube role rollupPolicy='partial' failure"</a>. The problem was a
* NullPointerException in
* {@link SchemaReader#getMemberParent(mondrian.olap.Member)} when called
* on a members returned in a result set. JPivot calls that method but
* Mondrian normally does not.
*/
public void testBugBiserver1574() {
final TestContext testContext =
TestContext.instance().create(
null, null, null, null, null, BiServer1574Role1)
.withRole("role1");
final String mdx =
"select {([Measures].[Store Invoice], [Store Size in SQFT].[All Store Size in SQFTs])} ON COLUMNS,\n"
+ " {[Warehouse].[All Warehouses]} ON ROWS\n"
+ "from [Warehouse]";
checkQuery(testContext, mdx);
testContext.assertQueryReturns(
mdx,
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[Store Invoice], [Store Size in SQFT].[All Store Size in SQFTs]}\n"
+ "Axis #2:\n"
+ "{[Warehouse].[All Warehouses]}\n"
+ "Row #0: 4,042.96\n");
}
/**
* Testcase for bug <a href="http://jira.pentaho.com/browse/MONDRIAN-435">
* MONDRIAN-435, "Internal error in HierarchizeArrayComparator"</a>. Occurs
* when apply Hierarchize function to tuples on a hierarchy with
* partial-rollup.
*/
public void testBugMondrian435() {
final TestContext testContext =
TestContext.instance().create(
null, null, null, null, null, BiServer1574Role1)
.withRole("role1");
// minimal testcase
testContext.assertQueryReturns(
"select hierarchize("
+ " crossjoin({[Store Size in SQFT], [Store Size in SQFT].Children}, {[Product]})"
+ ") on 0,"
+ "[Store Type].Members on 1 from [Warehouse]",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Store Size in SQFT].[All Store Size in SQFTs], [Product].[All Products]}\n"
+ "{[Store Size in SQFT].[20319], [Product].[All Products]}\n"
+ "Axis #2:\n"
+ "{[Store Type].[All Store Types]}\n"
+ "{[Store Type].[Supermarket]}\n"
+ "Row #0: 4,042.96\n"
+ "Row #0: 4,042.96\n"
+ "Row #1: 4,042.96\n"
+ "Row #1: 4,042.96\n");
// explicit tuples, not crossjoin
testContext.assertQueryReturns(
"select hierarchize("
+ " { ([Store Size in SQFT], [Product]),\n"
+ " ([Store Size in SQFT].[20319], [Product].[Food]),\n"
+ " ([Store Size in SQFT], [Product].[Drink].[Dairy]),\n"
+ " ([Store Size in SQFT].[20319], [Product]) }\n"
+ ") on 0,"
+ "[Store Type].Members on 1 from [Warehouse]",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Store Size in SQFT].[All Store Size in SQFTs], [Product].[All Products]}\n"
+ "{[Store Size in SQFT].[All Store Size in SQFTs], [Product].[Drink].[Dairy]}\n"
+ "{[Store Size in SQFT].[20319], [Product].[All Products]}\n"
+ "{[Store Size in SQFT].[20319], [Product].[Food]}\n"
+ "Axis #2:\n"
+ "{[Store Type].[All Store Types]}\n"
+ "{[Store Type].[Supermarket]}\n"
+ "Row #0: 4,042.96\n"
+ "Row #0: 82.454\n"
+ "Row #0: 4,042.96\n"
+ "Row #0: 2,696.758\n"
+ "Row #1: 4,042.96\n"
+ "Row #1: 82.454\n"
+ "Row #1: 4,042.96\n"
+ "Row #1: 2,696.758\n");
// extended testcase; note that [Store Size in SQFT].Parent is null,
// so disappears
testContext.assertQueryReturns(
"select non empty hierarchize("
+ "union("
+ " union("
+ " crossjoin({[Store Size in SQFT]}, {[Product]}),"
+ " crossjoin({[Store Size in SQFT], [Store Size in SQFT].Children}, {[Product]}),"
+ " all),"
+ " union("
+ " crossjoin({[Store Size in SQFT].Parent}, {[Product].[Drink]}),"
+ " crossjoin({[Store Size in SQFT].Children}, {[Product].[Food]}),"
+ " all),"
+ " all)) on 0,"
+ "[Store Type].Members on 1 from [Warehouse]",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Store Size in SQFT].[All Store Size in SQFTs], [Product].[All Products]}\n"
+ "{[Store Size in SQFT].[All Store Size in SQFTs], [Product].[All Products]}\n"
+ "{[Store Size in SQFT].[20319], [Product].[All Products]}\n"
+ "{[Store Size in SQFT].[20319], [Product].[Food]}\n"
+ "Axis #2:\n"
+ "{[Store Type].[All Store Types]}\n"
+ "{[Store Type].[Supermarket]}\n"
+ "Row #0: 4,042.96\n"
+ "Row #0: 4,042.96\n"
+ "Row #0: 4,042.96\n"
+ "Row #0: 2,696.758\n"
+ "Row #1: 4,042.96\n"
+ "Row #1: 4,042.96\n"
+ "Row #1: 4,042.96\n"
+ "Row #1: 2,696.758\n");
testContext.assertQueryReturns(
"select Hierarchize(\n"
+ " CrossJoin\n("
+ " CrossJoin(\n"
+ " {[Product].[All Products], "
+ " [Product].[Food],\n"
+ " [Product].[Food].[Eggs],\n"
+ " [Product].[Drink].[Dairy]},\n"
+ " [Store Type].MEMBERS),\n"
+ " [Store Size in SQFT].MEMBERS),\n"
+ " PRE) on 0\n"
+ "from [Warehouse]",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Product].[All Products], [Store Type].[All Store Types], [Store Size in SQFT].[All Store Size in SQFTs]}\n"
+ "{[Product].[All Products], [Store Type].[All Store Types], [Store Size in SQFT].[20319]}\n"
+ "{[Product].[All Products], [Store Type].[Supermarket], [Store Size in SQFT].[All Store Size in SQFTs]}\n"
+ "{[Product].[All Products], [Store Type].[Supermarket], [Store Size in SQFT].[20319]}\n"
+ "{[Product].[Drink].[Dairy], [Store Type].[All Store Types], [Store Size in SQFT].[All Store Size in SQFTs]}\n"
+ "{[Product].[Drink].[Dairy], [Store Type].[All Store Types], [Store Size in SQFT].[20319]}\n"
+ "{[Product].[Drink].[Dairy], [Store Type].[Supermarket], [Store Size in SQFT].[All Store Size in SQFTs]}\n"
+ "{[Product].[Drink].[Dairy], [Store Type].[Supermarket], [Store Size in SQFT].[20319]}\n"
+ "{[Product].[Food], [Store Type].[All Store Types], [Store Size in SQFT].[All Store Size in SQFTs]}\n"
+ "{[Product].[Food], [Store Type].[All Store Types], [Store Size in SQFT].[20319]}\n"
+ "{[Product].[Food], [Store Type].[Supermarket], [Store Size in SQFT].[All Store Size in SQFTs]}\n"
+ "{[Product].[Food], [Store Type].[Supermarket], [Store Size in SQFT].[20319]}\n"
+ "{[Product].[Food].[Eggs], [Store Type].[All Store Types], [Store Size in SQFT].[All Store Size in SQFTs]}\n"
+ "{[Product].[Food].[Eggs], [Store Type].[All Store Types], [Store Size in SQFT].[20319]}\n"
+ "{[Product].[Food].[Eggs], [Store Type].[Supermarket], [Store Size in SQFT].[All Store Size in SQFTs]}\n"
+ "{[Product].[Food].[Eggs], [Store Type].[Supermarket], [Store Size in SQFT].[20319]}\n"
+ "Row #0: 4,042.96\n"
+ "Row #0: 4,042.96\n"
+ "Row #0: 4,042.96\n"
+ "Row #0: 4,042.96\n"
+ "Row #0: 82.454\n"
+ "Row #0: 82.454\n"
+ "Row #0: 82.454\n"
+ "Row #0: 82.454\n"
+ "Row #0: 2,696.758\n"
+ "Row #0: 2,696.758\n"
+ "Row #0: 2,696.758\n"
+ "Row #0: 2,696.758\n"
+ "Row #0: \n"
+ "Row #0: \n"
+ "Row #0: \n"
+ "Row #0: \n");
}
/**
* Testcase for bug <a href="http://jira.pentaho.com/browse/MONDRIAN-436">
* MONDRIAN-436, "SubstitutingMemberReader.getMemberBuilder gives
* UnsupportedOperationException"</a>.
*/
public void testBugMondrian436() {
propSaver.set(propSaver.properties.EnableNativeCrossJoin, true);
propSaver.set(propSaver.properties.EnableNativeFilter, true);
propSaver.set(propSaver.properties.EnableNativeNonEmpty, true);
propSaver.set(propSaver.properties.EnableNativeTopCount, true);
propSaver.set(propSaver.properties.ExpandNonNative, true);
// Run with native enabled, then with whatever properties are set for
// this test run.
checkBugMondrian436();
propSaver.reset();
checkBugMondrian436();
}
private void checkBugMondrian436() {
final TestContext testContext =
TestContext.instance().create(
null, null, null, null, null, BiServer1574Role1)
.withRole("role1");
testContext.assertQueryReturns(
"select non empty {[Measures].[Units Ordered],\n"
+ " [Measures].[Units Shipped]} on 0,\n"
+ "non empty hierarchize(\n"
+ " union(\n"
+ " crossjoin(\n"
+ " {[Store Size in SQFT]},\n"
+ " {[Product].[Drink],\n"
+ " [Product].[Food],\n"
+ " [Product].[Drink].[Dairy]}),\n"
+ " crossjoin(\n"
+ " {[Store Size in SQFT].[20319]},\n"
+ " {[Product].Children}))) on 1\n"
+ "from [Warehouse]",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[Units Ordered]}\n"
+ "{[Measures].[Units Shipped]}\n"
+ "Axis #2:\n"
+ "{[Store Size in SQFT].[All Store Size in SQFTs], [Product].[Drink]}\n"
+ "{[Store Size in SQFT].[All Store Size in SQFTs], [Product].[Drink].[Dairy]}\n"
+ "{[Store Size in SQFT].[All Store Size in SQFTs], [Product].[Food]}\n"
+ "{[Store Size in SQFT].[20319], [Product].[Drink]}\n"
+ "{[Store Size in SQFT].[20319], [Product].[Food]}\n"
+ "{[Store Size in SQFT].[20319], [Product].[Non-Consumable]}\n"
+ "Row #0: 865.0\n"
+ "Row #0: 767.0\n"
+ "Row #1: 195.0\n"
+ "Row #1: 182.0\n"
+ "Row #2: 6065.0\n"
+ "Row #2: 5723.0\n"
+ "Row #3: 865.0\n"
+ "Row #3: 767.0\n"
+ "Row #4: 6065.0\n"
+ "Row #4: 5723.0\n"
+ "Row #5: 2179.0\n"
+ "Row #5: 2025.0\n");
}
/**
* Tests that hierarchy-level access control works on a virtual cube.
* See bug
* <a href="http://jira.pentaho.com/browse/MONDRIAN-456">
* MONDRIAN-456, "Roles and virtual cubes"</a>.
*/
public void testVirtualCube() {
TestContext testContext = TestContext.instance().create(
null, null, null, null, null,
"<Role name=\"VCRole\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Warehouse and Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Store]\" access=\"custom\">\n"
+ " <MemberGrant member=\"[Store].[USA].[CA]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[USA].[CA].[Los Angeles]\" access=\"none\"/>\n"
+ " </HierarchyGrant>\n"
+ " <HierarchyGrant hierarchy=\"[Customers]\" access=\"custom\"\n"
+ " topLevel=\"[Customers].[State Province]\" bottomLevel=\"[Customers].[City]\">\n"
+ " <MemberGrant member=\"[Customers].[USA].[CA]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Customers].[USA].[CA].[Los Angeles]\" access=\"none\"/>\n"
+ " </HierarchyGrant>\n"
+ " <HierarchyGrant hierarchy=\"[Gender]\" access=\"none\"/>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>").withRole("VCRole");
testContext.assertQueryReturns(
"select [Store].Members on 0 from [Warehouse and Sales]",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Store].[All Stores]}\n"
+ "{[Store].[USA]}\n"
+ "{[Store].[USA].[CA]}\n"
+ "{[Store].[USA].[CA].[Alameda]}\n"
+ "{[Store].[USA].[CA].[Alameda].[HQ]}\n"
+ "{[Store].[USA].[CA].[Beverly Hills]}\n"
+ "{[Store].[USA].[CA].[Beverly Hills].[Store 6]}\n"
+ "{[Store].[USA].[CA].[San Diego]}\n"
+ "{[Store].[USA].[CA].[San Diego].[Store 24]}\n"
+ "{[Store].[USA].[CA].[San Francisco]}\n"
+ "{[Store].[USA].[CA].[San Francisco].[Store 14]}\n"
+ "Row #0: 159,167.84\n"
+ "Row #0: 159,167.84\n"
+ "Row #0: 159,167.84\n"
+ "Row #0: \n"
+ "Row #0: \n"
+ "Row #0: 45,750.24\n"
+ "Row #0: 45,750.24\n"
+ "Row #0: 54,431.14\n"
+ "Row #0: 54,431.14\n"
+ "Row #0: 4,441.18\n"
+ "Row #0: 4,441.18\n");
}
/**
* this tests the fix for
* http://jira.pentaho.com/browse/BISERVER-2491
* rollupPolicy=partial and queries to upper members don't work
*/
public void testBugBiserver2491() {
final String BiServer2491Role2 =
"<Role name=\"role2\">"
+ " <SchemaGrant access=\"none\">"
+ " <CubeGrant cube=\"Sales\" access=\"all\">"
+ " <HierarchyGrant hierarchy=\"[Store]\" access=\"custom\" rollupPolicy=\"partial\">"
+ " <MemberGrant member=\"[Store].[USA].[CA]\" access=\"all\"/>"
+ " <MemberGrant member=\"[Store].[USA].[CA].[Los Angeles]\" access=\"none\"/>"
+ " </HierarchyGrant>"
+ " </CubeGrant>"
+ " </SchemaGrant>"
+ "</Role>";
final TestContext testContext =
TestContext.instance().create(
null, null, null, null, null, BiServer2491Role2)
.withRole("role2");
final String firstBrokenMdx =
"select [Measures].[Unit Sales] ON COLUMNS, {[Store].[Store Country].Members} ON ROWS from [Sales]";
checkQuery(testContext, firstBrokenMdx);
testContext.assertQueryReturns(
firstBrokenMdx,
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Store].[USA]}\n"
+ "Row #0: 49,085\n");
final String secondBrokenMdx =
"select [Measures].[Unit Sales] ON COLUMNS, "
+ "Descendants([Store],[Store].[Store Name]) ON ROWS from [Sales]";
checkQuery(testContext, secondBrokenMdx);
testContext.assertQueryReturns(
secondBrokenMdx,
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Store].[USA].[CA].[Alameda].[HQ]}\n"
+ "{[Store].[USA].[CA].[Beverly Hills].[Store 6]}\n"
+ "{[Store].[USA].[CA].[San Diego].[Store 24]}\n"
+ "{[Store].[USA].[CA].[San Francisco].[Store 14]}\n"
+ "Row #0: \n"
+ "Row #1: 21,333\n"
+ "Row #2: 25,635\n"
+ "Row #3: 2,117\n");
}
/**
* Test case for bug
* <a href="http://jira.pentaho.com/browse/MONDRIAN-622">MONDRIAN-622,
* "Poor performance with large union role"</a>.
*/
public void testBugMondrian622() {
StringBuilder buf = new StringBuilder();
StringBuilder buf2 = new StringBuilder();
final String cubeName = "Sales with multiple customers";
final Result result = TestContext.instance().executeQuery(
"select [Customers].[City].Members on 0 from [Sales]");
for (Position position : result.getAxes()[0].getPositions()) {
Member member = position.get(0);
String name = member.getParentMember().getName()
+ "."
+ member.getName(); // e.g. "BC.Burnaby"
// e.g. "[Customers].[State Province].[BC].[Burnaby]"
String uniqueName =
Util.replace(member.getUniqueName(), ".[All Customers]", "");
// e.g. "[Customers2].[State Province].[BC].[Burnaby]"
String uniqueName2 =
Util.replace(uniqueName, "Customers", "Customers2");
// e.g. "[Customers3].[State Province].[BC].[Burnaby]"
String uniqueName3 =
Util.replace(uniqueName, "Customers", "Customers3");
buf.append(
" <Role name=\"" + name + "\"> \n"
+ " <SchemaGrant access=\"none\"> \n"
+ " <CubeGrant access=\"all\" cube=\"" + cubeName
+ "\"> \n"
+ " <HierarchyGrant access=\"custom\" hierarchy=\"[Customers]\" rollupPolicy=\"partial\"> \n"
+ " <MemberGrant access=\"all\" member=\""
+ uniqueName + "\"/> \n"
+ " </HierarchyGrant> \n"
+ " <HierarchyGrant access=\"custom\" hierarchy=\"[Customers2]\" rollupPolicy=\"partial\"> \n"
+ " <MemberGrant access=\"all\" member=\""
+ uniqueName2 + "\"/> \n"
+ " </HierarchyGrant> \n"
+ " <HierarchyGrant access=\"custom\" hierarchy=\"[Customers3]\" rollupPolicy=\"partial\"> \n"
+ " <MemberGrant access=\"all\" member=\""
+ uniqueName3 + "\"/> \n"
+ " </HierarchyGrant> \n"
+ " </CubeGrant> \n"
+ " </SchemaGrant> \n"
+ " </Role> \n");
buf2.append(" <RoleUsage roleName=\"" + name + "\"/>\n");
}
final TestContext testContext = TestContext.instance().create(
" <Dimension name=\"Customers\"> \n"
+ " <Hierarchy hasAll=\"true\" primaryKey=\"customer_id\"> \n"
+ " <Table name=\"customer\"/> \n"
+ " <Level name=\"Country\" column=\"country\" uniqueMembers=\"true\"/> \n"
+ " <Level name=\"State Province\" column=\"state_province\" uniqueMembers=\"true\"/> \n"
+ " <Level name=\"City\" column=\"city\" uniqueMembers=\"false\"/> \n"
+ " <Level name=\"Name\" column=\"customer_id\" type=\"Numeric\" uniqueMembers=\"true\"/> \n"
+ " </Hierarchy> \n"
+ " </Dimension> ",
" <Cube name=\"" + cubeName + "\"> \n"
+ " <Table name=\"sales_fact_1997\"/> \n"
+ " <DimensionUsage name=\"Time\" source=\"Time\" foreignKey=\"time_id\"/> \n"
+ " <DimensionUsage name=\"Product\" source=\"Product\" foreignKey=\"product_id\"/> \n"
+ " <DimensionUsage name=\"Customers\" source=\"Customers\" foreignKey=\"customer_id\"/> \n"
+ " <DimensionUsage name=\"Customers2\" source=\"Customers\" foreignKey=\"customer_id\"/> \n"
+ " <DimensionUsage name=\"Customers3\" source=\"Customers\" foreignKey=\"customer_id\"/> \n"
+ " <Measure name=\"Unit Sales\" column=\"unit_sales\" aggregator=\"sum\" formatString=\"Standard\"/> \n"
+ " </Cube> \n",
null, null, null,
buf.toString()
+ " <Role name=\"Test\"> \n"
+ " <Union>\n"
+ buf2.toString()
+ " </Union>\n"
+ " </Role>\n");
final long t0 = System.currentTimeMillis();
final TestContext testContext1 = testContext.withRole("Test");
testContext1.executeQuery("select from [" + cubeName + "]");
final long t1 = System.currentTimeMillis();
// System.out.println("Elapsed=" + (t1 - t0) + " millis");
// System.out.println(
// "RoleImpl.accessCount=" + RoleImpl.accessCallCount);
// testContext1.executeQuery(
// "select from [Sales with multiple customers]");
// final long t2 = System.currentTimeMillis();
// System.out.println("Elapsed=" + (t2 - t1) + " millis");
// System.out.println("RoleImpl.accessCount=" + RoleImpl.accessCallCount);
}
/**
* Test case for bug
* <a href="http://jira.pentaho.com/browse/MONDRIAN-694">MONDRIAN-694,
* "Incorrect handling of child/parent relationship with hierarchy
* grants"</a>.
*/
public void testBugMondrian694() {
final TestContext testContext =
TestContext.instance().create(
null, null, null, null, null,
"<Role name=\"REG1\"> \n"
+ " <SchemaGrant access=\"none\"> \n"
+ " <CubeGrant cube=\"HR\" access=\"all\"> \n"
+ " <HierarchyGrant hierarchy=\"Employees\" access=\"custom\" rollupPolicy=\"partial\"> \n"
+ " <MemberGrant member=\"[Employees].[All Employees]\" access=\"none\"/>\n"
+ " <MemberGrant member=\"[Employees].[Sheri Nowmer].[Derrick Whelply].[Laurie Borges].[Cody Goldey].[Shanay Steelman].[Steven Betsekas]\" access=\"all\"/> \n"
+ " <MemberGrant member=\"[Employees].[Sheri Nowmer].[Derrick Whelply].[Laurie Borges].[Cody Goldey].[Shanay Steelman].[Arvid Ziegler]\" access=\"all\"/> \n"
+ " <MemberGrant member=\"[Employees].[Sheri Nowmer].[Derrick Whelply].[Laurie Borges].[Cody Goldey].[Shanay Steelman].[Ann Weyerhaeuser]\" access=\"all\"/> \n"
+ " </HierarchyGrant> \n"
+ " </CubeGrant> \n"
+ " </SchemaGrant> \n"
+ "</Role>")
.withRole("REG1");
// With bug MONDRIAN-694 returns 874.80, should return 79.20.
// Test case is minimal: doesn't happen without the Crossjoin, or
// without the NON EMPTY, or with [Employees] as opposed to
// [Employees].[All Employees], or with [Department].[All Departments].
testContext.assertQueryReturns(
"select NON EMPTY {[Measures].[Org Salary]} ON COLUMNS,\n"
+ "NON EMPTY Crossjoin({[Department].[14]}, {[Employees].[All Employees]}) ON ROWS\n"
+ "from [HR]",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[Org Salary]}\n"
+ "Axis #2:\n"
+ "{[Department].[14], [Employees].[All Employees]}\n"
+ "Row #0: $97.20\n");
// This query gave the right answer, even with MONDRIAN-694.
testContext.assertQueryReturns(
"select NON EMPTY {[Measures].[Org Salary]} ON COLUMNS, \n"
+ "NON EMPTY Hierarchize(Crossjoin({[Department].[14]}, {[Employees].[All Employees], [Employees].Children})) ON ROWS \n"
+ "from [HR] ",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[Org Salary]}\n"
+ "Axis #2:\n"
+ "{[Department].[14], [Employees].[All Employees]}\n"
+ "{[Department].[14], [Employees].[Sheri Nowmer]}\n"
+ "Row #0: $97.20\n"
+ "Row #1: $97.20\n");
// Original test case, not quite minimal. With MONDRIAN-694, returns
// $874.80 for [All Employees].
testContext.assertQueryReturns(
"select NON EMPTY {[Measures].[Org Salary]} ON COLUMNS, \n"
+ "NON EMPTY Hierarchize(Union(Crossjoin({[Department].[All Departments].[14]}, {[Employees].[All Employees]}), Crossjoin({[Department].[All Departments].[14]}, [Employees].[All Employees].Children))) ON ROWS \n"
+ "from [HR] ",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[Org Salary]}\n"
+ "Axis #2:\n"
+ "{[Department].[14], [Employees].[All Employees]}\n"
+ "{[Department].[14], [Employees].[Sheri Nowmer]}\n"
+ "Row #0: $97.20\n"
+ "Row #1: $97.20\n");
testContext.assertQueryReturns(
"select NON EMPTY {[Measures].[Org Salary]} ON COLUMNS, \n"
+ "NON EMPTY Crossjoin(Hierarchize(Union({[Employees].[All Employees]}, [Employees].[All Employees].Children)), {[Department].[14]}) ON ROWS \n"
+ "from [HR] ",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[Org Salary]}\n"
+ "Axis #2:\n"
+ "{[Employees].[All Employees], [Department].[14]}\n"
+ "{[Employees].[Sheri Nowmer], [Department].[14]}\n"
+ "Row #0: $97.20\n"
+ "Row #1: $97.20\n");
}
/**
* Test case for bug
* <a href="http://jira.pentaho.com/browse/MONDRIAN-722">MONDRIAN-722, "If
* ignoreInvalidMembers=true, should ignore grants with invalid
* members"</a>.
*/
public void testBugMondrian722() {
propSaver.set(
MondrianProperties.instance().IgnoreInvalidMembers,
true);
TestContext.instance().create(
null, null, null, null, null,
"<Role name=\"CTO\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Customers]\" access=\"custom\">\n"
+ " <MemberGrant member=\"[Customers].[USA].[XX]\" access=\"none\"/>\n"
+ " <MemberGrant member=\"[Customers].[USA].[XX].[Yyy Yyyyyyy]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Customers].[USA]\" access=\"none\"/>\n"
+ " <MemberGrant member=\"[Customers].[USA].[CA]\" access=\"none\"/>\n"
+ " <MemberGrant member=\"[Customers].[USA].[CA].[Los Angeles]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Customers].[USA].[CA].[Zzz Zzzz]\" access=\"none\"/>\n"
+ " <MemberGrant member=\"[Customers].[USA].[CA].[San Francisco]\" access=\"all\"/>\n"
+ " </HierarchyGrant>\n"
+ " <HierarchyGrant hierarchy=\"[Gender]\" access=\"none\"/>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>")
.withRole("CTO")
.assertQueryReturns(
"select [Measures] on 0,\n"
+ " Hierarchize(\n"
+ " {[Customers].[USA].Children,\n"
+ " [Customers].[USA].[CA].Children}) on 1\n"
+ "from [Sales]",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Customers].[USA].[CA]}\n"
+ "{[Customers].[USA].[CA].[Los Angeles]}\n"
+ "{[Customers].[USA].[CA].[San Francisco]}\n"
+ "Row #0: 74,748\n"
+ "Row #1: 2,009\n"
+ "Row #2: 88\n");
}
/**
* Test case for bug
* <a href="http://jira.pentaho.com/browse/MONDRIAN-746">MONDRIAN-746,
* "Report returns stack trace when turning on subtotals on a hierarchy with
* top level hidden"</a>.
*/
public void testCalcMemberLevel() {
checkCalcMemberLevel(getTestContext());
checkCalcMemberLevel(
TestContext.instance().create(
null, null, null, null, null,
"<Role name=\"Role1\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Store]\" access=\"custom\" rollupPolicy=\"Partial\" topLevel=\"[Store].[Store State]\">\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>\n")
.withRole("Role1"));
}
/**
* Test for bug MONDRIAN-568. Grants on OLAP elements are validated
* by name, thus granting implicit access to all cubes which have
* a dimension with the same name.
*/
public void testBugMondrian568() {
final TestContext testContext =
TestContext.instance().create(
null, null, null, null, null,
"<Role name=\"Role1\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"none\">\n"
+ " <HierarchyGrant hierarchy=\"[Measures]\" access=\"custom\">\n"
+ " <MemberGrant member=\"[Measures].[Unit Sales]\" access=\"all\"/>\n"
+ " </HierarchyGrant>"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>\n"
+ "<Role name=\"Role2\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales Ragged\" access=\"all\"/>\n"
+ " </SchemaGrant>\n"
+ "</Role>");
final TestContext testContextRole1 =
testContext
.withRole("Role1")
.withCube("Sales");
final TestContext testContextRole12 =
testContext
.withRole("Role1,Role2")
.withCube("Sales");
assertMemberAccess(
testContextRole1.getConnection(),
Access.NONE,
"[Measures].[Store Cost]");
assertMemberAccess(
testContextRole12.getConnection(),
Access.NONE,
"[Measures].[Store Cost]");
}
private void checkCalcMemberLevel(TestContext testContext) {
Result result = testContext.executeQuery(
"with member [Store].[USA].[CA].[Foo] as\n"
+ " 1\n"
+ "select {[Measures].[Unit Sales]} on columns,\n"
+ "{[Store].[USA].[CA],\n"
+ " [Store].[USA].[CA].[Los Angeles],\n"
+ " [Store].[USA].[CA].[Foo]} on rows\n"
+ "from [Sales]");
final List<Position> rowPos = result.getAxes()[1].getPositions();
final Member member0 = rowPos.get(0).get(0);
assertEquals("CA", member0.getName());
assertEquals("Store State", member0.getLevel().getName());
final Member member1 = rowPos.get(1).get(0);
assertEquals("Los Angeles", member1.getName());
assertEquals("Store City", member1.getLevel().getName());
final Member member2 = rowPos.get(2).get(0);
assertEquals("Foo", member2.getName());
assertEquals("Store City", member2.getLevel().getName());
}
/**
* Testcase for bug
* <a href="http://jira.pentaho.com/browse/MONDRIAN-935">MONDRIAN-935,
* "no results when some level members in a member grant have no data"</a>.
*/
public void testBugMondrian935() {
final TestContext testContext =
TestContext.instance().create(
null, null, null, null, null,
"<Role name='Role1'>\n"
+ " <SchemaGrant access='none'>\n"
+ " <CubeGrant cube='Sales' access='all'>\n"
+ " <HierarchyGrant hierarchy='[Store Type]' access='custom' rollupPolicy='partial'>\n"
+ " <MemberGrant member='[Store Type].[All Store Types]' access='none'/>\n"
+ " <MemberGrant member='[Store Type].[Supermarket]' access='all'/>\n"
+ " </HierarchyGrant>\n"
+ " <HierarchyGrant hierarchy='[Customers]' access='custom' rollupPolicy='partial' >\n"
+ " <MemberGrant member='[Customers].[All Customers]' access='none'/>\n"
+ " <MemberGrant member='[Customers].[USA].[WA]' access='all'/>\n"
+ " <MemberGrant member='[Customers].[USA].[CA]' access='none'/>\n"
+ " <MemberGrant member='[Customers].[USA].[CA].[Los Angeles]' access='all'/>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>\n");
testContext.withRole("Role1").assertQueryReturns(
"select [Measures] on 0,\n"
+ "[Customers].[USA].Children * [Store Type].Children on 1\n"
+ "from [Sales]",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Customers].[USA].[CA], [Store Type].[Supermarket]}\n"
+ "{[Customers].[USA].[WA], [Store Type].[Supermarket]}\n"
+ "Row #0: 1,118\n"
+ "Row #1: 73,178\n");
}
public void testDimensionGrant() throws Exception {
final TestContext context = TestContext.instance().create(
null, null, null, null, null,
"<Role name=\"Role1\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"custom\">\n"
+ " <DimensionGrant dimension=\"[Measures]\" access=\"all\" />\n"
+ " <DimensionGrant dimension=\"[Education Level]\" access=\"all\" />\n"
+ " <DimensionGrant dimension=\"[Gender]\" access=\"all\" />\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>\n"
+ "<Role name=\"Role2\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"custom\">\n"
+ " <DimensionGrant dimension=\"[Measures]\" access=\"all\" />\n"
+ " <DimensionGrant dimension=\"[Education Level]\" access=\"all\" />\n"
+ " <DimensionGrant dimension=\"[Customers]\" access=\"none\" />\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>\n"
+ "<Role name=\"Role3\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"custom\">\n"
+ " <DimensionGrant dimension=\"[Education Level]\" access=\"all\" />\n"
+ " <DimensionGrant dimension=\"[Measures]\" access=\"custom\" />\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>\n");
context.withRole("Role1").assertAxisReturns(
"[Education Level].Members",
"[Education Level].[All Education Levels]\n"
+ "[Education Level].[Bachelors Degree]\n"
+ "[Education Level].[Graduate Degree]\n"
+ "[Education Level].[High School Degree]\n"
+ "[Education Level].[Partial College]\n"
+ "[Education Level].[Partial High School]");
context.withRole("Role1").assertAxisThrows(
"[Customers].Members",
"Mondrian Error:Failed to parse query 'select {[Customers].Members} on columns from Sales'");
context.withRole("Role2").assertAxisThrows(
"[Customers].Members",
"Mondrian Error:Failed to parse query 'select {[Customers].Members} on columns from Sales'");
context.withRole("Role1").assertQueryReturns(
"select {[Education Level].Members} on columns, {[Measures].[Unit Sales]} on rows from Sales",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Education Level].[All Education Levels]}\n"
+ "{[Education Level].[Bachelors Degree]}\n"
+ "{[Education Level].[Graduate Degree]}\n"
+ "{[Education Level].[High School Degree]}\n"
+ "{[Education Level].[Partial College]}\n"
+ "{[Education Level].[Partial High School]}\n"
+ "Axis #2:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Row #0: 266,773\n"
+ "Row #0: 68,839\n"
+ "Row #0: 15,570\n"
+ "Row #0: 78,664\n"
+ "Row #0: 24,545\n"
+ "Row #0: 79,155\n");
context.withRole("Role3").assertQueryThrows(
"select {[Education Level].Members} on columns, {[Measures].[Unit Sales]} on rows from Sales",
"Mondrian Error:Failed to parse query 'select {[Education Level].Members} on columns, {[Measures].[Unit Sales]} on rows from Sales'");
}
// ~ Inner classes =========================================================
public static class PeopleRole extends DelegatingRole {
private final String repName;
public PeopleRole(Role role, Schema schema, String repName) {
super(((RoleImpl)role).makeMutableClone());
this.repName = repName;
defineGrantsForUser(schema);
}
private void defineGrantsForUser(Schema schema) {
RoleImpl role = (RoleImpl)this.role;
role.grant(schema, Access.NONE);
Cube cube = schema.lookupCube("HR", true);
role.grant(cube, Access.ALL);
Hierarchy hierarchy = cube.lookupHierarchy(
new Id.NameSegment("Employees"), false);
Level[] levels = hierarchy.getLevels();
Level topLevel = levels[1];
role.grant(hierarchy, Access.CUSTOM, null, null, RollupPolicy.FULL);
role.grant(hierarchy.getAllMember(), Access.NONE);
boolean foundMember = false;
List <Member> members =
schema.getSchemaReader().withLocus()
.getLevelMembers(topLevel, true);
for (Member member : members) {
if (member.getUniqueName().contains("[" + repName + "]")) {
foundMember = true;
role.grant(member, Access.ALL);
}
}
assertTrue(foundMember);
}
}
/**
* This is a test for MONDRIAN-1030. When the top level of a hierarchy
* is not accessible and a partial rollup policy is used, the results would
* be returned as those of the first member of those accessible only.
*
* <p>ie: If a union of roles give access to two two sibling root members
* and the level to which they belong is not included in a query, the
* returned cell data would be that of the first sibling and would exclude
* those of the second.
*
* <p>This is because the RolapEvaluator cannot represent default members
* as multiple members (only a single member is the default member) and
* because the default member is not the 'all member', it adds a constrain
* to the SQL for the first member only.
*
* <p>Currently, Mondrian disguises the root member in the evaluator as a
* RestrictedMemberReader.MultiCardinalityDefaultMember. Later,
* RolapHierarchy.LimitedRollupSubstitutingMemberReader will recognize it
* and use the correct rollup policy on the parent member to generate
* correct SQL.
*/
public void testMondrian1030() throws Exception {
final String mdx1 =
"With\n"
+ "Set [*NATIVE_CJ_SET] as 'NonEmptyCrossJoin([*BASE_MEMBERS_Customers],[*BASE_MEMBERS_Product])'\n"
+ "Set [*SORTED_ROW_AXIS] as 'Order([*CJ_ROW_AXIS],[Customers].CurrentMember.OrderKey,BASC,[Education Level].CurrentMember.OrderKey,BASC)'\n"
+ "Set [*BASE_MEMBERS_Customers] as '[Customers].[City].Members'\n"
+ "Set [*BASE_MEMBERS_Product] as '[Education Level].Members'\n"
+ "Set [*BASE_MEMBERS_Measures] as '{[Measures].[*FORMATTED_MEASURE_0]}'\n"
+ "Set [*CJ_ROW_AXIS] as 'Generate([*NATIVE_CJ_SET], {([Customers].currentMember,[Education Level].currentMember)})'\n"
+ "Set [*CJ_COL_AXIS] as '[*NATIVE_CJ_SET]'\n"
+ "Member [Measures].[*FORMATTED_MEASURE_0] as '[Measures].[Unit Sales]', FORMAT_STRING = '#,###', SOLVE_ORDER=400\n"
+ "Select\n"
+ "[*BASE_MEMBERS_Measures] on columns,\n"
+ "Non Empty [*SORTED_ROW_AXIS] on rows\n"
+ "From [Sales] \n";
final String mdx2 =
"With\n"
+ "Set [*BASE_MEMBERS_Product] as '[Education Level].Members'\n"
+ "Set [*BASE_MEMBERS_Measures] as '{[Measures].[*FORMATTED_MEASURE_0]}'\n"
+ "Member [Measures].[*FORMATTED_MEASURE_0] as '[Measures].[Unit Sales]', FORMAT_STRING = '#,###', SOLVE_ORDER=400\n"
+ "Select\n"
+ "[*BASE_MEMBERS_Measures] on columns,\n"
+ "Non Empty [*BASE_MEMBERS_Product] on rows\n"
+ "From [Sales] \n";
final TestContext context =
getTestContext().create(
null, null, null, null, null,
" <Role name=\"Role1\">\n"
+ " <SchemaGrant access=\"all\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Customers]\" access=\"custom\" topLevel=\"[Customers].[City]\" bottomLevel=\"[Customers].[City]\" rollupPolicy=\"partial\">\n"
+ " <MemberGrant member=\"[City].[Coronado]\" access=\"all\">\n"
+ " </MemberGrant>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ " </Role>\n"
+ " <Role name=\"Role2\">\n"
+ " <SchemaGrant access=\"all\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Customers]\" access=\"custom\" topLevel=\"[Customers].[City]\" bottomLevel=\"[Customers].[City]\" rollupPolicy=\"partial\">\n"
+ " <MemberGrant member=\"[City].[Burbank]\" access=\"all\">\n"
+ " </MemberGrant>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ " </Role>\n");
// Control tests
context.withRole("Role1").assertQueryReturns(
mdx1,
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[*FORMATTED_MEASURE_0]}\n"
+ "Axis #2:\n"
+ "{[Customers].[USA].[CA].[Coronado], [Education Level].[All Education Levels]}\n"
+ "{[Customers].[USA].[CA].[Coronado], [Education Level].[Bachelors Degree]}\n"
+ "{[Customers].[USA].[CA].[Coronado], [Education Level].[Graduate Degree]}\n"
+ "{[Customers].[USA].[CA].[Coronado], [Education Level].[High School Degree]}\n"
+ "{[Customers].[USA].[CA].[Coronado], [Education Level].[Partial College]}\n"
+ "{[Customers].[USA].[CA].[Coronado], [Education Level].[Partial High School]}\n"
+ "Row #0: 2,391\n"
+ "Row #1: 559\n"
+ "Row #2: 205\n"
+ "Row #3: 551\n"
+ "Row #4: 253\n"
+ "Row #5: 823\n");
context.withRole("Role2").assertQueryReturns(
mdx1,
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[*FORMATTED_MEASURE_0]}\n"
+ "Axis #2:\n"
+ "{[Customers].[USA].[CA].[Burbank], [Education Level].[All Education Levels]}\n"
+ "{[Customers].[USA].[CA].[Burbank], [Education Level].[Bachelors Degree]}\n"
+ "{[Customers].[USA].[CA].[Burbank], [Education Level].[Graduate Degree]}\n"
+ "{[Customers].[USA].[CA].[Burbank], [Education Level].[High School Degree]}\n"
+ "{[Customers].[USA].[CA].[Burbank], [Education Level].[Partial College]}\n"
+ "{[Customers].[USA].[CA].[Burbank], [Education Level].[Partial High School]}\n"
+ "Row #0: 3,086\n"
+ "Row #1: 914\n"
+ "Row #2: 126\n"
+ "Row #3: 1,029\n"
+ "Row #4: 286\n"
+ "Row #5: 731\n");
context.withRole("Role1,Role2").assertQueryReturns(
mdx1,
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[*FORMATTED_MEASURE_0]}\n"
+ "Axis #2:\n"
+ "{[Customers].[USA].[CA].[Burbank], [Education Level].[All Education Levels]}\n"
+ "{[Customers].[USA].[CA].[Burbank], [Education Level].[Bachelors Degree]}\n"
+ "{[Customers].[USA].[CA].[Burbank], [Education Level].[Graduate Degree]}\n"
+ "{[Customers].[USA].[CA].[Burbank], [Education Level].[High School Degree]}\n"
+ "{[Customers].[USA].[CA].[Burbank], [Education Level].[Partial College]}\n"
+ "{[Customers].[USA].[CA].[Burbank], [Education Level].[Partial High School]}\n"
+ "{[Customers].[USA].[CA].[Coronado], [Education Level].[All Education Levels]}\n"
+ "{[Customers].[USA].[CA].[Coronado], [Education Level].[Bachelors Degree]}\n"
+ "{[Customers].[USA].[CA].[Coronado], [Education Level].[Graduate Degree]}\n"
+ "{[Customers].[USA].[CA].[Coronado], [Education Level].[High School Degree]}\n"
+ "{[Customers].[USA].[CA].[Coronado], [Education Level].[Partial College]}\n"
+ "{[Customers].[USA].[CA].[Coronado], [Education Level].[Partial High School]}\n"
+ "Row #0: 3,086\n"
+ "Row #1: 914\n"
+ "Row #2: 126\n"
+ "Row #3: 1,029\n"
+ "Row #4: 286\n"
+ "Row #5: 731\n"
+ "Row #6: 2,391\n"
+ "Row #7: 559\n"
+ "Row #8: 205\n"
+ "Row #9: 551\n"
+ "Row #10: 253\n"
+ "Row #11: 823\n");
// Actual tests
context.withRole("Role1").assertQueryReturns(
mdx2,
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[*FORMATTED_MEASURE_0]}\n"
+ "Axis #2:\n"
+ "{[Education Level].[All Education Levels]}\n"
+ "{[Education Level].[Bachelors Degree]}\n"
+ "{[Education Level].[Graduate Degree]}\n"
+ "{[Education Level].[High School Degree]}\n"
+ "{[Education Level].[Partial College]}\n"
+ "{[Education Level].[Partial High School]}\n"
+ "Row #0: 2,391\n"
+ "Row #1: 559\n"
+ "Row #2: 205\n"
+ "Row #3: 551\n"
+ "Row #4: 253\n"
+ "Row #5: 823\n");
context.withRole("Role2").assertQueryReturns(
mdx2,
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[*FORMATTED_MEASURE_0]}\n"
+ "Axis #2:\n"
+ "{[Education Level].[All Education Levels]}\n"
+ "{[Education Level].[Bachelors Degree]}\n"
+ "{[Education Level].[Graduate Degree]}\n"
+ "{[Education Level].[High School Degree]}\n"
+ "{[Education Level].[Partial College]}\n"
+ "{[Education Level].[Partial High School]}\n"
+ "Row #0: 3,086\n"
+ "Row #1: 914\n"
+ "Row #2: 126\n"
+ "Row #3: 1,029\n"
+ "Row #4: 286\n"
+ "Row #5: 731\n");
context.withRole("Role1,Role2").assertQueryReturns(
mdx2,
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[*FORMATTED_MEASURE_0]}\n"
+ "Axis #2:\n"
+ "{[Education Level].[All Education Levels]}\n"
+ "{[Education Level].[Bachelors Degree]}\n"
+ "{[Education Level].[Graduate Degree]}\n"
+ "{[Education Level].[High School Degree]}\n"
+ "{[Education Level].[Partial College]}\n"
+ "{[Education Level].[Partial High School]}\n"
+ "Row #0: 5,477\n"
+ "Row #1: 1,473\n"
+ "Row #2: 331\n"
+ "Row #3: 1,580\n"
+ "Row #4: 539\n"
+ "Row #5: 1,554\n");
}
/**
* This is a test for
* <a href="http://jira.pentaho.com/browse/MONDRIAN-1030">MONDRIAN-1030</a>
* When a query is based on a level higher than one in the same hierarchy
* which has access controls, it would only constrain at the current level
* if the rollup policy of partial is used.
*
* <p>Example. A query on USA where only Los-Angeles is accessible would
* return the values for California instead of only LA.
*/
public void testBugMondrian1030_2() {
TestContext.instance().create(
null, null, null, null, null,
"<Role name=\"Bacon\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Customers]\" access=\"custom\" rollupPolicy=\"partial\">\n"
+ " <MemberGrant member=\"[Customers].[USA].[CA].[Los Angeles]\" access=\"all\"/>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>")
.withRole("Bacon")
.assertQueryReturns(
"select {[Measures].[Unit Sales]} on 0,\n"
+ " {[Customers].[USA]} on 1\n"
+ "from [Sales]",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Customers].[USA]}\n"
+ "Row #0: 2,009\n");
}
/**
* Test for
* <a href="http://jira.pentaho.com/browse/MONDRIAN-1091">MONDRIAN-1091</a>
* The RoleImpl would try to search for member grants by object identity
* rather than unique name. When using the partial rollup policy, the
* members are wrapped, so identity checks would fail.
*/
public void testMondrian1091() throws Exception {
final TestContext testContext = TestContext.instance().create(
null, null, null, null, null,
"<Role name=\"Role1\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Store]\" access=\"custom\" rollupPolicy=\"partial\">\n"
+ " <MemberGrant member=\"[Store].[USA].[CA]\" access=\"all\"/>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>")
.withRole("Role1");
testContext.assertQueryReturns(
"select {[Store].Members} on columns from [Sales]",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Store].[All Stores]}\n"
+ "{[Store].[USA]}\n"
+ "{[Store].[USA].[CA]}\n"
+ "{[Store].[USA].[CA].[Alameda]}\n"
+ "{[Store].[USA].[CA].[Alameda].[HQ]}\n"
+ "{[Store].[USA].[CA].[Beverly Hills]}\n"
+ "{[Store].[USA].[CA].[Beverly Hills].[Store 6]}\n"
+ "{[Store].[USA].[CA].[Los Angeles]}\n"
+ "{[Store].[USA].[CA].[Los Angeles].[Store 7]}\n"
+ "{[Store].[USA].[CA].[San Diego]}\n"
+ "{[Store].[USA].[CA].[San Diego].[Store 24]}\n"
+ "{[Store].[USA].[CA].[San Francisco]}\n"
+ "{[Store].[USA].[CA].[San Francisco].[Store 14]}\n"
+ "Row #0: 74,748\n"
+ "Row #0: 74,748\n"
+ "Row #0: 74,748\n"
+ "Row #0: \n"
+ "Row #0: \n"
+ "Row #0: 21,333\n"
+ "Row #0: 21,333\n"
+ "Row #0: 25,663\n"
+ "Row #0: 25,663\n"
+ "Row #0: 25,635\n"
+ "Row #0: 25,635\n"
+ "Row #0: 2,117\n"
+ "Row #0: 2,117\n");
org.olap4j.metadata.Cube cube =
testContext.getOlap4jConnection()
.getOlapSchema().getCubes().get("Sales");
org.olap4j.metadata.Member allMember =
cube.lookupMember(
IdentifierNode.parseIdentifier("[Store].[All Stores]")
.getSegmentList());
assertNotNull(allMember);
assertEquals(1, allMember.getHierarchy().getRootMembers().size());
assertEquals(
"[Store].[All Stores]",
allMember.getHierarchy().getRootMembers().get(0).getUniqueName());
}
/**
* Unit test for
* <a href="http://jira.pentaho.com/browse/mondrian-1259">MONDRIAN-1259,
* "Mondrian security: access leaks from one user to another"</a>.
*
* <p>Enhancements made to the SmartRestrictedMemberReader were causing
* security leaks between roles and potential class cast exceptions.
*/
public void testMondrian1259() throws Exception {
final String mdx =
"select non empty {[Store].Members} on columns from [Sales]";
final TestContext testContext = TestContext.instance().create(
null, null, null, null, null,
"<Role name=\"Role1\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Store]\" access=\"custom\" rollupPolicy=\"partial\">\n"
+ " <MemberGrant member=\"[Store].[USA].[CA]\" access=\"all\"/>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>"
+ "<Role name=\"Role2\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Store]\" access=\"custom\" rollupPolicy=\"partial\">\n"
+ " <MemberGrant member=\"[Store].[USA].[OR]\" access=\"all\"/>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>");
testContext.withRole("Role1").assertQueryReturns(
mdx,
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Store].[All Stores]}\n"
+ "{[Store].[USA]}\n"
+ "{[Store].[USA].[CA]}\n"
+ "{[Store].[USA].[CA].[Beverly Hills]}\n"
+ "{[Store].[USA].[CA].[Beverly Hills].[Store 6]}\n"
+ "{[Store].[USA].[CA].[Los Angeles]}\n"
+ "{[Store].[USA].[CA].[Los Angeles].[Store 7]}\n"
+ "{[Store].[USA].[CA].[San Diego]}\n"
+ "{[Store].[USA].[CA].[San Diego].[Store 24]}\n"
+ "{[Store].[USA].[CA].[San Francisco]}\n"
+ "{[Store].[USA].[CA].[San Francisco].[Store 14]}\n"
+ "Row #0: 74,748\n"
+ "Row #0: 74,748\n"
+ "Row #0: 74,748\n"
+ "Row #0: 21,333\n"
+ "Row #0: 21,333\n"
+ "Row #0: 25,663\n"
+ "Row #0: 25,663\n"
+ "Row #0: 25,635\n"
+ "Row #0: 25,635\n"
+ "Row #0: 2,117\n"
+ "Row #0: 2,117\n");
testContext.withRole("Role2").assertQueryReturns(
mdx,
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Store].[All Stores]}\n"
+ "{[Store].[USA]}\n"
+ "{[Store].[USA].[OR]}\n"
+ "{[Store].[USA].[OR].[Portland]}\n"
+ "{[Store].[USA].[OR].[Portland].[Store 11]}\n"
+ "{[Store].[USA].[OR].[Salem]}\n"
+ "{[Store].[USA].[OR].[Salem].[Store 13]}\n"
+ "Row #0: 67,659\n"
+ "Row #0: 67,659\n"
+ "Row #0: 67,659\n"
+ "Row #0: 26,079\n"
+ "Row #0: 26,079\n"
+ "Row #0: 41,580\n"
+ "Row #0: 41,580\n");
}
public void testMondrian1295() throws Exception {
final String mdx =
"With\n"
+ "Set [*NATIVE_CJ_SET] as 'NonEmptyCrossJoin([*BASE_MEMBERS_Time],[*BASE_MEMBERS_Product])'\n"
+ "Set [*SORTED_ROW_AXIS] as 'Order([*CJ_ROW_AXIS],Ancestor([Time].CurrentMember, [Time].[Year]).OrderKey,BASC,Ancestor([Time].CurrentMember, [Time].[Quarter]).OrderKey,BASC,[Time].CurrentMember.OrderKey,BASC,[Product].CurrentMember.OrderKey,BASC)'\n"
+ "Set [*BASE_MEMBERS_Product] as '{[Product].[All Products]}'\n"
+ "Set [*BASE_MEMBERS_Measures] as '{[Measures].[*FORMATTED_MEASURE_0]}'\n"
+ "Set [*CJ_ROW_AXIS] as 'Generate([*NATIVE_CJ_SET], {([Time].currentMember,[Product].currentMember)})'\n"
+ "Set [*BASE_MEMBERS_Time] as '[Time].[Year].Members'\n"
+ "Set [*CJ_COL_AXIS] as '[*NATIVE_CJ_SET]'\n"
+ "Member [Measures].[*FORMATTED_MEASURE_0] as '[Measures].[Unit Sales]', FORMAT_STRING = 'Standard', SOLVE_ORDER=400\n"
+ "Select\n"
+ "[*BASE_MEMBERS_Measures] on columns,\n"
+ "Non Empty [*SORTED_ROW_AXIS] on rows\n"
+ "From [Sales]\n";
final TestContext context =
getTestContext().create(
null, null, null, null, null,
"<Role name=\"Admin\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Store]\" rollupPolicy=\"partial\" access=\"custom\">\n"
+ " <MemberGrant member=\"[Store].[USA].[CA]\" access=\"all\">\n"
+ " </MemberGrant>\n"
+ " </HierarchyGrant>\n"
+ " <HierarchyGrant hierarchy=\"[Customers]\" rollupPolicy=\"partial\" access=\"custom\">\n"
+ " <MemberGrant member=\"[Customers].[USA].[CA]\" access=\"all\">\n"
+ " </MemberGrant>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role> \n");
// Control
context
.assertQueryReturns(
"select {[Measures].[Unit Sales]} on columns from [Sales]",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Row #0: 266,773\n");
context.withRole("Admin")
.assertQueryReturns(
"select {[Measures].[Unit Sales]} on columns from [Sales]",
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Row #0: 74,748\n");
// Test
context.withRole("Admin")
.assertQueryReturns(
mdx,
"Axis #0:\n"
+ "{}\n"
+ "Axis #1:\n"
+ "{[Measures].[*FORMATTED_MEASURE_0]}\n"
+ "Axis #2:\n"
+ "{[Time].[1997], [Product].[All Products]}\n"
+ "Row #0: 74,748\n");
}
public void testMondrian936() throws Exception {
final TestContext testContext = TestContext.instance().create(
null, null, null, null, null,
"<Role name=\"test\">\n"
+ " <SchemaGrant access=\"none\">\n"
+ " <CubeGrant cube=\"Sales\" access=\"all\">\n"
+ " <HierarchyGrant hierarchy=\"[Store]\" access=\"custom\"\n"
+ " topLevel=\"[Store].[Store Country]\" rollupPolicy=\"partial\">\n"
+ " <MemberGrant member=\"[Store].[All Stores]\" access=\"none\"/>\n"
+ " <MemberGrant member=\"[Store].[USA].[CA].[Los Angeles]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[USA].[CA].[Alameda]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[USA].[CA].[Beverly Hills]\"\n"
+ "access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[USA].[CA].[San Francisco]\"\n"
+ "access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[USA].[CA].[San Diego]\" access=\"all\"/>\n"
+ "\n"
+ " <MemberGrant member=\"[Store].[USA].[OR].[Portland]\" access=\"all\"/>\n"
+ " <MemberGrant member=\"[Store].[USA].[OR].[Salem]\" access=\"all\"/>\n"
+ " </HierarchyGrant>\n"
+ " </CubeGrant>\n"
+ " </SchemaGrant>\n"
+ "</Role>");
testContext.withRole("test").assertQueryReturns(
"select {[Measures].[Unit Sales]} on columns, "
+ " {[Product].[Food].[Baked Goods].[Bread]} on rows "
+ " from [Sales] "
+ " where { [Store].[USA].[OR], [Store].[USA].[CA]} ", "Axis #0:\n"
+ "{[Store].[USA].[OR]}\n"
+ "{[Store].[USA].[CA]}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Product].[Food].[Baked Goods].[Bread]}\n"
+ "Row #0: 4,163\n");
// changing ordering of members in the slicer should not change
// result
testContext.withRole("test").assertQueryReturns(
"select {[Measures].[Unit Sales]} on columns, "
+ " {[Product].[Food].[Baked Goods].[Bread]} on rows "
+ " from [Sales] "
+ " where { [Store].[USA].[CA], [Store].[USA].[OR]} ", "Axis #0:\n"
+ "{[Store].[USA].[CA]}\n"
+ "{[Store].[USA].[OR]}\n"
+ "Axis #1:\n"
+ "{[Measures].[Unit Sales]}\n"
+ "Axis #2:\n"
+ "{[Product].[Food].[Baked Goods].[Bread]}\n"
+ "Row #0: 4,163\n");
Result result = testContext.withRole("test").executeQuery(
"with member store.aggCaliforniaOregon as "
+ "'aggregate({ [Store].[USA].[CA], [Store].[USA].[OR]})'"
+ " select store.aggCaliforniaOregon on 0 from sales");
String valueAggMember = result
.getCell(new int[] {0}).getFormattedValue();
result = testContext.withRole("test").executeQuery(
" select from sales where "
+ "{ [Store].[USA].[CA], [Store].[USA].[OR]}");
String valueSlicerAgg = result
.getCell(new int[] {}).getFormattedValue();
// aggregating CA & OR in a calc member should produce same result
// as aggregating in the slicer.
assertTrue(valueAggMember.equals(valueSlicerAgg));
}
public void testMondrian1434() {
String roleDef =
"<Role name=\"dev\">"
+ " <SchemaGrant access=\"all\">"
+ " <CubeGrant cube=\"Sales\" access=\"all\">"
+ " </CubeGrant>"
+ " <CubeGrant cube=\"HR\" access=\"all\">"
+ " </CubeGrant>"
+ " <CubeGrant cube=\"Warehouse and Sales\" access=\"all\">"
+ " <HierarchyGrant hierarchy=\"Measures\" access=\"custom\">"
+ " <MemberGrant member=\"[Measures].[Warehouse Sales]\" access=\"all\">"
+ " </MemberGrant>"
+ " </HierarchyGrant>"
+ " </CubeGrant>"
+ " </SchemaGrant>"
+ "</Role>";
TestContext testContext = TestContext.instance()
.create(null, null, null, null, null, roleDef).withRole("dev");
testContext.executeQuery(
" select from [Sales] where {[Measures].[Unit Sales]}");
// test is that there is no exception
}
}
// End AccessControlTest.java
|
MONDRIAN-1434 - creating additional test case for when the base cube is restricted and the query is against the virtual cube.
|
testsrc/main/mondrian/test/AccessControlTest.java
|
MONDRIAN-1434 - creating additional test case for when the base cube is restricted and the query is against the virtual cube.
|
|
Java
|
epl-1.0
|
04c82f2291f610783b347c62aefb0a0fe737afdf
| 0
|
jenskastensson/openhab,jenskastensson/openhab,jenskastensson/openhab,jenskastensson/openhab,jenskastensson/openhab,jenskastensson/openhab,jenskastensson/openhab
|
/**
* Copyright (c) 2010-2014, openHAB.org and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.proserv.internal;
//import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.openhab.config.core.ConfigDispatcher;
import org.openhab.core.library.types.DecimalType;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.Dictionary;
import org.apache.commons.lang.StringUtils;
import org.openhab.binding.proserv.ProservBindingProvider;
import org.openhab.core.binding.AbstractActiveBinding;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.openhab.action.mail.internal.Mail;
//import java.io.PrintWriter;
//import org.rrd4j.core.RrdDb;
//import org.rrd4j.graph.RrdGraph;
//import org.rrd4j.graph.RrdGraphDef;
/**
* The proServ binding connects to a proServ device with the
* {@link ProservConnector} and read the internal state array every minute. With
* the state array each binding will be updated.
*
* @author JEKA
* @since 1.0.0
*/
@SuppressWarnings("unused")
public class ProservBinding extends AbstractActiveBinding<ProservBindingProvider> implements ManagedService {
private static final Logger logger = LoggerFactory.getLogger(ProservBinding.class);
private static ProservConnector connector = null;
/** Default refresh interval (currently 1 minute) */
private long refreshInterval = 60000L;
/* The IP address to connect to */
private static String ip;
private static int port = 80;
private static String mailTo = "";
private static String mailSubject = "";
private static String mailContent = "";
private static Boolean previousEmailTrigger = null;
private static String chartItemRefreshHour = null;
private static String chartItemRefreshDay = null;
private static String chartItemRefreshWeek = null;
private static String chartItemRefreshMonth = null;
private static String chartItemRefreshYear = null;
private ProservData proservData = null;
public void deactivate() {
connector.stopMonitor();
if (connector != null) {
connector.disconnect();
}
connector = null;
}
public void activate() {
// if(getRefreshInterval()>10000)
// execute();
// if(connector==null)
// {
// connector = new ProservConnector(ip, port);
// connector.startMonitor();
// }
}
/**
* {@inheritDoc}
*/
@SuppressWarnings("rawtypes")
public void updated(Dictionary config) throws ConfigurationException {
if (config != null) {
String ip = (String) config.get("ip");
String portString = (String) config.get("port");
ProservBinding.mailTo = (String) config.get("mailto");
ProservBinding.mailSubject = (String) config.get("mailsubject");
ProservBinding.mailContent = (String) config.get("mailcontent");
ProservBinding.chartItemRefreshHour = (String) config.get("chartItemRefreshHour");
ProservBinding.chartItemRefreshDay = (String) config.get("chartItemRefreshDay");
ProservBinding.chartItemRefreshWeek = (String) config.get("chartItemRefreshWeek");
ProservBinding.chartItemRefreshMonth = (String) config.get("chartItemRefreshMonth");
ProservBinding.chartItemRefreshYear = (String) config.get("chartItemRefreshYear");
if(ProservBinding.chartItemRefreshHour != null)
if(Integer.parseInt(ProservBinding.chartItemRefreshHour)<5000)
ProservBinding.chartItemRefreshHour = "5000";
if(ProservBinding.chartItemRefreshDay != null)
if(Integer.parseInt(ProservBinding.chartItemRefreshDay)<5000)
ProservBinding.chartItemRefreshDay = "5000";
if(ProservBinding.chartItemRefreshWeek != null)
if(Integer.parseInt(ProservBinding.chartItemRefreshWeek)<5000)
ProservBinding.chartItemRefreshWeek = "5000";
if(ProservBinding.chartItemRefreshMonth != null)
if(Integer.parseInt(ProservBinding.chartItemRefreshMonth)<5000)
ProservBinding.chartItemRefreshMonth = "5000";
if(ProservBinding.chartItemRefreshYear != null)
if(Integer.parseInt(ProservBinding.chartItemRefreshYear)<5000)
ProservBinding.chartItemRefreshYear = "5000";
int portTmp = 80;
if (StringUtils.isNotBlank(portString)) {
portTmp = (int) Long.parseLong(portString);
}
if ((StringUtils.isNotBlank(ip) && !ip.equals(ProservBinding.ip)) || portTmp != ProservBinding.port) {
// only do something if the ip or port has changed
ProservBinding.ip = ip;
ProservBinding.port = portTmp;
String refreshIntervalString = (String) config.get("refresh");
if (StringUtils.isNotBlank(refreshIntervalString)) {
refreshInterval = Long.parseLong(refreshIntervalString);
}
setProperlyConfigured(true);
}
}
}
public static String padRight(String s, int n) {
return String.format("%1$-" + n + "s", s);
}
public void sendMail() {
// String pathrrd = ConfigDispatcher.getConfigFolder() + File.separator + ".." +
// File.separator + "etc" + File.separator + "rrd4j" + File.separator + "itemProServLog0.rrd";
// String pathxml = ConfigDispatcher.getConfigFolder() + File.separator + ".." +
// File.separator + "etc" + File.separator + "rrd4j" + File.separator + "itemProServLog0.xml";
// String pathdmp = ConfigDispatcher.getConfigFolder() + File.separator + ".." +
// File.separator + "etc" + File.separator + "rrd4j" + File.separator + "itemProServLog0.txt";
// try {
// RrdDb rrd = new RrdDb(pathrrd);
// rrd.dumpXml(pathxml);
// PrintWriter writer = new PrintWriter(pathdmp, "ISO-8859-1");
// writer.write(rrd.dump());
// writer.close();
// } catch (IOException e1) {
// // TODO Auto-generated catch block
// e1.printStackTrace();
// }
String path = ConfigDispatcher.getConfigFolder() + File.separator + ".." +
File.separator + "logs" + File.separator + "proserv.log";
URL url = null;
try {
url = new File(path).toURI().toURL();
} catch (MalformedURLException e) {
e.printStackTrace();
}
Mail.sendMail(mailTo, mailSubject, mailContent, url.toString());
}
public void updateSendEmail(int x, int y, byte[] dataValue) {
int startDatapoint = (48*x) + (y*3) + 1;
proservData.setFunctionDataPoint(startDatapoint, x, y, 0);
switch ((int)proservData.getFunctionCodes(x, y) & 0xFF) {
case 0x31:{
boolean b = proservData.parse1ByteBooleanValue(dataValue[0]);
if(proservData.getFunctionStateIsInverted(x,y))
b = !b;
if(previousEmailTrigger!=null && previousEmailTrigger==false && b==true && proservData.getFunctionIsEmailTrigger(x, y))
{
sendMail();
}
previousEmailTrigger = b;
} break;
default:
logger.debug("proServ binding, unhandled functioncode 0x{}",
Integer.toHexString(((int)proservData.getFunctionCodes(x, y) & 0xFF)));
}
}
// The postUpdateSingleValueFunction function takes one function value, identified by x, y & z
// (z signifies actual or setpoint) and a single value as input and post update on the event bus.
// It is called from the the Monitor thread when the proServ notifies for a value change.
public void postUpdateSingleValueFunction(int x, int y, int z, byte[] dataValue) {
int startDatapoint = (48*x) + (y*3) + 1;
int Id = proservData.getFunctionMapId(x,y,z);
switch ((int)proservData.getFunctionCodes(x, y) & 0xFF) {
case 0x01:{
boolean b = proservData.parse1ByteBooleanValue(dataValue[0]);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id), new DecimalType(b?1:0));
} break;
case 0x02:{
int i = proservData.parse1BytePercentValue(dataValue[0]);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id), new DecimalType(i));
} break;
case 0x12:{
int i = proservData.parse1BytePercentValue(dataValue[0]);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id), new DecimalType(i));
} break;
case 0x31:{
boolean b = proservData.parse1ByteBooleanValue(dataValue[0]);
if(proservData.getFunctionStateIsInverted(x,y))
b = !b;
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id), new DecimalType(b?1:0));
} break;
case 0x26:
case 0x34:{
float f = proservData.parse2ByteFloatValue(dataValue,0);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id),
new DecimalType(new BigDecimal(f).setScale(2, RoundingMode.HALF_EVEN)));
} break;
case 0x38:{
float f = proservData.parse4ByteFloatValue(dataValue,0);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id),
new DecimalType(new BigDecimal(f).setScale(2, RoundingMode.HALF_EVEN)));
} break;
case 0x91:{
int i = proservData.parse1BytePercentValue(dataValue[0]);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id), new DecimalType(i));
} break;
case 0x92:{
int i = proservData.parse1ByteUnsignedValue(dataValue[0]);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id), new DecimalType(i));
} break;
case 0x94:{
float f = proservData.parse2ByteFloatValue(dataValue,0);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id),
new DecimalType(new BigDecimal(f).setScale(2, RoundingMode.HALF_EVEN)));
} break;
case 0x95:{
long uint32 = proservData.parse4ByteUnsignedValue(dataValue,0);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id), new DecimalType(uint32));
} break;
case 0x96:{
long int32 = proservData.parse4ByteSignedValue(dataValue,0);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id), new DecimalType(int32));
} break;
case 0x97:{
float f = proservData.parse4ByteFloatValue(dataValue,0);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id),
new DecimalType(new BigDecimal(f).setScale(2, RoundingMode.HALF_EVEN)));
} break;
default:
logger.debug("proServ binding, unhandled functioncode 0x{}",
Integer.toHexString(((int)proservData.getFunctionCodes(x, y) & 0xFF)));
}
shortDelayBetweenBusEvents();
}
// The postUpdateFunction function takes one function value, x & y
// and a buffer with 3 data values as input and post update on the event bus.
// It is called from the the polling thread.
// The postUpdateFunction also fill the proservData functionDataPoint values which are later used
// for lookup in the monitor thread. That is the async value update will only work after one successful data poll.
public void postUpdateFunction(int x, int y, byte[] dataValue) {
int startDatapoint = (48*x) + (y*3) + 1;
int Id = proservData.getFunctionMapId(x,y,0);
int IdPreset = proservData.getFunctionMapId(x,y,1);
proservData.setFunctionDataPoint(startDatapoint, x, y, 0);
switch ((int)proservData.getFunctionCodes(x, y) & 0xFF) {
case 0x01:{
proservData.setFunctionDataPoint(startDatapoint+1, x, y, 0);
boolean b = proservData.parse1ByteBooleanValue(dataValue[1]);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id), new DecimalType(b?1:0));
} break;
case 0x02:{
proservData.setFunctionDataPoint(startDatapoint+1, x, y, 0);
int i = proservData.parse1BytePercentValue(dataValue[1]);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id), new DecimalType(i));
} break;
case 0x12:{
proservData.setFunctionDataPoint(startDatapoint+2, x, y, 0);
int i = proservData.parse1BytePercentValue(dataValue[2]);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id), new DecimalType(i));
} break;
case 0x31:{
boolean b = proservData.parse1ByteBooleanValue(dataValue[0]);
if(proservData.getFunctionStateIsInverted(x,y))
b = !b;
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id), new DecimalType(b?1:0));
} break;
case 0x26:
case 0x34:{
float f = proservData.parse2ByteFloatValue(dataValue,0);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id),
new DecimalType(new BigDecimal(f).setScale(2, RoundingMode.HALF_EVEN)));
} break;
case 0x38:{
float f = proservData.parse4ByteFloatValue(dataValue,0);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id),
new DecimalType(new BigDecimal(f).setScale(2, RoundingMode.HALF_EVEN)));
} break;
case 0x91:{
if(proservData.getFunctionLogThis(x,y,0)) {
int i = proservData.parse1BytePercentValue(dataValue[0]);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id), new DecimalType(i));
}
if(proservData.getFunctionLogThis(x,y,1)) {
shortDelayBetweenBusEvents();
proservData.setFunctionDataPoint(startDatapoint+2, x, y, 1);
int preset = proservData.parse1BytePercentValue(dataValue[2]);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(IdPreset), new DecimalType(preset));
}
} break;
case 0x92:{
if(proservData.getFunctionLogThis(x,y,0)) {
int i = proservData.parse1ByteUnsignedValue(dataValue[0]);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id), new DecimalType(i));
}
if(proservData.getFunctionLogThis(x,y,1)) {
shortDelayBetweenBusEvents();
proservData.setFunctionDataPoint(startDatapoint+2, x, y, 1);
int preset = proservData.parse1ByteUnsignedValue(dataValue[2]);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(IdPreset),new DecimalType(preset));
}
} break;
case 0x94:{
if(proservData.getFunctionLogThis(x,y,0)) {
float f = proservData.parse2ByteFloatValue(dataValue,0);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id),
new DecimalType(new BigDecimal(f).setScale(2, RoundingMode.HALF_EVEN)));
}
if(proservData.getFunctionLogThis(x,y,1)) {
shortDelayBetweenBusEvents();
proservData.setFunctionDataPoint(startDatapoint+2, x, y, 1);
float f = proservData.parse2ByteFloatValue(dataValue,4);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(IdPreset),
new DecimalType(new BigDecimal(f).setScale(2, RoundingMode.HALF_EVEN)));
}
} break;
case 0x95:{
if(proservData.getFunctionLogThis(x,y,0)) {
long uint32 = proservData.parse4ByteUnsignedValue(dataValue,0);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id), new DecimalType(uint32));
}
if(proservData.getFunctionLogThis(x,y,1)) {
shortDelayBetweenBusEvents();
proservData.setFunctionDataPoint(startDatapoint+2, x, y, 1);
long uint32Preset = proservData.parse4ByteUnsignedValue(dataValue,8);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(IdPreset),
new DecimalType(uint32Preset));
}
} break;
case 0x96:{
if(proservData.getFunctionLogThis(x,y,0)) {
long int32 = proservData.parse4ByteSignedValue(dataValue,0);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id), new DecimalType(int32));
}
if(proservData.getFunctionLogThis(x,y,1)) {
shortDelayBetweenBusEvents();
proservData.setFunctionDataPoint(startDatapoint+2, x, y, 1);
long int32Preset = proservData.parse4ByteSignedValue(dataValue,8);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(IdPreset),
new DecimalType(int32Preset));
}
} break;
case 0x97:{
if(proservData.getFunctionLogThis(x,y,0)) {
float f = proservData.parse4ByteFloatValue(dataValue,0);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id),
new DecimalType(new BigDecimal(f).setScale(2, RoundingMode.HALF_EVEN)));
}
if(proservData.getFunctionLogThis(x,y,1)) {
shortDelayBetweenBusEvents();
proservData.setFunctionDataPoint(startDatapoint+2, x, y, 1);
float f = proservData.parse4ByteFloatValue(dataValue,8);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(IdPreset),
new DecimalType(new BigDecimal(f).setScale(2, RoundingMode.HALF_EVEN)));
}
} break;
default:
logger.debug("proServ binding, unhandled functioncode 0x{}",
Integer.toHexString(((int)proservData.getFunctionCodes(x, y) & 0xFF)));
}
shortDelayBetweenBusEvents();
}
// The postUpdateSingleValueHeating function takes one heating value, x (z signifies actual or setpoint)
// and a single value as input and post update on the event bus.
// It is called from the the Monitor thread when the proServ notifies for a value change.
public void postUpdateSingleValueHeating(int x, int z, byte[] dataValue) {
int Id = proservData.getHeatingMapId(x,z);
int startDatapoint = 865 + x * 5;
switch ( (int)(proservData.getHeatingCodes(x) & 0xFF) ) {
case 0x41:
case 0x42:
case 0x43:
case 0x44:
float f = proservData.parse2ByteFloatValue(dataValue, 0);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id),
new DecimalType(new BigDecimal(f).setScale(2, RoundingMode.HALF_EVEN)));
break;
default:
logger.debug("proServ binding, unhandled heatingCode {}", Integer.toHexString(((int)proservData.getHeatingCodes(x) & 0xFF)));
}
}
// The postUpdateHeating function takes one heating value, x
// and a buffer with 3 data values as input and post update on the event bus.
// It is called from the the polling thread.
// The postUpdateHeating also fill the proservData heatingDataPoint values which are later used
// for lookup in the monitor thread. That is the async value update will only work after one successful data poll.
public void postUpdateHeating(int x, byte[] dataValue) {
int IdActual = proservData.getHeatingMapId(x,0);
int IdPreset = proservData.getHeatingMapId(x,1);
int startDatapoint = 865 + x * 5;
switch ( (int)(proservData.getHeatingCodes(x) & 0xFF) ) {
case 0x41:
case 0x42:
case 0x43:
case 0x44:
proservData.setHeatingDataPoint(startDatapoint, x, 0);
float f0 = proservData.parse2ByteFloatValue(dataValue, 0);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(IdActual),
new DecimalType(new BigDecimal(f0).setScale(2, RoundingMode.HALF_EVEN)));
proservData.setHeatingDataPoint(startDatapoint+2, x, 1);
float f1 = proservData.parse2ByteFloatValue(dataValue, 4);
shortDelayBetweenBusEvents();
eventPublisher.postUpdate("itemProServLog" + Integer.toString(IdPreset),
new DecimalType(new BigDecimal(f1).setScale(2, RoundingMode.HALF_EVEN)));
logger.info("{}{}: {}{}: {}", padRight(proservData.getHeatingDescription(x), 20),
padRight(proservData.getStringProservLang(0), 5), padRight(Float.toString(f0), 10),
padRight(proservData.getStringProservLang(1), 5), padRight(Float.toString(f1), 10));
break;
default:
logger.debug("proServ binding, unhandled heatingCode {}", Integer.toHexString(((int)proservData.getHeatingCodes(x) & 0xFF)));
}
}
@Override
public void execute() {
logger.debug("proServ binding refresh cycle starts!");
if(connector==null)
{
connector = new ProservConnector(ip, port);
}
try {
connector.connect();
if (proservData == null) {
proservData = new ProservData(chartItemRefreshHour,chartItemRefreshDay, chartItemRefreshWeek, chartItemRefreshMonth, chartItemRefreshYear );
byte[] proservAllConfigValues = getConfigValues();
if (proservAllConfigValues == null) {
logger.debug("proServ getConfigValues failed try again");
proservAllConfigValues = getConfigValues(); // try again..
}
if (proservAllConfigValues != null) {
proservData.parseRawConfigData(proservAllConfigValues);
proservData.updateProservMapFile();
proservData.updateProservItemFile();
proservData.updateProservSitemapFile();
proservData.updateRrd4jPersistFile();
proservData.updateDb4oPersistFile();
connector.startMonitor(this.eventPublisher, this.proservData, this);
} else {
logger.debug("proServ getConfigValues failed twice in a row, try next refresh cycle!");
proservData = null; // force a reload of configdata
}
}
if (proservData != null) {
// function 1-1 .. function 18-16
for (int x = 0; x < 18; x++) {
for (int y = 0; y < 16; y++) {
if(proservData.getFunctionLogThis(x,y,0) || proservData.getFunctionLogThis(x,y,1) ||
proservData.getFunctionIsEmailTrigger(x,y)) {
int startDatapoint = (48*x) + (y*3) + 1;
int numberOfDatapoints = 3;
byte[] dataValue = connector.getDataPointValue((short) startDatapoint, (short) numberOfDatapoints);
if (dataValue != null) {
if(proservData.getFunctionLogThis(x,y,0) || proservData.getFunctionLogThis(x,y,1)) {
postUpdateFunction(x, y, dataValue);
}
if(proservData.getFunctionIsEmailTrigger(x,y)) {
updateSendEmail(x, y, dataValue);
}
}
}
}
}
// heating 1-18
for (int x = 0; x < 18; x++) {
if (proservData.getHeatingLogThis(x)) {
int startDatapoint = 865 + x * 5;
int numberOfDatapoints = 5;
byte[] dataValue = connector.getDataPointValue((short) startDatapoint, (short) numberOfDatapoints);
if (dataValue != null) {
postUpdateHeating(x, dataValue);
}
}
}
}
logger.debug("proServ binding refresh cycle completed");
} catch (NullPointerException e) {
logger.warn("proServ NullPointerException");
} catch (UnsupportedEncodingException e) {
logger.warn("proServ UnsupportedEncodingException");
} catch (UnknownHostException e) {
logger.warn("proServ the given hostname '{}' : port'{}' of the proServ is unknown", ip, port);
} catch (IOException e) {
logger.warn("proServ couldn't establish network connection [host '{}' : port'{}'] error:'{}'", ip, port, e);
} catch (Exception e) {
logger.warn("proServ Exception in execute error:{}", e);
} finally {
logger.debug("proServ binding refresh cycle reached finally");
if (connector != null) {
connector.disconnect();
}
}
}
private void shortDelayBetweenBusEvents() {
try {
Thread.sleep(100);
} catch (InterruptedException ie) {
// Handle the exception
}
}
private byte[] getConfigValues() {
byte[] proservAllConfigValues = null;
try {
short PROSERV_MEMORY_LENGTH = 19500;
short NUMBER_OF_BYTES_IN_CHUNK = 500;
proservAllConfigValues = new byte[PROSERV_MEMORY_LENGTH];
// read a chunk of values
short startByte = 1;
for (int chunkId = 0;; chunkId++) {
short numberOfBytesToRead = NUMBER_OF_BYTES_IN_CHUNK;
if (startByte + NUMBER_OF_BYTES_IN_CHUNK >= PROSERV_MEMORY_LENGTH)
numberOfBytesToRead = (short) (PROSERV_MEMORY_LENGTH - startByte);
byte[] proServValues = null;
for(int attempt=0;attempt<4;attempt++){
proServValues = connector.getParameterBytes(startByte, numberOfBytesToRead);
if(proServValues!=null)
break;
}
if(proServValues==null)
{
logger.info("proServ getConfigValues failed proServValues==null");
return null;
}
int offset = chunkId * NUMBER_OF_BYTES_IN_CHUNK;
startByte += NUMBER_OF_BYTES_IN_CHUNK;
for (int i = 0; i < numberOfBytesToRead; i++) {
proservAllConfigValues[offset + i] = proServValues[i];
}
if (numberOfBytesToRead != NUMBER_OF_BYTES_IN_CHUNK)
break;
if (offset > 10300)
break; // quick fix for now
}
logger.debug("proServ succesfully loaded all config values");
}
finally {
}
return proservAllConfigValues;
}
@Override
protected long getRefreshInterval() {
return refreshInterval;
}
@Override
protected String getName() {
return "proServ Refresh Service";
}
}
|
bundles/binding/org.openhab.binding.proserv/src/main/java/org/openhab/binding/proserv/internal/ProservBinding.java
|
/**
* Copyright (c) 2010-2014, openHAB.org and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.proserv.internal;
//import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.openhab.config.core.ConfigDispatcher;
import org.openhab.core.library.types.DecimalType;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.Dictionary;
import org.apache.commons.lang.StringUtils;
import org.openhab.binding.proserv.ProservBindingProvider;
import org.openhab.core.binding.AbstractActiveBinding;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.openhab.action.mail.internal.Mail;
//import java.io.PrintWriter;
//import org.rrd4j.core.RrdDb;
//import org.rrd4j.graph.RrdGraph;
//import org.rrd4j.graph.RrdGraphDef;
/**
* The proServ binding connects to a proServ device with the
* {@link ProservConnector} and read the internal state array every minute. With
* the state array each binding will be updated.
*
* @author JEKA
* @since 1.0.0
*/
@SuppressWarnings("unused")
public class ProservBinding extends AbstractActiveBinding<ProservBindingProvider> implements ManagedService {
private static final Logger logger = LoggerFactory.getLogger(ProservBinding.class);
private static ProservConnector connector = null;
/** Default refresh interval (currently 1 minute) */
private long refreshInterval = 60000L;
/* The IP address to connect to */
private static String ip;
private static int port = 80;
private static String mailTo = "";
private static String mailSubject = "";
private static String mailContent = "";
private static Boolean previousEmailTrigger = null;
private static String chartItemRefreshHour = null;
private static String chartItemRefreshDay = null;
private static String chartItemRefreshWeek = null;
private static String chartItemRefreshMonth = null;
private static String chartItemRefreshYear = null;
private ProservData proservData = null;
public void deactivate() {
connector.stopMonitor();
if (connector != null) {
connector.disconnect();
}
connector = null;
}
public void activate() {
// if(getRefreshInterval()>10000)
// execute();
// if(connector==null)
// {
// connector = new ProservConnector(ip, port);
// connector.startMonitor();
// }
}
/**
* {@inheritDoc}
*/
@SuppressWarnings("rawtypes")
public void updated(Dictionary config) throws ConfigurationException {
if (config != null) {
String ip = (String) config.get("ip");
String portString = (String) config.get("port");
ProservBinding.mailTo = (String) config.get("mailto");
ProservBinding.mailSubject = (String) config.get("mailsubject");
ProservBinding.mailContent = (String) config.get("mailcontent");
ProservBinding.chartItemRefreshHour = (String) config.get("chartItemRefreshHour");
ProservBinding.chartItemRefreshDay = (String) config.get("chartItemRefreshDay");
ProservBinding.chartItemRefreshWeek = (String) config.get("chartItemRefreshWeek");
ProservBinding.chartItemRefreshMonth = (String) config.get("chartItemRefreshMonth");
ProservBinding.chartItemRefreshYear = (String) config.get("chartItemRefreshYear");
if(ProservBinding.chartItemRefreshHour != null)
if(Integer.parseInt(ProservBinding.chartItemRefreshHour)<5000)
ProservBinding.chartItemRefreshHour = "5000";
if(ProservBinding.chartItemRefreshDay != null)
if(Integer.parseInt(ProservBinding.chartItemRefreshDay)<5000)
ProservBinding.chartItemRefreshDay = "5000";
if(ProservBinding.chartItemRefreshWeek != null)
if(Integer.parseInt(ProservBinding.chartItemRefreshWeek)<5000)
ProservBinding.chartItemRefreshWeek = "5000";
if(ProservBinding.chartItemRefreshMonth != null)
if(Integer.parseInt(ProservBinding.chartItemRefreshMonth)<5000)
ProservBinding.chartItemRefreshMonth = "5000";
if(ProservBinding.chartItemRefreshYear != null)
if(Integer.parseInt(ProservBinding.chartItemRefreshYear)<5000)
ProservBinding.chartItemRefreshYear = "5000";
int portTmp = 80;
if (StringUtils.isNotBlank(portString)) {
portTmp = (int) Long.parseLong(portString);
}
if ((StringUtils.isNotBlank(ip) && !ip.equals(ProservBinding.ip)) || portTmp != ProservBinding.port) {
// only do something if the ip or port has changed
ProservBinding.ip = ip;
ProservBinding.port = portTmp;
String refreshIntervalString = (String) config.get("refresh");
if (StringUtils.isNotBlank(refreshIntervalString)) {
refreshInterval = Long.parseLong(refreshIntervalString);
}
setProperlyConfigured(true);
}
}
}
public static String padRight(String s, int n) {
return String.format("%1$-" + n + "s", s);
}
public void sendMail() {
// String pathrrd = ConfigDispatcher.getConfigFolder() + File.separator + ".." +
// File.separator + "etc" + File.separator + "rrd4j" + File.separator + "itemProServLog0.rrd";
// String pathxml = ConfigDispatcher.getConfigFolder() + File.separator + ".." +
// File.separator + "etc" + File.separator + "rrd4j" + File.separator + "itemProServLog0.xml";
// String pathdmp = ConfigDispatcher.getConfigFolder() + File.separator + ".." +
// File.separator + "etc" + File.separator + "rrd4j" + File.separator + "itemProServLog0.txt";
// try {
// RrdDb rrd = new RrdDb(pathrrd);
// rrd.dumpXml(pathxml);
// PrintWriter writer = new PrintWriter(pathdmp, "ISO-8859-1");
// writer.write(rrd.dump());
// writer.close();
// } catch (IOException e1) {
// // TODO Auto-generated catch block
// e1.printStackTrace();
// }
String path = ConfigDispatcher.getConfigFolder() + File.separator + ".." +
File.separator + "logs" + File.separator + "proserv.log";
URL url = null;
try {
url = new File(path).toURI().toURL();
} catch (MalformedURLException e) {
e.printStackTrace();
}
Mail.sendMail(mailTo, mailSubject, mailContent, url.toString());
}
public void updateSendEmail(int x, int y, byte[] dataValue) {
int startDatapoint = (48*x) + (y*3) + 1;
proservData.setFunctionDataPoint(startDatapoint, x, y, 0);
switch ((int)proservData.getFunctionCodes(x, y) & 0xFF) {
case 0x31:{
boolean b = proservData.parse1ByteBooleanValue(dataValue[0]);
if(proservData.getFunctionStateIsInverted(x,y))
b = !b;
if(previousEmailTrigger!=null && previousEmailTrigger==false && b==true && proservData.getFunctionIsEmailTrigger(x, y))
{
sendMail();
}
previousEmailTrigger = b;
} break;
default:
logger.debug("proServ binding, unhandled functioncode 0x{}",
Integer.toHexString(((int)proservData.getFunctionCodes(x, y) & 0xFF)));
}
}
// The postUpdateSingleValueFunction function takes one function value, identified by x, y & z
// (z signifies actual or setpoint) and a single value as input and post update on the event bus.
// It is called from the the Monitor thread when the proServ notifies for a value change.
public void postUpdateSingleValueFunction(int x, int y, int z, byte[] dataValue) {
int startDatapoint = (48*x) + (y*3) + 1;
int Id = proservData.getFunctionMapId(x,y,z);
switch ((int)proservData.getFunctionCodes(x, y) & 0xFF) {
case 0x01:{
boolean b = proservData.parse1ByteBooleanValue(dataValue[0]);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id), new DecimalType(b?1:0));
} break;
case 0x02:{
int i = proservData.parse1BytePercentValue(dataValue[0]);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id),
new DecimalType(new BigDecimal(i).setScale(2, RoundingMode.HALF_EVEN)));
} break;
case 0x12:{
int i = proservData.parse1BytePercentValue(dataValue[0]);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id),
new DecimalType(new BigDecimal(i).setScale(2, RoundingMode.HALF_EVEN)));
} break;
case 0x31:{
boolean b = proservData.parse1ByteBooleanValue(dataValue[0]);
if(proservData.getFunctionStateIsInverted(x,y))
b = !b;
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id), new DecimalType(b?1:0));
} break;
case 0x26:
case 0x34:{
float f = proservData.parse2ByteFloatValue(dataValue,0);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id),
new DecimalType(new BigDecimal(f).setScale(2, RoundingMode.HALF_EVEN)));
} break;
case 0x38:{
float f = proservData.parse4ByteFloatValue(dataValue,0);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id),
new DecimalType(new BigDecimal(f).setScale(2, RoundingMode.HALF_EVEN)));
} break;
case 0x91:{
int i = proservData.parse1BytePercentValue(dataValue[0]);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id),
new DecimalType(new BigDecimal(i).setScale(2, RoundingMode.HALF_EVEN)));
} break;
case 0x92:{
int i = proservData.parse1ByteUnsignedValue(dataValue[0]);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id), new DecimalType(i));
} break;
case 0x94:{
float f = proservData.parse2ByteFloatValue(dataValue,0);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id),
new DecimalType(new BigDecimal(f).setScale(2, RoundingMode.HALF_EVEN)));
} break;
case 0x95:{
long uint32 = proservData.parse4ByteUnsignedValue(dataValue,0);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id), new DecimalType(uint32));
} break;
case 0x96:{
long int32 = proservData.parse4ByteSignedValue(dataValue,0);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id), new DecimalType(int32));
} break;
case 0x97:{
float f = proservData.parse4ByteFloatValue(dataValue,0);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id),
new DecimalType(new BigDecimal(f).setScale(2, RoundingMode.HALF_EVEN)));
} break;
default:
logger.debug("proServ binding, unhandled functioncode 0x{}",
Integer.toHexString(((int)proservData.getFunctionCodes(x, y) & 0xFF)));
}
shortDelayBetweenBusEvents();
}
// The postUpdateFunction function takes one function value, x & y
// and a buffer with 3 data values as input and post update on the event bus.
// It is called from the the polling thread.
// The postUpdateFunction also fill the proservData functionDataPoint values which are later used
// for lookup in the monitor thread. That is the async value update will only work after one successful data poll.
public void postUpdateFunction(int x, int y, byte[] dataValue) {
int startDatapoint = (48*x) + (y*3) + 1;
int Id = proservData.getFunctionMapId(x,y,0);
int IdPreset = proservData.getFunctionMapId(x,y,1);
proservData.setFunctionDataPoint(startDatapoint, x, y, 0);
switch ((int)proservData.getFunctionCodes(x, y) & 0xFF) {
case 0x01:{
proservData.setFunctionDataPoint(startDatapoint+1, x, y, 0);
boolean b = proservData.parse1ByteBooleanValue(dataValue[1]);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id), new DecimalType(b?1:0));
} break;
case 0x02:{
proservData.setFunctionDataPoint(startDatapoint+1, x, y, 0);
int i = proservData.parse1BytePercentValue(dataValue[1]);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id),
new DecimalType(new BigDecimal(i).setScale(2, RoundingMode.HALF_EVEN)));
} break;
case 0x12:{
proservData.setFunctionDataPoint(startDatapoint+2, x, y, 0);
int i = proservData.parse1BytePercentValue(dataValue[2]);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id),
new DecimalType(new BigDecimal(i).setScale(2, RoundingMode.HALF_EVEN)));
} break;
case 0x31:{
boolean b = proservData.parse1ByteBooleanValue(dataValue[0]);
if(proservData.getFunctionStateIsInverted(x,y))
b = !b;
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id), new DecimalType(b?1:0));
} break;
case 0x26:
case 0x34:{
float f = proservData.parse2ByteFloatValue(dataValue,0);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id),
new DecimalType(new BigDecimal(f).setScale(2, RoundingMode.HALF_EVEN)));
} break;
case 0x38:{
float f = proservData.parse4ByteFloatValue(dataValue,0);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id),
new DecimalType(new BigDecimal(f).setScale(2, RoundingMode.HALF_EVEN)));
} break;
case 0x91:{
if(proservData.getFunctionLogThis(x,y,0)) {
int i = proservData.parse1BytePercentValue(dataValue[0]);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id),
new DecimalType(new BigDecimal(i).setScale(2, RoundingMode.HALF_EVEN)));
}
if(proservData.getFunctionLogThis(x,y,1)) {
shortDelayBetweenBusEvents();
proservData.setFunctionDataPoint(startDatapoint+2, x, y, 1);
int preset = proservData.parse1BytePercentValue(dataValue[2]);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(IdPreset),
new DecimalType(new BigDecimal(preset).setScale(2, RoundingMode.HALF_EVEN)));
}
} break;
case 0x92:{
if(proservData.getFunctionLogThis(x,y,0)) {
int i = proservData.parse1ByteUnsignedValue(dataValue[0]);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id), new DecimalType(i));
}
if(proservData.getFunctionLogThis(x,y,1)) {
shortDelayBetweenBusEvents();
proservData.setFunctionDataPoint(startDatapoint+2, x, y, 1);
int preset = proservData.parse1ByteUnsignedValue(dataValue[2]);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(IdPreset),new DecimalType(preset));
}
} break;
case 0x94:{
if(proservData.getFunctionLogThis(x,y,0)) {
float f = proservData.parse2ByteFloatValue(dataValue,0);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id),
new DecimalType(new BigDecimal(f).setScale(2, RoundingMode.HALF_EVEN)));
}
if(proservData.getFunctionLogThis(x,y,1)) {
shortDelayBetweenBusEvents();
proservData.setFunctionDataPoint(startDatapoint+2, x, y, 1);
float f = proservData.parse2ByteFloatValue(dataValue,4);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(IdPreset),
new DecimalType(new BigDecimal(f).setScale(2, RoundingMode.HALF_EVEN)));
}
} break;
case 0x95:{
if(proservData.getFunctionLogThis(x,y,0)) {
long uint32 = proservData.parse4ByteUnsignedValue(dataValue,0);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id), new DecimalType(uint32));
}
if(proservData.getFunctionLogThis(x,y,1)) {
shortDelayBetweenBusEvents();
proservData.setFunctionDataPoint(startDatapoint+2, x, y, 1);
long uint32Preset = proservData.parse4ByteUnsignedValue(dataValue,8);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(IdPreset),
new DecimalType(uint32Preset));
}
} break;
case 0x96:{
if(proservData.getFunctionLogThis(x,y,0)) {
long int32 = proservData.parse4ByteSignedValue(dataValue,0);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id), new DecimalType(int32));
}
if(proservData.getFunctionLogThis(x,y,1)) {
shortDelayBetweenBusEvents();
proservData.setFunctionDataPoint(startDatapoint+2, x, y, 1);
long int32Preset = proservData.parse4ByteSignedValue(dataValue,8);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(IdPreset),
new DecimalType(int32Preset));
}
} break;
case 0x97:{
if(proservData.getFunctionLogThis(x,y,0)) {
float f = proservData.parse4ByteFloatValue(dataValue,0);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id),
new DecimalType(new BigDecimal(f).setScale(2, RoundingMode.HALF_EVEN)));
}
if(proservData.getFunctionLogThis(x,y,1)) {
shortDelayBetweenBusEvents();
proservData.setFunctionDataPoint(startDatapoint+2, x, y, 1);
float f = proservData.parse4ByteFloatValue(dataValue,8);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(IdPreset),
new DecimalType(new BigDecimal(f).setScale(2, RoundingMode.HALF_EVEN)));
}
} break;
default:
logger.debug("proServ binding, unhandled functioncode 0x{}",
Integer.toHexString(((int)proservData.getFunctionCodes(x, y) & 0xFF)));
}
shortDelayBetweenBusEvents();
}
// The postUpdateSingleValueHeating function takes one heating value, x (z signifies actual or setpoint)
// and a single value as input and post update on the event bus.
// It is called from the the Monitor thread when the proServ notifies for a value change.
public void postUpdateSingleValueHeating(int x, int z, byte[] dataValue) {
int Id = proservData.getHeatingMapId(x,z);
int startDatapoint = 865 + x * 5;
switch ( (int)(proservData.getHeatingCodes(x) & 0xFF) ) {
case 0x41:
case 0x42:
case 0x43:
case 0x44:
float f = proservData.parse2ByteFloatValue(dataValue, 0);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id),
new DecimalType(new BigDecimal(f).setScale(2, RoundingMode.HALF_EVEN)));
break;
default:
logger.debug("proServ binding, unhandled heatingCode {}", Integer.toHexString(((int)proservData.getHeatingCodes(x) & 0xFF)));
}
}
// The postUpdateHeating function takes one heating value, x
// and a buffer with 3 data values as input and post update on the event bus.
// It is called from the the polling thread.
// The postUpdateHeating also fill the proservData heatingDataPoint values which are later used
// for lookup in the monitor thread. That is the async value update will only work after one successful data poll.
public void postUpdateHeating(int x, byte[] dataValue) {
int IdActual = proservData.getHeatingMapId(x,0);
int IdPreset = proservData.getHeatingMapId(x,1);
int startDatapoint = 865 + x * 5;
switch ( (int)(proservData.getHeatingCodes(x) & 0xFF) ) {
case 0x41:
case 0x42:
case 0x43:
case 0x44:
proservData.setHeatingDataPoint(startDatapoint, x, 0);
float f0 = proservData.parse2ByteFloatValue(dataValue, 0);
eventPublisher.postUpdate("itemProServLog" + Integer.toString(IdActual),
new DecimalType(new BigDecimal(f0).setScale(2, RoundingMode.HALF_EVEN)));
proservData.setHeatingDataPoint(startDatapoint+2, x, 1);
float f1 = proservData.parse2ByteFloatValue(dataValue, 4);
shortDelayBetweenBusEvents();
eventPublisher.postUpdate("itemProServLog" + Integer.toString(IdPreset),
new DecimalType(new BigDecimal(f1).setScale(2, RoundingMode.HALF_EVEN)));
logger.info("{}{}: {}{}: {}", padRight(proservData.getHeatingDescription(x), 20),
padRight(proservData.getStringProservLang(0), 5), padRight(Float.toString(f0), 10),
padRight(proservData.getStringProservLang(1), 5), padRight(Float.toString(f1), 10));
break;
default:
logger.debug("proServ binding, unhandled heatingCode {}", Integer.toHexString(((int)proservData.getHeatingCodes(x) & 0xFF)));
}
}
@Override
public void execute() {
logger.debug("proServ binding refresh cycle starts!");
if(connector==null)
{
connector = new ProservConnector(ip, port);
}
try {
connector.connect();
if (proservData == null) {
proservData = new ProservData(chartItemRefreshHour,chartItemRefreshDay, chartItemRefreshWeek, chartItemRefreshMonth, chartItemRefreshYear );
byte[] proservAllConfigValues = getConfigValues();
if (proservAllConfigValues == null) {
logger.debug("proServ getConfigValues failed try again");
proservAllConfigValues = getConfigValues(); // try again..
}
if (proservAllConfigValues != null) {
proservData.parseRawConfigData(proservAllConfigValues);
proservData.updateProservMapFile();
proservData.updateProservItemFile();
proservData.updateProservSitemapFile();
proservData.updateRrd4jPersistFile();
proservData.updateDb4oPersistFile();
connector.startMonitor(this.eventPublisher, this.proservData, this);
} else {
logger.debug("proServ getConfigValues failed twice in a row, try next refresh cycle!");
proservData = null; // force a reload of configdata
}
}
if (proservData != null) {
// function 1-1 .. function 18-16
for (int x = 0; x < 18; x++) {
for (int y = 0; y < 16; y++) {
if(proservData.getFunctionLogThis(x,y,0) || proservData.getFunctionLogThis(x,y,1) ||
proservData.getFunctionIsEmailTrigger(x,y)) {
int startDatapoint = (48*x) + (y*3) + 1;
int numberOfDatapoints = 3;
byte[] dataValue = connector.getDataPointValue((short) startDatapoint, (short) numberOfDatapoints);
if (dataValue != null) {
if(proservData.getFunctionLogThis(x,y,0) || proservData.getFunctionLogThis(x,y,1)) {
postUpdateFunction(x, y, dataValue);
}
if(proservData.getFunctionIsEmailTrigger(x,y)) {
updateSendEmail(x, y, dataValue);
}
}
}
}
}
// heating 1-18
for (int x = 0; x < 18; x++) {
if (proservData.getHeatingLogThis(x)) {
int startDatapoint = 865 + x * 5;
int numberOfDatapoints = 5;
byte[] dataValue = connector.getDataPointValue((short) startDatapoint, (short) numberOfDatapoints);
if (dataValue != null) {
postUpdateHeating(x, dataValue);
}
}
}
}
logger.debug("proServ binding refresh cycle completed");
} catch (NullPointerException e) {
logger.warn("proServ NullPointerException");
} catch (UnsupportedEncodingException e) {
logger.warn("proServ UnsupportedEncodingException");
} catch (UnknownHostException e) {
logger.warn("proServ the given hostname '{}' : port'{}' of the proServ is unknown", ip, port);
} catch (IOException e) {
logger.warn("proServ couldn't establish network connection [host '{}' : port'{}'] error:'{}'", ip, port, e);
} catch (Exception e) {
logger.warn("proServ Exception in execute error:{}", e);
} finally {
logger.debug("proServ binding refresh cycle reached finally");
if (connector != null) {
connector.disconnect();
}
}
}
private void shortDelayBetweenBusEvents() {
try {
Thread.sleep(100);
} catch (InterruptedException ie) {
// Handle the exception
}
}
private byte[] getConfigValues() {
byte[] proservAllConfigValues = null;
try {
short PROSERV_MEMORY_LENGTH = 19500;
short NUMBER_OF_BYTES_IN_CHUNK = 500;
proservAllConfigValues = new byte[PROSERV_MEMORY_LENGTH];
// read a chunk of values
short startByte = 1;
for (int chunkId = 0;; chunkId++) {
short numberOfBytesToRead = NUMBER_OF_BYTES_IN_CHUNK;
if (startByte + NUMBER_OF_BYTES_IN_CHUNK >= PROSERV_MEMORY_LENGTH)
numberOfBytesToRead = (short) (PROSERV_MEMORY_LENGTH - startByte);
byte[] proServValues = null;
for(int attempt=0;attempt<4;attempt++){
proServValues = connector.getParameterBytes(startByte, numberOfBytesToRead);
if(proServValues!=null)
break;
}
if(proServValues==null)
{
logger.info("proServ getConfigValues failed proServValues==null");
return null;
}
int offset = chunkId * NUMBER_OF_BYTES_IN_CHUNK;
startByte += NUMBER_OF_BYTES_IN_CHUNK;
for (int i = 0; i < numberOfBytesToRead; i++) {
proservAllConfigValues[offset + i] = proServValues[i];
}
if (numberOfBytesToRead != NUMBER_OF_BYTES_IN_CHUNK)
break;
if (offset > 10300)
break; // quick fix for now
}
logger.debug("proServ succesfully loaded all config values");
}
finally {
}
return proservAllConfigValues;
}
@Override
protected long getRefreshInterval() {
return refreshInterval;
}
@Override
protected String getName() {
return "proServ Refresh Service";
}
}
|
simplification: remove rounding of value from parse1BytePercentValue (it is an int already rounded)
|
bundles/binding/org.openhab.binding.proserv/src/main/java/org/openhab/binding/proserv/internal/ProservBinding.java
|
simplification: remove rounding of value from parse1BytePercentValue (it is an int already rounded)
|
|
Java
|
lgpl-2.1
|
2c34ea9a7e00e54e1444b18158f65c4e40bcbf72
| 0
|
Fosstrak/fosstrak-epcis,Jonnychen/fosstrak-epcis
|
/*
* Copyright (C) 2007 ETH Zurich
*
* This file is part of Fosstrak (www.fosstrak.org).
*
* Fosstrak is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* Fosstrak is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with Fosstrak; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
package org.fosstrak.epcis.repository.capture;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.Principal;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.fosstrak.epcis.repository.EpcisConstants;
import org.fosstrak.epcis.repository.InvalidFormatException;
import org.fosstrak.epcis.utils.TimeParser;
import org.fosstrak.epcis.repository.model.Action;
import org.fosstrak.epcis.repository.model.AggregationEvent;
import org.fosstrak.epcis.repository.model.BaseEvent;
import org.fosstrak.epcis.repository.model.BusinessLocationId;
import org.fosstrak.epcis.repository.model.BusinessStepId;
import org.fosstrak.epcis.repository.model.BusinessTransaction;
import org.fosstrak.epcis.repository.model.BusinessTransactionId;
import org.fosstrak.epcis.repository.model.BusinessTransactionTypeId;
import org.fosstrak.epcis.repository.model.DispositionId;
import org.fosstrak.epcis.repository.model.EPCClass;
import org.fosstrak.epcis.repository.model.EventFieldExtension;
import org.fosstrak.epcis.repository.model.ObjectEvent;
import org.fosstrak.epcis.repository.model.QuantityEvent;
import org.fosstrak.epcis.repository.model.ReadPointId;
import org.fosstrak.epcis.repository.model.TransactionEvent;
import org.fosstrak.epcis.repository.model.VocabularyElement;
import org.fosstrak.epcis.repository.model.VocabularyAttrCiD;
import org.fosstrak.epcis.repository.model.VocabularyAttributeElement;
import org.fosstrak.epcis.repository.model.BusinessLocationAttrId;
import org.fosstrak.epcis.repository.model.BusinessStepAttrId;
import org.fosstrak.epcis.repository.model.BusinessTransactionAttrId;
import org.fosstrak.epcis.repository.model.BusinessTransactionTypeAttrId;
import org.fosstrak.epcis.repository.model.DispositionAttrId;
import org.fosstrak.epcis.repository.model.EPCClassAttrId;
import org.fosstrak.epcis.repository.model.ReadPointAttrId;
import org.hibernate.Criteria;
import org.hibernate.ObjectNotFoundException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
/**
* CaptureOperationsModule implements the core capture operations. Converts XML
* events delivered by HTTP POST into SQL and inserts them into the database.
* <p>
* TODO: the parsing of the xml inputstream should be done in the
* CaptureOperationsServlet; this class should implement EpcisCaptureInterface
* such that CaptureOperationsServlet can call its capture method and provide it
* with the parsed events.
*
* @author David Gubler
* @author Alain Remund
* @author Marco Steybe
* @author Nikos Kefalakis (nkef)
*/
public class CaptureOperationsModule {
private static final Log LOG = LogFactory.getLog(CaptureOperationsModule.class);
private static final Map<String, Class<?>> vocClassMap = new HashMap<String, Class<?>>();
static {
vocClassMap.put(EpcisConstants.BUSINESS_LOCATION_ID, BusinessLocationId.class);
vocClassMap.put(EpcisConstants.BUSINESS_STEP_ID, BusinessStepId.class);
vocClassMap.put(EpcisConstants.BUSINESS_TRANSACTION_ID, BusinessTransactionId.class);
vocClassMap.put(EpcisConstants.BUSINESS_TRANSACTION_TYPE_ID, BusinessTransactionTypeId.class);
vocClassMap.put(EpcisConstants.DISPOSITION_ID, DispositionId.class);
vocClassMap.put(EpcisConstants.EPC_CLASS_ID, EPCClass.class);
vocClassMap.put(EpcisConstants.READ_POINT_ID, ReadPointId.class);
}
// (nkef) Added to support the Master Data Capture I/F
private static final Map<String, Class<?>> vocAttributeClassMap = new HashMap<String, Class<?>>();
private static final Map<String, String> vocAttributeTablesMap = new HashMap<String, String>();
private static Map<String, String> vocabularyTablenameMap = new HashMap<String, String>();
static {
vocAttributeClassMap.put(EpcisConstants.BUSINESS_LOCATION_ID, BusinessLocationAttrId.class);
vocAttributeClassMap.put(EpcisConstants.BUSINESS_STEP_ID, BusinessStepAttrId.class);
vocAttributeClassMap.put(EpcisConstants.BUSINESS_TRANSACTION_ID, BusinessTransactionAttrId.class);
vocAttributeClassMap.put(EpcisConstants.BUSINESS_TRANSACTION_TYPE_ID, BusinessTransactionTypeAttrId.class);
vocAttributeClassMap.put(EpcisConstants.DISPOSITION_ID, DispositionAttrId.class);
vocAttributeClassMap.put(EpcisConstants.EPC_CLASS_ID, EPCClassAttrId.class);
vocAttributeClassMap.put(EpcisConstants.READ_POINT_ID, ReadPointAttrId.class);
vocAttributeTablesMap.put(EpcisConstants.BUSINESS_LOCATION_ID, "voc_BizLoc_attr");
vocAttributeTablesMap.put(EpcisConstants.BUSINESS_STEP_ID, "voc_BizStep_attr");
vocAttributeTablesMap.put(EpcisConstants.BUSINESS_TRANSACTION_ID, "voc_BizTrans_attr");
vocAttributeTablesMap.put(EpcisConstants.BUSINESS_TRANSACTION_TYPE_ID, "voc_BizTransType_attr");
vocAttributeTablesMap.put(EpcisConstants.DISPOSITION_ID, "voc_Disposition_attr");
vocAttributeTablesMap.put(EpcisConstants.EPC_CLASS_ID, "voc_EPCClass_attr");
vocAttributeTablesMap.put(EpcisConstants.READ_POINT_ID, "voc_ReadPoint_attr");
vocabularyTablenameMap.put(EpcisConstants.BUSINESS_STEP_ID, "voc_BizStep");
vocabularyTablenameMap.put(EpcisConstants.BUSINESS_LOCATION_ID, "voc_BizLoc");
vocabularyTablenameMap.put(EpcisConstants.BUSINESS_TRANSACTION_ID, "voc_BizTrans");
vocabularyTablenameMap.put(EpcisConstants.BUSINESS_TRANSACTION_TYPE_ID, "voc_BizTransType");
vocabularyTablenameMap.put(EpcisConstants.DISPOSITION_ID, "voc_Disposition");
vocabularyTablenameMap.put(EpcisConstants.EPC_CLASS_ID, "voc_EPCClass");
vocabularyTablenameMap.put(EpcisConstants.READ_POINT_ID, "voc_ReadPoint");
}
/**
* The XSD schema which validates the incoming messages.
*/
private Schema schema;
/**
* The XSD schema which validates the MasterData incoming messages.(nkef)
*/
private Schema masterDataSchema;
/**
* Whether we should insert new vocabulary or throw an error message.
*/
private boolean insertMissingVoc = true;
/**
* Whether the dbReset operation is allowed or not.
*/
private boolean dbResetAllowed = false;
/**
* The SQL files to be executed when the dbReset operation is invoked.
*/
private List<File> dbResetScripts = null;
/**
* Interface to the database.
*/
private SessionFactory sessionFactory;
/**
* Initializes the EPCIS schema used for validating incoming capture
* requests. Loads the WSDL and XSD files from the classpath (the schema is
* bundled with epcis-commons.jar).
*
* @return An instantiated schema validation object.
*/
private Schema initEpcisSchema(String xsdFile) {
InputStream is = this.getClass().getResourceAsStream(xsdFile);
if (is != null) {
try {
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Source schemaSrc = new StreamSource(is);
schemaSrc.setSystemId(CaptureOperationsServlet.class.getResource(xsdFile).toString());
Schema schema = schemaFactory.newSchema(schemaSrc);
LOG.debug("EPCIS schema file initialized and loaded successfully");
return schema;
} catch (Exception e) {
LOG.warn("Unable to load or parse the EPCIS schema", e);
}
} else {
LOG.error("Unable to load the EPCIS schema file from classpath: cannot find resource " + xsdFile);
}
LOG.warn("Schema validation will not be available!");
return null;
}
/**
* Resets the database.
*
* @throws SQLException
* If something goes wrong resetting the database.
* @throws IOException
* If something goes wrong reading the reset script.
* @throws UnsupportedOperationsException
* If database resets are not allowed.
*/
public void doDbReset() throws SQLException, IOException, UnsupportedOperationException {
if (dbResetAllowed) {
if (dbResetScripts == null || dbResetScripts.isEmpty()) {
LOG.warn("dbReset operation invoked but no dbReset script is configured!");
} else {
Session session = null;
try {
session = sessionFactory.openSession();
Transaction tx = null;
for (File file : dbResetScripts) {
try {
tx = session.beginTransaction();
LOG.info("Running db reset script from file " + file);
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
String sql = "";
while ((line = reader.readLine()) != null) {
if (!line.startsWith("--") && StringUtils.isNotBlank(line)) {
sql += line;
if (sql.endsWith(";")) {
LOG.debug("SQL: " + sql);
session.createSQLQuery(sql).executeUpdate();
sql = "";
}
}
}
tx.commit();
} catch (Throwable e) {
LOG.error("dbReset failed for " + file + ": " + e.toString(), e);
if (tx != null) {
tx.rollback();
}
throw new SQLException(e.toString());
}
}
} finally {
if (session != null) {
session.close();
}
}
}
} else {
throw new UnsupportedOperationException();
}
}
/**
* Implements the EPCIS capture operation. Takes an input stream, extracts
* the payload into an XML document, validates the document against the
* EPCIS schema, and captures the EPCIS events given in the document.
*
* @throws IOException
* If an error occurred while validating the request or writing
* the response.
* @throws ParserConfigurationException
* @throws SAXException
* If the XML document is malformed or invalid
* @throws InvalidFormatException
*/
public void doCapture(InputStream in, Principal principal) throws SAXException, IOException, InvalidFormatException {
// parse the payload as XML document
Document document;
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.parse(in);
LOG.debug("Payload successfully parsed as XML document");
if (LOG.isDebugEnabled()) {
try {
TransformerFactory tfFactory = TransformerFactory.newInstance();
Transformer transformer = tfFactory.newTransformer();
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(document), new StreamResult(writer));
String xml = writer.toString();
if (xml.length() > 100 * 1024) {
// too large, do not log
xml = null;
} else {
LOG.debug("Incoming contents:\n\n" + writer.toString() + "\n");
}
} catch (Exception e) {
// never mind ... do not log
}
}
// validate incoming document against its! schema(changed by nkef)
if (isEPCISDocument(document)) {
// validate the XML document against the EPCISDocument schema
if (schema != null) {
Validator validator = schema.newValidator();
try {
validator.validate(new DOMSource(document), null);
}
catch (SAXParseException e) {
// TODO: we need to ignore XML element order, the
// following
// is only a hack to pass some of the conformance tests
if (e.getMessage().contains("parentID")) {
LOG.warn("Ignoring XML validation exception: " + e.getMessage());
}
else {
throw e;
}
}
LOG.info("Incoming capture request was successfully validated against the EPCISDocument schema");
}
else {
LOG.warn("Schema validator unavailable. Unable to validate EPCIS capture event against schema!");
}
}
else if (isEPCISMasterDataDocument(document)) {
// TODO: Validate EPCIS Master Data incoming Document
}
}
catch (ParserConfigurationException e) {
throw new SAXException(e);
}
// handle the capture operation
Session session = null;
try {
session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
LOG.debug("DB connection opened.");
if (isEPCISDocument(document)) {
handleEventDocument(session, document);
}
else if (isEPCISMasterDataDocument(document)) {
handleMasterDataDocument(session, document);
}
tx.commit();
// return OK
LOG.info("EPCIS Capture Interface request succeeded");
} catch (SAXException e) {
LOG.error("EPCIS Capture Interface request failed: " + e.toString());
if (tx != null) {
tx.rollback();
}
throw e;
} catch (InvalidFormatException e) {
LOG.error("EPCIS Capture Interface request failed: " + e.toString());
if (tx != null) {
tx.rollback();
}
throw e;
} catch (Exception e) {
// Hibernate throws RuntimeExceptions, so don't let them
// (or anything else) escape without clean up
LOG.error("EPCIS Capture Interface request failed: " + e.toString(), e);
if (tx != null) {
tx.rollback();
}
throw new IOException(e.toString());
}
} finally {
if (session != null) {
session.close();
}
// sessionFactory.getStatistics().logSummary();
LOG.debug("DB connection closed");
}
}
/**
* @param document
* @return
*/
private boolean isEPCISDocument(Document document) {
return document.getDocumentElement().getLocalName().equals("EPCISDocument");
}
/**
* @param document
* @return
*/
private boolean isEPCISMasterDataDocument(Document document) {
return document.getDocumentElement().getLocalName().equals("EPCISMasterDataDocument");
}
/**
* Parses the entire document and handles the supplied events.
*
* @throws Exception
* @throws DOMException
*/
private void handleEventDocument(Session session, Document document) throws DOMException, SAXException,
InvalidFormatException {
NodeList eventList = document.getElementsByTagName("EventList");
NodeList events = eventList.item(0).getChildNodes();
// walk through all supplied events
int eventCount = 0;
for (int i = 0; i < events.getLength(); i++) {
Node eventNode = events.item(i);
String nodeName = eventNode.getNodeName();
if (nodeName.equals(EpcisConstants.OBJECT_EVENT) || nodeName.equals(EpcisConstants.AGGREGATION_EVENT)
|| nodeName.equals(EpcisConstants.QUANTITY_EVENT)
|| nodeName.equals(EpcisConstants.TRANSACTION_EVENT)) {
LOG.debug("processing event " + i + ": '" + nodeName + "'.");
handleEvent(session, eventNode, nodeName);
eventCount++;
if (eventCount % 50 == 0) {
session.flush();
session.clear();
}
} else if (!nodeName.equals("#text") && !nodeName.equals("#comment")) {
throw new SAXException("Encountered unknown event '" + nodeName + "'.");
}
}
}
/**
* Takes an XML document node, parses it as EPCIS event and inserts the data
* into the database. The parse routine is generic for all event types; the
* query generation part has some if/elses to take care of different event
* parameters.
*
* @param eventNode
* The current event node.
* @param eventType
* The current event type.
* @throws Exception
* @throws DOMException
*/
private void handleEvent(Session session, final Node eventNode, final String eventType) throws DOMException,
SAXException, InvalidFormatException {
if (eventNode == null) {
// nothing to do
return;
} else if (eventNode.getChildNodes().getLength() == 0) {
throw new SAXException("Event element '" + eventNode.getNodeName() + "' has no children elements.");
}
Node curEventNode = null;
// A lot of the initialized variables have type URI. This type isn't to
// compare with the URI-Type of the standard. In fact, most of the
// variables having type URI are declared as Vocabularies in the
// Standard. Commonly, we use String for the Standard-Type URI.
Calendar eventTime = null;
Calendar recordTime = GregorianCalendar.getInstance();
String eventTimeZoneOffset = null;
String action = null;
String parentId = null;
Long quantity = null;
String bizStepUri = null;
String dispositionUri = null;
String readPointUri = null;
String bizLocationUri = null;
String epcClassUri = null;
List<String> epcs = null;
List<BusinessTransaction> bizTransList = null;
List<EventFieldExtension> fieldNameExtList = new ArrayList<EventFieldExtension>();
for (int i = 0; i < eventNode.getChildNodes().getLength(); i++) {
curEventNode = eventNode.getChildNodes().item(i);
String nodeName = curEventNode.getNodeName();
if (nodeName.equals("#text") || nodeName.equals("#comment")) {
// ignore text or comments
LOG.debug(" ignoring text or comment: '" + curEventNode.getTextContent().trim() + "'");
continue;
}
LOG.debug(" handling event field: '" + nodeName + "'");
if (nodeName.equals("eventTime")) {
String xmlTime = curEventNode.getTextContent();
LOG.debug(" eventTime in xml is '" + xmlTime + "'");
try {
eventTime = TimeParser.parseAsCalendar(xmlTime);
} catch (ParseException e) {
throw new SAXException("Invalid date/time (must be ISO8601).", e);
}
LOG.debug(" eventTime parsed as '" + eventTime.getTime() + "'");
} else if (nodeName.equals("recordTime")) {
// ignore recordTime
} else if (nodeName.equals("eventTimeZoneOffset")) {
eventTimeZoneOffset = checkEventTimeZoneOffset(curEventNode.getTextContent());
} else if (nodeName.equals("epcList") || nodeName.equals("childEPCs")) {
epcs = handleEpcs(eventType, curEventNode);
} else if (nodeName.equals("bizTransactionList")) {
bizTransList = handleBizTransactions(session, curEventNode);
} else if (nodeName.equals("action")) {
action = curEventNode.getTextContent();
if (!action.equals("ADD") && !action.equals("OBSERVE") && !action.equals("DELETE")) {
throw new SAXException("Encountered illegal 'action' value: " + action);
}
} else if (nodeName.equals("bizStep")) {
bizStepUri = curEventNode.getTextContent();
} else if (nodeName.equals("disposition")) {
dispositionUri = curEventNode.getTextContent();
} else if (nodeName.equals("readPoint")) {
Element attrElem = (Element) curEventNode;
Node id = attrElem.getElementsByTagName("id").item(0);
readPointUri = id.getTextContent();
} else if (nodeName.equals("bizLocation")) {
Element attrElem = (Element) curEventNode;
Node id = attrElem.getElementsByTagName("id").item(0);
bizLocationUri = id.getTextContent();
} else if (nodeName.equals("epcClass")) {
epcClassUri = curEventNode.getTextContent();
} else if (nodeName.equals("quantity")) {
quantity = Long.valueOf(curEventNode.getTextContent());
} else if (nodeName.equals("parentID")) {
checkEpcOrUri(curEventNode.getTextContent(), false);
parentId = curEventNode.getTextContent();
} else {
String[] parts = nodeName.split(":");
if (parts.length == 2) {
LOG.debug(" treating unknown event field as extension.");
String prefix = parts[0];
String localname = parts[1];
// String namespace =
// document.getDocumentElement().getAttribute("xmlns:" +
// prefix);
String namespace = curEventNode.lookupNamespaceURI(prefix);
String value = curEventNode.getTextContent();
EventFieldExtension evf = new EventFieldExtension(prefix, namespace, localname, value);
fieldNameExtList.add(evf);
} else {
// this is not a valid extension
throw new SAXException(" encountered unknown event field: '" + nodeName + "'.");
}
}
}
if (eventType.equals(EpcisConstants.AGGREGATION_EVENT)) {
// for AggregationEvents, the parentID is only optional for
// action=OBSERVE
if (parentId == null && ("ADD".equals(action) || "DELETE".equals(action))) {
throw new InvalidFormatException("'parentID' is required if 'action' is ADD or DELETE");
}
}
//Changed by nkef (use "getOrEditVocabularyElement" instead of "getOrInsertVocabularyElement")
String nodeName = eventNode.getNodeName();
VocabularyElement bizStep = bizStepUri != null ? getOrEditVocabularyElement(session, EpcisConstants.BUSINESS_STEP_ID, String
.valueOf(bizStepUri), "1") : null;
VocabularyElement disposition = dispositionUri != null ? getOrEditVocabularyElement(session, EpcisConstants.DISPOSITION_ID, String
.valueOf(dispositionUri), "1") : null;
VocabularyElement readPoint = readPointUri != null ? getOrEditVocabularyElement(session, EpcisConstants.READ_POINT_ID, String
.valueOf(readPointUri), "1") : null;
VocabularyElement bizLocation = bizLocationUri != null ? getOrEditVocabularyElement(session, EpcisConstants.BUSINESS_LOCATION_ID, String
.valueOf(bizLocationUri), "1") : null;
VocabularyElement epcClass = epcClassUri != null ? getOrEditVocabularyElement(session, EpcisConstants.EPC_CLASS_ID, String
.valueOf(epcClassUri), "1") : null;
BaseEvent be;
if (nodeName.equals(EpcisConstants.AGGREGATION_EVENT)) {
AggregationEvent ae = new AggregationEvent();
ae.setParentId(parentId);
ae.setChildEpcs(epcs);
ae.setAction(Action.valueOf(action));
be = ae;
} else if (nodeName.equals(EpcisConstants.OBJECT_EVENT)) {
ObjectEvent oe = new ObjectEvent();
oe.setAction(Action.valueOf(action));
if (epcs != null && epcs.size() > 0) {
oe.setEpcList(epcs);
}
be = oe;
} else if (nodeName.equals(EpcisConstants.QUANTITY_EVENT)) {
QuantityEvent qe = new QuantityEvent();
qe.setEpcClass((EPCClass) epcClass);
if (quantity != null) {
qe.setQuantity(quantity.longValue());
}
be = qe;
} else if (nodeName.equals(EpcisConstants.TRANSACTION_EVENT)) {
TransactionEvent te = new TransactionEvent();
te.setParentId(parentId);
te.setEpcList(epcs);
te.setAction(Action.valueOf(action));
be = te;
} else {
throw new SAXException("Encountered unknown event element '" + nodeName + "'.");
}
be.setEventTime(eventTime);
be.setRecordTime(recordTime);
be.setEventTimeZoneOffset(eventTimeZoneOffset);
be.setBizStep((BusinessStepId) bizStep);
be.setDisposition((DispositionId) disposition);
be.setBizLocation((BusinessLocationId) bizLocation);
be.setReadPoint((ReadPointId) readPoint);
if (bizTransList != null && bizTransList.size() > 0) {
be.setBizTransList(bizTransList);
}
if (!fieldNameExtList.isEmpty()) {
be.setExtensions(fieldNameExtList);
}
session.save(be);
}
/**
* (nkef) Parses the entire document and handles the supplied Master Data.
*
*
* @throws Exception
* @throws DOMException
*/
private void handleMasterDataDocument(Session session, Document document) throws DOMException, SAXException, InvalidFormatException {
// Handle Vocabulary List
NodeList vocabularyList = document.getElementsByTagName("VocabularyList");
if (vocabularyList.item(0).hasChildNodes()) {
NodeList vocabularys = vocabularyList.item(0).getChildNodes();
// walk through all supplied vocabularies
int vocabularyCount = 0;
for (int i = 0; i < vocabularys.getLength(); i++) {
Node vocabularyNode = vocabularys.item(i);
String nodeName = vocabularyNode.getNodeName();
if (nodeName.equals("Vocabulary")) {
String vocabularyType = vocabularyNode.getAttributes().getNamedItem("type").getNodeValue();
if (EpcisConstants.VOCABULARY_TYPES.contains(vocabularyType)) {
LOG.debug("processing " + i + ": '" + nodeName + "':" + vocabularyType + ".");
handleVocabulary(session, vocabularyNode, vocabularyType);
vocabularyCount++;
if (vocabularyCount % 50 == 0) {
session.flush();
session.clear();
}
}
}
else if (!nodeName.equals("#text") && !nodeName.equals("#comment")) {
throw new SAXException("Encountered unknown vocabulary '" + nodeName + "'.");
}
}
}
}
/**
* (nkef) Takes an XML document node, parses it as EPCIS Master Data and
* inserts the data into the database. The parse routine is generic for all
* Vocabulary types;
*
* @param vocabularyNode
* The current vocabulary node.
* @param vocabularyType
* The current vocabulary type.
* @throws Exception
* @throws DOMException
*/
private void handleVocabulary(Session session, final Node vocabularyNode, final String vocabularyType) throws DOMException, SAXException,
InvalidFormatException {
if (vocabularyNode == null) {
// nothing to do
return;
}
else if (vocabularyNode.getChildNodes().getLength() == 0) {
throw new SAXException("Vocabulary element '" + vocabularyNode.getNodeName() + "' has no children elements.");
}
Node curVocabularyNode = null;
Node curVocabularyElementNode = null;
Node curVocabularyAttributeNode = null;
String curVocabularyURI = null;
String curVocabularyAttribute = null;
String curVocabularyAttributeValue = null;
VocabularyElement curVocabularyElement = null;
for (int i = 0; i < vocabularyNode.getChildNodes().getLength(); i++) {
curVocabularyNode = vocabularyNode.getChildNodes().item(i);
String curVocabularyNodeName = curVocabularyNode.getNodeName();
if (curVocabularyNodeName.equals("#text") || curVocabularyNodeName.equals("#comment")) {
// ignore text or comments
LOG.debug(" ignoring text or comment: '" + curVocabularyNode.getTextContent().trim() + "'");
continue;
}
for (int j = 0; j < curVocabularyNode.getChildNodes().getLength(); j++) {
curVocabularyElementNode = curVocabularyNode.getChildNodes().item(j);
String curVocabularyElementNodeName = curVocabularyElementNode.getNodeName();
if (curVocabularyElementNodeName.equals("#text") || curVocabularyElementNodeName.equals("#comment")) {
// ignore text or comments
LOG.debug(" ignoring text or comment: '" + curVocabularyElementNode.getTextContent().trim() + "'");
continue;
}
LOG.debug(" handling vocabulary field: '" + curVocabularyElementNodeName + "'");
curVocabularyURI = curVocabularyElementNode.getAttributes().getNamedItem("id").getNodeValue();
/*
* vocabularyElementEditMode
* 1: insert((it can be anything except 2,3,4))
* 2: alterURI
* 3: singleDelete
* 4: Delete element with it's direct or indirect
* descendants
*/
String vocabularyElementEditMode = "";
if (!(curVocabularyElementNode.getAttributes().getNamedItem("mode") == null)) {
vocabularyElementEditMode = curVocabularyElementNode.getAttributes().getNamedItem("mode").getNodeValue();
}
else {
vocabularyElementEditMode = "1";
}
curVocabularyElement = getOrEditVocabularyElement(session, vocabularyType, curVocabularyURI, vocabularyElementEditMode);
// *****************************************
if (curVocabularyElement != null) {
for (int k = 0; k < curVocabularyElementNode.getChildNodes().getLength(); k++) {
curVocabularyAttributeNode = curVocabularyElementNode.getChildNodes().item(k);
String curVocabularyAttributeElementNodeName = curVocabularyAttributeNode.getNodeName();
if (curVocabularyAttributeElementNodeName.equals("#text") || curVocabularyAttributeElementNodeName.equals("#comment")) {
// ignore text or comments
LOG.debug(" ignoring text or comment: '" + curVocabularyAttributeNode.getTextContent().trim() + "'");
continue;
}
LOG.debug(" handling vocabulary field: '" + curVocabularyAttributeElementNodeName + "'");
curVocabularyAttribute = curVocabularyAttributeNode.getAttributes().getNamedItem("id").getNodeValue();
if (curVocabularyAttributeNode.getAttributes().getNamedItem("value")!=null) {
curVocabularyAttributeValue = curVocabularyAttributeNode.getAttributes().getNamedItem("value").getNodeValue();
} else if (curVocabularyAttributeNode.getFirstChild()!=null) {
curVocabularyAttributeValue = curVocabularyAttributeNode.getFirstChild().getNodeValue();
} else {
curVocabularyAttributeValue = "";
}
/*
* vocabularyAttributeEditMode
* 1: Insert (it can be anything except 3))
* 2: Alter Attribute Value (it can be anything except 3)
* 3: Delete Attribute (required)
*/
String vocabularyAttributeEditMode = "";
if (!(curVocabularyAttributeNode.getAttributes().getNamedItem("mode") == null)) {
vocabularyAttributeEditMode = curVocabularyAttributeNode.getAttributes().getNamedItem("mode").getNodeValue();
}
else {
vocabularyAttributeEditMode = "add/alter";
}
getOrEditVocabularyAttributeElement(session, vocabularyType, curVocabularyElement.getId(), curVocabularyAttribute,
curVocabularyAttributeValue, vocabularyAttributeEditMode);
}
}
// *****************************************
}
}
if (vocabularyType.equals(EpcisConstants.BUSINESS_LOCATION_ID)) {
}
}
/**
* Parses the xml tree for epc nodes and returns a list of EPC URIs.
*
* @param eventType
* @param epcNode
* The parent Node from which EPC URIs should be extracted.
* @return An array of vocabularies containing all the URIs found in the
* given node.
* @throws SAXException
* If an unknown tag (no <epc>) is encountered.
* @throws InvalidFormatException
* @throws DOMException
*/
private List<String> handleEpcs(final String eventType, final Node epcNode) throws SAXException, DOMException,
InvalidFormatException {
List<String> epcList = new ArrayList<String>();
boolean isEpc = false;
boolean epcRequired = false;
boolean atLeastOneNonEpc = false;
for (int i = 0; i < epcNode.getChildNodes().getLength(); i++) {
Node curNode = epcNode.getChildNodes().item(i);
if (curNode.getNodeName().equals("epc")) {
isEpc = checkEpcOrUri(curNode.getTextContent(), epcRequired);
if (isEpc) {
// if one of the values is an EPC, then all of them must be
// valid EPCs
epcRequired = true;
} else {
atLeastOneNonEpc = true;
}
epcList.add(curNode.getTextContent());
} else {
if (curNode.getNodeName() != "#text" && curNode.getNodeName() != "#comment") {
throw new SAXException("Unknown XML tag: " + curNode.getNodeName(), null);
}
}
}
if (atLeastOneNonEpc && isEpc) {
throw new InvalidFormatException(
"One of the provided EPCs was a 'pure identity' EPC, so all of them must be 'pure identity' EPCs");
}
return epcList;
}
/**
* @param epcOrUri
* The EPC or URI to check.
* @param epcRequired
* <code>true</code> if an EPC is required (will throw an
* InvalidFormatException if the given <code>epcOrUri</code> is
* an invalid EPC, but might be a valid URI), <code>false</code>
* otherwise.
* @return <code>true</code> if the given <code>epcOrUri</code> is a valid
* EPC, <code>false</code> otherwise.
* @throws InvalidFormatException
*/
protected boolean checkEpcOrUri(String epcOrUri, boolean epcRequired) throws InvalidFormatException {
boolean isEpc = false;
if (epcOrUri.startsWith("urn:epc:id:")) {
// check if it is a valid EPC
checkEpc(epcOrUri);
isEpc = true;
} else {
// childEPCs in AggregationEvents, and epcList in
// TransactionEvents might also be simple URIs
if (epcRequired) {
throw new InvalidFormatException(
"One of the provided EPCs was a 'pure identity' EPC, so all of them must be 'pure identity' EPCs");
}
checkUri(epcOrUri);
}
return isEpc;
}
/**
* Parses the xml tree for epc nodes and returns a List of BizTransaction
* URIs with their corresponding type.
*
* @param bizNode
* The parent Node from which BizTransaction URIs should be
* extracted.
* @return A List of BizTransaction.
* @throws SAXException
* If an unknown tag (no <epc>) is encountered.
*/
private List<BusinessTransaction> handleBizTransactions(Session session, Node bizNode) throws SAXException {
List<BusinessTransaction> bizTransactionList = new ArrayList<BusinessTransaction>();
for (int i = 0; i < bizNode.getChildNodes().getLength(); i++) {
Node curNode = bizNode.getChildNodes().item(i);
if (curNode.getNodeName().equals("bizTransaction")) {
//Changed by nkef (use "getOrEditVocabularyElement" instead of "getOrInsertVocabularyElement")
String bizTransTypeUri = curNode.getAttributes().item(0).getTextContent();
String bizTransUri = curNode.getTextContent();
BusinessTransactionId bizTrans = (BusinessTransactionId) getOrEditVocabularyElement(session, EpcisConstants.BUSINESS_TRANSACTION_ID,
bizTransUri.toString(), "1");
BusinessTransactionTypeId type = (BusinessTransactionTypeId) getOrEditVocabularyElement(session,
EpcisConstants.BUSINESS_TRANSACTION_TYPE_ID, bizTransTypeUri.toString(), "1");
Criteria c0 = session.createCriteria(BusinessTransaction.class);
c0.add(Restrictions.eq("bizTransaction", bizTrans));
c0.add(Restrictions.eq("type", type));
BusinessTransaction bizTransaction = (BusinessTransaction) c0.uniqueResult();
if (bizTransaction == null) {
bizTransaction = new BusinessTransaction();
bizTransaction.setBizTransaction(bizTrans);
bizTransaction.setType(type);
session.save(bizTransaction);
}
bizTransactionList.add(bizTransaction);
} else {
if (!curNode.getNodeName().equals("#text") && !curNode.getNodeName().equals("#comment")) {
throw new SAXException("Unknown XML tag: " + curNode.getNodeName(), null);
}
}
}
return bizTransactionList;
}
/**
* (depricated)
* Inserts vocabulary into the database by searching for already existing
* entries; if found, the corresponding ID is returned. If not found, the
* vocabulary is extended if "insertmissingvoc" is true; otherwise an
* SQLException is thrown
*
* @param tableName
* The name of the vocabulary table.
* @param uri
* The vocabulary adapting the URI to be inserted into the
* vocabulary table.
* @return The ID of an already existing vocabulary table with the given
* uri.
* @throws UnsupportedOperationException
* If we are not allowed to insert a missing vocabulary.
*/
public VocabularyElement getOrInsertVocabularyElement(Session session, String vocabularyType,
String vocabularyElement) throws SAXException {
Class<?> c = vocClassMap.get(vocabularyType);
Criteria c0 = session.createCriteria(c);
c0.setCacheable(true);
c0.add(Restrictions.eq("uri", vocabularyElement));
VocabularyElement ve;
try {
ve = (VocabularyElement) c0.uniqueResult();
} catch (ObjectNotFoundException e) {
ve = null;
}
if (ve == null) {
// the uri does not yet exist: insert it if allowed. According to
// the specs, some vocabulary is not allowed to be extended; this is
// currently ignored here
if (!insertMissingVoc) {
throw new UnsupportedOperationException("Not allowed to add new vocabulary - use existing vocabulary");
} else {
// VocabularyElement subclasses should always have public
// zero-arg constructor to avoid problems here
try {
ve = (VocabularyElement) c.newInstance();
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
ve.setUri(vocabularyElement);
session.save(ve);
session.flush();
}
}
return ve;
}
/**
* (changed by nkef to support MasterDataCapture. Previusly known
* as "getOrInsertVocabularyElement")
* Inserts vocabulary into the database by searching for
* already existing entries; if found, the corresponding ID is returned. If
* not found, the vocabulary is extended if "insertmissingvoc" is true;
* otherwise an SQLException is thrown
*
* @param tableName
* The name of the vocabulary table.
* @param uri
* The vocabulary adapting the URI to be inserted into the
* vocabulary table.
* @return The ID of an already existing vocabulary table with the given
* uri.
* @throws UnsupportedOperationException
* If we are not allowed to insert a missing vocabulary.
*/
public VocabularyElement getOrEditVocabularyElement(Session session, String vocabularyType, String vocabularyElementURI, String mode)
throws SAXException {
boolean alterURI = false;
boolean singleDelete = false;
boolean wdDelete = false;
Long vocabularyElementID = null;
if (mode.equals("2")) {
alterURI = true;
}
else if (mode.equals("3")) {
singleDelete = true;
}
else if (mode.equals("4")) {
wdDelete = true;
}
Class<?> c = vocClassMap.get(vocabularyType);
Criteria c0 = session.createCriteria(c);
c0.setCacheable(true);
c0.add(Restrictions.eq("uri", alterURI ? vocabularyElementURI.split("#")[0] : vocabularyElementURI));
VocabularyElement ve;
try {
ve = (VocabularyElement) c0.uniqueResult();
}
catch (ObjectNotFoundException e) {
ve = null;
}
if (ve != null) {
vocabularyElementID = ve.getId();
}
if (ve == null || ((singleDelete || alterURI || wdDelete) && ve != null)) {
// the uri does not yet exist: insert it if allowed. According to
// the specs, some vocabulary is not allowed to be extended; this is
// currently ignored here
if (!insertMissingVoc) {
throw new UnsupportedOperationException("Not allowed to add new vocabulary - use existing vocabulary");
}
else {
// VocabularyElement subclasses should always have public
// zero-arg constructor to avoid problems here
if (alterURI) {
ve.setUri(vocabularyElementURI.split("#")[1]);
session.update(ve);
session.flush();
return ve;
}
else if (singleDelete) {
Object vocabularyElementObject = session.get(c, vocabularyElementID);
if (vocabularyElementObject != null)
session.delete(vocabularyElementObject);
deleteVocabularyElementAttributes(session, vocabularyType, vocabularyElementID);
session.flush();
return null;
}
else if (wdDelete) {
Object vocabularyElementObject = session.get(c, vocabularyElementID);
if (vocabularyElementObject != null)
session.delete(vocabularyElementObject);
deleteVocabularyElementAttributes(session, vocabularyType, vocabularyElementID);
deleteVocabularyElementDescendants(session, vocabularyType, vocabularyElementURI);
session.flush();
return null;
}
else {
try {
ve = (VocabularyElement) c.newInstance();
}
catch (InstantiationException e) {
throw new RuntimeException(e);
}
catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
ve.setUri(vocabularyElementURI);
session.save(ve);
}
session.flush();
}
}
return ve;
}
/**
* (nkef) Delete the a vocabulary's Element Descendants and all of their
* Attributes
*
* @param session
* @param vocabularyType
* @param vocabularyElementURI
*/
private void deleteVocabularyElementDescendants(Session session, String vocabularyType, String vocabularyElementURI) {
Class<?> c = vocClassMap.get(vocabularyType);
List vocElementChildrens = session.createSQLQuery(
"SELECT * FROM " + vocabularyTablenameMap.get(vocabularyType) + " WHERE uri LIKE '" + vocabularyElementURI + ",%'").addEntity(c)
.list();
for (int i = 0; i < vocElementChildrens.size(); i++) {
session.delete((VocabularyElement) vocElementChildrens.get(i));
deleteVocabularyElementAttributes(session, vocabularyType, ((VocabularyElement) vocElementChildrens.get(i)).getId());
}
session.flush();
}
/**
* (nkef) Delete selected id vocabulary elements attributes
*
* @param session
* @param vocabularyType
* @param vocabularyElementID
*/
private void deleteVocabularyElementAttributes(Session session, String vocabularyType, Long vocabularyElementID) {
Class<?> c = vocAttributeClassMap.get(vocabularyType);
List vocAttributeElements = session.createSQLQuery(
"select * FROM " + vocAttributeTablesMap.get(vocabularyType) + " where id = '" + vocabularyElementID + "'").addEntity(c).list();
for (int i = 0; i < vocAttributeElements.size(); i++) {
session.delete((VocabularyAttributeElement) vocAttributeElements.get(i));
}
session.flush();
}
/**
* (nkef) Inserts vocabulary attribute into the database by searching for
* already existing entries; if found, the corresponding ID is returned. If
* not found, the vocabulary is extended if "insertmissingvoc" is true;
* otherwise an SQLException is thrown
*
* @param tableName
* The name of the vocabulary table.
* @param uri
* The vocabulary adapting the URI to be inserted into the
* vocabulary table.
* @return The ID of an already existing vocabulary table with the given
* uri.
* @throws UnsupportedOperationException
* If we are not allowed to insert a missing vocabulary.
*/
public VocabularyAttributeElement getOrEditVocabularyAttributeElement(Session session, String vocabularyType, Long vocabularyElementID,
String vocabularyAttributeElement, String vocabularyAttributeElementValue, String mode) throws SAXException {
boolean deleteAttribute = false;
if (mode.equals("3")) {
deleteAttribute = true;
}
Class<?> c = vocAttributeClassMap.get(vocabularyType);
Criteria c0 = session.createCriteria(c);
c0.setCacheable(true);
VocabularyAttrCiD vocabularyAttrCiD = new VocabularyAttrCiD();
vocabularyAttrCiD.setAttribute(vocabularyAttributeElement);
vocabularyAttrCiD.setId(vocabularyElementID);
c0.add(Restrictions.idEq(vocabularyAttrCiD));
VocabularyAttributeElement vocAttributeElement = null;
try {
vocAttributeElement = (VocabularyAttributeElement) c0.uniqueResult();
}
catch (ObjectNotFoundException e) {
vocAttributeElement = null;
e.printStackTrace();
}
if(vocAttributeElement == null || (deleteAttribute && (vocAttributeElement != null)) || vocAttributeElement!=null){
// the uri does not yet exist: insert it if allowed. According to
// the specs, some vocabulary is not allowed to be extended; this is
// currently ignored here
if (!insertMissingVoc) {
throw new UnsupportedOperationException("Not allowed to add new vocabulary - use existing vocabulary");
}
else {
// VocabularyAttributeElement subclasses should always have
// public
// zero-arg constructor to avoid problems here
try {
vocAttributeElement = (VocabularyAttributeElement) c.newInstance();
}
catch (InstantiationException e) {
throw new RuntimeException(e);
}
catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
vocAttributeElement.setVocabularyAttrCiD(vocabularyAttrCiD);
vocAttributeElement.setValue(vocabularyAttributeElementValue);
if (vocAttributeElement == null) {
session.save(vocAttributeElement);
}
else if (deleteAttribute) {
Object vocabularyAttr = session.get(c, vocabularyAttrCiD);
if (vocabularyAttr != null)
session.delete(vocabularyAttr);
session.flush();
return null;
}
else {
session.merge(vocAttributeElement);
}
session.flush();
}
}
return vocAttributeElement;
}
/**
* TODO: javadoc!
*
* @param textContent
* @return
* @throws InvalidFormatException
*/
protected String checkEventTimeZoneOffset(String textContent) throws InvalidFormatException {
// first check the provided String against the expected pattern
Pattern p = Pattern.compile("[+-]\\d\\d:\\d\\d");
Matcher m = p.matcher(textContent);
boolean matches = m.matches();
if (matches) {
// second check the values (hours and minutes)
int h = Integer.parseInt(textContent.substring(1, 3));
int min = Integer.parseInt(textContent.substring(4, 6));
if ((h < 0) || (h > 14)) {
matches = false;
} else if (h == 14 && min != 0) {
matches = false;
} else if ((min < 0) || (min > 59)) {
matches = false;
}
}
if (matches) {
return textContent;
} else {
throw new InvalidFormatException("'eventTimeZoneOffset' has invalid format: " + textContent);
}
}
/**
* TODO: javadoc!
*
* @param textContent
* @return
* @throws InvalidFormatException
*/
private boolean checkUri(String textContent) throws InvalidFormatException {
try {
new URI(textContent);
} catch (URISyntaxException e) {
throw new InvalidFormatException(e.getMessage(), e);
}
return true;
}
/**
* Check EPC according to 'pure identity' URI as specified in Tag Data
* Standard.
*
* @param textContent
* @throws InvalidFormatException
*/
protected void checkEpc(String textContent) throws InvalidFormatException {
String uri = textContent;
if (!uri.startsWith("urn:epc:id:")) {
throw new InvalidFormatException("Invalid 'pure identity' EPC format: must start with \"urn:epc:id:\"");
}
uri = uri.substring("urn:epc:id:".length());
// check the patterns for the different EPC types
String epcType = uri.substring(0, uri.indexOf(":"));
uri = uri.substring(epcType.length() + 1);
LOG.debug("Checking pattern for EPC type " + epcType + ": " + uri);
Pattern p;
if ("gid".equals(epcType)) {
p = Pattern.compile("((0|[1-9][0-9]*)\\.){2}(0|[1-9][0-9]*)");
} else if ("sgtin".equals(epcType) || "sgln".equals(epcType) || "grai".equals(epcType)) {
p = Pattern.compile("([0-9]+\\.){2}([0-9]|[A-Z]|[a-z]|[\\!\\(\\)\\*\\+\\-',:;=_]|(%(([0-9]|[A-F])|[a-f]){2}))+");
} else if ("sscc".equals(epcType)) {
p = Pattern.compile("[0-9]+\\.[0-9]+");
} else if ("giai".equals(epcType)) {
p = Pattern.compile("[0-9]+\\.([0-9]|[A-Z]|[a-z]|[\\!\\(\\)\\*\\+\\-',:;=_]|(%(([0-9]|[A-F])|[a-f]){2}))+");
} else {
throw new InvalidFormatException("Invalid 'pure identity' EPC format: unknown EPC type: " + epcType);
}
Matcher m = p.matcher(uri);
if (!m.matches()) {
throw new InvalidFormatException("Invalid 'pure identity' EPC format: pattern \"" + uri
+ "\" is invalid for EPC type \"" + epcType + "\" - check with Tag Data Standard");
}
// check the number of digits for the different EPC types
boolean exceeded = false;
int count1 = uri.indexOf(".");
if ("sgtin".equals(epcType)) {
int count2 = uri.indexOf(".", count1 + 1) - (count1 + 1);
if (count1 + count2 > 13) {
exceeded = true;
}
} else if ("sgln".equals(epcType)) {
int count2 = uri.indexOf(".", count1 + 1) - (count1 + 1);
if (count1 + count2 > 12) {
exceeded = true;
}
} else if ("grai".equals(epcType)) {
int count2 = uri.indexOf(".", count1 + 1) - (count1 + 1);
if (count1 + count2 > 12) {
exceeded = true;
}
} else if ("sscc".equals(epcType)) {
int count2 = uri.length() - (count1 + 1);
if (count1 + count2 > 17) {
exceeded = true;
}
} else if ("giai".equals(epcType)) {
int count2 = uri.length() - (count1 + 1);
if (count1 + count2 > 30) {
exceeded = true;
}
} else {
// nothing to count
}
if (exceeded) {
throw new InvalidFormatException(
"Invalid 'pure identity' EPC format: check allowed number of characters for EPC type '" + epcType
+ "'");
}
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public boolean isDbResetAllowed() {
return dbResetAllowed;
}
public void setDbResetAllowed(boolean dbResetAllowed) {
this.dbResetAllowed = dbResetAllowed;
}
public void setDbResetScript(String dbResetScript) {
if (dbResetScript != null) {
String[] scripts = dbResetScript.split(",");
List<File> scriptList = new ArrayList<File>(scripts.length);
for (String script : scripts) {
if (!StringUtils.isBlank(script)) {
script = "/" + script.trim();
URL url = ClassLoader.getSystemResource(script);
if (url == null) {
url = this.getClass().getResource(script);
}
if (url == null) {
LOG.warn("unable to find sql script " + script + " in classpath");
} else {
LOG.debug("found dbReset sql script at " + url);
scriptList.add(new File(url.getFile()));
}
}
}
this.dbResetScripts = scriptList;
}
}
public boolean isInsertMissingVoc() {
return insertMissingVoc;
}
public void setInsertMissingVoc(boolean insertMissingVoc) {
this.insertMissingVoc = insertMissingVoc;
}
public Schema getSchema() {
return schema;
}
public void setSchema(Schema schema) {
this.schema = schema;
}
public void setEpcisSchemaFile(String epcisSchemaFile) {
Schema schema = initEpcisSchema(epcisSchemaFile);
setSchema(schema);
}
// (nkef)
public Schema getMasterDataSchema() {
return masterDataSchema;
}
// (nkef)
public void setMasterDataSchema(Schema masterDataSchema) {
this.masterDataSchema = masterDataSchema;
}
}
|
epcis-repository/src/main/java/org/fosstrak/epcis/repository/capture/CaptureOperationsModule.java
|
/*
* Copyright (C) 2007 ETH Zurich
*
* This file is part of Fosstrak (www.fosstrak.org).
*
* Fosstrak is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* Fosstrak is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with Fosstrak; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
package org.fosstrak.epcis.repository.capture;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.Principal;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.fosstrak.epcis.repository.EpcisConstants;
import org.fosstrak.epcis.repository.InvalidFormatException;
import org.fosstrak.epcis.utils.TimeParser;
import org.fosstrak.epcis.repository.model.Action;
import org.fosstrak.epcis.repository.model.AggregationEvent;
import org.fosstrak.epcis.repository.model.BaseEvent;
import org.fosstrak.epcis.repository.model.BusinessLocationId;
import org.fosstrak.epcis.repository.model.BusinessStepId;
import org.fosstrak.epcis.repository.model.BusinessTransaction;
import org.fosstrak.epcis.repository.model.BusinessTransactionId;
import org.fosstrak.epcis.repository.model.BusinessTransactionTypeId;
import org.fosstrak.epcis.repository.model.DispositionId;
import org.fosstrak.epcis.repository.model.EPCClass;
import org.fosstrak.epcis.repository.model.EventFieldExtension;
import org.fosstrak.epcis.repository.model.ObjectEvent;
import org.fosstrak.epcis.repository.model.QuantityEvent;
import org.fosstrak.epcis.repository.model.ReadPointId;
import org.fosstrak.epcis.repository.model.TransactionEvent;
import org.fosstrak.epcis.repository.model.VocabularyElement;
import org.fosstrak.epcis.repository.model.VocabularyAttrCiD;
import org.fosstrak.epcis.repository.model.VocabularyAttributeElement;
import org.fosstrak.epcis.repository.model.BusinessLocationAttrId;
import org.fosstrak.epcis.repository.model.BusinessStepAttrId;
import org.fosstrak.epcis.repository.model.BusinessTransactionAttrId;
import org.fosstrak.epcis.repository.model.BusinessTransactionTypeAttrId;
import org.fosstrak.epcis.repository.model.DispositionAttrId;
import org.fosstrak.epcis.repository.model.EPCClassAttrId;
import org.fosstrak.epcis.repository.model.ReadPointAttrId;
import org.hibernate.Criteria;
import org.hibernate.ObjectNotFoundException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
/**
* CaptureOperationsModule implements the core capture operations. Converts XML
* events delivered by HTTP POST into SQL and inserts them into the database.
* <p>
* TODO: the parsing of the xml inputstream should be done in the
* CaptureOperationsServlet; this class should implement EpcisCaptureInterface
* such that CaptureOperationsServlet can call its capture method and provide it
* with the parsed events.
*
* @author David Gubler
* @author Alain Remund
* @author Marco Steybe
* @author Nikos Kefalakis (nkef)
*/
public class CaptureOperationsModule {
private static final Log LOG = LogFactory.getLog(CaptureOperationsModule.class);
private static final Map<String, Class<?>> vocClassMap = new HashMap<String, Class<?>>();
static {
vocClassMap.put(EpcisConstants.BUSINESS_LOCATION_ID, BusinessLocationId.class);
vocClassMap.put(EpcisConstants.BUSINESS_STEP_ID, BusinessStepId.class);
vocClassMap.put(EpcisConstants.BUSINESS_TRANSACTION_ID, BusinessTransactionId.class);
vocClassMap.put(EpcisConstants.BUSINESS_TRANSACTION_TYPE_ID, BusinessTransactionTypeId.class);
vocClassMap.put(EpcisConstants.DISPOSITION_ID, DispositionId.class);
vocClassMap.put(EpcisConstants.EPC_CLASS_ID, EPCClass.class);
vocClassMap.put(EpcisConstants.READ_POINT_ID, ReadPointId.class);
}
// (nkef) Added to support the Master Data Capture I/F
private static final Map<String, Class<?>> vocAttributeClassMap = new HashMap<String, Class<?>>();
private static final Map<String, String> vocAttributeTablesMap = new HashMap<String, String>();
private static Map<String, String> vocabularyTablenameMap = new HashMap<String, String>();
static {
vocAttributeClassMap.put(EpcisConstants.BUSINESS_LOCATION_ID, BusinessLocationAttrId.class);
vocAttributeClassMap.put(EpcisConstants.BUSINESS_STEP_ID, BusinessStepAttrId.class);
vocAttributeClassMap.put(EpcisConstants.BUSINESS_TRANSACTION_ID, BusinessTransactionAttrId.class);
vocAttributeClassMap.put(EpcisConstants.BUSINESS_TRANSACTION_TYPE_ID, BusinessTransactionTypeAttrId.class);
vocAttributeClassMap.put(EpcisConstants.DISPOSITION_ID, DispositionAttrId.class);
vocAttributeClassMap.put(EpcisConstants.EPC_CLASS_ID, EPCClassAttrId.class);
vocAttributeClassMap.put(EpcisConstants.READ_POINT_ID, ReadPointAttrId.class);
vocAttributeTablesMap.put(EpcisConstants.BUSINESS_LOCATION_ID, "voc_BizLoc_attr");
vocAttributeTablesMap.put(EpcisConstants.BUSINESS_STEP_ID, "voc_BizStep_attr");
vocAttributeTablesMap.put(EpcisConstants.BUSINESS_TRANSACTION_ID, "voc_BizTrans_attr");
vocAttributeTablesMap.put(EpcisConstants.BUSINESS_TRANSACTION_TYPE_ID, "voc_BizTransType_attr");
vocAttributeTablesMap.put(EpcisConstants.DISPOSITION_ID, "voc_Disposition_attr");
vocAttributeTablesMap.put(EpcisConstants.EPC_CLASS_ID, "voc_EPCClass_attr");
vocAttributeTablesMap.put(EpcisConstants.READ_POINT_ID, "voc_ReadPoint_attr");
vocabularyTablenameMap.put(EpcisConstants.BUSINESS_STEP_ID, "voc_BizStep");
vocabularyTablenameMap.put(EpcisConstants.BUSINESS_LOCATION_ID, "voc_BizLoc");
vocabularyTablenameMap.put(EpcisConstants.BUSINESS_TRANSACTION_ID, "voc_BizTrans");
vocabularyTablenameMap.put(EpcisConstants.BUSINESS_TRANSACTION_TYPE_ID, "voc_BizTransType");
vocabularyTablenameMap.put(EpcisConstants.DISPOSITION_ID, "voc_Disposition");
vocabularyTablenameMap.put(EpcisConstants.EPC_CLASS_ID, "voc_EPCClass");
vocabularyTablenameMap.put(EpcisConstants.READ_POINT_ID, "voc_ReadPoint");
}
/**
* The XSD schema which validates the incoming messages.
*/
private Schema schema;
/**
* The XSD schema which validates the MasterData incoming messages.(nkef)
*/
private Schema masterDataSchema;
/**
* Whether we should insert new vocabulary or throw an error message.
*/
private boolean insertMissingVoc = true;
/**
* Whether the dbReset operation is allowed or not.
*/
private boolean dbResetAllowed = false;
/**
* The SQL files to be executed when the dbReset operation is invoked.
*/
private List<File> dbResetScripts = null;
/**
* Interface to the database.
*/
private SessionFactory sessionFactory;
/**
* Initializes the EPCIS schema used for validating incoming capture
* requests. Loads the WSDL and XSD files from the classpath (the schema is
* bundled with epcis-commons.jar).
*
* @return An instantiated schema validation object.
*/
private Schema initEpcisSchema(String xsdFile) {
InputStream is = this.getClass().getResourceAsStream(xsdFile);
if (is != null) {
try {
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Source schemaSrc = new StreamSource(is);
schemaSrc.setSystemId(CaptureOperationsServlet.class.getResource(xsdFile).toString());
Schema schema = schemaFactory.newSchema(schemaSrc);
LOG.debug("EPCIS schema file initialized and loaded successfully");
return schema;
} catch (Exception e) {
LOG.warn("Unable to load or parse the EPCIS schema", e);
}
} else {
LOG.error("Unable to load the EPCIS schema file from classpath: cannot find resource " + xsdFile);
}
LOG.warn("Schema validation will not be available!");
return null;
}
/**
* Resets the database.
*
* @throws SQLException
* If something goes wrong resetting the database.
* @throws IOException
* If something goes wrong reading the reset script.
* @throws UnsupportedOperationsException
* If database resets are not allowed.
*/
public void doDbReset() throws SQLException, IOException, UnsupportedOperationException {
if (dbResetAllowed) {
if (dbResetScripts == null || dbResetScripts.isEmpty()) {
LOG.warn("dbReset operation invoked but no dbReset script is configured!");
} else {
Session session = null;
try {
session = sessionFactory.openSession();
Transaction tx = null;
for (File file : dbResetScripts) {
try {
tx = session.beginTransaction();
LOG.info("Running db reset script from file " + file);
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
String sql = "";
while ((line = reader.readLine()) != null) {
if (!line.startsWith("--") && StringUtils.isNotBlank(line)) {
sql += line;
if (sql.endsWith(";")) {
LOG.debug("SQL: " + sql);
session.createSQLQuery(sql).executeUpdate();
sql = "";
}
}
}
tx.commit();
} catch (Throwable e) {
LOG.error("dbReset failed for " + file + ": " + e.toString(), e);
if (tx != null) {
tx.rollback();
}
throw new SQLException(e.toString());
}
}
} finally {
if (session != null) {
session.close();
}
}
}
} else {
throw new UnsupportedOperationException();
}
}
/**
* Implements the EPCIS capture operation. Takes an input stream, extracts
* the payload into an XML document, validates the document against the
* EPCIS schema, and captures the EPCIS events given in the document.
*
* @throws IOException
* If an error occurred while validating the request or writing
* the response.
* @throws ParserConfigurationException
* @throws SAXException
* If the XML document is malformed or invalid
* @throws InvalidFormatException
*/
public void doCapture(InputStream in, Principal principal) throws SAXException, IOException, InvalidFormatException {
// parse the payload as XML document
Document document;
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.parse(in);
LOG.debug("Payload successfully parsed as XML document");
if (LOG.isDebugEnabled()) {
try {
TransformerFactory tfFactory = TransformerFactory.newInstance();
Transformer transformer = tfFactory.newTransformer();
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(document), new StreamResult(writer));
String xml = writer.toString();
if (xml.length() > 100 * 1024) {
// too large, do not log
xml = null;
} else {
LOG.debug("Incoming contents:\n\n" + writer.toString() + "\n");
}
} catch (Exception e) {
// never mind ... do not log
}
}
// validate incoming document against its! schema(changed by nkef)
if (isEPCISDocument(document)) {
// validate the XML document against the EPCISDocument schema
if (schema != null) {
Validator validator = schema.newValidator();
try {
validator.validate(new DOMSource(document), null);
}
catch (SAXParseException e) {
// TODO: we need to ignore XML element order, the
// following
// is only a hack to pass some of the conformance tests
if (e.getMessage().contains("parentID")) {
LOG.warn("Ignoring XML validation exception: " + e.getMessage());
}
else {
throw e;
}
}
LOG.info("Incoming capture request was successfully validated against the EPCISDocument schema");
}
else {
LOG.warn("Schema validator unavailable. Unable to validate EPCIS capture event against schema!");
}
}
else if (isEPCISMasterDataDocument(document)) {
// TODO: Validate EPCIS Master Data incoming Document
}
}
catch (ParserConfigurationException e) {
throw new SAXException(e);
}
// handle the capture operation
Session session = null;
try {
session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
LOG.debug("DB connection opened.");
if (isEPCISDocument(document)) {
handleEventDocument(session, document);
}
else if (isEPCISMasterDataDocument(document)) {
handleMasterDataDocument(session, document);
}
tx.commit();
// return OK
LOG.info("EPCIS Capture Interface request succeeded");
} catch (SAXException e) {
LOG.error("EPCIS Capture Interface request failed: " + e.toString());
if (tx != null) {
tx.rollback();
}
throw e;
} catch (InvalidFormatException e) {
LOG.error("EPCIS Capture Interface request failed: " + e.toString());
if (tx != null) {
tx.rollback();
}
throw e;
} catch (Exception e) {
// Hibernate throws RuntimeExceptions, so don't let them
// (or anything else) escape without clean up
LOG.error("EPCIS Capture Interface request failed: " + e.toString(), e);
if (tx != null) {
tx.rollback();
}
throw new IOException(e.toString());
}
} finally {
if (session != null) {
session.close();
}
// sessionFactory.getStatistics().logSummary();
LOG.debug("DB connection closed");
}
}
/**
* @param document
* @return
*/
private boolean isEPCISDocument(Document document) {
return document.getDocumentElement().getLocalName().equals("EPCISDocument");
}
/**
* @param document
* @return
*/
private boolean isEPCISMasterDataDocument(Document document) {
return document.getDocumentElement().getLocalName().equals("EPCISMasterDataDocument");
}
/**
* Parses the entire document and handles the supplied events.
*
* @throws Exception
* @throws DOMException
*/
private void handleEventDocument(Session session, Document document) throws DOMException, SAXException,
InvalidFormatException {
NodeList eventList = document.getElementsByTagName("EventList");
NodeList events = eventList.item(0).getChildNodes();
// walk through all supplied events
int eventCount = 0;
for (int i = 0; i < events.getLength(); i++) {
Node eventNode = events.item(i);
String nodeName = eventNode.getNodeName();
if (nodeName.equals(EpcisConstants.OBJECT_EVENT) || nodeName.equals(EpcisConstants.AGGREGATION_EVENT)
|| nodeName.equals(EpcisConstants.QUANTITY_EVENT)
|| nodeName.equals(EpcisConstants.TRANSACTION_EVENT)) {
LOG.debug("processing event " + i + ": '" + nodeName + "'.");
handleEvent(session, eventNode, nodeName);
eventCount++;
if (eventCount % 50 == 0) {
session.flush();
session.clear();
}
} else if (!nodeName.equals("#text") && !nodeName.equals("#comment")) {
throw new SAXException("Encountered unknown event '" + nodeName + "'.");
}
}
}
/**
* Takes an XML document node, parses it as EPCIS event and inserts the data
* into the database. The parse routine is generic for all event types; the
* query generation part has some if/elses to take care of different event
* parameters.
*
* @param eventNode
* The current event node.
* @param eventType
* The current event type.
* @throws Exception
* @throws DOMException
*/
private void handleEvent(Session session, final Node eventNode, final String eventType) throws DOMException,
SAXException, InvalidFormatException {
if (eventNode == null) {
// nothing to do
return;
} else if (eventNode.getChildNodes().getLength() == 0) {
throw new SAXException("Event element '" + eventNode.getNodeName() + "' has no children elements.");
}
Node curEventNode = null;
// A lot of the initialized variables have type URI. This type isn't to
// compare with the URI-Type of the standard. In fact, most of the
// variables having type URI are declared as Vocabularies in the
// Standard. Commonly, we use String for the Standard-Type URI.
Calendar eventTime = null;
Calendar recordTime = GregorianCalendar.getInstance();
String eventTimeZoneOffset = null;
String action = null;
String parentId = null;
Long quantity = null;
String bizStepUri = null;
String dispositionUri = null;
String readPointUri = null;
String bizLocationUri = null;
String epcClassUri = null;
List<String> epcs = null;
List<BusinessTransaction> bizTransList = null;
List<EventFieldExtension> fieldNameExtList = new ArrayList<EventFieldExtension>();
for (int i = 0; i < eventNode.getChildNodes().getLength(); i++) {
curEventNode = eventNode.getChildNodes().item(i);
String nodeName = curEventNode.getNodeName();
if (nodeName.equals("#text") || nodeName.equals("#comment")) {
// ignore text or comments
LOG.debug(" ignoring text or comment: '" + curEventNode.getTextContent().trim() + "'");
continue;
}
LOG.debug(" handling event field: '" + nodeName + "'");
if (nodeName.equals("eventTime")) {
String xmlTime = curEventNode.getTextContent();
LOG.debug(" eventTime in xml is '" + xmlTime + "'");
try {
eventTime = TimeParser.parseAsCalendar(xmlTime);
} catch (ParseException e) {
throw new SAXException("Invalid date/time (must be ISO8601).", e);
}
LOG.debug(" eventTime parsed as '" + eventTime.getTime() + "'");
} else if (nodeName.equals("recordTime")) {
// ignore recordTime
} else if (nodeName.equals("eventTimeZoneOffset")) {
eventTimeZoneOffset = checkEventTimeZoneOffset(curEventNode.getTextContent());
} else if (nodeName.equals("epcList") || nodeName.equals("childEPCs")) {
epcs = handleEpcs(eventType, curEventNode);
} else if (nodeName.equals("bizTransactionList")) {
bizTransList = handleBizTransactions(session, curEventNode);
} else if (nodeName.equals("action")) {
action = curEventNode.getTextContent();
if (!action.equals("ADD") && !action.equals("OBSERVE") && !action.equals("DELETE")) {
throw new SAXException("Encountered illegal 'action' value: " + action);
}
} else if (nodeName.equals("bizStep")) {
bizStepUri = curEventNode.getTextContent();
} else if (nodeName.equals("disposition")) {
dispositionUri = curEventNode.getTextContent();
} else if (nodeName.equals("readPoint")) {
Element attrElem = (Element) curEventNode;
Node id = attrElem.getElementsByTagName("id").item(0);
readPointUri = id.getTextContent();
} else if (nodeName.equals("bizLocation")) {
Element attrElem = (Element) curEventNode;
Node id = attrElem.getElementsByTagName("id").item(0);
bizLocationUri = id.getTextContent();
} else if (nodeName.equals("epcClass")) {
epcClassUri = curEventNode.getTextContent();
} else if (nodeName.equals("quantity")) {
quantity = Long.valueOf(curEventNode.getTextContent());
} else if (nodeName.equals("parentID")) {
checkEpcOrUri(curEventNode.getTextContent(), false);
parentId = curEventNode.getTextContent();
} else {
String[] parts = nodeName.split(":");
if (parts.length == 2) {
LOG.debug(" treating unknown event field as extension.");
String prefix = parts[0];
String localname = parts[1];
// String namespace =
// document.getDocumentElement().getAttribute("xmlns:" +
// prefix);
String namespace = curEventNode.lookupNamespaceURI(prefix);
String value = curEventNode.getTextContent();
EventFieldExtension evf = new EventFieldExtension(prefix, namespace, localname, value);
fieldNameExtList.add(evf);
} else {
// this is not a valid extension
throw new SAXException(" encountered unknown event field: '" + nodeName + "'.");
}
}
}
if (eventType.equals(EpcisConstants.AGGREGATION_EVENT)) {
// for AggregationEvents, the parentID is only optional for
// action=OBSERVE
if (parentId == null && ("ADD".equals(action) || "DELETE".equals(action))) {
throw new InvalidFormatException("'parentID' is required if 'action' is ADD or DELETE");
}
}
//Changed by nkef (use "getOrEditVocabularyElement" instead of "getOrInsertVocabularyElement")
String nodeName = eventNode.getNodeName();
VocabularyElement bizStep = bizStepUri != null ? getOrEditVocabularyElement(session, EpcisConstants.BUSINESS_STEP_ID, String
.valueOf(bizStepUri), "1") : null;
VocabularyElement disposition = dispositionUri != null ? getOrEditVocabularyElement(session, EpcisConstants.DISPOSITION_ID, String
.valueOf(dispositionUri), "1") : null;
VocabularyElement readPoint = readPointUri != null ? getOrEditVocabularyElement(session, EpcisConstants.READ_POINT_ID, String
.valueOf(readPointUri), "1") : null;
VocabularyElement bizLocation = bizLocationUri != null ? getOrEditVocabularyElement(session, EpcisConstants.BUSINESS_LOCATION_ID, String
.valueOf(bizLocationUri), "1") : null;
VocabularyElement epcClass = epcClassUri != null ? getOrEditVocabularyElement(session, EpcisConstants.EPC_CLASS_ID, String
.valueOf(epcClassUri), "1") : null;
BaseEvent be;
if (nodeName.equals(EpcisConstants.AGGREGATION_EVENT)) {
AggregationEvent ae = new AggregationEvent();
ae.setParentId(parentId);
ae.setChildEpcs(epcs);
ae.setAction(Action.valueOf(action));
be = ae;
} else if (nodeName.equals(EpcisConstants.OBJECT_EVENT)) {
ObjectEvent oe = new ObjectEvent();
oe.setAction(Action.valueOf(action));
if (epcs != null && epcs.size() > 0) {
oe.setEpcList(epcs);
}
be = oe;
} else if (nodeName.equals(EpcisConstants.QUANTITY_EVENT)) {
QuantityEvent qe = new QuantityEvent();
qe.setEpcClass((EPCClass) epcClass);
if (quantity != null) {
qe.setQuantity(quantity.longValue());
}
be = qe;
} else if (nodeName.equals(EpcisConstants.TRANSACTION_EVENT)) {
TransactionEvent te = new TransactionEvent();
te.setParentId(parentId);
te.setEpcList(epcs);
te.setAction(Action.valueOf(action));
be = te;
} else {
throw new SAXException("Encountered unknown event element '" + nodeName + "'.");
}
be.setEventTime(eventTime);
be.setRecordTime(recordTime);
be.setEventTimeZoneOffset(eventTimeZoneOffset);
be.setBizStep((BusinessStepId) bizStep);
be.setDisposition((DispositionId) disposition);
be.setBizLocation((BusinessLocationId) bizLocation);
be.setReadPoint((ReadPointId) readPoint);
if (bizTransList != null && bizTransList.size() > 0) {
be.setBizTransList(bizTransList);
}
if (!fieldNameExtList.isEmpty()) {
be.setExtensions(fieldNameExtList);
}
session.save(be);
}
/**
* (nkef) Parses the entire document and handles the supplied Master Data.
*
*
* @throws Exception
* @throws DOMException
*/
private void handleMasterDataDocument(Session session, Document document) throws DOMException, SAXException, InvalidFormatException {
// Handle Vocabulary List
NodeList vocabularyList = document.getElementsByTagName("VocabularyList");
if (vocabularyList.item(0).hasChildNodes()) {
NodeList vocabularys = vocabularyList.item(0).getChildNodes();
// walk through all supplied vocabularies
int vocabularyCount = 0;
for (int i = 0; i < vocabularys.getLength(); i++) {
Node vocabularyNode = vocabularys.item(i);
String nodeName = vocabularyNode.getNodeName();
if (nodeName.equals("Vocabulary")) {
String vocabularyType = vocabularyNode.getAttributes().getNamedItem("type").getNodeValue();
if (EpcisConstants.VOCABULARY_TYPES.contains(vocabularyType)) {
LOG.debug("processing " + i + ": '" + nodeName + "':" + vocabularyType + ".");
handleVocabulary(session, vocabularyNode, vocabularyType);
vocabularyCount++;
if (vocabularyCount % 50 == 0) {
session.flush();
session.clear();
}
}
}
else if (!nodeName.equals("#text") && !nodeName.equals("#comment")) {
throw new SAXException("Encountered unknown vocabulary '" + nodeName + "'.");
}
}
}
}
/**
* (nkef) Takes an XML document node, parses it as EPCIS Master Data and
* inserts the data into the database. The parse routine is generic for all
* Vocabulary types;
*
* @param vocabularyNode
* The current vocabulary node.
* @param vocabularyType
* The current vocabulary type.
* @throws Exception
* @throws DOMException
*/
private void handleVocabulary(Session session, final Node vocabularyNode, final String vocabularyType) throws DOMException, SAXException,
InvalidFormatException {
if (vocabularyNode == null) {
// nothing to do
return;
}
else if (vocabularyNode.getChildNodes().getLength() == 0) {
throw new SAXException("Vocabulary element '" + vocabularyNode.getNodeName() + "' has no children elements.");
}
Node curVocabularyNode = null;
Node curVocabularyElementNode = null;
Node curVocabularyAttributeNode = null;
String curVocabularyURI = null;
String curVocabularyAttribute = null;
String curVocabularyAttributeValue = null;
VocabularyElement curVocabularyElement = null;
for (int i = 0; i < vocabularyNode.getChildNodes().getLength(); i++) {
curVocabularyNode = vocabularyNode.getChildNodes().item(i);
String curVocabularyNodeName = curVocabularyNode.getNodeName();
if (curVocabularyNodeName.equals("#text") || curVocabularyNodeName.equals("#comment")) {
// ignore text or comments
LOG.debug(" ignoring text or comment: '" + curVocabularyNode.getTextContent().trim() + "'");
continue;
}
for (int j = 0; j < curVocabularyNode.getChildNodes().getLength(); j++) {
curVocabularyElementNode = curVocabularyNode.getChildNodes().item(j);
String curVocabularyElementNodeName = curVocabularyElementNode.getNodeName();
if (curVocabularyElementNodeName.equals("#text") || curVocabularyElementNodeName.equals("#comment")) {
// ignore text or comments
LOG.debug(" ignoring text or comment: '" + curVocabularyElementNode.getTextContent().trim() + "'");
continue;
}
LOG.debug(" handling vocabulary field: '" + curVocabularyElementNodeName + "'");
curVocabularyURI = curVocabularyElementNode.getAttributes().getNamedItem("id").getNodeValue();
/*
* vocabularyElementEditMode
* 1: insert((it can be anything except 2,3,4))
* 2: alterURI
* 3: singleDelete
* 4: Delete element with it's direct or indirect
* descendants
*/
String vocabularyElementEditMode = "";
if (!(curVocabularyElementNode.getAttributes().getNamedItem("mode") == null)) {
vocabularyElementEditMode = curVocabularyElementNode.getAttributes().getNamedItem("mode").getNodeValue();
}
else {
vocabularyElementEditMode = "1";
}
curVocabularyElement = getOrEditVocabularyElement(session, vocabularyType, curVocabularyURI, vocabularyElementEditMode);
// *****************************************
if (curVocabularyElement != null) {
for (int k = 0; k < curVocabularyElementNode.getChildNodes().getLength(); k++) {
curVocabularyAttributeNode = curVocabularyElementNode.getChildNodes().item(k);
String curVocabularyAttributeElementNodeName = curVocabularyAttributeNode.getNodeName();
if (curVocabularyAttributeElementNodeName.equals("#text") || curVocabularyAttributeElementNodeName.equals("#comment")) {
// ignore text or comments
LOG.debug(" ignoring text or comment: '" + curVocabularyAttributeNode.getTextContent().trim() + "'");
continue;
}
LOG.debug(" handling vocabulary field: '" + curVocabularyAttributeElementNodeName + "'");
curVocabularyAttribute = curVocabularyAttributeNode.getAttributes().getNamedItem("id").getNodeValue();
curVocabularyAttributeValue = curVocabularyAttributeNode.getAttributes().getNamedItem("value").getNodeValue();//.getFirstChild().getNodeValue();
/*
* vocabularyAttributeEditMode
* 1: Insert (it can be anything except 3))
* 2: Alter Attribute Value (it can be anything except 3)
* 3: Delete Attribute (required)
*/
String vocabularyAttributeEditMode = "";
if (!(curVocabularyAttributeNode.getAttributes().getNamedItem("mode") == null)) {
vocabularyAttributeEditMode = curVocabularyAttributeNode.getAttributes().getNamedItem("mode").getNodeValue();
}
else {
vocabularyAttributeEditMode = "add/alter";
}
getOrEditVocabularyAttributeElement(session, vocabularyType, curVocabularyElement.getId(), curVocabularyAttribute,
curVocabularyAttributeValue, vocabularyAttributeEditMode);
}
}
// *****************************************
}
}
if (vocabularyType.equals(EpcisConstants.BUSINESS_LOCATION_ID)) {
}
}
/**
* Parses the xml tree for epc nodes and returns a list of EPC URIs.
*
* @param eventType
* @param epcNode
* The parent Node from which EPC URIs should be extracted.
* @return An array of vocabularies containing all the URIs found in the
* given node.
* @throws SAXException
* If an unknown tag (no <epc>) is encountered.
* @throws InvalidFormatException
* @throws DOMException
*/
private List<String> handleEpcs(final String eventType, final Node epcNode) throws SAXException, DOMException,
InvalidFormatException {
List<String> epcList = new ArrayList<String>();
boolean isEpc = false;
boolean epcRequired = false;
boolean atLeastOneNonEpc = false;
for (int i = 0; i < epcNode.getChildNodes().getLength(); i++) {
Node curNode = epcNode.getChildNodes().item(i);
if (curNode.getNodeName().equals("epc")) {
isEpc = checkEpcOrUri(curNode.getTextContent(), epcRequired);
if (isEpc) {
// if one of the values is an EPC, then all of them must be
// valid EPCs
epcRequired = true;
} else {
atLeastOneNonEpc = true;
}
epcList.add(curNode.getTextContent());
} else {
if (curNode.getNodeName() != "#text" && curNode.getNodeName() != "#comment") {
throw new SAXException("Unknown XML tag: " + curNode.getNodeName(), null);
}
}
}
if (atLeastOneNonEpc && isEpc) {
throw new InvalidFormatException(
"One of the provided EPCs was a 'pure identity' EPC, so all of them must be 'pure identity' EPCs");
}
return epcList;
}
/**
* @param epcOrUri
* The EPC or URI to check.
* @param epcRequired
* <code>true</code> if an EPC is required (will throw an
* InvalidFormatException if the given <code>epcOrUri</code> is
* an invalid EPC, but might be a valid URI), <code>false</code>
* otherwise.
* @return <code>true</code> if the given <code>epcOrUri</code> is a valid
* EPC, <code>false</code> otherwise.
* @throws InvalidFormatException
*/
protected boolean checkEpcOrUri(String epcOrUri, boolean epcRequired) throws InvalidFormatException {
boolean isEpc = false;
if (epcOrUri.startsWith("urn:epc:id:")) {
// check if it is a valid EPC
checkEpc(epcOrUri);
isEpc = true;
} else {
// childEPCs in AggregationEvents, and epcList in
// TransactionEvents might also be simple URIs
if (epcRequired) {
throw new InvalidFormatException(
"One of the provided EPCs was a 'pure identity' EPC, so all of them must be 'pure identity' EPCs");
}
checkUri(epcOrUri);
}
return isEpc;
}
/**
* Parses the xml tree for epc nodes and returns a List of BizTransaction
* URIs with their corresponding type.
*
* @param bizNode
* The parent Node from which BizTransaction URIs should be
* extracted.
* @return A List of BizTransaction.
* @throws SAXException
* If an unknown tag (no <epc>) is encountered.
*/
private List<BusinessTransaction> handleBizTransactions(Session session, Node bizNode) throws SAXException {
List<BusinessTransaction> bizTransactionList = new ArrayList<BusinessTransaction>();
for (int i = 0; i < bizNode.getChildNodes().getLength(); i++) {
Node curNode = bizNode.getChildNodes().item(i);
if (curNode.getNodeName().equals("bizTransaction")) {
//Changed by nkef (use "getOrEditVocabularyElement" instead of "getOrInsertVocabularyElement")
String bizTransTypeUri = curNode.getAttributes().item(0).getTextContent();
String bizTransUri = curNode.getTextContent();
BusinessTransactionId bizTrans = (BusinessTransactionId) getOrEditVocabularyElement(session, EpcisConstants.BUSINESS_TRANSACTION_ID,
bizTransUri.toString(), "1");
BusinessTransactionTypeId type = (BusinessTransactionTypeId) getOrEditVocabularyElement(session,
EpcisConstants.BUSINESS_TRANSACTION_TYPE_ID, bizTransTypeUri.toString(), "1");
Criteria c0 = session.createCriteria(BusinessTransaction.class);
c0.add(Restrictions.eq("bizTransaction", bizTrans));
c0.add(Restrictions.eq("type", type));
BusinessTransaction bizTransaction = (BusinessTransaction) c0.uniqueResult();
if (bizTransaction == null) {
bizTransaction = new BusinessTransaction();
bizTransaction.setBizTransaction(bizTrans);
bizTransaction.setType(type);
session.save(bizTransaction);
}
bizTransactionList.add(bizTransaction);
} else {
if (!curNode.getNodeName().equals("#text") && !curNode.getNodeName().equals("#comment")) {
throw new SAXException("Unknown XML tag: " + curNode.getNodeName(), null);
}
}
}
return bizTransactionList;
}
/**
* (depricated)
* Inserts vocabulary into the database by searching for already existing
* entries; if found, the corresponding ID is returned. If not found, the
* vocabulary is extended if "insertmissingvoc" is true; otherwise an
* SQLException is thrown
*
* @param tableName
* The name of the vocabulary table.
* @param uri
* The vocabulary adapting the URI to be inserted into the
* vocabulary table.
* @return The ID of an already existing vocabulary table with the given
* uri.
* @throws UnsupportedOperationException
* If we are not allowed to insert a missing vocabulary.
*/
public VocabularyElement getOrInsertVocabularyElement(Session session, String vocabularyType,
String vocabularyElement) throws SAXException {
Class<?> c = vocClassMap.get(vocabularyType);
Criteria c0 = session.createCriteria(c);
c0.setCacheable(true);
c0.add(Restrictions.eq("uri", vocabularyElement));
VocabularyElement ve;
try {
ve = (VocabularyElement) c0.uniqueResult();
} catch (ObjectNotFoundException e) {
ve = null;
}
if (ve == null) {
// the uri does not yet exist: insert it if allowed. According to
// the specs, some vocabulary is not allowed to be extended; this is
// currently ignored here
if (!insertMissingVoc) {
throw new UnsupportedOperationException("Not allowed to add new vocabulary - use existing vocabulary");
} else {
// VocabularyElement subclasses should always have public
// zero-arg constructor to avoid problems here
try {
ve = (VocabularyElement) c.newInstance();
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
ve.setUri(vocabularyElement);
session.save(ve);
session.flush();
}
}
return ve;
}
/**
* (changed by nkef to support MasterDataCapture. Previusly known
* as "getOrInsertVocabularyElement")
* Inserts vocabulary into the database by searching for
* already existing entries; if found, the corresponding ID is returned. If
* not found, the vocabulary is extended if "insertmissingvoc" is true;
* otherwise an SQLException is thrown
*
* @param tableName
* The name of the vocabulary table.
* @param uri
* The vocabulary adapting the URI to be inserted into the
* vocabulary table.
* @return The ID of an already existing vocabulary table with the given
* uri.
* @throws UnsupportedOperationException
* If we are not allowed to insert a missing vocabulary.
*/
public VocabularyElement getOrEditVocabularyElement(Session session, String vocabularyType, String vocabularyElementURI, String mode)
throws SAXException {
boolean alterURI = false;
boolean singleDelete = false;
boolean wdDelete = false;
Long vocabularyElementID = null;
if (mode.equals("2")) {
alterURI = true;
}
else if (mode.equals("3")) {
singleDelete = true;
}
else if (mode.equals("4")) {
wdDelete = true;
}
Class<?> c = vocClassMap.get(vocabularyType);
Criteria c0 = session.createCriteria(c);
c0.setCacheable(true);
c0.add(Restrictions.eq("uri", alterURI ? vocabularyElementURI.split("#")[0] : vocabularyElementURI));
VocabularyElement ve;
try {
ve = (VocabularyElement) c0.uniqueResult();
}
catch (ObjectNotFoundException e) {
ve = null;
}
if (ve != null) {
vocabularyElementID = ve.getId();
}
if (ve == null || ((singleDelete || alterURI || wdDelete) && ve != null)) {
// the uri does not yet exist: insert it if allowed. According to
// the specs, some vocabulary is not allowed to be extended; this is
// currently ignored here
if (!insertMissingVoc) {
throw new UnsupportedOperationException("Not allowed to add new vocabulary - use existing vocabulary");
}
else {
// VocabularyElement subclasses should always have public
// zero-arg constructor to avoid problems here
if (alterURI) {
ve.setUri(vocabularyElementURI.split("#")[1]);
session.update(ve);
session.flush();
return ve;
}
else if (singleDelete) {
Object vocabularyElementObject = session.get(c, vocabularyElementID);
if (vocabularyElementObject != null)
session.delete(vocabularyElementObject);
deleteVocabularyElementAttributes(session, vocabularyType, vocabularyElementID);
session.flush();
return null;
}
else if (wdDelete) {
Object vocabularyElementObject = session.get(c, vocabularyElementID);
if (vocabularyElementObject != null)
session.delete(vocabularyElementObject);
deleteVocabularyElementAttributes(session, vocabularyType, vocabularyElementID);
deleteVocabularyElementDescendants(session, vocabularyType, vocabularyElementURI);
session.flush();
return null;
}
else {
try {
ve = (VocabularyElement) c.newInstance();
}
catch (InstantiationException e) {
throw new RuntimeException(e);
}
catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
ve.setUri(vocabularyElementURI);
session.save(ve);
}
session.flush();
}
}
return ve;
}
/**
* (nkef) Delete the a vocabulary's Element Descendants and all of their
* Attributes
*
* @param session
* @param vocabularyType
* @param vocabularyElementURI
*/
private void deleteVocabularyElementDescendants(Session session, String vocabularyType, String vocabularyElementURI) {
Class<?> c = vocClassMap.get(vocabularyType);
List vocElementChildrens = session.createSQLQuery(
"SELECT * FROM " + vocabularyTablenameMap.get(vocabularyType) + " WHERE uri LIKE '" + vocabularyElementURI + ",%'").addEntity(c)
.list();
for (int i = 0; i < vocElementChildrens.size(); i++) {
session.delete((VocabularyElement) vocElementChildrens.get(i));
deleteVocabularyElementAttributes(session, vocabularyType, ((VocabularyElement) vocElementChildrens.get(i)).getId());
}
session.flush();
}
/**
* (nkef) Delete selected id vocabulary elements attributes
*
* @param session
* @param vocabularyType
* @param vocabularyElementID
*/
private void deleteVocabularyElementAttributes(Session session, String vocabularyType, Long vocabularyElementID) {
Class<?> c = vocAttributeClassMap.get(vocabularyType);
List vocAttributeElements = session.createSQLQuery(
"select * FROM " + vocAttributeTablesMap.get(vocabularyType) + " where id = '" + vocabularyElementID + "'").addEntity(c).list();
for (int i = 0; i < vocAttributeElements.size(); i++) {
session.delete((VocabularyAttributeElement) vocAttributeElements.get(i));
}
session.flush();
}
/**
* (nkef) Inserts vocabulary attribute into the database by searching for
* already existing entries; if found, the corresponding ID is returned. If
* not found, the vocabulary is extended if "insertmissingvoc" is true;
* otherwise an SQLException is thrown
*
* @param tableName
* The name of the vocabulary table.
* @param uri
* The vocabulary adapting the URI to be inserted into the
* vocabulary table.
* @return The ID of an already existing vocabulary table with the given
* uri.
* @throws UnsupportedOperationException
* If we are not allowed to insert a missing vocabulary.
*/
public VocabularyAttributeElement getOrEditVocabularyAttributeElement(Session session, String vocabularyType, Long vocabularyElementID,
String vocabularyAttributeElement, String vocabularyAttributeElementValue, String mode) throws SAXException {
boolean deleteAttribute = false;
if (mode.equals("3")) {
deleteAttribute = true;
}
Class<?> c = vocAttributeClassMap.get(vocabularyType);
Criteria c0 = session.createCriteria(c);
c0.setCacheable(true);
VocabularyAttrCiD vocabularyAttrCiD = new VocabularyAttrCiD();
vocabularyAttrCiD.setAttribute(vocabularyAttributeElement);
vocabularyAttrCiD.setId(vocabularyElementID);
c0.add(Restrictions.idEq(vocabularyAttrCiD));
VocabularyAttributeElement vocAttributeElement = null;
try {
vocAttributeElement = (VocabularyAttributeElement) c0.uniqueResult();
}
catch (ObjectNotFoundException e) {
vocAttributeElement = null;
e.printStackTrace();
}
if(vocAttributeElement == null || (deleteAttribute && (vocAttributeElement != null)) || vocAttributeElement!=null){
// the uri does not yet exist: insert it if allowed. According to
// the specs, some vocabulary is not allowed to be extended; this is
// currently ignored here
if (!insertMissingVoc) {
throw new UnsupportedOperationException("Not allowed to add new vocabulary - use existing vocabulary");
}
else {
// VocabularyAttributeElement subclasses should always have
// public
// zero-arg constructor to avoid problems here
try {
vocAttributeElement = (VocabularyAttributeElement) c.newInstance();
}
catch (InstantiationException e) {
throw new RuntimeException(e);
}
catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
vocAttributeElement.setVocabularyAttrCiD(vocabularyAttrCiD);
vocAttributeElement.setValue(vocabularyAttributeElementValue);
if (vocAttributeElement == null) {
session.save(vocAttributeElement);
}
else if (deleteAttribute) {
Object vocabularyAttr = session.get(c, vocabularyAttrCiD);
if (vocabularyAttr != null)
session.delete(vocabularyAttr);
session.flush();
return null;
}
else {
session.merge(vocAttributeElement);
}
session.flush();
}
}
return vocAttributeElement;
}
/**
* TODO: javadoc!
*
* @param textContent
* @return
* @throws InvalidFormatException
*/
protected String checkEventTimeZoneOffset(String textContent) throws InvalidFormatException {
// first check the provided String against the expected pattern
Pattern p = Pattern.compile("[+-]\\d\\d:\\d\\d");
Matcher m = p.matcher(textContent);
boolean matches = m.matches();
if (matches) {
// second check the values (hours and minutes)
int h = Integer.parseInt(textContent.substring(1, 3));
int min = Integer.parseInt(textContent.substring(4, 6));
if ((h < 0) || (h > 14)) {
matches = false;
} else if (h == 14 && min != 0) {
matches = false;
} else if ((min < 0) || (min > 59)) {
matches = false;
}
}
if (matches) {
return textContent;
} else {
throw new InvalidFormatException("'eventTimeZoneOffset' has invalid format: " + textContent);
}
}
/**
* TODO: javadoc!
*
* @param textContent
* @return
* @throws InvalidFormatException
*/
private boolean checkUri(String textContent) throws InvalidFormatException {
try {
new URI(textContent);
} catch (URISyntaxException e) {
throw new InvalidFormatException(e.getMessage(), e);
}
return true;
}
/**
* Check EPC according to 'pure identity' URI as specified in Tag Data
* Standard.
*
* @param textContent
* @throws InvalidFormatException
*/
protected void checkEpc(String textContent) throws InvalidFormatException {
String uri = textContent;
if (!uri.startsWith("urn:epc:id:")) {
throw new InvalidFormatException("Invalid 'pure identity' EPC format: must start with \"urn:epc:id:\"");
}
uri = uri.substring("urn:epc:id:".length());
// check the patterns for the different EPC types
String epcType = uri.substring(0, uri.indexOf(":"));
uri = uri.substring(epcType.length() + 1);
LOG.debug("Checking pattern for EPC type " + epcType + ": " + uri);
Pattern p;
if ("gid".equals(epcType)) {
p = Pattern.compile("((0|[1-9][0-9]*)\\.){2}(0|[1-9][0-9]*)");
} else if ("sgtin".equals(epcType) || "sgln".equals(epcType) || "grai".equals(epcType)) {
p = Pattern.compile("([0-9]+\\.){2}([0-9]|[A-Z]|[a-z]|[\\!\\(\\)\\*\\+\\-',:;=_]|(%(([0-9]|[A-F])|[a-f]){2}))+");
} else if ("sscc".equals(epcType)) {
p = Pattern.compile("[0-9]+\\.[0-9]+");
} else if ("giai".equals(epcType)) {
p = Pattern.compile("[0-9]+\\.([0-9]|[A-Z]|[a-z]|[\\!\\(\\)\\*\\+\\-',:;=_]|(%(([0-9]|[A-F])|[a-f]){2}))+");
} else {
throw new InvalidFormatException("Invalid 'pure identity' EPC format: unknown EPC type: " + epcType);
}
Matcher m = p.matcher(uri);
if (!m.matches()) {
throw new InvalidFormatException("Invalid 'pure identity' EPC format: pattern \"" + uri
+ "\" is invalid for EPC type \"" + epcType + "\" - check with Tag Data Standard");
}
// check the number of digits for the different EPC types
boolean exceeded = false;
int count1 = uri.indexOf(".");
if ("sgtin".equals(epcType)) {
int count2 = uri.indexOf(".", count1 + 1) - (count1 + 1);
if (count1 + count2 > 13) {
exceeded = true;
}
} else if ("sgln".equals(epcType)) {
int count2 = uri.indexOf(".", count1 + 1) - (count1 + 1);
if (count1 + count2 > 12) {
exceeded = true;
}
} else if ("grai".equals(epcType)) {
int count2 = uri.indexOf(".", count1 + 1) - (count1 + 1);
if (count1 + count2 > 12) {
exceeded = true;
}
} else if ("sscc".equals(epcType)) {
int count2 = uri.length() - (count1 + 1);
if (count1 + count2 > 17) {
exceeded = true;
}
} else if ("giai".equals(epcType)) {
int count2 = uri.length() - (count1 + 1);
if (count1 + count2 > 30) {
exceeded = true;
}
} else {
// nothing to count
}
if (exceeded) {
throw new InvalidFormatException(
"Invalid 'pure identity' EPC format: check allowed number of characters for EPC type '" + epcType
+ "'");
}
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public boolean isDbResetAllowed() {
return dbResetAllowed;
}
public void setDbResetAllowed(boolean dbResetAllowed) {
this.dbResetAllowed = dbResetAllowed;
}
public void setDbResetScript(String dbResetScript) {
if (dbResetScript != null) {
String[] scripts = dbResetScript.split(",");
List<File> scriptList = new ArrayList<File>(scripts.length);
for (String script : scripts) {
if (!StringUtils.isBlank(script)) {
script = "/" + script.trim();
URL url = ClassLoader.getSystemResource(script);
if (url == null) {
url = this.getClass().getResource(script);
}
if (url == null) {
LOG.warn("unable to find sql script " + script + " in classpath");
} else {
LOG.debug("found dbReset sql script at " + url);
scriptList.add(new File(url.getFile()));
}
}
}
this.dbResetScripts = scriptList;
}
}
public boolean isInsertMissingVoc() {
return insertMissingVoc;
}
public void setInsertMissingVoc(boolean insertMissingVoc) {
this.insertMissingVoc = insertMissingVoc;
}
public Schema getSchema() {
return schema;
}
public void setSchema(Schema schema) {
this.schema = schema;
}
public void setEpcisSchemaFile(String epcisSchemaFile) {
Schema schema = initEpcisSchema(epcisSchemaFile);
setSchema(schema);
}
// (nkef)
public Schema getMasterDataSchema() {
return masterDataSchema;
}
// (nkef)
public void setMasterDataSchema(Schema masterDataSchema) {
this.masterDataSchema = masterDataSchema;
}
}
|
Accept various vocabulary attributes in CaptureOperationsModule
e.g.
<VocabularyElement id="urn:epc:id:sgln:0037000.00729.0">
<attribute id="urn:epcglobal:fmcg:mda:production"/>
<attribute id="urn:epcglobal:fmcg:mda:name">Production site</attribute>
<attribute id="urn:epcglobal:fmcg:mda:description" value="Production site"></attribute>
</VocabularyElement>
|
epcis-repository/src/main/java/org/fosstrak/epcis/repository/capture/CaptureOperationsModule.java
|
Accept various vocabulary attributes in CaptureOperationsModule e.g. <VocabularyElement id="urn:epc:id:sgln:0037000.00729.0"> <attribute id="urn:epcglobal:fmcg:mda:production"/> <attribute id="urn:epcglobal:fmcg:mda:name">Production site</attribute> <attribute id="urn:epcglobal:fmcg:mda:description" value="Production site"></attribute> </VocabularyElement>
|
|
Java
|
lgpl-2.1
|
ad54b65206a45beb013f3ebf3d8c69131091c209
| 0
|
jboss-msc/jboss-msc,ropalka/jboss-msc
|
package org.jboss.msc.bench;
import org.jboss.msc.registry.ServiceDefinition;
import org.jboss.msc.registry.ServiceRegistrationBatchBuilder;
import org.jboss.msc.registry.ServiceRegistry;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceContainer;
import org.jboss.msc.service.ServiceName;
public class NoDepBench {
public static void main(String[] args) throws Exception {
final int totalServiceDefinitions = Integer.parseInt(args[0]);
ServiceRegistrationBatchBuilder batch = ServiceRegistry.Factory.create(ServiceContainer.Factory.create()).batchBuilder();
long start = System.nanoTime();
for (int i = 0; i < totalServiceDefinitions; i++) {
batch.add(ServiceDefinition.build(ServiceName.of("test" + i), Service.NULL_VALUE).create());
}
batch.install();
long end = System.nanoTime();
System.out.println(totalServiceDefinitions + " : " + (end - start) / 1000000000.0);
}
}
|
src/main/java/org/jboss/msc/bench/NoDepBench.java
|
package org.jboss.msc.bench;
import org.jboss.msc.registry.ServiceDefinition;
import org.jboss.msc.registry.ServiceRegistry;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceContainer;
import org.jboss.msc.service.ServiceName;
public class NoDepBench {
public static void main(String[] args) throws Exception {
final int totalServiceDefinitions = Integer.parseInt(args[0]);
ServiceRegistry.BatchBuilder batch = ServiceRegistry.Factory.create(ServiceContainer.Factory.create()).batchBuilder();
long start = System.nanoTime();
for (int i = 0; i < totalServiceDefinitions; i++) {
batch.add(ServiceDefinition.build(ServiceName.of("test" + i), Service.NULL_VALUE).create());
}
batch.install();
long end = System.nanoTime();
System.out.println(totalServiceDefinitions + " : " + (end - start) / 1000000000.0);
}
}
|
Mismerge
|
src/main/java/org/jboss/msc/bench/NoDepBench.java
|
Mismerge
|
|
Java
|
lgpl-2.1
|
b66bc765b351957e630824fb8ad2ec4eb190404b
| 0
|
daisy/pipeline-gui
|
package org.daisy.pipeline.gui;
import java.io.IOException;
import org.daisy.pipeline.updater.Updater;
import org.daisy.pipeline.updater.UpdaterObserver;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.control.Button;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.ProgressBar;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Paint;
import javafx.scene.text.Text;
import javafx.util.Callback;
public class UpdaterPane extends BorderPane{
public void build() {
final VBox controls=new VBox();
controls.getStyleClass().add("blank");
final Button butt=new Button("Check for updates");
final LogPane logPane= new LogPane();
//logPane.setPadding(new Insets(15, 12, 15, 12));
final ProgressBar bar= new ProgressBar();
bar.setVisible(false);
bar.setProgress(-1);
bar.setMaxWidth(this.getWidth()-50);
logPane.getStyleClass().add("messages");
butt.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent t) {
butt.setDisable(true);
bar.setVisible(true);
new Thread(){
public void run(){
try {
new Updater().update(logPane);
} catch (IOException e) {
e.printStackTrace();
logPane.error("Couldn't start the update process");
} catch (IllegalArgumentException e) {
e.printStackTrace();
logPane.error(e.getMessage());
}finally{
Platform.runLater(new Runnable(){
public void run(){
bar.setVisible(false);
}
});
}
}
}.start();
}
});
controls.getChildren().add(butt);
this.setTop(controls);
this.setCenter(bar);
this.setBottom(logPane);
}
}
class LogPane extends VBox implements UpdaterObserver{
private ListView<String> messages;
private ObservableList<String> messageList;
/**
*
*/
public LogPane() {
super();
this.getStyleClass().add("messages");
Text title = new Text("Messages");
title.getStyleClass().add("subtitle");
messages = new ListView<String>();
messages.setCellFactory(new Callback<ListView<String>,
ListCell<String>>() {
@Override
public ListCell<String> call(ListView<String> list) {
return new ColorRectCell();
}
}
);
this.messageList=FXCollections.observableArrayList();
messages.setItems(this.messageList);
this.getChildren().add(title);
this.getChildren().add(messages);
}
public void addMessage(String msg){
this.messageList.add(msg);
}
public void info(final String msg){
Platform.runLater(new Runnable(){
public void run(){
messageList.add("INFO "+msg);
messages.scrollTo(messageList.size()-1);
}
});
};
public void error(final String msg){
Platform.runLater(new Runnable(){
public void run(){
messageList.add("ERROR "+msg);
messages.scrollTo(messageList.size()-1);
}
});
};
static class ColorRectCell extends ListCell<String> {
@Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (!empty && item.startsWith("ERROR ")) {
this.setBackground(new Background(new BackgroundFill(Paint.valueOf("rgba(120,0,0,0.25)"),null,null)));
}else{
this.setBackground(new Background(new BackgroundFill(Paint.valueOf("rgba(255,255,255,0.25)"),null,null)));
}
this.setText(item);
}
}
}
|
src/main/java/org/daisy/pipeline/gui/UpdaterPane.java
|
package org.daisy.pipeline.gui;
import java.io.IOException;
import org.daisy.pipeline.updater.Updater;
import org.daisy.pipeline.updater.UpdaterObserver;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.control.Button;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.ProgressBar;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Paint;
import javafx.scene.text.Text;
import javafx.util.Callback;
public class UpdaterPane extends BorderPane{
public void build() {
final VBox controls=new VBox();
controls.getStyleClass().add("blank");
final Button butt=new Button("Check for updates");
final LogPane logPane= new LogPane();
//logPane.setPadding(new Insets(15, 12, 15, 12));
final ProgressBar bar= new ProgressBar();
bar.setVisible(false);
bar.setProgress(-1);
bar.setMaxWidth(this.getWidth()-50);
logPane.getStyleClass().add("messages");
butt.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent t) {
butt.setDisable(true);
bar.setVisible(true);
new Thread(){
public void run(){
try {
new Updater().update(logPane);
} catch (IOException e) {
e.printStackTrace();
logPane.error("Couldn't start the update process");
}finally{
Platform.runLater(new Runnable(){
public void run(){
butt.setDisable(false);
bar.setVisible(false);
}
});
}
}
}.start();
}
});
controls.getChildren().add(butt);
this.setTop(controls);
this.setCenter(bar);
this.setBottom(logPane);
}
}
class LogPane extends VBox implements UpdaterObserver{
private ListView<String> messages;
private ObservableList<String> messageList;
/**
*
*/
public LogPane() {
super();
this.getStyleClass().add("messages");
Text title = new Text("Messages");
title.getStyleClass().add("subtitle");
messages = new ListView<String>();
messages.setCellFactory(new Callback<ListView<String>,
ListCell<String>>() {
@Override
public ListCell<String> call(ListView<String> list) {
return new ColorRectCell();
}
}
);
this.messageList=FXCollections.observableArrayList();
messages.setItems(this.messageList);
this.getChildren().add(title);
this.getChildren().add(messages);
}
public void addMessage(String msg){
this.messageList.add(msg);
}
public void info(final String msg){
Platform.runLater(new Runnable(){
public void run(){
messageList.add("INFO "+msg);
messages.scrollTo(messageList.size()-1);
}
});
};
public void error(final String msg){
Platform.runLater(new Runnable(){
public void run(){
messageList.add("ERROR "+msg);
messages.scrollTo(messageList.size()-1);
}
});
};
static class ColorRectCell extends ListCell<String> {
@Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (!empty && item.startsWith("ERROR ")) {
this.setBackground(new Background(new BackgroundFill(Paint.valueOf("rgba(120,0,0,0.25)"),null,null)));
}else{
this.setBackground(new Background(new BackgroundFill(Paint.valueOf("rgba(255,255,255,0.25)"),null,null)));
}
this.setText(item);
}
}
}
|
Disable "Check for updates" button if updating is done
see https://github.com/daisy/pipeline-gui/issues/52
|
src/main/java/org/daisy/pipeline/gui/UpdaterPane.java
|
Disable "Check for updates" button if updating is done
|
|
Java
|
apache-2.0
|
ceba9c9c405376029a81cc42b4ff7d91ac0d3e0a
| 0
|
Cantara/Whydah-UserAdminWebApp,Cantara/Whydah-UserAdminWebApp,Cantara/Whydah-UserAdminWebApp,Cantara/Whydah-UserAdminWebApp
|
package net.whydah.identity.admin.usertoken;
import net.whydah.sso.user.UserXpathHelper;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class UserTokenXpathHelperTest {
@Test
public void testHasUserAdminRightAllowed() {
String[] noAccessRoleValues = new String[]{"1", "true", "enabled", ""};
for (String allowedRoleValue : noAccessRoleValues) {
assertTrue(UserTokenXpathHelper.hasUserAdminRight(getUserToken(allowedRoleValue)));
}
}
@Test
public void testHasUserAdminRightDenied() {
String[] noAccessRoleValues = new String[]{"0", "false", "disabled"};
for (String noAccessRoleValue : noAccessRoleValues) {
// assertFalse(noAccessRoleValue + " was expected to result in access denied.", UserTokenXpathHelper.hasUserAdminRight(getUserToken(noAccessRoleValue)));
}
}
@Test
public void testHasUserAdminRightDeniedWrongRoles() {
String[] noAccessRoleValues = new String[]{"User", "Admin", "Manager"};
for (String noAccessRoleValue : noAccessRoleValues) {
assertFalse(noAccessRoleValue + " was expected to result in access denied.", UserXpathHelper.getRoleValueFromUserToken(getUserToken(noAccessRoleValue),"19","WhydahUserAdmin")==null);
}
}
private String getUserToken(String roleValue) {
return "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" +
"<usertoken xmlns:ns2=\"http://www.w3.org/1999/xhtml\" id=\"4bd6ec15-f298-4cf8-9b46-d92775f6292c\">\n" +
" <uid>03124866-f094-42ca-9ff3-46d10fa4eff5</uid>\n" +
" <timestamp>1412079640658</timestamp>\n" +
" <lifespan>3600000</lifespan>\n" +
" <issuer></issuer>\n" +
" <securitylevel>1</securitylevel>\n" +
" <DEFCON>5</DEFCON>\n" +
" <username>totto@totto.org</username>\n" +
" <firstname>Thor Henning</firstname>\n" +
" <lastname>Hetland</lastname>\n" +
" <email>totto@totto.org</email>\n" +
" <personRef>22</personRef>\n" +
" <application ID=\"19\">\n" +
" <applicationName>UserAdminWebApplication</applicationName>\n" +
" <organizationName>Altran</organizationName>\n" +
" <role name=\"WhydahUserAdmin\" value=\"" + roleValue + "\"/>\n" +
" </application>\n" +
" <application ID=\"100\">\n" +
" <applicationName>ACS</applicationName>\n" +
" <organizationName>Altran</organizationName>\n" +
" <role name=\"Employee\" value=\"totto@altran.com\"/>\n" +
" </application>\n" +
"\n" +
" <ns2:link type=\"application/xml\" href=\"/4bd6ec15-f298-4cf8-9b46-d92775f6292c\" rel=\"self\"/>\n" +
" <hash type=\"MD5\">21d3f0edf36cb5a0486b592fe84621</hash>\n" +
"</usertoken>";
}
private String getUserTokenWithRoleName(String roleName) {
return "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" +
"<usertoken xmlns:ns2=\"http://www.w3.org/1999/xhtml\" id=\"4bd6ec15-f298-4cf8-9b46-d92775f6292c\">\n" +
" <uid>03124866-f094-42ca-9ff3-46d10fa4eff5</uid>\n" +
" <timestamp>1412079640658</timestamp>\n" +
" <lifespan>3600000</lifespan>\n" +
" <issuer></issuer>\n" +
" <securitylevel>1</securitylevel>\n" +
" <DEFCON>5</DEFCON>\n" +
" <username>totto@totto.org</username>\n" +
" <firstname>Thor Henning</firstname>\n" +
" <lastname>Hetland</lastname>\n" +
" <email>totto@totto.org</email>\n" +
" <personRef>22</personRef>\n" +
" <application ID=\"19\">\n" +
" <applicationName>UserAdminWebApplication</applicationName>\n" +
" <organizationName>Altran</organizationName>\n" +
" <role name=\""+roleName+"\" value=\"" + "true" + "\"/>\n" +
" </application>\n" +
" <application ID=\"100\">\n" +
" <applicationName>ACS</applicationName>\n" +
" <organizationName>Altran</organizationName>\n" +
" <role name=\"Employee\" value=\"totto@altran.com\"/>\n" +
" </application>\n" +
"\n" +
" <ns2:link type=\"application/xml\" href=\"/4bd6ec15-f298-4cf8-9b46-d92775f6292c\" rel=\"self\"/>\n" +
" <hash type=\"MD5\">21d3f0edf36cb5a0486b592fe84621</hash>\n" +
"</usertoken>";
}
}
|
src/test/java/net/whydah/identity/admin/usertoken/UserTokenXpathHelperTest.java
|
package net.whydah.identity.admin.usertoken;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class UserTokenXpathHelperTest {
@Test
public void testHasUserAdminRightAllowed() {
String[] noAccessRoleValues = new String[]{"1", "true", "enabled", ""};
for (String allowedRoleValue : noAccessRoleValues) {
assertTrue(UserTokenXpathHelper.hasUserAdminRight(getUserToken(allowedRoleValue)));
}
}
@Test
public void testHasUserAdminRightDenied() {
String[] noAccessRoleValues = new String[]{"0", "false", "disabled"};
for (String noAccessRoleValue : noAccessRoleValues) {
assertFalse(noAccessRoleValue + " was expected to result in access denied.", UserTokenXpathHelper.hasUserAdminRight(getUserToken(noAccessRoleValue)));
}
}
private String getUserToken(String roleValue) {
return "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" +
"<usertoken xmlns:ns2=\"http://www.w3.org/1999/xhtml\" id=\"4bd6ec15-f298-4cf8-9b46-d92775f6292c\">\n" +
" <uid>03124866-f094-42ca-9ff3-46d10fa4eff5</uid>\n" +
" <timestamp>1412079640658</timestamp>\n" +
" <lifespan>3600000</lifespan>\n" +
" <issuer></issuer>\n" +
" <securitylevel>1</securitylevel>\n" +
" <DEFCON>5</DEFCON>\n" +
" <username>totto@totto.org</username>\n" +
" <firstname>Thor Henning</firstname>\n" +
" <lastname>Hetland</lastname>\n" +
" <email>totto@totto.org</email>\n" +
" <personRef>22</personRef>\n" +
" <application ID=\"19\">\n" +
" <applicationName>UserAdminWebApplication</applicationName>\n" +
" <organizationName>Altran</organizationName>\n" +
" <role name=\"WhydahUserAdmin\" value=\"" + roleValue + "\"/>\n" +
" </application>\n" +
" <application ID=\"100\">\n" +
" <applicationName>ACS</applicationName>\n" +
" <organizationName>Altran</organizationName>\n" +
" <role name=\"Employee\" value=\"totto@altran.com\"/>\n" +
" </application>\n" +
"\n" +
" <ns2:link type=\"application/xml\" href=\"/4bd6ec15-f298-4cf8-9b46-d92775f6292c\" rel=\"self\"/>\n" +
" <hash type=\"MD5\">21d3f0edf36cb5a0486b592fe84621</hash>\n" +
"</usertoken>";
}
}
|
Using JDK function
|
src/test/java/net/whydah/identity/admin/usertoken/UserTokenXpathHelperTest.java
|
Using JDK function
|
|
Java
|
apache-2.0
|
8023a5b13eb0215cd2991762c719c923970ed373
| 0
|
JNOSQL/artemis-extension
|
/*
* Copyright (c) 2017 Otávio Santana and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Apache License v2.0 is available at http://www.opensource.org/licenses/apache2.0.php.
*
* You may elect to redistribute this code under either of these licenses.
*
* Contributors:
*
* Otavio Santana
*/
package org.jnosql.artemis.graph;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.jnosql.artemis.graph.cdi.CDIExtension;
import org.junit.jupiter.api.extension.ExtendWith;
import javax.inject.Inject;
@ExtendWith(CDIExtension.class)
class DefaultTraversalGraphConverterTest extends AbstractGraphConverterTest {
@Inject
@GraphTraversalSourceOperation
private GraphConverter converter;
@Inject
private Graph graph;
@Override
protected Graph getGraph() {
return graph;
}
@Override
protected GraphConverter getConverter() {
return converter;
}
}
|
graph-extension/src/test/java/org/jnosql/artemis/graph/DefaultTraversalGraphConverterTest.java
|
/*
* Copyright (c) 2017 Otávio Santana and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Apache License v2.0 is available at http://www.opensource.org/licenses/apache2.0.php.
*
* You may elect to redistribute this code under either of these licenses.
*
* Contributors:
*
* Otavio Santana
*/
package org.jnosql.artemis.graph;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.jnosql.artemis.graph.cdi.CDIExtension;
import org.junit.jupiter.api.extension.ExtendWith;
import javax.inject.Inject;
@ExtendWith(CDIExtension.class)
class DefaultTraversalGraphConverterTest extends AbstractGraphConverterTest{
@Inject
@GraphTraversalSourceOperation
private GraphConverter converter;
@Inject
private Graph graph;
@Override
protected Graph getGraph() {
return graph;
}
@Override
protected GraphConverter getConverter() {
return converter;
}
}
|
fixes align
|
graph-extension/src/test/java/org/jnosql/artemis/graph/DefaultTraversalGraphConverterTest.java
|
fixes align
|
|
Java
|
apache-2.0
|
be535437d0cbcbcd14b5350886cd7371914d4e9a
| 0
|
sushilmohanty/incubator-lens,rajubairishetti/incubator-lens,adeelmahmood/lens,rajubairishetti/lens,sriksun/incubator-lens,RaghavendraSingh/lens,prongs/grill,sushrutikhar/grill,sushrutikhar/grill,rajubairishetti/incubator-lens,archanah24/lens,archanah24/lens,prongs/grill,archanah24/lens,archanah24/lens,prongs/grill,adeelmahmood/lens,rajubairishetti/incubator-lens,guptapuneet/lens,rajubairishetti/lens,sriksun/incubator-lens,adeelmahmood/lens,Flipkart/incubator-lens,RaghavendraSingh/lens,sushrutikhar/grill,RaghavendraSingh/lens,kamaldeep-ebay/lens,sushilmohanty/incubator-lens,RaghavendraSingh/lens,guptapuneet/lens,rajubairishetti/lens,Flipkart/incubator-lens,archanah24/lens,sriksun/incubator-lens,kamaldeep-ebay/lens,guptapuneet/lens,Flipkart/incubator-lens,sushrutikhar/grill,RaghavendraSingh/lens,sriksun/incubator-lens,sushilmohanty/incubator-lens,adeelmahmood/lens,kamaldeep-ebay/lens,sushilmohanty/incubator-lens,sushilmohanty/incubator-lens,sriksun/incubator-lens,kamaldeep-ebay/lens,sushrutikhar/grill,Flipkart/incubator-lens,guptapuneet/lens
|
package com.inmobi.grill.driver.hive;
/*
* #%L
* Grill Hive Driver
* %%
* Copyright (C) 2014 Inmobi
* %%
* 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 static org.testng.Assert.*;
import java.io.*;
import java.util.*;
import junit.framework.Assert;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.api.Database;
import org.apache.hadoop.hive.ql.HiveDriverRunHook;
import org.apache.hadoop.hive.ql.HiveDriverRunHookContext;
import org.apache.hadoop.hive.ql.metadata.Hive;
import org.apache.hadoop.hive.ql.session.SessionState;
import org.apache.hive.service.cli.ColumnDescriptor;
import org.testng.annotations.*;
import com.inmobi.grill.api.GrillException;
import com.inmobi.grill.api.query.QueryHandle;
import com.inmobi.grill.api.query.ResultColumn;
import com.inmobi.grill.server.api.GrillConfConstants;
import com.inmobi.grill.server.api.driver.DriverQueryPlan;
import com.inmobi.grill.server.api.driver.DriverQueryStatus.DriverQueryState;
import com.inmobi.grill.server.api.driver.GrillResultSet;
import com.inmobi.grill.server.api.driver.GrillResultSetMetadata;
import com.inmobi.grill.server.api.query.PreparedQueryContext;
import com.inmobi.grill.server.api.query.QueryContext;
public class TestHiveDriver {
public static final String TEST_DATA_FILE = "testdata/testdata1.txt";
public final String TEST_OUTPUT_DIR = "target/" + this.getClass().getSimpleName() + "/test-output";
protected HiveConf conf = new HiveConf();
protected HiveDriver driver;
public final String DATA_BASE = this.getClass().getSimpleName();
@BeforeTest
public void beforeTest() throws Exception {
// Check if hadoop property set
System.out.println("###HADOOP_PATH " + System.getProperty("hadoop.bin.path"));
assertNotNull(System.getProperty("hadoop.bin.path"));
conf.addResource("hivedriver-site.xml");
conf.setClass(HiveDriver.GRILL_HIVE_CONNECTION_CLASS,
EmbeddedThriftConnection.class,
ThriftConnection.class);
conf.set("hive.lock.manager", "org.apache.hadoop.hive.ql.lockmgr.EmbeddedLockManager");
SessionState ss = new SessionState(conf, "testuser");
SessionState.start(ss);
Hive client = Hive.get(conf);
Database database = new Database();
database.setName(TestHiveDriver.class.getSimpleName());
client.createDatabase(database, true);
SessionState.get().setCurrentDatabase(TestHiveDriver.class.getSimpleName());
driver = new HiveDriver();
driver.configure(conf);
conf.setBoolean(GrillConfConstants.GRILL_ADD_INSERT_OVEWRITE, false);
conf.setBoolean(GrillConfConstants.QUERY_PERSISTENT_RESULT_INDRIVER, false);
QueryContext context = new QueryContext(
"USE " + TestHiveDriver.class.getSimpleName(), null, conf);
driver.execute(context);
conf.setBoolean(GrillConfConstants.GRILL_ADD_INSERT_OVEWRITE, true);
conf.setBoolean(GrillConfConstants.QUERY_PERSISTENT_RESULT_INDRIVER, true);
System.out.println("Driver created");
Assert.assertEquals(0, driver.getHiveHandleSize());
}
@AfterTest
public void afterTest() throws Exception {
driver.close();
Hive.get(conf).dropDatabase(TestHiveDriver.class.getSimpleName(), true, true, true);
}
protected void createTestTable(String tableName) throws Exception {
System.out.println("Hadoop Location: " + System.getProperty("hadoop.bin.path"));
String createTable = "CREATE TABLE IF NOT EXISTS " + tableName +"(ID STRING)" +
" TBLPROPERTIES ('" + GrillConfConstants.STORAGE_COST + "'='500')";
conf.setBoolean(GrillConfConstants.QUERY_PERSISTENT_RESULT_INDRIVER, false);
// Craete again
QueryContext context = new QueryContext(createTable, null, conf);
GrillResultSet resultSet = driver.execute(context);
assertNull(resultSet);
// Load some data into the table
String dataLoad = "LOAD DATA LOCAL INPATH '"+ TEST_DATA_FILE +"' OVERWRITE INTO TABLE " + tableName;
context = new QueryContext(dataLoad, null, conf);
resultSet = driver.execute(context);
assertNull(resultSet);
Assert.assertEquals(0, driver.getHiveHandleSize());
}
// Tests
@Test
public void testInsertOverwriteConf() throws Exception {
createTestTable("test_insert_overwrite");
conf.setBoolean(GrillConfConstants.GRILL_ADD_INSERT_OVEWRITE, false);
String query = "SELECT ID FROM test_insert_overwrite";
QueryContext context = new QueryContext(query, null, conf);
driver.addPersistentPath(context);
assertEquals(context.getUserQuery(), query);
assertNotNull(context.getDriverQuery());
assertEquals(context.getDriverQuery(), context.getUserQuery());
}
@Test
public void testTemptable() throws Exception {
createTestTable("test_temp");
conf.setBoolean(GrillConfConstants.QUERY_PERSISTENT_RESULT_INDRIVER, false);
Hive.get(conf).dropTable("test_temp_output");
String query = "CREATE TABLE test_temp_output AS SELECT ID FROM test_temp";
QueryContext context = new QueryContext(query, null, conf);
GrillResultSet resultSet = driver.execute(context);
assertNull(resultSet);
Assert.assertEquals(0, driver.getHiveHandleSize());
// fetch results from temp table
String select = "SELECT * FROM test_temp_output";
context = new QueryContext(select, null, conf);
resultSet = driver.execute(context);
Assert.assertEquals(0, driver.getHiveHandleSize());
validateInMemoryResult(resultSet, "test_temp_output");
Assert.assertEquals(0, driver.getHiveHandleSize());
}
@Test
public void testExecuteQuery() throws Exception {
createTestTable("test_execute");
GrillResultSet resultSet = null;
// Execute a select query
conf.setBoolean(GrillConfConstants.QUERY_PERSISTENT_RESULT_INDRIVER, false);
String select = "SELECT ID FROM test_execute";
QueryContext context = new QueryContext(select, null, conf);
resultSet = driver.execute(context);
validateInMemoryResult(resultSet);
conf.setBoolean(GrillConfConstants.QUERY_PERSISTENT_RESULT_INDRIVER, true);
context = new QueryContext(select, null, conf);
resultSet = driver.execute(context);
validatePersistentResult(resultSet, TEST_DATA_FILE, context.getHDFSResultDir(), false);
conf.set(GrillConfConstants.QUERY_OUTPUT_DIRECTORY_FORMAT,
"ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe'" +
" WITH SERDEPROPERTIES ('serialization.null.format'='-NA-'," +
" 'field.delim'=',' ) STORED AS TEXTFILE ");
select = "SELECT ID, null, ID FROM test_execute";
context = new QueryContext(select, null, conf);
resultSet = driver.execute(context);
validatePersistentResult(resultSet, TEST_DATA_FILE, context.getHDFSResultDir(), true);
Assert.assertEquals(0, driver.getHiveHandleSize());
}
private void validateInMemoryResult(GrillResultSet resultSet) throws GrillException, IOException {
validateInMemoryResult(resultSet, null);
}
private void validateInMemoryResult(GrillResultSet resultSet, String outputTable)
throws GrillException, IOException {
assertNotNull(resultSet);
assertTrue(resultSet instanceof HiveInMemoryResultSet);
HiveInMemoryResultSet inmemrs = (HiveInMemoryResultSet) resultSet;
// check metadata
GrillResultSetMetadata rsMeta = inmemrs.getMetadata();
List<ColumnDescriptor> columns = rsMeta.getColumns();
assertNotNull(columns);
assertEquals(columns.size(), 1);
String expectedCol = "";
if (outputTable != null) {
expectedCol += outputTable + ".";
}
expectedCol += "ID";
assertTrue(columns.get(0).getName().toLowerCase().equals(expectedCol.toLowerCase())
|| columns.get(0).getName().toLowerCase().equals("ID".toLowerCase()));
assertEquals(columns.get(0).getTypeName().toLowerCase(), "STRING".toLowerCase());
List<String> expectedRows = new ArrayList<String>();
// Read data from the test file into expectedRows
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(TEST_DATA_FILE)));
String line = "";
while ((line = br.readLine()) != null) {
expectedRows.add(line.trim());
}
br.close();
List<String> actualRows = new ArrayList<String>();
while (inmemrs.hasNext()) {
List<Object> row = inmemrs.next().getValues();
actualRows.add((String)row.get(0));
}
assertEquals(actualRows, expectedRows);
}
public static class FailHook implements HiveDriverRunHook {
@Override
public void postDriverRun(HiveDriverRunHookContext arg0) throws Exception {
// TODO Auto-generated method stub
}
@Override
public void preDriverRun(HiveDriverRunHookContext arg0) throws Exception {
throw new GrillException("Failing this run");
}
}
// executeAsync
@Test
public void testExecuteQueryAsync() throws Exception {
createTestTable("test_execute_sync");
// Now run a command that would fail
String expectFail = "SELECT ID FROM test_execute_sync";
conf.setBoolean(GrillConfConstants.QUERY_PERSISTENT_RESULT_INDRIVER, true);
conf.set("hive.exec.driver.run.hooks", FailHook.class.getCanonicalName());
QueryContext context = new QueryContext(expectFail, null, conf);
driver.executeAsync(context);
Assert.assertEquals(1, driver.getHiveHandleSize());
validateExecuteAsync(context, DriverQueryState.FAILED, true, false);
Assert.assertEquals(1, driver.getHiveHandleSize());
driver.closeQuery(context.getQueryHandle());
Assert.assertEquals(0, driver.getHiveHandleSize());
conf.set("hive.exec.driver.run.hooks", "");
// Async select query
String select = "SELECT ID FROM test_execute_sync";
conf.setBoolean(GrillConfConstants.QUERY_PERSISTENT_RESULT_INDRIVER, false);
context = new QueryContext(select, null, conf);
driver.executeAsync(context);
Assert.assertEquals(1, driver.getHiveHandleSize());
validateExecuteAsync(context, DriverQueryState.SUCCESSFUL, false, false);
driver.closeQuery(context.getQueryHandle());
Assert.assertEquals(0, driver.getHiveHandleSize());
conf.setBoolean(GrillConfConstants.QUERY_PERSISTENT_RESULT_INDRIVER, true);
context = new QueryContext(select, null, conf);
driver.executeAsync(context);
Assert.assertEquals(1, driver.getHiveHandleSize());
validateExecuteAsync(context, DriverQueryState.SUCCESSFUL, true, false);
driver.closeQuery(context.getQueryHandle());
Assert.assertEquals(0, driver.getHiveHandleSize());
conf.set(GrillConfConstants.QUERY_OUTPUT_DIRECTORY_FORMAT,
"ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe'" +
" WITH SERDEPROPERTIES ('serialization.null.format'='-NA-'," +
" 'field.delim'=',' ) STORED AS TEXTFILE ");
select = "SELECT ID, null, ID FROM test_execute_sync";
context = new QueryContext(select, null, conf);
driver.executeAsync(context);
Assert.assertEquals(1, driver.getHiveHandleSize());
validateExecuteAsync(context, DriverQueryState.SUCCESSFUL, true, true);
driver.closeQuery(context.getQueryHandle());
Assert.assertEquals(0, driver.getHiveHandleSize());
}
protected void validateExecuteAsync(QueryContext ctx, DriverQueryState finalState,
boolean isPersistent, boolean formatNulls, HiveDriver driver) throws Exception {
waitForAsyncQuery(ctx, driver);
driver.updateStatus(ctx);
assertEquals(ctx.getDriverStatus().getState(), finalState, "Expected query to finish with"
+ finalState);
assertTrue(ctx.getDriverStatus().getDriverFinishTime() > 0);
if (finalState.equals(DriverQueryState.SUCCESSFUL)) {
System.out.println("Progress:" + ctx.getDriverStatus().getProgressMessage());
assertNotNull(ctx.getDriverStatus().getProgressMessage());
if (!isPersistent) {
validateInMemoryResult(driver.fetchResultSet(ctx));
} else{
validatePersistentResult(driver.fetchResultSet(ctx), TEST_DATA_FILE, ctx.getHDFSResultDir(), formatNulls);
}
} else if (finalState.equals(DriverQueryState.FAILED)) {
System.out.println("Error:" + ctx.getDriverStatus().getErrorMessage());
System.out.println("Status:" + ctx.getDriverStatus().getStatusMessage());
assertNotNull(ctx.getDriverStatus().getErrorMessage());
}
}
protected void validateExecuteAsync(QueryContext ctx, DriverQueryState finalState,
boolean isPersistent, boolean formatNulls) throws Exception {
validateExecuteAsync(ctx, finalState, isPersistent, formatNulls, driver);
}
@Test
public void testCancelAsyncQuery() throws Exception {
createTestTable("test_cancel_async");
conf.setBoolean(GrillConfConstants.QUERY_PERSISTENT_RESULT_INDRIVER, false);
QueryContext context = new QueryContext("SELECT ID FROM test_cancel_async", null, conf);
driver.executeAsync(context);
driver.cancelQuery(context.getQueryHandle());
driver.updateStatus(context);
assertEquals(context.getDriverStatus().getState(), DriverQueryState.CANCELED, "Expecting query to be cancelled");
driver.closeQuery(context.getQueryHandle());
Assert.assertEquals(0, driver.getHiveHandleSize());
try {
driver.cancelQuery(context.getQueryHandle());
fail("Cancel on closed query should throw error");
} catch (GrillException exc) {
assertTrue(exc.getMessage().startsWith("Query not found"));
}
}
private void validatePersistentResult(GrillResultSet resultSet, String dataFile,
Path outptuDir, boolean formatNulls) throws Exception {
assertTrue(resultSet instanceof HivePersistentResultSet);
HivePersistentResultSet persistentResultSet = (HivePersistentResultSet) resultSet;
String path = persistentResultSet.getOutputPath();
Path actualPath = new Path(path);
FileSystem fs = actualPath.getFileSystem(conf);
assertEquals(actualPath, fs.makeQualified(outptuDir));
List<String> actualRows = new ArrayList<String>();
for (FileStatus stat : fs.listStatus(actualPath)) {
FSDataInputStream in = fs.open(stat.getPath());
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = br.readLine()) != null) {
System.out.println("Actual:" +line);
actualRows.add(line.trim());
}
} finally {
if (br != null) {
br.close();
}
}
}
BufferedReader br = null;
List<String> expectedRows = new ArrayList<String>();
try {
br = new BufferedReader(new FileReader(new File(dataFile)));
String line = "";
while ((line = br.readLine()) != null) {
String row = line.trim();
if (formatNulls) {
row += ",-NA-,";
row += line.trim();
}
expectedRows.add(row);
}
} finally {
if (br != null) {
br.close();
}
}
assertEquals(actualRows, expectedRows);
}
@Test
public void testPersistentResultSet() throws Exception {
createTestTable("test_persistent_result_set");
conf.setBoolean(GrillConfConstants.QUERY_PERSISTENT_RESULT_INDRIVER, true);
conf.setBoolean(GrillConfConstants.GRILL_ADD_INSERT_OVEWRITE, true);
conf.set(GrillConfConstants.GRILL_RESULT_SET_PARENT_DIR, TEST_OUTPUT_DIR);
QueryContext ctx = new QueryContext("SELECT ID FROM test_persistent_result_set", null, conf);
GrillResultSet resultSet = driver.execute(ctx);
validatePersistentResult(resultSet, TEST_DATA_FILE, ctx.getHDFSResultDir(), false);
Assert.assertEquals(0, driver.getHiveHandleSize());
ctx = new QueryContext("SELECT ID FROM test_persistent_result_set", null, conf);
driver.executeAsync(ctx);
Assert.assertEquals(1, driver.getHiveHandleSize());
validateExecuteAsync(ctx, DriverQueryState.SUCCESSFUL, true, false);
driver.closeQuery(ctx.getQueryHandle());
Assert.assertEquals(0, driver.getHiveHandleSize());
conf.set(GrillConfConstants.QUERY_OUTPUT_DIRECTORY_FORMAT,
"ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe'" +
" WITH SERDEPROPERTIES ('serialization.null.format'='-NA-'," +
" 'field.delim'=',' ) STORED AS TEXTFILE ");
ctx = new QueryContext("SELECT ID, null, ID FROM test_persistent_result_set", null, conf);
resultSet = driver.execute(ctx);
Assert.assertEquals(0, driver.getHiveHandleSize());
validatePersistentResult(resultSet, TEST_DATA_FILE, ctx.getHDFSResultDir(), true);
driver.closeQuery(ctx.getQueryHandle());
Assert.assertEquals(0, driver.getHiveHandleSize());
ctx = new QueryContext("SELECT ID, null, ID FROM test_persistent_result_set", null, conf);
driver.executeAsync(ctx);
Assert.assertEquals(1, driver.getHiveHandleSize());
validateExecuteAsync(ctx, DriverQueryState.SUCCESSFUL, true, true);
driver.closeQuery(ctx.getQueryHandle());
Assert.assertEquals(0, driver.getHiveHandleSize());
}
private void waitForAsyncQuery(QueryContext ctx, HiveDriver driver) throws Exception {
while (true) {
driver.updateStatus(ctx);
System.out.println("#W Waiting for query " + ctx.getQueryHandle() + " status: " + ctx.getDriverStatus().getState());
assertNotNull(ctx.getDriverStatus());
if (ctx.getDriverStatus().isFinished()) {
assertTrue(ctx.getDriverStatus().getDriverFinishTime() > 0);
break;
}
System.out.println("Progress:" + ctx.getDriverStatus().getProgressMessage());
Thread.sleep(1000);
assertTrue(ctx.getDriverStatus().getDriverStartTime() > 0);
}
}
// explain
@Test
public void testExplain() throws Exception {
createTestTable("test_explain");
DriverQueryPlan plan = driver.explain("SELECT ID FROM test_explain", conf);
assertTrue(plan instanceof HiveQueryPlan);
assertEquals(plan.getTableWeight("test_explain"), 500.0);
Assert.assertEquals(0, driver.getHiveHandleSize());
// test execute prepare
PreparedQueryContext pctx = new PreparedQueryContext(
"SELECT ID FROM test_explain", null, conf);
plan = driver.explainAndPrepare(pctx);
QueryContext qctx = new QueryContext(pctx, null, conf);
GrillResultSet result = driver.execute(qctx);
Assert.assertEquals(0, driver.getHiveHandleSize());
validateInMemoryResult(result);
// test execute prepare async
qctx = new QueryContext(pctx, null, conf);
driver.executeAsync(qctx);
assertNotNull(qctx.getDriverOpHandle());
validateExecuteAsync(qctx, DriverQueryState.SUCCESSFUL, false, false);
Assert.assertEquals(1, driver.getHiveHandleSize());
driver.closeQuery(qctx.getQueryHandle());
Assert.assertEquals(0, driver.getHiveHandleSize());
// for backward compatibility
qctx = new QueryContext(pctx, null, conf);
qctx.setQueryHandle(new QueryHandle(pctx.getPrepareHandle().getPrepareHandleId()));
result = driver.execute(qctx);
assertNotNull(qctx.getDriverOpHandle());
Assert.assertEquals(0, driver.getHiveHandleSize());
validateInMemoryResult(result);
// test execute prepare async
qctx = new QueryContext(pctx, null, conf);
qctx.setQueryHandle(new QueryHandle(pctx.getPrepareHandle().getPrepareHandleId()));
driver.executeAsync(qctx);
Assert.assertEquals(1, driver.getHiveHandleSize());
validateExecuteAsync(qctx, DriverQueryState.SUCCESSFUL, false, false);
driver.closeQuery(qctx.getQueryHandle());
driver.closePreparedQuery(pctx.getPrepareHandle());
Assert.assertEquals(0, driver.getHiveHandleSize());
conf.setBoolean(GrillConfConstants.PREPARE_ON_EXPLAIN, false);
plan = driver.explain("SELECT ID FROM test_explain", conf);
assertTrue(plan instanceof HiveQueryPlan);
assertNull(plan.getHandle());
conf.setBoolean(GrillConfConstants.PREPARE_ON_EXPLAIN, true);
Assert.assertEquals(0, driver.getHiveHandleSize());
}
@Test
public void testExplainOutput() throws Exception {
createTestTable("explain_test_1");
createTestTable("explain_test_2");
DriverQueryPlan plan = driver.explain("SELECT explain_test_1.ID, count(1) FROM " +
" explain_test_1 join explain_test_2 on explain_test_1.ID = explain_test_2.ID" +
" WHERE explain_test_1.ID = 'foo' or explain_test_2.ID = 'bar'" +
" GROUP BY explain_test_1.ID", conf);
Assert.assertEquals(0, driver.getHiveHandleSize());
assertTrue(plan instanceof HiveQueryPlan);
assertNotNull(plan.getTablesQueried());
assertEquals(plan.getTablesQueried().size(), 2);
assertNotNull(plan.getTableWeights());
assertTrue(plan.getTableWeights().containsKey("explain_test_1"));
assertTrue(plan.getTableWeights().containsKey("explain_test_2"));
assertEquals(plan.getNumJoins(), 1);
assertTrue(plan.getPlan() != null && !plan.getPlan().isEmpty());
driver.closeQuery(plan.getHandle());
}
@Test
public void testExplainOutputPersistent() throws Exception {
createTestTable("explain_test_1");
conf.setBoolean(GrillConfConstants.QUERY_PERSISTENT_RESULT_INDRIVER, true);
String query2 = "SELECT DISTINCT ID FROM explain_test_1";
PreparedQueryContext pctx = new PreparedQueryContext(query2, null, conf);
DriverQueryPlan plan2 = driver.explainAndPrepare(pctx);
//assertNotNull(plan2.getResultDestination());
Assert.assertEquals(0, driver.getHiveHandleSize());
assertNotNull(plan2.getTablesQueried());
assertEquals(plan2.getTablesQueried().size(), 1);
assertTrue(plan2.getTableWeights().containsKey("explain_test_1"));
assertEquals(plan2.getNumSels(), 1);
QueryContext ctx = new QueryContext(pctx, null, conf);
GrillResultSet resultSet = driver.execute(ctx);
Assert.assertEquals(0, driver.getHiveHandleSize());
HivePersistentResultSet persistentResultSet = (HivePersistentResultSet) resultSet;
String path = persistentResultSet.getOutputPath();
assertEquals(ctx.getHdfsoutPath(), path);
driver.closeQuery(plan2.getHandle());
}
}
|
grill-driver-hive/src/test/java/com/inmobi/grill/driver/hive/TestHiveDriver.java
|
package com.inmobi.grill.driver.hive;
/*
* #%L
* Grill Hive Driver
* %%
* Copyright (C) 2014 Inmobi
* %%
* 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 static org.testng.Assert.*;
import java.io.*;
import java.util.*;
import junit.framework.Assert;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.api.Database;
import org.apache.hadoop.hive.ql.HiveDriverRunHook;
import org.apache.hadoop.hive.ql.HiveDriverRunHookContext;
import org.apache.hadoop.hive.ql.metadata.Hive;
import org.apache.hadoop.hive.ql.session.SessionState;
import org.apache.hive.service.cli.ColumnDescriptor;
import org.testng.annotations.*;
import com.inmobi.grill.api.GrillException;
import com.inmobi.grill.api.query.QueryHandle;
import com.inmobi.grill.api.query.ResultColumn;
import com.inmobi.grill.server.api.GrillConfConstants;
import com.inmobi.grill.server.api.driver.DriverQueryPlan;
import com.inmobi.grill.server.api.driver.DriverQueryStatus.DriverQueryState;
import com.inmobi.grill.server.api.driver.GrillResultSet;
import com.inmobi.grill.server.api.driver.GrillResultSetMetadata;
import com.inmobi.grill.server.api.query.PreparedQueryContext;
import com.inmobi.grill.server.api.query.QueryContext;
public class TestHiveDriver {
public static final String TEST_DATA_FILE = "testdata/testdata1.txt";
public final String TEST_OUTPUT_DIR = "target/" + this.getClass().getSimpleName() + "/test-output";
protected HiveConf conf = new HiveConf();
protected HiveDriver driver;
public final String DATA_BASE = this.getClass().getSimpleName();
@BeforeTest
public void beforeTest() throws Exception {
// Check if hadoop property set
System.out.println("###HADOOP_PATH " + System.getProperty("hadoop.bin.path"));
assertNotNull(System.getProperty("hadoop.bin.path"));
conf.addResource("hivedriver-site.xml");
conf.setClass(HiveDriver.GRILL_HIVE_CONNECTION_CLASS,
EmbeddedThriftConnection.class,
ThriftConnection.class);
conf.set("hive.lock.manager", "org.apache.hadoop.hive.ql.lockmgr.EmbeddedLockManager");
SessionState ss = new SessionState(conf, "testuser");
SessionState.start(ss);
Hive client = Hive.get(conf);
Database database = new Database();
database.setName(TestHiveDriver.class.getSimpleName());
client.createDatabase(database, true);
SessionState.get().setCurrentDatabase(TestHiveDriver.class.getSimpleName());
driver = new HiveDriver();
driver.configure(conf);
conf.setBoolean(GrillConfConstants.GRILL_ADD_INSERT_OVEWRITE, false);
conf.setBoolean(GrillConfConstants.QUERY_PERSISTENT_RESULT_INDRIVER, false);
QueryContext context = new QueryContext(
"USE " + TestHiveDriver.class.getSimpleName(), null, conf);
driver.execute(context);
conf.setBoolean(GrillConfConstants.GRILL_ADD_INSERT_OVEWRITE, true);
conf.setBoolean(GrillConfConstants.QUERY_PERSISTENT_RESULT_INDRIVER, true);
System.out.println("Driver created");
Assert.assertEquals(0, driver.getHiveHandleSize());
}
@AfterTest
public void afterTest() throws Exception {
driver.close();
Hive.get(conf).dropDatabase(TestHiveDriver.class.getSimpleName(), true, true, true);
}
protected void createTestTable(String tableName) throws Exception {
System.out.println("Hadoop Location: " + System.getProperty("hadoop.bin.path"));
String createTable = "CREATE TABLE IF NOT EXISTS " + tableName +"(ID STRING)" +
" TBLPROPERTIES ('" + GrillConfConstants.STORAGE_COST + "'='500')";
conf.setBoolean(GrillConfConstants.QUERY_PERSISTENT_RESULT_INDRIVER, false);
// Craete again
QueryContext context = new QueryContext(createTable, null, conf);
GrillResultSet resultSet = driver.execute(context);
assertNull(resultSet);
// Load some data into the table
String dataLoad = "LOAD DATA LOCAL INPATH '"+ TEST_DATA_FILE +"' OVERWRITE INTO TABLE " + tableName;
context = new QueryContext(dataLoad, null, conf);
resultSet = driver.execute(context);
assertNull(resultSet);
Assert.assertEquals(0, driver.getHiveHandleSize());
}
// Tests
@Test
public void testInsertOverwriteConf() throws Exception {
createTestTable("test_insert_overwrite");
conf.setBoolean(GrillConfConstants.GRILL_ADD_INSERT_OVEWRITE, false);
String query = "SELECT ID FROM test_insert_overwrite";
QueryContext context = new QueryContext(query, null, conf);
driver.addPersistentPath(context);
assertEquals(context.getUserQuery(), query);
assertNotNull(context.getDriverQuery());
assertEquals(context.getDriverQuery(), context.getUserQuery());
}
@Test
public void testTemptable() throws Exception {
createTestTable("test_temp");
conf.setBoolean(GrillConfConstants.QUERY_PERSISTENT_RESULT_INDRIVER, false);
String query = "CREATE TABLE test_temp_output AS SELECT ID FROM test_insert_overwrite";
QueryContext context = new QueryContext(query, null, conf);
GrillResultSet resultSet = driver.execute(context);
assertNull(resultSet);
Assert.assertEquals(0, driver.getHiveHandleSize());
// fetch results from temp table
String select = "SELECT * FROM test_temp_output";
context = new QueryContext(select, null, conf);
resultSet = driver.execute(context);
Assert.assertEquals(0, driver.getHiveHandleSize());
validateInMemoryResult(resultSet, "test_temp_output");
Assert.assertEquals(0, driver.getHiveHandleSize());
}
@Test
public void testExecuteQuery() throws Exception {
createTestTable("test_execute");
GrillResultSet resultSet = null;
// Execute a select query
conf.setBoolean(GrillConfConstants.QUERY_PERSISTENT_RESULT_INDRIVER, false);
String select = "SELECT ID FROM test_execute";
QueryContext context = new QueryContext(select, null, conf);
resultSet = driver.execute(context);
validateInMemoryResult(resultSet);
conf.setBoolean(GrillConfConstants.QUERY_PERSISTENT_RESULT_INDRIVER, true);
context = new QueryContext(select, null, conf);
resultSet = driver.execute(context);
validatePersistentResult(resultSet, TEST_DATA_FILE, context.getHDFSResultDir(), false);
conf.set(GrillConfConstants.QUERY_OUTPUT_DIRECTORY_FORMAT,
"ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe'" +
" WITH SERDEPROPERTIES ('serialization.null.format'='-NA-'," +
" 'field.delim'=',' ) STORED AS TEXTFILE ");
select = "SELECT ID, null, ID FROM test_execute";
context = new QueryContext(select, null, conf);
resultSet = driver.execute(context);
validatePersistentResult(resultSet, TEST_DATA_FILE, context.getHDFSResultDir(), true);
Assert.assertEquals(0, driver.getHiveHandleSize());
}
private void validateInMemoryResult(GrillResultSet resultSet) throws GrillException, IOException {
validateInMemoryResult(resultSet, null);
}
private void validateInMemoryResult(GrillResultSet resultSet, String outputTable)
throws GrillException, IOException {
assertNotNull(resultSet);
assertTrue(resultSet instanceof HiveInMemoryResultSet);
HiveInMemoryResultSet inmemrs = (HiveInMemoryResultSet) resultSet;
// check metadata
GrillResultSetMetadata rsMeta = inmemrs.getMetadata();
List<ColumnDescriptor> columns = rsMeta.getColumns();
assertNotNull(columns);
assertEquals(columns.size(), 1);
String expectedCol = "";
if (outputTable != null) {
expectedCol += outputTable + ".";
}
expectedCol += "ID";
assertTrue(columns.get(0).getName().toLowerCase().equals(expectedCol.toLowerCase())
|| columns.get(0).getName().toLowerCase().equals("ID".toLowerCase()));
assertEquals(columns.get(0).getTypeName().toLowerCase(), "STRING".toLowerCase());
List<String> expectedRows = new ArrayList<String>();
// Read data from the test file into expectedRows
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(TEST_DATA_FILE)));
String line = "";
while ((line = br.readLine()) != null) {
expectedRows.add(line.trim());
}
br.close();
List<String> actualRows = new ArrayList<String>();
while (inmemrs.hasNext()) {
List<Object> row = inmemrs.next().getValues();
actualRows.add((String)row.get(0));
}
assertEquals(actualRows, expectedRows);
}
public static class FailHook implements HiveDriverRunHook {
@Override
public void postDriverRun(HiveDriverRunHookContext arg0) throws Exception {
// TODO Auto-generated method stub
}
@Override
public void preDriverRun(HiveDriverRunHookContext arg0) throws Exception {
throw new GrillException("Failing this run");
}
}
// executeAsync
@Test
public void testExecuteQueryAsync() throws Exception {
createTestTable("test_execute_sync");
// Now run a command that would fail
String expectFail = "SELECT ID FROM test_execute_sync";
conf.setBoolean(GrillConfConstants.QUERY_PERSISTENT_RESULT_INDRIVER, true);
conf.set("hive.exec.driver.run.hooks", FailHook.class.getCanonicalName());
QueryContext context = new QueryContext(expectFail, null, conf);
driver.executeAsync(context);
Assert.assertEquals(1, driver.getHiveHandleSize());
validateExecuteAsync(context, DriverQueryState.FAILED, true, false);
Assert.assertEquals(1, driver.getHiveHandleSize());
driver.closeQuery(context.getQueryHandle());
Assert.assertEquals(0, driver.getHiveHandleSize());
conf.set("hive.exec.driver.run.hooks", "");
// Async select query
String select = "SELECT ID FROM test_execute_sync";
conf.setBoolean(GrillConfConstants.QUERY_PERSISTENT_RESULT_INDRIVER, false);
context = new QueryContext(select, null, conf);
driver.executeAsync(context);
Assert.assertEquals(1, driver.getHiveHandleSize());
validateExecuteAsync(context, DriverQueryState.SUCCESSFUL, false, false);
driver.closeQuery(context.getQueryHandle());
Assert.assertEquals(0, driver.getHiveHandleSize());
conf.setBoolean(GrillConfConstants.QUERY_PERSISTENT_RESULT_INDRIVER, true);
context = new QueryContext(select, null, conf);
driver.executeAsync(context);
Assert.assertEquals(1, driver.getHiveHandleSize());
validateExecuteAsync(context, DriverQueryState.SUCCESSFUL, true, false);
driver.closeQuery(context.getQueryHandle());
Assert.assertEquals(0, driver.getHiveHandleSize());
conf.set(GrillConfConstants.QUERY_OUTPUT_DIRECTORY_FORMAT,
"ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe'" +
" WITH SERDEPROPERTIES ('serialization.null.format'='-NA-'," +
" 'field.delim'=',' ) STORED AS TEXTFILE ");
select = "SELECT ID, null, ID FROM test_execute_sync";
context = new QueryContext(select, null, conf);
driver.executeAsync(context);
Assert.assertEquals(1, driver.getHiveHandleSize());
validateExecuteAsync(context, DriverQueryState.SUCCESSFUL, true, true);
driver.closeQuery(context.getQueryHandle());
Assert.assertEquals(0, driver.getHiveHandleSize());
}
protected void validateExecuteAsync(QueryContext ctx, DriverQueryState finalState,
boolean isPersistent, boolean formatNulls, HiveDriver driver) throws Exception {
waitForAsyncQuery(ctx, driver);
driver.updateStatus(ctx);
assertEquals(ctx.getDriverStatus().getState(), finalState, "Expected query to finish with"
+ finalState);
assertTrue(ctx.getDriverStatus().getDriverFinishTime() > 0);
if (finalState.equals(DriverQueryState.SUCCESSFUL)) {
System.out.println("Progress:" + ctx.getDriverStatus().getProgressMessage());
assertNotNull(ctx.getDriverStatus().getProgressMessage());
if (!isPersistent) {
validateInMemoryResult(driver.fetchResultSet(ctx));
} else{
validatePersistentResult(driver.fetchResultSet(ctx), TEST_DATA_FILE, ctx.getHDFSResultDir(), formatNulls);
}
} else if (finalState.equals(DriverQueryState.FAILED)) {
System.out.println("Error:" + ctx.getDriverStatus().getErrorMessage());
System.out.println("Status:" + ctx.getDriverStatus().getStatusMessage());
assertNotNull(ctx.getDriverStatus().getErrorMessage());
}
}
protected void validateExecuteAsync(QueryContext ctx, DriverQueryState finalState,
boolean isPersistent, boolean formatNulls) throws Exception {
validateExecuteAsync(ctx, finalState, isPersistent, formatNulls, driver);
}
@Test
public void testCancelAsyncQuery() throws Exception {
createTestTable("test_cancel_async");
conf.setBoolean(GrillConfConstants.QUERY_PERSISTENT_RESULT_INDRIVER, false);
QueryContext context = new QueryContext("SELECT ID FROM test_cancel_async", null, conf);
driver.executeAsync(context);
driver.cancelQuery(context.getQueryHandle());
driver.updateStatus(context);
assertEquals(context.getDriverStatus().getState(), DriverQueryState.CANCELED, "Expecting query to be cancelled");
driver.closeQuery(context.getQueryHandle());
Assert.assertEquals(0, driver.getHiveHandleSize());
try {
driver.cancelQuery(context.getQueryHandle());
fail("Cancel on closed query should throw error");
} catch (GrillException exc) {
assertTrue(exc.getMessage().startsWith("Query not found"));
}
}
private void validatePersistentResult(GrillResultSet resultSet, String dataFile,
Path outptuDir, boolean formatNulls) throws Exception {
assertTrue(resultSet instanceof HivePersistentResultSet);
HivePersistentResultSet persistentResultSet = (HivePersistentResultSet) resultSet;
String path = persistentResultSet.getOutputPath();
Path actualPath = new Path(path);
FileSystem fs = actualPath.getFileSystem(conf);
assertEquals(actualPath, fs.makeQualified(outptuDir));
List<String> actualRows = new ArrayList<String>();
for (FileStatus stat : fs.listStatus(actualPath)) {
FSDataInputStream in = fs.open(stat.getPath());
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = br.readLine()) != null) {
System.out.println("Actual:" +line);
actualRows.add(line.trim());
}
} finally {
if (br != null) {
br.close();
}
}
}
BufferedReader br = null;
List<String> expectedRows = new ArrayList<String>();
try {
br = new BufferedReader(new FileReader(new File(dataFile)));
String line = "";
while ((line = br.readLine()) != null) {
String row = line.trim();
if (formatNulls) {
row += ",-NA-,";
row += line.trim();
}
expectedRows.add(row);
}
} finally {
if (br != null) {
br.close();
}
}
assertEquals(actualRows, expectedRows);
}
@Test
public void testPersistentResultSet() throws Exception {
createTestTable("test_persistent_result_set");
conf.setBoolean(GrillConfConstants.QUERY_PERSISTENT_RESULT_INDRIVER, true);
conf.setBoolean(GrillConfConstants.GRILL_ADD_INSERT_OVEWRITE, true);
conf.set(GrillConfConstants.GRILL_RESULT_SET_PARENT_DIR, TEST_OUTPUT_DIR);
QueryContext ctx = new QueryContext("SELECT ID FROM test_persistent_result_set", null, conf);
GrillResultSet resultSet = driver.execute(ctx);
validatePersistentResult(resultSet, TEST_DATA_FILE, ctx.getHDFSResultDir(), false);
Assert.assertEquals(0, driver.getHiveHandleSize());
ctx = new QueryContext("SELECT ID FROM test_persistent_result_set", null, conf);
driver.executeAsync(ctx);
Assert.assertEquals(1, driver.getHiveHandleSize());
validateExecuteAsync(ctx, DriverQueryState.SUCCESSFUL, true, false);
driver.closeQuery(ctx.getQueryHandle());
Assert.assertEquals(0, driver.getHiveHandleSize());
conf.set(GrillConfConstants.QUERY_OUTPUT_DIRECTORY_FORMAT,
"ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe'" +
" WITH SERDEPROPERTIES ('serialization.null.format'='-NA-'," +
" 'field.delim'=',' ) STORED AS TEXTFILE ");
ctx = new QueryContext("SELECT ID, null, ID FROM test_persistent_result_set", null, conf);
resultSet = driver.execute(ctx);
Assert.assertEquals(0, driver.getHiveHandleSize());
validatePersistentResult(resultSet, TEST_DATA_FILE, ctx.getHDFSResultDir(), true);
driver.closeQuery(ctx.getQueryHandle());
Assert.assertEquals(0, driver.getHiveHandleSize());
ctx = new QueryContext("SELECT ID, null, ID FROM test_persistent_result_set", null, conf);
driver.executeAsync(ctx);
Assert.assertEquals(1, driver.getHiveHandleSize());
validateExecuteAsync(ctx, DriverQueryState.SUCCESSFUL, true, true);
driver.closeQuery(ctx.getQueryHandle());
Assert.assertEquals(0, driver.getHiveHandleSize());
}
private void waitForAsyncQuery(QueryContext ctx, HiveDriver driver) throws Exception {
while (true) {
driver.updateStatus(ctx);
System.out.println("#W Waiting for query " + ctx.getQueryHandle() + " status: " + ctx.getDriverStatus().getState());
assertNotNull(ctx.getDriverStatus());
if (ctx.getDriverStatus().isFinished()) {
assertTrue(ctx.getDriverStatus().getDriverFinishTime() > 0);
break;
}
System.out.println("Progress:" + ctx.getDriverStatus().getProgressMessage());
Thread.sleep(1000);
assertTrue(ctx.getDriverStatus().getDriverStartTime() > 0);
}
}
// explain
@Test
public void testExplain() throws Exception {
createTestTable("test_explain");
DriverQueryPlan plan = driver.explain("SELECT ID FROM test_explain", conf);
assertTrue(plan instanceof HiveQueryPlan);
assertEquals(plan.getTableWeight("test_explain"), 500.0);
Assert.assertEquals(0, driver.getHiveHandleSize());
// test execute prepare
PreparedQueryContext pctx = new PreparedQueryContext(
"SELECT ID FROM test_explain", null, conf);
plan = driver.explainAndPrepare(pctx);
QueryContext qctx = new QueryContext(pctx, null, conf);
GrillResultSet result = driver.execute(qctx);
Assert.assertEquals(0, driver.getHiveHandleSize());
validateInMemoryResult(result);
// test execute prepare async
qctx = new QueryContext(pctx, null, conf);
driver.executeAsync(qctx);
assertNotNull(qctx.getDriverOpHandle());
validateExecuteAsync(qctx, DriverQueryState.SUCCESSFUL, false, false);
Assert.assertEquals(1, driver.getHiveHandleSize());
driver.closeQuery(qctx.getQueryHandle());
Assert.assertEquals(0, driver.getHiveHandleSize());
// for backward compatibility
qctx = new QueryContext(pctx, null, conf);
qctx.setQueryHandle(new QueryHandle(pctx.getPrepareHandle().getPrepareHandleId()));
result = driver.execute(qctx);
assertNotNull(qctx.getDriverOpHandle());
Assert.assertEquals(0, driver.getHiveHandleSize());
validateInMemoryResult(result);
// test execute prepare async
qctx = new QueryContext(pctx, null, conf);
qctx.setQueryHandle(new QueryHandle(pctx.getPrepareHandle().getPrepareHandleId()));
driver.executeAsync(qctx);
Assert.assertEquals(1, driver.getHiveHandleSize());
validateExecuteAsync(qctx, DriverQueryState.SUCCESSFUL, false, false);
driver.closeQuery(qctx.getQueryHandle());
driver.closePreparedQuery(pctx.getPrepareHandle());
Assert.assertEquals(0, driver.getHiveHandleSize());
conf.setBoolean(GrillConfConstants.PREPARE_ON_EXPLAIN, false);
plan = driver.explain("SELECT ID FROM test_explain", conf);
assertTrue(plan instanceof HiveQueryPlan);
assertNull(plan.getHandle());
conf.setBoolean(GrillConfConstants.PREPARE_ON_EXPLAIN, true);
Assert.assertEquals(0, driver.getHiveHandleSize());
}
@Test
public void testExplainOutput() throws Exception {
createTestTable("explain_test_1");
createTestTable("explain_test_2");
DriverQueryPlan plan = driver.explain("SELECT explain_test_1.ID, count(1) FROM " +
" explain_test_1 join explain_test_2 on explain_test_1.ID = explain_test_2.ID" +
" WHERE explain_test_1.ID = 'foo' or explain_test_2.ID = 'bar'" +
" GROUP BY explain_test_1.ID", conf);
Assert.assertEquals(0, driver.getHiveHandleSize());
assertTrue(plan instanceof HiveQueryPlan);
assertNotNull(plan.getTablesQueried());
assertEquals(plan.getTablesQueried().size(), 2);
assertNotNull(plan.getTableWeights());
assertTrue(plan.getTableWeights().containsKey("explain_test_1"));
assertTrue(plan.getTableWeights().containsKey("explain_test_2"));
assertEquals(plan.getNumJoins(), 1);
assertTrue(plan.getPlan() != null && !plan.getPlan().isEmpty());
driver.closeQuery(plan.getHandle());
}
@Test
public void testExplainOutputPersistent() throws Exception {
createTestTable("explain_test_1");
conf.setBoolean(GrillConfConstants.QUERY_PERSISTENT_RESULT_INDRIVER, true);
String query2 = "SELECT DISTINCT ID FROM explain_test_1";
PreparedQueryContext pctx = new PreparedQueryContext(query2, null, conf);
DriverQueryPlan plan2 = driver.explainAndPrepare(pctx);
//assertNotNull(plan2.getResultDestination());
Assert.assertEquals(0, driver.getHiveHandleSize());
assertNotNull(plan2.getTablesQueried());
assertEquals(plan2.getTablesQueried().size(), 1);
assertTrue(plan2.getTableWeights().containsKey("explain_test_1"));
assertEquals(plan2.getNumSels(), 1);
QueryContext ctx = new QueryContext(pctx, null, conf);
GrillResultSet resultSet = driver.execute(ctx);
Assert.assertEquals(0, driver.getHiveHandleSize());
HivePersistentResultSet persistentResultSet = (HivePersistentResultSet) resultSet;
String path = persistentResultSet.getOutputPath();
assertEquals(ctx.getHdfsoutPath(), path);
driver.closeQuery(plan2.getHandle());
}
}
|
Remove temp table created
|
grill-driver-hive/src/test/java/com/inmobi/grill/driver/hive/TestHiveDriver.java
|
Remove temp table created
|
|
Java
|
apache-2.0
|
e313379ed506dfa9ee090020e5ce219a81a561c1
| 0
|
cnfire/elasticsearch-1,ivansun1010/elasticsearch,phani546/elasticsearch,andrejserafim/elasticsearch,wittyameta/elasticsearch,fooljohnny/elasticsearch,Stacey-Gammon/elasticsearch,kimchy/elasticsearch,ThalaivaStars/OrgRepo1,opendatasoft/elasticsearch,uboness/elasticsearch,franklanganke/elasticsearch,ivansun1010/elasticsearch,jaynblue/elasticsearch,nomoa/elasticsearch,kenshin233/elasticsearch,elancom/elasticsearch,zeroctu/elasticsearch,artnowo/elasticsearch,yynil/elasticsearch,rento19962/elasticsearch,ImpressTV/elasticsearch,ulkas/elasticsearch,lydonchandra/elasticsearch,schonfeld/elasticsearch,myelin/elasticsearch,kaneshin/elasticsearch,brwe/elasticsearch,lchennup/elasticsearch,mikemccand/elasticsearch,codebunt/elasticsearch,GlenRSmith/elasticsearch,JervyShi/elasticsearch,mkis-/elasticsearch,vietlq/elasticsearch,spiegela/elasticsearch,queirozfcom/elasticsearch,Charlesdong/elasticsearch,karthikjaps/elasticsearch,mkis-/elasticsearch,yanjunh/elasticsearch,alexkuk/elasticsearch,infusionsoft/elasticsearch,Ansh90/elasticsearch,tebriel/elasticsearch,Rygbee/elasticsearch,yongminxia/elasticsearch,rento19962/elasticsearch,infusionsoft/elasticsearch,brandonkearby/elasticsearch,jsgao0/elasticsearch,HarishAtGitHub/elasticsearch,ESamir/elasticsearch,Shekharrajak/elasticsearch,Asimov4/elasticsearch,MjAbuz/elasticsearch,lchennup/elasticsearch,humandb/elasticsearch,nezirus/elasticsearch,areek/elasticsearch,yuy168/elasticsearch,glefloch/elasticsearch,wayeast/elasticsearch,franklanganke/elasticsearch,kenshin233/elasticsearch,vietlq/elasticsearch,Ansh90/elasticsearch,lmtwga/elasticsearch,Siddartha07/elasticsearch,vrkansagara/elasticsearch,IanvsPoplicola/elasticsearch,hanst/elasticsearch,iacdingping/elasticsearch,mikemccand/elasticsearch,snikch/elasticsearch,mute/elasticsearch,Siddartha07/elasticsearch,anti-social/elasticsearch,Fsero/elasticsearch,jango2015/elasticsearch,ouyangkongtong/elasticsearch,djschny/elasticsearch,dylan8902/elasticsearch,davidvgalbraith/elasticsearch,wittyameta/elasticsearch,dylan8902/elasticsearch,brwe/elasticsearch,rhoml/elasticsearch,jchampion/elasticsearch,vingupta3/elasticsearch,alexksikes/elasticsearch,pablocastro/elasticsearch,adrianbk/elasticsearch,fforbeck/elasticsearch,fubuki/elasticsearch,kunallimaye/elasticsearch,kalimatas/elasticsearch,wuranbo/elasticsearch,wbowling/elasticsearch,gingerwizard/elasticsearch,btiernay/elasticsearch,sjohnr/elasticsearch,s1monw/elasticsearch,andrestc/elasticsearch,F0lha/elasticsearch,fernandozhu/elasticsearch,LewayneNaidoo/elasticsearch,onegambler/elasticsearch,hanswang/elasticsearch,18098924759/elasticsearch,jbertouch/elasticsearch,ThiagoGarciaAlves/elasticsearch,vingupta3/elasticsearch,iacdingping/elasticsearch,mohit/elasticsearch,knight1128/elasticsearch,shreejay/elasticsearch,golubev/elasticsearch,Shekharrajak/elasticsearch,YosuaMichael/elasticsearch,humandb/elasticsearch,himanshuag/elasticsearch,AleksKochev/elasticsearch,golubev/elasticsearch,vvcephei/elasticsearch,achow/elasticsearch,janmejay/elasticsearch,Uiho/elasticsearch,fekaputra/elasticsearch,MetSystem/elasticsearch,apepper/elasticsearch,Ansh90/elasticsearch,vinsonlou/elasticsearch,scottsom/elasticsearch,mrorii/elasticsearch,adrianbk/elasticsearch,Ansh90/elasticsearch,mohsinh/elasticsearch,sreeramjayan/elasticsearch,mapr/elasticsearch,wuranbo/elasticsearch,18098924759/elasticsearch,wayeast/elasticsearch,kkirsche/elasticsearch,YosuaMichael/elasticsearch,strapdata/elassandra,Kakakakakku/elasticsearch,combinatorist/elasticsearch,opendatasoft/elasticsearch,jeteve/elasticsearch,rmuir/elasticsearch,drewr/elasticsearch,lmenezes/elasticsearch,masterweb121/elasticsearch,mapr/elasticsearch,iacdingping/elasticsearch,sarwarbhuiyan/elasticsearch,AleksKochev/elasticsearch,phani546/elasticsearch,gfyoung/elasticsearch,sjohnr/elasticsearch,MaineC/elasticsearch,dongjoon-hyun/elasticsearch,kkirsche/elasticsearch,alexshadow007/elasticsearch,episerver/elasticsearch,Rygbee/elasticsearch,brandonkearby/elasticsearch,sdauletau/elasticsearch,ThiagoGarciaAlves/elasticsearch,ImpressTV/elasticsearch,Microsoft/elasticsearch,brandonkearby/elasticsearch,obourgain/elasticsearch,jeteve/elasticsearch,overcome/elasticsearch,dataduke/elasticsearch,linglaiyao1314/elasticsearch,tkssharma/elasticsearch,mmaracic/elasticsearch,amit-shar/elasticsearch,mgalushka/elasticsearch,snikch/elasticsearch,codebunt/elasticsearch,awislowski/elasticsearch,kkirsche/elasticsearch,nrkkalyan/elasticsearch,xpandan/elasticsearch,Clairebi/ElasticsearchClone,milodky/elasticsearch,umeshdangat/elasticsearch,phani546/elasticsearch,Clairebi/ElasticsearchClone,thecocce/elasticsearch,Kakakakakku/elasticsearch,rento19962/elasticsearch,Charlesdong/elasticsearch,rmuir/elasticsearch,Fsero/elasticsearch,palecur/elasticsearch,Uiho/elasticsearch,petmit/elasticsearch,AshishThakur/elasticsearch,fforbeck/elasticsearch,markllama/elasticsearch,onegambler/elasticsearch,wittyameta/elasticsearch,schonfeld/elasticsearch,janmejay/elasticsearch,wittyameta/elasticsearch,nellicus/elasticsearch,cwurm/elasticsearch,dantuffery/elasticsearch,Charlesdong/elasticsearch,hanswang/elasticsearch,njlawton/elasticsearch,winstonewert/elasticsearch,thecocce/elasticsearch,maddin2016/elasticsearch,snikch/elasticsearch,iamjakob/elasticsearch,Brijeshrpatel9/elasticsearch,KimTaehee/elasticsearch,abibell/elasticsearch,hanst/elasticsearch,lzo/elasticsearch-1,davidvgalbraith/elasticsearch,EasonYi/elasticsearch,iantruslove/elasticsearch,kalburgimanjunath/elasticsearch,zeroctu/elasticsearch,wimvds/elasticsearch,btiernay/elasticsearch,LeoYao/elasticsearch,markharwood/elasticsearch,Kakakakakku/elasticsearch,szroland/elasticsearch,zhaocloud/elasticsearch,jw0201/elastic,humandb/elasticsearch,kcompher/elasticsearch,Siddartha07/elasticsearch,luiseduardohdbackup/elasticsearch,alexkuk/elasticsearch,tsohil/elasticsearch,yuy168/elasticsearch,queirozfcom/elasticsearch,sarwarbhuiyan/elasticsearch,hafkensite/elasticsearch,pranavraman/elasticsearch,rlugojr/elasticsearch,mm0/elasticsearch,KimTaehee/elasticsearch,onegambler/elasticsearch,janmejay/elasticsearch,jpountz/elasticsearch,nellicus/elasticsearch,onegambler/elasticsearch,wayeast/elasticsearch,Shepard1212/elasticsearch,TonyChai24/ESSource,schonfeld/elasticsearch,javachengwc/elasticsearch,kalburgimanjunath/elasticsearch,awislowski/elasticsearch,PhaedrusTheGreek/elasticsearch,mjason3/elasticsearch,Rygbee/elasticsearch,mapr/elasticsearch,lydonchandra/elasticsearch,maddin2016/elasticsearch,zkidkid/elasticsearch,szroland/elasticsearch,Brijeshrpatel9/elasticsearch,gmarz/elasticsearch,javachengwc/elasticsearch,kalburgimanjunath/elasticsearch,markwalkom/elasticsearch,hafkensite/elasticsearch,qwerty4030/elasticsearch,nellicus/elasticsearch,Fsero/elasticsearch,polyfractal/elasticsearch,ImpressTV/elasticsearch,vorce/es-metrics,Ansh90/elasticsearch,fernandozhu/elasticsearch,kaneshin/elasticsearch,alexkuk/elasticsearch,wangyuxue/elasticsearch,thecocce/elasticsearch,mrorii/elasticsearch,btiernay/elasticsearch,koxa29/elasticsearch,pritishppai/elasticsearch,hanswang/elasticsearch,socialrank/elasticsearch,GlenRSmith/elasticsearch,xuzha/elasticsearch,likaiwalkman/elasticsearch,chirilo/elasticsearch,nrkkalyan/elasticsearch,synhershko/elasticsearch,MisterAndersen/elasticsearch,petabytedata/elasticsearch,mcku/elasticsearch,aparo/elasticsearch,sdauletau/elasticsearch,mgalushka/elasticsearch,tebriel/elasticsearch,zkidkid/elasticsearch,hanst/elasticsearch,luiseduardohdbackup/elasticsearch,aglne/elasticsearch,djschny/elasticsearch,mm0/elasticsearch,feiqitian/elasticsearch,Shepard1212/elasticsearch,zeroctu/elasticsearch,HonzaKral/elasticsearch,truemped/elasticsearch,winstonewert/elasticsearch,nazarewk/elasticsearch,boliza/elasticsearch,palecur/elasticsearch,pozhidaevak/elasticsearch,hanswang/elasticsearch,petmit/elasticsearch,zhiqinghuang/elasticsearch,mcku/elasticsearch,tahaemin/elasticsearch,ydsakyclguozi/elasticsearch,wangtuo/elasticsearch,phani546/elasticsearch,pritishppai/elasticsearch,javachengwc/elasticsearch,MjAbuz/elasticsearch,aparo/elasticsearch,Liziyao/elasticsearch,kcompher/elasticsearch,pranavraman/elasticsearch,a2lin/elasticsearch,jeteve/elasticsearch,tcucchietti/elasticsearch,MjAbuz/elasticsearch,adrianbk/elasticsearch,fooljohnny/elasticsearch,markwalkom/elasticsearch,MichaelLiZhou/elasticsearch,sarwarbhuiyan/elasticsearch,MichaelLiZhou/elasticsearch,AleksKochev/elasticsearch,mmaracic/elasticsearch,davidvgalbraith/elasticsearch,lmtwga/elasticsearch,elancom/elasticsearch,vvcephei/elasticsearch,strapdata/elassandra,caengcjd/elasticsearch,nezirus/elasticsearch,golubev/elasticsearch,mjason3/elasticsearch,achow/elasticsearch,xuzha/elasticsearch,girirajsharma/elasticsearch,ulkas/elasticsearch,amaliujia/elasticsearch,cwurm/elasticsearch,JackyMai/elasticsearch,lks21c/elasticsearch,LewayneNaidoo/elasticsearch,rlugojr/elasticsearch,ouyangkongtong/elasticsearch,avikurapati/elasticsearch,qwerty4030/elasticsearch,socialrank/elasticsearch,HarishAtGitHub/elasticsearch,lightslife/elasticsearch,coding0011/elasticsearch,elancom/elasticsearch,loconsolutions/elasticsearch,wbowling/elasticsearch,PhaedrusTheGreek/elasticsearch,vroyer/elassandra,dpursehouse/elasticsearch,AshishThakur/elasticsearch,fekaputra/elasticsearch,StefanGor/elasticsearch,LeoYao/elasticsearch,zeroctu/elasticsearch,javachengwc/elasticsearch,ESamir/elasticsearch,MaineC/elasticsearch,truemped/elasticsearch,elancom/elasticsearch,Liziyao/elasticsearch,sauravmondallive/elasticsearch,kimimj/elasticsearch,jprante/elasticsearch,andrewvc/elasticsearch,kcompher/elasticsearch,ThalaivaStars/OrgRepo1,amaliujia/elasticsearch,fred84/elasticsearch,iantruslove/elasticsearch,GlenRSmith/elasticsearch,mjhennig/elasticsearch,robin13/elasticsearch,likaiwalkman/elasticsearch,ricardocerq/elasticsearch,truemped/elasticsearch,lmtwga/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,geidies/elasticsearch,hirdesh2008/elasticsearch,Liziyao/elasticsearch,libosu/elasticsearch,khiraiwa/elasticsearch,heng4fun/elasticsearch,winstonewert/elasticsearch,andrewvc/elasticsearch,micpalmia/elasticsearch,s1monw/elasticsearch,fforbeck/elasticsearch,amaliujia/elasticsearch,IanvsPoplicola/elasticsearch,franklanganke/elasticsearch,janmejay/elasticsearch,sposam/elasticsearch,ImpressTV/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,janmejay/elasticsearch,elancom/elasticsearch,jbertouch/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,weipinghe/elasticsearch,fernandozhu/elasticsearch,s1monw/elasticsearch,fubuki/elasticsearch,karthikjaps/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,hafkensite/elasticsearch,martinstuga/elasticsearch,Siddartha07/elasticsearch,fubuki/elasticsearch,abhijitiitr/es,kimchy/elasticsearch,mortonsykes/elasticsearch,lightslife/elasticsearch,uschindler/elasticsearch,yuy168/elasticsearch,acchen97/elasticsearch,dantuffery/elasticsearch,humandb/elasticsearch,wittyameta/elasticsearch,iantruslove/elasticsearch,Flipkart/elasticsearch,LewayneNaidoo/elasticsearch,mkis-/elasticsearch,weipinghe/elasticsearch,dongjoon-hyun/elasticsearch,synhershko/elasticsearch,pablocastro/elasticsearch,mortonsykes/elasticsearch,JackyMai/elasticsearch,Siddartha07/elasticsearch,MetSystem/elasticsearch,dylan8902/elasticsearch,Stacey-Gammon/elasticsearch,drewr/elasticsearch,alexkuk/elasticsearch,infusionsoft/elasticsearch,mm0/elasticsearch,tcucchietti/elasticsearch,khiraiwa/elasticsearch,dataduke/elasticsearch,fekaputra/elasticsearch,franklanganke/elasticsearch,hechunwen/elasticsearch,alexshadow007/elasticsearch,HonzaKral/elasticsearch,vrkansagara/elasticsearch,dpursehouse/elasticsearch,trangvh/elasticsearch,boliza/elasticsearch,djschny/elasticsearch,StefanGor/elasticsearch,Charlesdong/elasticsearch,JSCooke/elasticsearch,mbrukman/elasticsearch,SergVro/elasticsearch,mute/elasticsearch,gmarz/elasticsearch,springning/elasticsearch,uschindler/elasticsearch,JackyMai/elasticsearch,kalburgimanjunath/elasticsearch,smflorentino/elasticsearch,petmit/elasticsearch,anti-social/elasticsearch,franklanganke/elasticsearch,petmit/elasticsearch,i-am-Nathan/elasticsearch,vingupta3/elasticsearch,PhaedrusTheGreek/elasticsearch,petabytedata/elasticsearch,lks21c/elasticsearch,MjAbuz/elasticsearch,tahaemin/elasticsearch,bawse/elasticsearch,ajhalani/elasticsearch,gfyoung/elasticsearch,ImpressTV/elasticsearch,myelin/elasticsearch,lmtwga/elasticsearch,nezirus/elasticsearch,yanjunh/elasticsearch,nilabhsagar/elasticsearch,Uiho/elasticsearch,mrorii/elasticsearch,libosu/elasticsearch,Widen/elasticsearch,jango2015/elasticsearch,TonyChai24/ESSource,karthikjaps/elasticsearch,i-am-Nathan/elasticsearch,boliza/elasticsearch,hydro2k/elasticsearch,abhijitiitr/es,jw0201/elastic,ThiagoGarciaAlves/elasticsearch,clintongormley/elasticsearch,huanzhong/elasticsearch,hafkensite/elasticsearch,xingguang2013/elasticsearch,chirilo/elasticsearch,chrismwendt/elasticsearch,kevinkluge/elasticsearch,lmtwga/elasticsearch,rento19962/elasticsearch,phani546/elasticsearch,YosuaMichael/elasticsearch,anti-social/elasticsearch,jimczi/elasticsearch,kimimj/elasticsearch,feiqitian/elasticsearch,chrismwendt/elasticsearch,marcuswr/elasticsearch-dateline,socialrank/elasticsearch,AshishThakur/elasticsearch,Microsoft/elasticsearch,Widen/elasticsearch,Rygbee/elasticsearch,robin13/elasticsearch,hirdesh2008/elasticsearch,kunallimaye/elasticsearch,brandonkearby/elasticsearch,ckclark/elasticsearch,lzo/elasticsearch-1,salyh/elasticsearch,zeroctu/elasticsearch,huypx1292/elasticsearch,hanst/elasticsearch,mgalushka/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,rento19962/elasticsearch,robin13/elasticsearch,abhijitiitr/es,amit-shar/elasticsearch,hydro2k/elasticsearch,janmejay/elasticsearch,wayeast/elasticsearch,wuranbo/elasticsearch,robin13/elasticsearch,micpalmia/elasticsearch,mute/elasticsearch,masterweb121/elasticsearch,rajanm/elasticsearch,sreeramjayan/elasticsearch,JackyMai/elasticsearch,clintongormley/elasticsearch,mnylen/elasticsearch,obourgain/elasticsearch,a2lin/elasticsearch,nknize/elasticsearch,lydonchandra/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,rento19962/elasticsearch,dataduke/elasticsearch,gfyoung/elasticsearch,mcku/elasticsearch,wangtuo/elasticsearch,MjAbuz/elasticsearch,markllama/elasticsearch,LeoYao/elasticsearch,nilabhsagar/elasticsearch,xuzha/elasticsearch,rhoml/elasticsearch,queirozfcom/elasticsearch,sposam/elasticsearch,drewr/elasticsearch,beiske/elasticsearch,yanjunh/elasticsearch,adrianbk/elasticsearch,bestwpw/elasticsearch,Flipkart/elasticsearch,dylan8902/elasticsearch,kalimatas/elasticsearch,fernandozhu/elasticsearch,Ansh90/elasticsearch,IanvsPoplicola/elasticsearch,kimimj/elasticsearch,umeshdangat/elasticsearch,lchennup/elasticsearch,gmarz/elasticsearch,skearns64/elasticsearch,slavau/elasticsearch,xingguang2013/elasticsearch,mrorii/elasticsearch,apepper/elasticsearch,Widen/elasticsearch,yynil/elasticsearch,sc0ttkclark/elasticsearch,huanzhong/elasticsearch,humandb/elasticsearch,naveenhooda2000/elasticsearch,a2lin/elasticsearch,andrejserafim/elasticsearch,abibell/elasticsearch,VukDukic/elasticsearch,EasonYi/elasticsearch,dpursehouse/elasticsearch,nrkkalyan/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,bawse/elasticsearch,shreejay/elasticsearch,schonfeld/elasticsearch,palecur/elasticsearch,coding0011/elasticsearch,a2lin/elasticsearch,mjhennig/elasticsearch,obourgain/elasticsearch,apepper/elasticsearch,MisterAndersen/elasticsearch,markwalkom/elasticsearch,zhiqinghuang/elasticsearch,yynil/elasticsearch,opendatasoft/elasticsearch,jimczi/elasticsearch,javachengwc/elasticsearch,raishiv/elasticsearch,dataduke/elasticsearch,cwurm/elasticsearch,dylan8902/elasticsearch,tsohil/elasticsearch,mrorii/elasticsearch,humandb/elasticsearch,scottsom/elasticsearch,EasonYi/elasticsearch,feiqitian/elasticsearch,jaynblue/elasticsearch,skearns64/elasticsearch,chirilo/elasticsearch,ricardocerq/elasticsearch,milodky/elasticsearch,palecur/elasticsearch,artnowo/elasticsearch,himanshuag/elasticsearch,zhiqinghuang/elasticsearch,mbrukman/elasticsearch,chirilo/elasticsearch,loconsolutions/elasticsearch,Liziyao/elasticsearch,vrkansagara/elasticsearch,mohsinh/elasticsearch,codebunt/elasticsearch,mrorii/elasticsearch,mmaracic/elasticsearch,qwerty4030/elasticsearch,cnfire/elasticsearch-1,dantuffery/elasticsearch,cnfire/elasticsearch-1,adrianbk/elasticsearch,karthikjaps/elasticsearch,Widen/elasticsearch,wuranbo/elasticsearch,camilojd/elasticsearch,lks21c/elasticsearch,TonyChai24/ESSource,pozhidaevak/elasticsearch,sposam/elasticsearch,wayeast/elasticsearch,kcompher/elasticsearch,MisterAndersen/elasticsearch,luiseduardohdbackup/elasticsearch,diendt/elasticsearch,markwalkom/elasticsearch,zhiqinghuang/elasticsearch,yynil/elasticsearch,MaineC/elasticsearch,GlenRSmith/elasticsearch,martinstuga/elasticsearch,infusionsoft/elasticsearch,kimchy/elasticsearch,slavau/elasticsearch,areek/elasticsearch,Stacey-Gammon/elasticsearch,markharwood/elasticsearch,mapr/elasticsearch,achow/elasticsearch,F0lha/elasticsearch,nellicus/elasticsearch,Kakakakakku/elasticsearch,naveenhooda2000/elasticsearch,markwalkom/elasticsearch,fubuki/elasticsearch,linglaiyao1314/elasticsearch,ThalaivaStars/OrgRepo1,vorce/es-metrics,TonyChai24/ESSource,dylan8902/elasticsearch,sauravmondallive/elasticsearch,rento19962/elasticsearch,sauravmondallive/elasticsearch,mikemccand/elasticsearch,Liziyao/elasticsearch,YosuaMichael/elasticsearch,sc0ttkclark/elasticsearch,ZTE-PaaS/elasticsearch,Brijeshrpatel9/elasticsearch,slavau/elasticsearch,Chhunlong/elasticsearch,lmtwga/elasticsearch,xingguang2013/elasticsearch,VukDukic/elasticsearch,areek/elasticsearch,libosu/elasticsearch,knight1128/elasticsearch,tsohil/elasticsearch,likaiwalkman/elasticsearch,cnfire/elasticsearch-1,xuzha/elasticsearch,sdauletau/elasticsearch,YosuaMichael/elasticsearch,socialrank/elasticsearch,KimTaehee/elasticsearch,chrismwendt/elasticsearch,skearns64/elasticsearch,i-am-Nathan/elasticsearch,ulkas/elasticsearch,apepper/elasticsearch,nomoa/elasticsearch,kevinkluge/elasticsearch,beiske/elasticsearch,thecocce/elasticsearch,HarishAtGitHub/elasticsearch,AndreKR/elasticsearch,mjhennig/elasticsearch,knight1128/elasticsearch,snikch/elasticsearch,kunallimaye/elasticsearch,rmuir/elasticsearch,milodky/elasticsearch,markllama/elasticsearch,AndreKR/elasticsearch,mgalushka/elasticsearch,nellicus/elasticsearch,umeshdangat/elasticsearch,mjhennig/elasticsearch,fred84/elasticsearch,tahaemin/elasticsearch,polyfractal/elasticsearch,tkssharma/elasticsearch,karthikjaps/elasticsearch,caengcjd/elasticsearch,kevinkluge/elasticsearch,uschindler/elasticsearch,mbrukman/elasticsearch,smflorentino/elasticsearch,queirozfcom/elasticsearch,wimvds/elasticsearch,mnylen/elasticsearch,Collaborne/elasticsearch,yongminxia/elasticsearch,a2lin/elasticsearch,Clairebi/ElasticsearchClone,salyh/elasticsearch,hydro2k/elasticsearch,jw0201/elastic,fubuki/elasticsearch,Microsoft/elasticsearch,jprante/elasticsearch,wenpos/elasticsearch,myelin/elasticsearch,tahaemin/elasticsearch,JackyMai/elasticsearch,kingaj/elasticsearch,kaneshin/elasticsearch,yuy168/elasticsearch,yongminxia/elasticsearch,sjohnr/elasticsearch,masterweb121/elasticsearch,s1monw/elasticsearch,mgalushka/elasticsearch,beiske/elasticsearch,mmaracic/elasticsearch,umeshdangat/elasticsearch,sarwarbhuiyan/elasticsearch,rlugojr/elasticsearch,acchen97/elasticsearch,masterweb121/elasticsearch,spiegela/elasticsearch,likaiwalkman/elasticsearch,gmarz/elasticsearch,KimTaehee/elasticsearch,alexbrasetvik/elasticsearch,snikch/elasticsearch,szroland/elasticsearch,HarishAtGitHub/elasticsearch,Shekharrajak/elasticsearch,jango2015/elasticsearch,ajhalani/elasticsearch,Liziyao/elasticsearch,jimhooker2002/elasticsearch,pritishppai/elasticsearch,amaliujia/elasticsearch,mkis-/elasticsearch,AleksKochev/elasticsearch,rlugojr/elasticsearch,feiqitian/elasticsearch,easonC/elasticsearch,yongminxia/elasticsearch,acchen97/elasticsearch,knight1128/elasticsearch,jbertouch/elasticsearch,dpursehouse/elasticsearch,18098924759/elasticsearch,wangtuo/elasticsearch,mgalushka/elasticsearch,golubev/elasticsearch,jimhooker2002/elasticsearch,dantuffery/elasticsearch,AshishThakur/elasticsearch,henakamaMSFT/elasticsearch,MetSystem/elasticsearch,SergVro/elasticsearch,jsgao0/elasticsearch,koxa29/elasticsearch,Shepard1212/elasticsearch,Asimov4/elasticsearch,libosu/elasticsearch,Charlesdong/elasticsearch,Shepard1212/elasticsearch,vietlq/elasticsearch,jw0201/elastic,weipinghe/elasticsearch,nazarewk/elasticsearch,rajanm/elasticsearch,pablocastro/elasticsearch,btiernay/elasticsearch,ouyangkongtong/elasticsearch,MaineC/elasticsearch,yuy168/elasticsearch,kevinkluge/elasticsearch,anti-social/elasticsearch,lchennup/elasticsearch,marcuswr/elasticsearch-dateline,uboness/elasticsearch,lzo/elasticsearch-1,henakamaMSFT/elasticsearch,jeteve/elasticsearch,jbertouch/elasticsearch,jchampion/elasticsearch,Stacey-Gammon/elasticsearch,artnowo/elasticsearch,yuy168/elasticsearch,Flipkart/elasticsearch,Chhunlong/elasticsearch,Flipkart/elasticsearch,hirdesh2008/elasticsearch,TonyChai24/ESSource,Asimov4/elasticsearch,markharwood/elasticsearch,Helen-Zhao/elasticsearch,heng4fun/elasticsearch,himanshuag/elasticsearch,areek/elasticsearch,JervyShi/elasticsearch,trangvh/elasticsearch,tcucchietti/elasticsearch,MetSystem/elasticsearch,Helen-Zhao/elasticsearch,diendt/elasticsearch,bestwpw/elasticsearch,strapdata/elassandra-test,nrkkalyan/elasticsearch,pablocastro/elasticsearch,strapdata/elassandra,areek/elasticsearch,chirilo/elasticsearch,davidvgalbraith/elasticsearch,hanswang/elasticsearch,aglne/elasticsearch,kimimj/elasticsearch,gfyoung/elasticsearch,jaynblue/elasticsearch,ESamir/elasticsearch,tkssharma/elasticsearch,Rygbee/elasticsearch,raishiv/elasticsearch,gingerwizard/elasticsearch,caengcjd/elasticsearch,Chhunlong/elasticsearch,episerver/elasticsearch,vietlq/elasticsearch,Siddartha07/elasticsearch,jimhooker2002/elasticsearch,NBSW/elasticsearch,caengcjd/elasticsearch,Shekharrajak/elasticsearch,sarwarbhuiyan/elasticsearch,sc0ttkclark/elasticsearch,mkis-/elasticsearch,andrejserafim/elasticsearch,hydro2k/elasticsearch,thecocce/elasticsearch,wayeast/elasticsearch,petabytedata/elasticsearch,lchennup/elasticsearch,tebriel/elasticsearch,salyh/elasticsearch,fooljohnny/elasticsearch,jaynblue/elasticsearch,cwurm/elasticsearch,avikurapati/elasticsearch,Charlesdong/elasticsearch,btiernay/elasticsearch,hanswang/elasticsearch,Collaborne/elasticsearch,pritishppai/elasticsearch,jsgao0/elasticsearch,hanswang/elasticsearch,Shekharrajak/elasticsearch,masterweb121/elasticsearch,andrestc/elasticsearch,huanzhong/elasticsearch,pritishppai/elasticsearch,kubum/elasticsearch,phani546/elasticsearch,vingupta3/elasticsearch,djschny/elasticsearch,bawse/elasticsearch,MjAbuz/elasticsearch,cnfire/elasticsearch-1,obourgain/elasticsearch,wbowling/elasticsearch,vroyer/elassandra,jimhooker2002/elasticsearch,beiske/elasticsearch,sarwarbhuiyan/elasticsearch,kevinkluge/elasticsearch,fekaputra/elasticsearch,tkssharma/elasticsearch,AleksKochev/elasticsearch,sposam/elasticsearch,pablocastro/elasticsearch,mmaracic/elasticsearch,amit-shar/elasticsearch,djschny/elasticsearch,trangvh/elasticsearch,xingguang2013/elasticsearch,pritishppai/elasticsearch,sjohnr/elasticsearch,kubum/elasticsearch,martinstuga/elasticsearch,opendatasoft/elasticsearch,glefloch/elasticsearch,geidies/elasticsearch,lightslife/elasticsearch,lydonchandra/elasticsearch,Collaborne/elasticsearch,smflorentino/elasticsearch,mjhennig/elasticsearch,szroland/elasticsearch,jimhooker2002/elasticsearch,kenshin233/elasticsearch,kingaj/elasticsearch,ThiagoGarciaAlves/elasticsearch,artnowo/elasticsearch,F0lha/elasticsearch,Brijeshrpatel9/elasticsearch,wimvds/elasticsearch,rlugojr/elasticsearch,aglne/elasticsearch,ThiagoGarciaAlves/elasticsearch,beiske/elasticsearch,jango2015/elasticsearch,Brijeshrpatel9/elasticsearch,Helen-Zhao/elasticsearch,lmenezes/elasticsearch,sauravmondallive/elasticsearch,episerver/elasticsearch,lightslife/elasticsearch,raishiv/elasticsearch,kubum/elasticsearch,polyfractal/elasticsearch,scottsom/elasticsearch,mm0/elasticsearch,jango2015/elasticsearch,chrismwendt/elasticsearch,ESamir/elasticsearch,pranavraman/elasticsearch,peschlowp/elasticsearch,GlenRSmith/elasticsearch,qwerty4030/elasticsearch,jsgao0/elasticsearch,JervyShi/elasticsearch,SergVro/elasticsearch,Chhunlong/elasticsearch,javachengwc/elasticsearch,davidvgalbraith/elasticsearch,nomoa/elasticsearch,kalburgimanjunath/elasticsearch,truemped/elasticsearch,strapdata/elassandra-test,zhiqinghuang/elasticsearch,mcku/elasticsearch,khiraiwa/elasticsearch,EasonYi/elasticsearch,jbertouch/elasticsearch,zeroctu/elasticsearch,Shepard1212/elasticsearch,jchampion/elasticsearch,kunallimaye/elasticsearch,jchampion/elasticsearch,petabytedata/elasticsearch,MichaelLiZhou/elasticsearch,tahaemin/elasticsearch,easonC/elasticsearch,golubev/elasticsearch,MetSystem/elasticsearch,truemped/elasticsearch,tkssharma/elasticsearch,iamjakob/elasticsearch,easonC/elasticsearch,markllama/elasticsearch,scottsom/elasticsearch,avikurapati/elasticsearch,micpalmia/elasticsearch,elasticdog/elasticsearch,linglaiyao1314/elasticsearch,AndreKR/elasticsearch,masaruh/elasticsearch,ThalaivaStars/OrgRepo1,jeteve/elasticsearch,abibell/elasticsearch,uboness/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,uboness/elasticsearch,LewayneNaidoo/elasticsearch,truemped/elasticsearch,iantruslove/elasticsearch,VukDukic/elasticsearch,Collaborne/elasticsearch,wangyuxue/elasticsearch,MichaelLiZhou/elasticsearch,Chhunlong/elasticsearch,infusionsoft/elasticsearch,jpountz/elasticsearch,Helen-Zhao/elasticsearch,cnfire/elasticsearch-1,caengcjd/elasticsearch,njlawton/elasticsearch,wangyuxue/elasticsearch,sneivandt/elasticsearch,spiegela/elasticsearch,adrianbk/elasticsearch,mikemccand/elasticsearch,acchen97/elasticsearch,fforbeck/elasticsearch,skearns64/elasticsearch,avikurapati/elasticsearch,lchennup/elasticsearch,sneivandt/elasticsearch,LeoYao/elasticsearch,onegambler/elasticsearch,zhaocloud/elasticsearch,khiraiwa/elasticsearch,aglne/elasticsearch,huanzhong/elasticsearch,ulkas/elasticsearch,rajanm/elasticsearch,hafkensite/elasticsearch,kimimj/elasticsearch,zhaocloud/elasticsearch,socialrank/elasticsearch,rmuir/elasticsearch,kunallimaye/elasticsearch,alexksikes/elasticsearch,Kakakakakku/elasticsearch,MichaelLiZhou/elasticsearch,sposam/elasticsearch,Shekharrajak/elasticsearch,jaynblue/elasticsearch,Collaborne/elasticsearch,jeteve/elasticsearch,kevinkluge/elasticsearch,geidies/elasticsearch,abhijitiitr/es,nazarewk/elasticsearch,peschlowp/elasticsearch,C-Bish/elasticsearch,18098924759/elasticsearch,gingerwizard/elasticsearch,kenshin233/elasticsearch,LewayneNaidoo/elasticsearch,girirajsharma/elasticsearch,strapdata/elassandra5-rc,markwalkom/elasticsearch,ricardocerq/elasticsearch,xpandan/elasticsearch,bestwpw/elasticsearch,IanvsPoplicola/elasticsearch,bestwpw/elasticsearch,ajhalani/elasticsearch,wimvds/elasticsearch,smflorentino/elasticsearch,aparo/elasticsearch,umeshdangat/elasticsearch,schonfeld/elasticsearch,camilojd/elasticsearch,dpursehouse/elasticsearch,infusionsoft/elasticsearch,rhoml/elasticsearch,golubev/elasticsearch,lzo/elasticsearch-1,zhiqinghuang/elasticsearch,loconsolutions/elasticsearch,lzo/elasticsearch-1,Uiho/elasticsearch,clintongormley/elasticsearch,thecocce/elasticsearch,JervyShi/elasticsearch,heng4fun/elasticsearch,mohit/elasticsearch,nknize/elasticsearch,acchen97/elasticsearch,luiseduardohdbackup/elasticsearch,lydonchandra/elasticsearch,mohit/elasticsearch,andrestc/elasticsearch,scottsom/elasticsearch,Rygbee/elasticsearch,koxa29/elasticsearch,springning/elasticsearch,ajhalani/elasticsearch,mortonsykes/elasticsearch,strapdata/elassandra-test,PhaedrusTheGreek/elasticsearch,kalimatas/elasticsearch,mapr/elasticsearch,strapdata/elassandra-test,apepper/elasticsearch,scorpionvicky/elasticsearch,naveenhooda2000/elasticsearch,ricardocerq/elasticsearch,marcuswr/elasticsearch-dateline,Chhunlong/elasticsearch,caengcjd/elasticsearch,acchen97/elasticsearch,lmtwga/elasticsearch,kubum/elasticsearch,zhaocloud/elasticsearch,lydonchandra/elasticsearch,dongjoon-hyun/elasticsearch,abibell/elasticsearch,wimvds/elasticsearch,i-am-Nathan/elasticsearch,iantruslove/elasticsearch,cnfire/elasticsearch-1,pranavraman/elasticsearch,maddin2016/elasticsearch,mmaracic/elasticsearch,HonzaKral/elasticsearch,milodky/elasticsearch,clintongormley/elasticsearch,nellicus/elasticsearch,amit-shar/elasticsearch,onegambler/elasticsearch,dongaihua/highlight-elasticsearch,strapdata/elassandra5-rc,jimczi/elasticsearch,sauravmondallive/elasticsearch,vvcephei/elasticsearch,VukDukic/elasticsearch,iamjakob/elasticsearch,wenpos/elasticsearch,nknize/elasticsearch,SergVro/elasticsearch,tebriel/elasticsearch,andrestc/elasticsearch,sjohnr/elasticsearch,vietlq/elasticsearch,Uiho/elasticsearch,mute/elasticsearch,nazarewk/elasticsearch,djschny/elasticsearch,sreeramjayan/elasticsearch,YosuaMichael/elasticsearch,Asimov4/elasticsearch,easonC/elasticsearch,palecur/elasticsearch,likaiwalkman/elasticsearch,ouyangkongtong/elasticsearch,lightslife/elasticsearch,linglaiyao1314/elasticsearch,C-Bish/elasticsearch,nknize/elasticsearch,likaiwalkman/elasticsearch,mjhennig/elasticsearch,salyh/elasticsearch,alexksikes/elasticsearch,himanshuag/elasticsearch,C-Bish/elasticsearch,mnylen/elasticsearch,kalburgimanjunath/elasticsearch,petmit/elasticsearch,dataduke/elasticsearch,F0lha/elasticsearch,StefanGor/elasticsearch,codebunt/elasticsearch,ouyangkongtong/elasticsearch,NBSW/elasticsearch,alexbrasetvik/elasticsearch,dataduke/elasticsearch,overcome/elasticsearch,spiegela/elasticsearch,vorce/es-metrics,MisterAndersen/elasticsearch,pranavraman/elasticsearch,iacdingping/elasticsearch,kkirsche/elasticsearch,polyfractal/elasticsearch,Kakakakakku/elasticsearch,loconsolutions/elasticsearch,vrkansagara/elasticsearch,kubum/elasticsearch,alexbrasetvik/elasticsearch,tsohil/elasticsearch,camilojd/elasticsearch,PhaedrusTheGreek/elasticsearch,pablocastro/elasticsearch,huypx1292/elasticsearch,kimimj/elasticsearch,ckclark/elasticsearch,AndreKR/elasticsearch,amaliujia/elasticsearch,hydro2k/elasticsearch,xingguang2013/elasticsearch,bestwpw/elasticsearch,masaruh/elasticsearch,zhiqinghuang/elasticsearch,huypx1292/elasticsearch,HarishAtGitHub/elasticsearch,mortonsykes/elasticsearch,petabytedata/elasticsearch,YosuaMichael/elasticsearch,sc0ttkclark/elasticsearch,LeoYao/elasticsearch,StefanGor/elasticsearch,Flipkart/elasticsearch,AshishThakur/elasticsearch,MjAbuz/elasticsearch,camilojd/elasticsearch,markharwood/elasticsearch,maddin2016/elasticsearch,njlawton/elasticsearch,diendt/elasticsearch,mnylen/elasticsearch,EasonYi/elasticsearch,MetSystem/elasticsearch,springning/elasticsearch,ydsakyclguozi/elasticsearch,knight1128/elasticsearch,slavau/elasticsearch,lchennup/elasticsearch,tahaemin/elasticsearch,martinstuga/elasticsearch,henakamaMSFT/elasticsearch,JSCooke/elasticsearch,weipinghe/elasticsearch,knight1128/elasticsearch,Collaborne/elasticsearch,MisterAndersen/elasticsearch,mikemccand/elasticsearch,andrejserafim/elasticsearch,Chhunlong/elasticsearch,glefloch/elasticsearch,hechunwen/elasticsearch,vingupta3/elasticsearch,zkidkid/elasticsearch,anti-social/elasticsearch,PhaedrusTheGreek/elasticsearch,heng4fun/elasticsearch,ThalaivaStars/OrgRepo1,ZTE-PaaS/elasticsearch,anti-social/elasticsearch,fubuki/elasticsearch,kubum/elasticsearch,adrianbk/elasticsearch,alexksikes/elasticsearch,pozhidaevak/elasticsearch,queirozfcom/elasticsearch,queirozfcom/elasticsearch,libosu/elasticsearch,humandb/elasticsearch,dongaihua/highlight-elasticsearch,diendt/elasticsearch,mbrukman/elasticsearch,ajhalani/elasticsearch,kkirsche/elasticsearch,s1monw/elasticsearch,awislowski/elasticsearch,linglaiyao1314/elasticsearch,tahaemin/elasticsearch,jpountz/elasticsearch,tkssharma/elasticsearch,myelin/elasticsearch,mute/elasticsearch,AshishThakur/elasticsearch,drewr/elasticsearch,ivansun1010/elasticsearch,MichaelLiZhou/elasticsearch,ivansun1010/elasticsearch,EasonYi/elasticsearch,strapdata/elassandra5-rc,kingaj/elasticsearch,kubum/elasticsearch,kunallimaye/elasticsearch,feiqitian/elasticsearch,kkirsche/elasticsearch,nilabhsagar/elasticsearch,ulkas/elasticsearch,kaneshin/elasticsearch,kenshin233/elasticsearch,areek/elasticsearch,alexshadow007/elasticsearch,robin13/elasticsearch,yanjunh/elasticsearch,fforbeck/elasticsearch,mm0/elasticsearch,naveenhooda2000/elasticsearch,mjason3/elasticsearch,hirdesh2008/elasticsearch,jimczi/elasticsearch,Clairebi/ElasticsearchClone,nomoa/elasticsearch,masaruh/elasticsearch,amaliujia/elasticsearch,weipinghe/elasticsearch,liweinan0423/elasticsearch,jprante/elasticsearch,fred84/elasticsearch,sauravmondallive/elasticsearch,Stacey-Gammon/elasticsearch,elancom/elasticsearch,clintongormley/elasticsearch,easonC/elasticsearch,jpountz/elasticsearch,hanst/elasticsearch,vroyer/elasticassandra,uschindler/elasticsearch,MichaelLiZhou/elasticsearch,girirajsharma/elasticsearch,jango2015/elasticsearch,xuzha/elasticsearch,codebunt/elasticsearch,rajanm/elasticsearch,boliza/elasticsearch,nrkkalyan/elasticsearch,18098924759/elasticsearch,abibell/elasticsearch,girirajsharma/elasticsearch,sscarduzio/elasticsearch,xuzha/elasticsearch,achow/elasticsearch,szroland/elasticsearch,jeteve/elasticsearch,spiegela/elasticsearch,brwe/elasticsearch,beiske/elasticsearch,lydonchandra/elasticsearch,ouyangkongtong/elasticsearch,karthikjaps/elasticsearch,sposam/elasticsearch,yanjunh/elasticsearch,easonC/elasticsearch,bestwpw/elasticsearch,achow/elasticsearch,ThiagoGarciaAlves/elasticsearch,ivansun1010/elasticsearch,pozhidaevak/elasticsearch,vrkansagara/elasticsearch,himanshuag/elasticsearch,jprante/elasticsearch,ESamir/elasticsearch,zhaocloud/elasticsearch,mbrukman/elasticsearch,vvcephei/elasticsearch,Helen-Zhao/elasticsearch,scorpionvicky/elasticsearch,myelin/elasticsearch,franklanganke/elasticsearch,drewr/elasticsearch,sreeramjayan/elasticsearch,KimTaehee/elasticsearch,nezirus/elasticsearch,jbertouch/elasticsearch,slavau/elasticsearch,sdauletau/elasticsearch,micpalmia/elasticsearch,Microsoft/elasticsearch,ivansun1010/elasticsearch,KimTaehee/elasticsearch,pozhidaevak/elasticsearch,strapdata/elassandra5-rc,HarishAtGitHub/elasticsearch,sc0ttkclark/elasticsearch,dataduke/elasticsearch,tcucchietti/elasticsearch,jimhooker2002/elasticsearch,huypx1292/elasticsearch,mcku/elasticsearch,jpountz/elasticsearch,chrismwendt/elasticsearch,markharwood/elasticsearch,dongjoon-hyun/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,elasticdog/elasticsearch,aparo/elasticsearch,Collaborne/elasticsearch,ricardocerq/elasticsearch,bawse/elasticsearch,alexshadow007/elasticsearch,brwe/elasticsearch,mortonsykes/elasticsearch,rmuir/elasticsearch,NBSW/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,i-am-Nathan/elasticsearch,sdauletau/elasticsearch,mnylen/elasticsearch,iacdingping/elasticsearch,HarishAtGitHub/elasticsearch,henakamaMSFT/elasticsearch,iantruslove/elasticsearch,wenpos/elasticsearch,wbowling/elasticsearch,mnylen/elasticsearch,lightslife/elasticsearch,luiseduardohdbackup/elasticsearch,shreejay/elasticsearch,EasonYi/elasticsearch,khiraiwa/elasticsearch,dylan8902/elasticsearch,yongminxia/elasticsearch,schonfeld/elasticsearch,iantruslove/elasticsearch,brandonkearby/elasticsearch,iamjakob/elasticsearch,iamjakob/elasticsearch,ckclark/elasticsearch,mjason3/elasticsearch,mkis-/elasticsearch,sscarduzio/elasticsearch,vroyer/elasticassandra,sjohnr/elasticsearch,awislowski/elasticsearch,NBSW/elasticsearch,18098924759/elasticsearch,wbowling/elasticsearch,fred84/elasticsearch,ydsakyclguozi/elasticsearch,Asimov4/elasticsearch,LeoYao/elasticsearch,ZTE-PaaS/elasticsearch,pritishppai/elasticsearch,amit-shar/elasticsearch,smflorentino/elasticsearch,geidies/elasticsearch,overcome/elasticsearch,HonzaKral/elasticsearch,marcuswr/elasticsearch-dateline,aglne/elasticsearch,dantuffery/elasticsearch,lzo/elasticsearch-1,koxa29/elasticsearch,alexksikes/elasticsearch,JSCooke/elasticsearch,markllama/elasticsearch,fooljohnny/elasticsearch,JervyShi/elasticsearch,sarwarbhuiyan/elasticsearch,strapdata/elassandra-test,sreeramjayan/elasticsearch,salyh/elasticsearch,nknize/elasticsearch,smflorentino/elasticsearch,tkssharma/elasticsearch,sscarduzio/elasticsearch,yongminxia/elasticsearch,jchampion/elasticsearch,slavau/elasticsearch,huypx1292/elasticsearch,mute/elasticsearch,JSCooke/elasticsearch,vvcephei/elasticsearch,strapdata/elassandra-test,Widen/elasticsearch,lightslife/elasticsearch,mbrukman/elasticsearch,amit-shar/elasticsearch,huypx1292/elasticsearch,NBSW/elasticsearch,areek/elasticsearch,Ansh90/elasticsearch,ThalaivaStars/OrgRepo1,zeroctu/elasticsearch,Liziyao/elasticsearch,NBSW/elasticsearch,Clairebi/ElasticsearchClone,sneivandt/elasticsearch,shreejay/elasticsearch,ulkas/elasticsearch,milodky/elasticsearch,kenshin233/elasticsearch,likaiwalkman/elasticsearch,cwurm/elasticsearch,pranavraman/elasticsearch,vingupta3/elasticsearch,sc0ttkclark/elasticsearch,qwerty4030/elasticsearch,franklanganke/elasticsearch,AndreKR/elasticsearch,overcome/elasticsearch,hechunwen/elasticsearch,diendt/elasticsearch,fooljohnny/elasticsearch,knight1128/elasticsearch,NBSW/elasticsearch,martinstuga/elasticsearch,gfyoung/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,alexkuk/elasticsearch,kunallimaye/elasticsearch,iacdingping/elasticsearch,SergVro/elasticsearch,djschny/elasticsearch,opendatasoft/elasticsearch,ulkas/elasticsearch,sscarduzio/elasticsearch,andrejserafim/elasticsearch,bestwpw/elasticsearch,skearns64/elasticsearch,gingerwizard/elasticsearch,MaineC/elasticsearch,springning/elasticsearch,Rygbee/elasticsearch,mohit/elasticsearch,VukDukic/elasticsearch,koxa29/elasticsearch,sdauletau/elasticsearch,martinstuga/elasticsearch,avikurapati/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,ZTE-PaaS/elasticsearch,mnylen/elasticsearch,clintongormley/elasticsearch,khiraiwa/elasticsearch,winstonewert/elasticsearch,C-Bish/elasticsearch,Uiho/elasticsearch,18098924759/elasticsearch,btiernay/elasticsearch,henakamaMSFT/elasticsearch,girirajsharma/elasticsearch,socialrank/elasticsearch,wenpos/elasticsearch,acchen97/elasticsearch,petabytedata/elasticsearch,tcucchietti/elasticsearch,strapdata/elassandra,scorpionvicky/elasticsearch,Charlesdong/elasticsearch,jaynblue/elasticsearch,strapdata/elassandra,masterweb121/elasticsearch,gingerwizard/elasticsearch,elancom/elasticsearch,wbowling/elasticsearch,himanshuag/elasticsearch,episerver/elasticsearch,mohsinh/elasticsearch,maddin2016/elasticsearch,kalimatas/elasticsearch,pranavraman/elasticsearch,apepper/elasticsearch,coding0011/elasticsearch,opendatasoft/elasticsearch,mcku/elasticsearch,feiqitian/elasticsearch,himanshuag/elasticsearch,nilabhsagar/elasticsearch,springning/elasticsearch,linglaiyao1314/elasticsearch,vorce/es-metrics,tsohil/elasticsearch,Brijeshrpatel9/elasticsearch,hirdesh2008/elasticsearch,brwe/elasticsearch,ouyangkongtong/elasticsearch,njlawton/elasticsearch,sreeramjayan/elasticsearch,wangtuo/elasticsearch,kingaj/elasticsearch,F0lha/elasticsearch,lks21c/elasticsearch,wenpos/elasticsearch,liweinan0423/elasticsearch,dongjoon-hyun/elasticsearch,sneivandt/elasticsearch,achow/elasticsearch,kcompher/elasticsearch,infusionsoft/elasticsearch,alexbrasetvik/elasticsearch,vietlq/elasticsearch,rajanm/elasticsearch,davidvgalbraith/elasticsearch,heng4fun/elasticsearch,rhoml/elasticsearch,hirdesh2008/elasticsearch,xpandan/elasticsearch,Fsero/elasticsearch,Widen/elasticsearch,vroyer/elasticassandra,njlawton/elasticsearch,ckclark/elasticsearch,TonyChai24/ESSource,fred84/elasticsearch,zkidkid/elasticsearch,raishiv/elasticsearch,jsgao0/elasticsearch,polyfractal/elasticsearch,gingerwizard/elasticsearch,overcome/elasticsearch,ImpressTV/elasticsearch,jimczi/elasticsearch,alexkuk/elasticsearch,mm0/elasticsearch,aglne/elasticsearch,combinatorist/elasticsearch,caengcjd/elasticsearch,Clairebi/ElasticsearchClone,nellicus/elasticsearch,geidies/elasticsearch,scorpionvicky/elasticsearch,nomoa/elasticsearch,Fsero/elasticsearch,slavau/elasticsearch,nilabhsagar/elasticsearch,SergVro/elasticsearch,hafkensite/elasticsearch,truemped/elasticsearch,tebriel/elasticsearch,F0lha/elasticsearch,wangtuo/elasticsearch,abhijitiitr/es,strapdata/elassandra5-rc,andrejserafim/elasticsearch,obourgain/elasticsearch,hydro2k/elasticsearch,jw0201/elastic,peschlowp/elasticsearch,abibell/elasticsearch,hirdesh2008/elasticsearch,libosu/elasticsearch,aparo/elasticsearch,hechunwen/elasticsearch,glefloch/elasticsearch,Widen/elasticsearch,ckclark/elasticsearch,peschlowp/elasticsearch,ImpressTV/elasticsearch,weipinghe/elasticsearch,jw0201/elastic,liweinan0423/elasticsearch,weipinghe/elasticsearch,amit-shar/elasticsearch,vingupta3/elasticsearch,geidies/elasticsearch,StefanGor/elasticsearch,andrestc/elasticsearch,btiernay/elasticsearch,mbrukman/elasticsearch,shreejay/elasticsearch,wuranbo/elasticsearch,mm0/elasticsearch,fekaputra/elasticsearch,mohsinh/elasticsearch,zkidkid/elasticsearch,boliza/elasticsearch,Uiho/elasticsearch,episerver/elasticsearch,jprante/elasticsearch,naveenhooda2000/elasticsearch,overcome/elasticsearch,kingaj/elasticsearch,vinsonlou/elasticsearch,sposam/elasticsearch,JSCooke/elasticsearch,Shekharrajak/elasticsearch,szroland/elasticsearch,onegambler/elasticsearch,Siddartha07/elasticsearch,hafkensite/elasticsearch,xpandan/elasticsearch,loconsolutions/elasticsearch,zhaocloud/elasticsearch,xingguang2013/elasticsearch,artnowo/elasticsearch,sc0ttkclark/elasticsearch,wimvds/elasticsearch,chirilo/elasticsearch,springning/elasticsearch,LeoYao/elasticsearch,liweinan0423/elasticsearch,xingguang2013/elasticsearch,skearns64/elasticsearch,elasticdog/elasticsearch,masaruh/elasticsearch,huanzhong/elasticsearch,mjason3/elasticsearch,kcompher/elasticsearch,nrkkalyan/elasticsearch,markllama/elasticsearch,rmuir/elasticsearch,huanzhong/elasticsearch,snikch/elasticsearch,alexbrasetvik/elasticsearch,andrestc/elasticsearch,raishiv/elasticsearch,yynil/elasticsearch,combinatorist/elasticsearch,rhoml/elasticsearch,elasticdog/elasticsearch,tebriel/elasticsearch,bawse/elasticsearch,wittyameta/elasticsearch,lks21c/elasticsearch,fekaputra/elasticsearch,kingaj/elasticsearch,combinatorist/elasticsearch,gmarz/elasticsearch,sneivandt/elasticsearch,vietlq/elasticsearch,markharwood/elasticsearch,andrestc/elasticsearch,kalburgimanjunath/elasticsearch,xpandan/elasticsearch,Flipkart/elasticsearch,jimhooker2002/elasticsearch,mgalushka/elasticsearch,rajanm/elasticsearch,kcompher/elasticsearch,mapr/elasticsearch,vrkansagara/elasticsearch,nazarewk/elasticsearch,petabytedata/elasticsearch,wbowling/elasticsearch,aparo/elasticsearch,AndreKR/elasticsearch,peschlowp/elasticsearch,alexshadow007/elasticsearch,wimvds/elasticsearch,Fsero/elasticsearch,girirajsharma/elasticsearch,lzo/elasticsearch-1,gingerwizard/elasticsearch,camilojd/elasticsearch,kimimj/elasticsearch,trangvh/elasticsearch,elasticdog/elasticsearch,trangvh/elasticsearch,micpalmia/elasticsearch,strapdata/elassandra-test,Microsoft/elasticsearch,kenshin233/elasticsearch,nezirus/elasticsearch,alexbrasetvik/elasticsearch,rhoml/elasticsearch,wittyameta/elasticsearch,diendt/elasticsearch,masaruh/elasticsearch,tsohil/elasticsearch,jango2015/elasticsearch,kaneshin/elasticsearch,vorce/es-metrics,winstonewert/elasticsearch,yuy168/elasticsearch,mute/elasticsearch,pablocastro/elasticsearch,iamjakob/elasticsearch,huanzhong/elasticsearch,Brijeshrpatel9/elasticsearch,karthikjaps/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,scorpionvicky/elasticsearch,IanvsPoplicola/elasticsearch,queirozfcom/elasticsearch,markllama/elasticsearch,Asimov4/elasticsearch,iacdingping/elasticsearch,polyfractal/elasticsearch,hydro2k/elasticsearch,ydsakyclguozi/elasticsearch,iamjakob/elasticsearch,schonfeld/elasticsearch,ydsakyclguozi/elasticsearch,socialrank/elasticsearch,fekaputra/elasticsearch,jsgao0/elasticsearch,hanst/elasticsearch,PhaedrusTheGreek/elasticsearch,kingaj/elasticsearch,C-Bish/elasticsearch,fooljohnny/elasticsearch,ckclark/elasticsearch,hechunwen/elasticsearch,jchampion/elasticsearch,coding0011/elasticsearch,xpandan/elasticsearch,ydsakyclguozi/elasticsearch,loconsolutions/elasticsearch,Fsero/elasticsearch,MetSystem/elasticsearch,kaneshin/elasticsearch,milodky/elasticsearch,sscarduzio/elasticsearch,TonyChai24/ESSource,apepper/elasticsearch,vvcephei/elasticsearch,yynil/elasticsearch,yongminxia/elasticsearch,achow/elasticsearch,ckclark/elasticsearch,sdauletau/elasticsearch,kalimatas/elasticsearch,abibell/elasticsearch,mohit/elasticsearch,mcku/elasticsearch,coding0011/elasticsearch,ZTE-PaaS/elasticsearch,luiseduardohdbackup/elasticsearch,camilojd/elasticsearch,mjhennig/elasticsearch,JervyShi/elasticsearch,ESamir/elasticsearch,uschindler/elasticsearch,luiseduardohdbackup/elasticsearch,mohsinh/elasticsearch,awislowski/elasticsearch,combinatorist/elasticsearch,fernandozhu/elasticsearch,codebunt/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,drewr/elasticsearch,koxa29/elasticsearch,glefloch/elasticsearch,hechunwen/elasticsearch,tsohil/elasticsearch,masterweb121/elasticsearch,nrkkalyan/elasticsearch,vroyer/elassandra,drewr/elasticsearch,jpountz/elasticsearch,andrewvc/elasticsearch,linglaiyao1314/elasticsearch,wayeast/elasticsearch,springning/elasticsearch,marcuswr/elasticsearch-dateline,kevinkluge/elasticsearch,KimTaehee/elasticsearch,liweinan0423/elasticsearch,beiske/elasticsearch
|
/*
* Licensed to Elastic Search and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Elastic Search licenses this
* file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.threadpool.support;
import org.elasticsearch.common.component.AbstractComponent;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.threadpool.FutureListener;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.threadpool.ThreadPoolInfo;
import org.elasticsearch.threadpool.ThreadPoolStats;
import java.util.concurrent.*;
/**
* @author kimchy (shay.banon)
*/
public abstract class AbstractThreadPool extends AbstractComponent implements ThreadPool {
protected volatile boolean started;
protected ExecutorService executorService;
protected ScheduledExecutorService scheduledExecutorService;
protected ExecutorService cached;
protected AbstractThreadPool(Settings settings) {
super(settings);
}
public abstract String getType();
@Override public ThreadPoolInfo info() {
return new ThreadPoolInfo(getType(), getMinThreads(), getMaxThreads(), getSchedulerThreads());
}
@Override public ThreadPoolStats stats() {
return new ThreadPoolStats(getPoolSize(), getActiveCount(), getSchedulerPoolSize(), getSchedulerActiveCount());
}
@Override public boolean isStarted() {
return started;
}
@Override public Executor cached() {
return cached;
}
@Override public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
return scheduledExecutorService.schedule(command, delay, unit);
}
@Override public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
return scheduledExecutorService.schedule(callable, delay, unit);
}
@Override public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
return scheduledExecutorService.scheduleAtFixedRate(command, initialDelay, period, unit);
}
@Override public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {
return scheduledExecutorService.scheduleWithFixedDelay(command, initialDelay, delay, unit);
}
@Override public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, TimeValue interval) {
return scheduleWithFixedDelay(command, interval.millis(), interval.millis(), TimeUnit.MILLISECONDS);
}
@Override public void shutdown() {
started = false;
logger.debug("shutting down {} thread pool", getType());
executorService.shutdown();
scheduledExecutorService.shutdown();
cached.shutdown();
}
@Override public void shutdownNow() {
started = false;
if (!executorService.isTerminated()) {
executorService.shutdownNow();
}
if (!scheduledExecutorService.isTerminated()) {
scheduledExecutorService.shutdownNow();
}
if (cached != executorService) {
if (!cached.isTerminated()) {
cached.shutdownNow();
}
}
}
@Override public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
boolean result = executorService.awaitTermination(timeout, unit);
if (cached != executorService) {
result &= cached.awaitTermination(timeout, unit);
}
result &= scheduledExecutorService.awaitTermination(timeout, unit);
return result;
}
@Override public ScheduledFuture<?> schedule(Runnable command, TimeValue delay) {
return schedule(command, delay.millis(), TimeUnit.MILLISECONDS);
}
@Override public void execute(Runnable command) {
executorService.execute(command);
}
protected static class FutureCallable<T> implements Callable<T> {
private final Callable<T> callable;
private final FutureListener<T> listener;
public FutureCallable(Callable<T> callable, FutureListener<T> listener) {
this.callable = callable;
this.listener = listener;
}
@Override public T call() throws Exception {
try {
T result = callable.call();
listener.onResult(result);
return result;
} catch (Exception e) {
listener.onException(e);
throw e;
}
}
}
protected static class FutureRunnable<T> implements Runnable {
private final Runnable runnable;
private final T result;
private final FutureListener<T> listener;
private FutureRunnable(Runnable runnable, T result, FutureListener<T> listener) {
this.runnable = runnable;
this.result = result;
this.listener = listener;
}
@Override public void run() {
try {
runnable.run();
listener.onResult(result);
} catch (Exception e) {
listener.onException(e);
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
}
}
}
}
|
modules/elasticsearch/src/main/java/org/elasticsearch/threadpool/support/AbstractThreadPool.java
|
/*
* Licensed to Elastic Search and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Elastic Search licenses this
* file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.threadpool.support;
import org.elasticsearch.common.component.AbstractComponent;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.threadpool.FutureListener;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.threadpool.ThreadPoolInfo;
import org.elasticsearch.threadpool.ThreadPoolStats;
import java.util.concurrent.*;
/**
* @author kimchy (shay.banon)
*/
public abstract class AbstractThreadPool extends AbstractComponent implements ThreadPool {
protected volatile boolean started;
protected ExecutorService executorService;
protected ScheduledExecutorService scheduledExecutorService;
protected ExecutorService cached;
protected AbstractThreadPool(Settings settings) {
super(settings);
}
public abstract String getType();
@Override public ThreadPoolInfo info() {
return new ThreadPoolInfo(getType(), getMinThreads(), getMaxThreads(), getSchedulerThreads());
}
@Override public ThreadPoolStats stats() {
return new ThreadPoolStats(getPoolSize(), getActiveCount(), getSchedulerPoolSize(), getSchedulerActiveCount());
}
@Override public boolean isStarted() {
return started;
}
@Override public Executor cached() {
return cached;
}
@Override public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
return scheduledExecutorService.schedule(command, delay, unit);
}
@Override public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
return scheduledExecutorService.schedule(callable, delay, unit);
}
@Override public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
return scheduledExecutorService.scheduleAtFixedRate(command, initialDelay, period, unit);
}
@Override public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {
return scheduledExecutorService.scheduleWithFixedDelay(command, initialDelay, delay, unit);
}
@Override public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, TimeValue interval) {
return scheduleWithFixedDelay(command, interval.millis(), interval.millis(), TimeUnit.MILLISECONDS);
}
@Override public void shutdown() {
started = false;
logger.debug("shutting down {} thread pool", getType());
executorService.shutdown();
scheduledExecutorService.shutdown();
if (!cached.isShutdown()) {
cached.shutdown();
}
}
@Override public void shutdownNow() {
started = false;
if (!executorService.isTerminated()) {
executorService.shutdownNow();
}
if (!scheduledExecutorService.isTerminated()) {
scheduledExecutorService.shutdownNow();
}
if (!cached.isTerminated()) {
cached.shutdownNow();
}
}
@Override public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
boolean result = executorService.awaitTermination(timeout, unit);
result &= cached.awaitTermination(timeout, unit);
result &= scheduledExecutorService.awaitTermination(timeout, unit);
return result;
}
@Override public ScheduledFuture<?> schedule(Runnable command, TimeValue delay) {
return schedule(command, delay.millis(), TimeUnit.MILLISECONDS);
}
@Override public void execute(Runnable command) {
executorService.execute(command);
}
protected static class FutureCallable<T> implements Callable<T> {
private final Callable<T> callable;
private final FutureListener<T> listener;
public FutureCallable(Callable<T> callable, FutureListener<T> listener) {
this.callable = callable;
this.listener = listener;
}
@Override public T call() throws Exception {
try {
T result = callable.call();
listener.onResult(result);
return result;
} catch (Exception e) {
listener.onException(e);
throw e;
}
}
}
protected static class FutureRunnable<T> implements Runnable {
private final Runnable runnable;
private final T result;
private final FutureListener<T> listener;
private FutureRunnable(Runnable runnable, T result, FutureListener<T> listener) {
this.runnable = runnable;
this.result = result;
this.listener = listener;
}
@Override public void run() {
try {
runnable.run();
listener.onResult(result);
} catch (Exception e) {
listener.onException(e);
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
}
}
}
}
|
only force shutdown on cached threadpool if its not the same as the execture service
|
modules/elasticsearch/src/main/java/org/elasticsearch/threadpool/support/AbstractThreadPool.java
|
only force shutdown on cached threadpool if its not the same as the execture service
|
|
Java
|
apache-2.0
|
853c1f42cf11b654378e91c0307e7692b92fb27c
| 0
|
mandusm/presto,electrum/presto,zzhao0/presto,svstanev/presto,dain/presto,Praveen2112/presto,toyama0919/presto,ocono-tech/presto,kietly/presto,Praveen2112/presto,mandusm/presto,albertocsm/presto,treasure-data/presto,ptkool/presto,wagnermarkd/presto,suyucs/presto,propene/presto,mbeitchman/presto,sopel39/presto,TeradataCenterForHadoop/bootcamp,mugglmenzel/presto,Yaliang/presto,erichwang/presto,mbeitchman/presto,chrisunder/presto,Zoomdata/presto,bloomberg/presto,RobinUS2/presto,losipiuk/presto,joy-yao/presto,jiangyifangh/presto,propene/presto,EvilMcJerkface/presto,damiencarol/presto,totticarter/presto,miniway/presto,shixuan-fan/presto,TeradataCenterForHadoop/bootcamp,haitaoyao/presto,mpilman/presto,tellproject/presto,hulu/presto,RobinUS2/presto,nileema/presto,idemura/presto,ptkool/presto,Teradata/presto,gh351135612/presto,mandusm/presto,wyukawa/presto,martint/presto,zhenyuy-fb/presto,mpilman/presto,wagnermarkd/presto,prestodb/presto,erichwang/presto,chrisunder/presto,geraint0923/presto,electrum/presto,EvilMcJerkface/presto,ebd2/presto,damiencarol/presto,TeradataCenterForHadoop/bootcamp,aglne/presto,aleph-zero/presto,suyucs/presto,sumitkgec/presto,hgschmie/presto,Jimexist/presto,toyama0919/presto,joy-yao/presto,y-lan/presto,Nasdaq/presto,ebyhr/presto,jxiang/presto,cberner/presto,twitter-forks/presto,cawallin/presto,cosinequanon/presto,mvp/presto,totticarter/presto,nezihyigitbasi/presto,zzhao0/presto,mpilman/presto,geraint0923/presto,martint/presto,mandusm/presto,facebook/presto,twitter-forks/presto,gh351135612/presto,svstanev/presto,totticarter/presto,y-lan/presto,troels/nz-presto,ocono-tech/presto,hgschmie/presto,yuananf/presto,cberner/presto,tellproject/presto,mode/presto,haozhun/presto,haitaoyao/presto,11xor6/presto,sumitkgec/presto,aleph-zero/presto,dabaitu/presto,cberner/presto,erichwang/presto,jiangyifangh/presto,ptkool/presto,gh351135612/presto,Nasdaq/presto,damiencarol/presto,jiangyifangh/presto,nileema/presto,fiedukow/presto,takari/presto,Teradata/presto,Jimexist/presto,hulu/presto,haitaoyao/presto,elonazoulay/presto,facebook/presto,toyama0919/presto,martint/presto,youngwookim/presto,nezihyigitbasi/presto,mbeitchman/presto,ArturGajowy/presto,losipiuk/presto,haitaoyao/presto,aramesh117/presto,youngwookim/presto,miniway/presto,twitter-forks/presto,albertocsm/presto,mpilman/presto,EvilMcJerkface/presto,ptkool/presto,sumitkgec/presto,sunchao/presto,elonazoulay/presto,shixuan-fan/presto,nileema/presto,chrisunder/presto,mvp/presto,joy-yao/presto,takari/presto,cosinequanon/presto,electrum/presto,gh351135612/presto,Teradata/presto,yuananf/presto,nezihyigitbasi/presto,dain/presto,lingochamp/presto,stewartpark/presto,haitaoyao/presto,joy-yao/presto,y-lan/presto,raghavsethi/presto,miniway/presto,jf367/presto,lingochamp/presto,albertocsm/presto,youngwookim/presto,arhimondr/presto,arhimondr/presto,wagnermarkd/presto,haozhun/presto,dabaitu/presto,albertocsm/presto,Teradata/presto,tellproject/presto,y-lan/presto,prestodb/presto,hulu/presto,Jimexist/presto,jiangyifangh/presto,mbeitchman/presto,kietly/presto,aramesh117/presto,ocono-tech/presto,ebyhr/presto,jf367/presto,zhenyuy-fb/presto,bloomberg/presto,hgschmie/presto,11xor6/presto,idemura/presto,raghavsethi/presto,Zoomdata/presto,facebook/presto,mugglmenzel/presto,fiedukow/presto,Nasdaq/presto,wagnermarkd/presto,sopel39/presto,harunurhan/presto,svstanev/presto,smartnews/presto,erichwang/presto,tomz/presto,Nasdaq/presto,wyukawa/presto,cosinequanon/presto,Zoomdata/presto,stewartpark/presto,cosinequanon/presto,ipros-team/presto,dabaitu/presto,electrum/presto,smartnews/presto,wrmsr/presto,cawallin/presto,miniway/presto,zhenyuy-fb/presto,raghavsethi/presto,cawallin/presto,facebook/presto,Yaliang/presto,11xor6/presto,svstanev/presto,shixuan-fan/presto,aleph-zero/presto,ArturGajowy/presto,mugglmenzel/presto,suyucs/presto,prateek1306/presto,zzhao0/presto,11xor6/presto,aleph-zero/presto,RobinUS2/presto,cawallin/presto,prateek1306/presto,soz-fb/presto,twitter-forks/presto,troels/nz-presto,wagnermarkd/presto,tellproject/presto,yuananf/presto,smartnews/presto,idemura/presto,zzhao0/presto,yuananf/presto,wrmsr/presto,TeradataCenterForHadoop/bootcamp,joy-yao/presto,Yaliang/presto,chrisunder/presto,tellproject/presto,jxiang/presto,damiencarol/presto,cosinequanon/presto,bloomberg/presto,totticarter/presto,geraint0923/presto,suyucs/presto,mpilman/presto,troels/nz-presto,mode/presto,jxiang/presto,ebd2/presto,ebyhr/presto,nezihyigitbasi/presto,losipiuk/presto,fiedukow/presto,youngwookim/presto,tomz/presto,treasure-data/presto,arhimondr/presto,kietly/presto,jf367/presto,y-lan/presto,raghavsethi/presto,ebd2/presto,ebyhr/presto,tellproject/presto,sunchao/presto,losipiuk/presto,ipros-team/presto,ptkool/presto,bloomberg/presto,mode/presto,sopel39/presto,Jimexist/presto,wrmsr/presto,treasure-data/presto,wrmsr/presto,elonazoulay/presto,treasure-data/presto,zzhao0/presto,jf367/presto,mpilman/presto,Zoomdata/presto,losipiuk/presto,cberner/presto,ArturGajowy/presto,propene/presto,shixuan-fan/presto,idemura/presto,prateek1306/presto,aglne/presto,stewartpark/presto,jxiang/presto,wyukawa/presto,wrmsr/presto,zhenyuy-fb/presto,hulu/presto,stewartpark/presto,ocono-tech/presto,stewartpark/presto,Praveen2112/presto,yuananf/presto,damiencarol/presto,soz-fb/presto,dabaitu/presto,wyukawa/presto,svstanev/presto,mode/presto,ipros-team/presto,RobinUS2/presto,fiedukow/presto,smartnews/presto,wyukawa/presto,dain/presto,aglne/presto,nezihyigitbasi/presto,sunchao/presto,dain/presto,ocono-tech/presto,mvp/presto,haozhun/presto,aramesh117/presto,nileema/presto,electrum/presto,raghavsethi/presto,aglne/presto,takari/presto,jxiang/presto,harunurhan/presto,ebyhr/presto,prestodb/presto,aglne/presto,smartnews/presto,geraint0923/presto,sopel39/presto,treasure-data/presto,mandusm/presto,propene/presto,hulu/presto,fiedukow/presto,takari/presto,jiangyifangh/presto,sunchao/presto,harunurhan/presto,gh351135612/presto,sumitkgec/presto,youngwookim/presto,ipros-team/presto,aramesh117/presto,RobinUS2/presto,troels/nz-presto,zhenyuy-fb/presto,ipros-team/presto,sunchao/presto,harunurhan/presto,prestodb/presto,prestodb/presto,Nasdaq/presto,propene/presto,soz-fb/presto,kietly/presto,troels/nz-presto,shixuan-fan/presto,lingochamp/presto,geraint0923/presto,albertocsm/presto,Teradata/presto,mbeitchman/presto,suyucs/presto,Jimexist/presto,soz-fb/presto,ArturGajowy/presto,takari/presto,wrmsr/presto,sumitkgec/presto,arhimondr/presto,toyama0919/presto,bloomberg/presto,tomz/presto,toyama0919/presto,haozhun/presto,hgschmie/presto,tomz/presto,arhimondr/presto,prateek1306/presto,Yaliang/presto,mugglmenzel/presto,TeradataCenterForHadoop/bootcamp,prestodb/presto,idemura/presto,chrisunder/presto,EvilMcJerkface/presto,mvp/presto,treasure-data/presto,EvilMcJerkface/presto,aramesh117/presto,martint/presto,sopel39/presto,haozhun/presto,elonazoulay/presto,elonazoulay/presto,totticarter/presto,erichwang/presto,11xor6/presto,dabaitu/presto,aleph-zero/presto,cawallin/presto,ebd2/presto,twitter-forks/presto,Yaliang/presto,lingochamp/presto,mugglmenzel/presto,ebd2/presto,tomz/presto,nileema/presto,jf367/presto,ArturGajowy/presto,kietly/presto,facebook/presto,miniway/presto,mvp/presto,hgschmie/presto,prateek1306/presto,Praveen2112/presto,dain/presto,Praveen2112/presto,soz-fb/presto,cberner/presto,martint/presto,mode/presto,lingochamp/presto,Zoomdata/presto,harunurhan/presto
|
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.sql.gen;
import com.facebook.presto.bytecode.BytecodeBlock;
import com.facebook.presto.bytecode.BytecodeNode;
import com.facebook.presto.bytecode.ClassDefinition;
import com.facebook.presto.bytecode.FieldDefinition;
import com.facebook.presto.bytecode.MethodDefinition;
import com.facebook.presto.bytecode.Parameter;
import com.facebook.presto.bytecode.Scope;
import com.facebook.presto.bytecode.Variable;
import com.facebook.presto.bytecode.control.ForLoop;
import com.facebook.presto.bytecode.control.IfStatement;
import com.facebook.presto.bytecode.expression.BytecodeExpression;
import com.facebook.presto.bytecode.instruction.LabelNode;
import com.facebook.presto.metadata.Metadata;
import com.facebook.presto.operator.PageProcessor;
import com.facebook.presto.spi.ConnectorSession;
import com.facebook.presto.spi.Page;
import com.facebook.presto.spi.PageBuilder;
import com.facebook.presto.spi.block.Block;
import com.facebook.presto.spi.block.BlockBuilder;
import com.facebook.presto.spi.block.DictionaryBlock;
import com.facebook.presto.spi.block.LazyBlock;
import com.facebook.presto.spi.block.RunLengthEncodedBlock;
import com.facebook.presto.spi.type.Type;
import com.facebook.presto.sql.relational.CallExpression;
import com.facebook.presto.sql.relational.ConstantExpression;
import com.facebook.presto.sql.relational.Expressions;
import com.facebook.presto.sql.relational.InputReferenceExpression;
import com.facebook.presto.sql.relational.RowExpression;
import com.facebook.presto.sql.relational.RowExpressionVisitor;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.primitives.Primitives;
import io.airlift.slice.Slice;
import io.airlift.slice.Slices;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import static com.facebook.presto.bytecode.Access.FINAL;
import static com.facebook.presto.bytecode.Access.PRIVATE;
import static com.facebook.presto.bytecode.Access.PUBLIC;
import static com.facebook.presto.bytecode.Access.a;
import static com.facebook.presto.bytecode.Parameter.arg;
import static com.facebook.presto.bytecode.ParameterizedType.type;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.add;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.constantFalse;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.constantInt;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.constantNull;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.constantTrue;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.equal;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.invokeStatic;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.lessThan;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.multiply;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.newArray;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.newInstance;
import static com.facebook.presto.bytecode.instruction.JumpInstruction.jump;
import static com.facebook.presto.sql.gen.BytecodeUtils.generateWrite;
import static com.facebook.presto.sql.gen.BytecodeUtils.loadConstant;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Verify.verify;
import static com.google.common.collect.Iterables.concat;
import static io.airlift.slice.SizeOf.SIZE_OF_INT;
import static java.lang.String.format;
import static java.util.stream.Collectors.toList;
public class PageProcessorCompiler
implements BodyCompiler<PageProcessor>
{
private final Metadata metadata;
public PageProcessorCompiler(Metadata metadata)
{
this.metadata = metadata;
}
@Override
public void generateMethods(ClassDefinition classDefinition, CallSiteBinder callSiteBinder, RowExpression filter, List<RowExpression> projections)
{
CachedInstanceBinder cachedInstanceBinder = new CachedInstanceBinder(classDefinition, callSiteBinder);
ImmutableList.Builder<MethodDefinition> projectMethods = ImmutableList.builder();
ImmutableList.Builder<MethodDefinition> projectColumnarMethods = ImmutableList.builder();
ImmutableList.Builder<MethodDefinition> projectDictionaryMethods = ImmutableList.builder();
for (int i = 0; i < projections.size(); i++) {
MethodDefinition project = generateProjectMethod(classDefinition, callSiteBinder, cachedInstanceBinder, "project_" + i, projections.get(i));
MethodDefinition projectColumnar = generateProjectColumnarMethod(classDefinition, callSiteBinder, "projectColumnar_" + i, projections.get(i), project);
MethodDefinition projectDictionary = generateProjectDictionaryMethod(classDefinition, "projectDictionary_" + i, projections.get(i), project, projectColumnar);
projectMethods.add(project);
projectColumnarMethods.add(projectColumnar);
projectDictionaryMethods.add(projectDictionary);
}
List<MethodDefinition> projectMethodDefinitions = projectMethods.build();
List<MethodDefinition> projectColumnarMethodDefinitions = projectColumnarMethods.build();
List<MethodDefinition> projectDictionaryMethodDefinitions = projectDictionaryMethods.build();
generateProcessMethod(classDefinition, filter, projections, projectMethodDefinitions);
generateGetNonLazyPageMethod(classDefinition, filter, projections);
generateProcessColumnarMethod(classDefinition, projections, projectColumnarMethodDefinitions);
generateProcessColumnarDictionaryMethod(classDefinition, projections, projectColumnarMethodDefinitions, projectDictionaryMethodDefinitions);
generateFilterPageMethod(classDefinition, filter);
generateFilterMethod(classDefinition, callSiteBinder, cachedInstanceBinder, filter);
generateConstructor(classDefinition, cachedInstanceBinder, projections.size());
}
private static void generateConstructor(ClassDefinition classDefinition, CachedInstanceBinder cachedInstanceBinder, int projectionCount)
{
MethodDefinition constructorDefinition = classDefinition.declareConstructor(a(PUBLIC));
FieldDefinition inputDictionaries = classDefinition.declareField(a(PRIVATE, FINAL), "inputDictionaries", Block[].class);
FieldDefinition outputDictionaries = classDefinition.declareField(a(PRIVATE, FINAL), "outputDictionaries", Block[].class);
BytecodeBlock body = constructorDefinition.getBody();
Variable thisVariable = constructorDefinition.getThis();
body.comment("super();")
.append(thisVariable)
.invokeConstructor(Object.class);
body.append(thisVariable.setField(inputDictionaries, newArray(type(Block[].class), projectionCount)));
body.append(thisVariable.setField(outputDictionaries, newArray(type(Block[].class), projectionCount)));
cachedInstanceBinder.generateInitializations(thisVariable, body);
body.ret();
}
private static void generateProcessMethod(ClassDefinition classDefinition, RowExpression filter, List<RowExpression> projections, List<MethodDefinition> projectionMethods)
{
Parameter session = arg("session", ConnectorSession.class);
Parameter page = arg("page", Page.class);
Parameter start = arg("start", int.class);
Parameter end = arg("end", int.class);
Parameter pageBuilder = arg("pageBuilder", PageBuilder.class);
MethodDefinition method = classDefinition.declareMethod(a(PUBLIC), "process", type(int.class), session, page, start, end, pageBuilder);
Scope scope = method.getScope();
BytecodeBlock body = method.getBody();
Variable thisVariable = method.getThis();
// extract blocks
List<Integer> allInputChannels = getInputChannels(concat(projections, ImmutableList.of(filter)));
ImmutableMap.Builder<Integer, Variable> builder = ImmutableMap.builder();
for (int channel : allInputChannels) {
Variable blockVariable = scope.declareVariable("block_" + channel, body, page.invoke("getBlock", Block.class, constantInt(channel)));
builder.put(channel, blockVariable);
}
Map<Integer, Variable> channelBlocks = builder.build();
Map<RowExpression, List<Variable>> expressionInputBlocks = getExpressionInputBlocks(projections, filter, channelBlocks);
// projection body
Variable position = scope.declareVariable(int.class, "position");
BytecodeBlock project = new BytecodeBlock()
.append(pageBuilder.invoke("declarePosition", void.class));
for (int projectionIndex = 0; projectionIndex < projections.size(); projectionIndex++) {
RowExpression projection = projections.get(projectionIndex);
project.append(invokeProject(thisVariable, session, expressionInputBlocks.get(projection), position, pageBuilder, constantInt(projectionIndex), projectionMethods.get(projectionIndex)));
}
LabelNode done = new LabelNode("done");
// for loop loop body
ForLoop loop = new ForLoop()
.initialize(position.set(start))
.condition(lessThan(position, end))
.update(position.set(add(position, constantInt(1))))
.body(new BytecodeBlock()
.append(new IfStatement()
.condition(pageBuilder.invoke("isFull", boolean.class))
.ifTrue(jump(done)))
.append(new IfStatement()
.condition(invokeFilter(thisVariable, session, expressionInputBlocks.get(filter), position))
.ifTrue(project)));
body
.append(loop)
.visitLabel(done)
.append(position.ret());
}
private static void generateProcessColumnarMethod(
ClassDefinition classDefinition,
List<RowExpression> projections,
List<MethodDefinition> projectColumnarMethods)
{
Parameter session = arg("session", ConnectorSession.class);
Parameter page = arg("page", Page.class);
Parameter types = arg("types", List.class);
MethodDefinition method = classDefinition.declareMethod(a(PUBLIC), "processColumnar", type(Page.class), session, page, types);
Scope scope = method.getScope();
BytecodeBlock body = method.getBody();
Variable thisVariable = method.getThis();
Variable selectedPositions = scope.declareVariable("selectedPositions", body, thisVariable.invoke("filterPage", int[].class, session, page));
Variable cardinality = scope.declareVariable("cardinality", body, selectedPositions.length());
body.comment("if no rows selected return null")
.append(new IfStatement()
.condition(equal(cardinality, constantInt(0)))
.ifTrue(constantNull(Page.class).ret()));
if (projections.isEmpty()) {
// if no projections, return new page with selected rows
body.append(newInstance(Page.class, cardinality, newArray(type(Block[].class), 0)).ret());
return;
}
Variable pageBuilder = scope.declareVariable("pageBuilder", body, newInstance(PageBuilder.class, cardinality, types));
Variable outputBlocks = scope.declareVariable("outputBlocks", body, newArray(type(Block[].class), projections.size()));
for (int projectionIndex = 0; projectionIndex < projections.size(); projectionIndex++) {
List<BytecodeExpression> params = ImmutableList.<BytecodeExpression>builder()
.add(session)
.add(page)
.add(selectedPositions)
.add(pageBuilder)
.add(constantInt(projectionIndex))
.build();
body.append(outputBlocks.setElement(projectionIndex, thisVariable.invoke(projectColumnarMethods.get(projectionIndex), params)));
}
// create new page from outputBlocks
body.append(newInstance(Page.class, cardinality, outputBlocks).ret());
}
private static MethodDefinition generateProjectColumnarMethod(
ClassDefinition classDefinition,
CallSiteBinder callSiteBinder,
String methodName,
RowExpression projection,
MethodDefinition projectionMethod)
{
Parameter session = arg("session", ConnectorSession.class);
Parameter page = arg("page", Page.class);
Parameter selectedPositions = arg("selectedPositions", int[].class);
Parameter pageBuilder = arg("pageBuilder", PageBuilder.class);
Parameter projectionIndex = arg("projectionIndex", int.class);
List<Parameter> params = ImmutableList.<Parameter>builder()
.add(session)
.add(page)
.add(selectedPositions)
.add(pageBuilder)
.add(projectionIndex)
.build();
MethodDefinition method = classDefinition.declareMethod(a(PRIVATE), methodName, type(Block.class), params);
BytecodeBlock body = method.getBody();
Scope scope = method.getScope();
Variable thisVariable = method.getThis();
ImmutableList.Builder<Variable> builder = ImmutableList.<Variable>builder();
for (int channel : getInputChannels(projection)) {
Variable blockVariable = scope.declareVariable("block_" + channel, body, page.invoke("getBlock", Block.class, constantInt(channel)));
builder.add(blockVariable);
}
List<Variable> inputs = builder.build();
Variable positionCount = scope.declareVariable("positionCount", body, page.invoke("getPositionCount", int.class));
Variable position = scope.declareVariable("position", body, constantInt(0));
Variable cardinality = scope.declareVariable("cardinality", body, selectedPositions.length());
Variable outputBlock = scope.declareVariable(Block.class, "outputBlock");
Variable blockBuilder = scope.declareVariable("blockBuilder", body, pageBuilder.invoke("getBlockBuilder", BlockBuilder.class, projectionIndex));
Variable type = scope.declareVariable("type", body, pageBuilder.invoke("getType", Type.class, projectionIndex));
BytecodeBlock projectBlock = new BytecodeBlock()
.append(new ForLoop()
.initialize(position.set(constantInt(0)))
.condition(lessThan(position, cardinality))
.update(position.increment())
.body(invokeProject(
thisVariable,
session,
inputs,
selectedPositions.getElement(position),
pageBuilder,
projectionIndex,
projectionMethod)))
.append(outputBlock.set(blockBuilder.invoke("build", Block.class)));
if (isIdentityExpression(projection)) {
// if nothing is filtered out, copy the entire block, else project it
body.append(new IfStatement()
.condition(equal(cardinality, positionCount))
.ifTrue(outputBlock.set(inputs.get(0)))
.ifFalse(projectBlock));
}
else if (isConstantExpression(projection)) {
// if projection is a constant, create RLE block of constant expression with cardinality positions
ConstantExpression constantExpression = (ConstantExpression) projection;
verify(getInputChannels(projection).isEmpty());
BytecodeExpression value = loadConstant(callSiteBinder, constantExpression.getValue(), Object.class);
body.append(outputBlock.set(invokeStatic(RunLengthEncodedBlock.class, "create", Block.class, type, value, cardinality)));
}
else {
body.append(projectBlock);
}
body.append(outputBlock.ret());
return method;
}
private static MethodDefinition generateProjectDictionaryMethod(
ClassDefinition classDefinition,
String methodName,
RowExpression projection,
MethodDefinition project,
MethodDefinition projectColumnar)
{
Parameter session = arg("session", ConnectorSession.class);
Parameter page = arg("page", Page.class);
Parameter selectedPositions = arg("selectedPositions", int[].class);
Parameter pageBuilder = arg("pageBuilder", PageBuilder.class);
Parameter projectionIndex = arg("projectionIndex", int.class);
List<Parameter> params = ImmutableList.<Parameter>builder()
.add(session)
.add(page)
.add(selectedPositions)
.add(pageBuilder)
.add(projectionIndex)
.build();
MethodDefinition method = classDefinition.declareMethod(a(PRIVATE), methodName, type(Block.class), params);
BytecodeBlock body = method.getBody();
Scope scope = method.getScope();
Variable thisVariable = method.getThis();
List<Integer> inputChannels = getInputChannels(projection);
if (inputChannels.size() != 1) {
body.append(thisVariable.invoke(projectColumnar, params).ret());
return method;
}
Variable inputBlock = scope.declareVariable("inputBlock", body, page.invoke("getBlock", Block.class, constantInt(Iterables.getOnlyElement(inputChannels))));
IfStatement ifStatement = new IfStatement()
.condition(inputBlock.instanceOf(DictionaryBlock.class))
.ifFalse(thisVariable.invoke(projectColumnar, params).ret());
body.append(ifStatement);
Variable blockBuilder = scope.declareVariable("blockBuilder", body, pageBuilder.invoke("getBlockBuilder", BlockBuilder.class, projectionIndex));
Variable cardinality = scope.declareVariable("cardinality", body, selectedPositions.length());
Variable dictionary = scope.declareVariable(Block.class, "dictionary");
Variable ids = scope.declareVariable(Slice.class, "ids");
Variable dictionaryCount = scope.declareVariable(int.class, "dictionaryCount");
Variable outputDictionary = scope.declareVariable(Block.class, "outputDictionary");
Variable outputIds = scope.declareVariable(int[].class, "outputIds");
BytecodeExpression inputDictionaries = thisVariable.getField("inputDictionaries", Block[].class);
BytecodeExpression outputDictionaries = thisVariable.getField("outputDictionaries", Block[].class);
Variable position = scope.declareVariable("position", body, constantInt(0));
body.comment("Extract dictionary and ids")
.append(dictionary.set(inputBlock.cast(DictionaryBlock.class).invoke("getDictionary", Block.class)))
.append(ids.set(inputBlock.cast(DictionaryBlock.class).invoke("getIds", Slice.class)))
.append(dictionaryCount.set(dictionary.invoke("getPositionCount", int.class)));
BytecodeBlock projectDictionary = new BytecodeBlock()
.comment("Project dictionary")
.append(new ForLoop()
.initialize(position.set(constantInt(0)))
.condition(lessThan(position, dictionaryCount))
.update(position.increment())
.body(invokeProject(thisVariable, session, ImmutableList.of(dictionary), position, pageBuilder, projectionIndex, project)))
.append(outputDictionary.set(blockBuilder.invoke("build", Block.class)))
.append(inputDictionaries.setElement(projectionIndex, dictionary))
.append(outputDictionaries.setElement(projectionIndex, outputDictionary));
body.comment("Use processed dictionary, if available, else project it")
.append(
new IfStatement()
.condition(equal(inputDictionaries.getElement(projectionIndex), dictionary))
.ifTrue(outputDictionary.set(outputDictionaries.getElement(projectionIndex)))
.ifFalse(projectDictionary));
body.comment("Filter ids")
.append(outputIds.set(newArray(type(int[].class), cardinality)))
.append(new ForLoop()
.initialize(position.set(constantInt(0)))
.condition(lessThan(position, cardinality))
.update(position.increment())
.body(outputIds.setElement(position, ids.invoke("getInt", int.class, multiply(selectedPositions.getElement(position), constantInt(SIZE_OF_INT))))));
body.append(newInstance(DictionaryBlock.class, cardinality, outputDictionary, invokeStatic(Slices.class, "wrappedIntArray", Slice.class, outputIds)).cast(Block.class).ret());
return method;
}
private static void generateProcessColumnarDictionaryMethod(
ClassDefinition classDefinition,
List<RowExpression> projections,
List<MethodDefinition> projectColumnarMethods,
List<MethodDefinition> projectDictionaryMethods)
{
Parameter session = arg("session", ConnectorSession.class);
Parameter page = arg("page", Page.class);
Parameter types = arg("types", List.class);
MethodDefinition method = classDefinition.declareMethod(a(PUBLIC), "processColumnarDictionary", type(Page.class), session, page, types);
Scope scope = method.getScope();
BytecodeBlock body = method.getBody();
Variable thisVariable = method.getThis();
Variable selectedPositions = scope.declareVariable("selectedPositions", body, thisVariable.invoke("filterPage", int[].class, session, page));
Variable cardinality = scope.declareVariable("cardinality", body, selectedPositions.length());
body.comment("if no rows selected return null")
.append(new IfStatement()
.condition(equal(cardinality, constantInt(0)))
.ifTrue(constantNull(Page.class).ret()));
if (projectColumnarMethods.isEmpty()) {
// if no projections, return new page with selected rows
body.append(newInstance(Page.class, cardinality, newArray(type(Block[].class), 0)).ret());
return;
}
// create PageBuilder
Variable pageBuilder = scope.declareVariable("pageBuilder", body, newInstance(PageBuilder.class, cardinality, types));
body.append(page.set(thisVariable.invoke("getNonLazyPage", Page.class, page)));
// create outputBlocks
Variable outputBlocks = scope.declareVariable("outputBlocks", body, newArray(type(Block[].class), projections.size()));
for (int projectionIndex = 0; projectionIndex < projections.size(); projectionIndex++) {
List<BytecodeExpression> params = ImmutableList.<BytecodeExpression>builder()
.add(session)
.add(page)
.add(selectedPositions)
.add(pageBuilder)
.add(constantInt(projectionIndex))
.build();
body.append(outputBlocks.setElement(projectionIndex, thisVariable.invoke(projectDictionaryMethods.get(projectionIndex), params)));
}
body.append(newInstance(Page.class, cardinality, outputBlocks).ret());
}
private static void generateGetNonLazyPageMethod(ClassDefinition classDefinition, RowExpression filter, List<RowExpression> projections)
{
Parameter page = arg("page", Page.class);
MethodDefinition method = classDefinition.declareMethod(a(PRIVATE), "getNonLazyPage", type(Page.class), page);
Scope scope = method.getScope();
BytecodeBlock body = method.getBody();
List<Integer> allInputChannels = getInputChannels(concat(projections, ImmutableList.of(filter)));
if (allInputChannels.isEmpty()) {
body.append(page.ret());
return;
}
Variable index = scope.declareVariable(int.class, "index");
Variable channelCount = scope.declareVariable("channelCount", body, page.invoke("getChannelCount", int.class));
Variable blocks = scope.declareVariable("blocks", body, newArray(type(Block[].class), channelCount));
Variable inputBlock = scope.declareVariable(Block.class, "inputBlock");
Variable positionCount = scope.declareVariable("positionCount", body, page.invoke("getPositionCount", int.class));
Variable createNewPage = scope.declareVariable("createNewPage", body, constantFalse());
ForLoop forLoop = new ForLoop()
.initialize(index.set(constantInt(0)))
.condition(lessThan(index, channelCount))
.update(index.increment())
.body(new BytecodeBlock()
.append(inputBlock.set(page.invoke("getBlock", Block.class, index)))
.append(new IfStatement()
.condition(inputBlock.instanceOf(LazyBlock.class))
.ifTrue(new BytecodeBlock()
.append(blocks.setElement(index, inputBlock.cast(LazyBlock.class).invoke("getBlock", Block.class)))
.append(createNewPage.set(constantTrue())))
.ifFalse(blocks.setElement(index, inputBlock))));
body.append(forLoop);
body.append(new IfStatement()
.condition(createNewPage)
.ifTrue(page.set(newInstance(Page.class, positionCount, blocks))));
body.append(page.ret());
}
private static void generateFilterPageMethod(ClassDefinition classDefinition, RowExpression filter)
{
Parameter session = arg("session", ConnectorSession.class);
Parameter page = arg("page", Page.class);
MethodDefinition method = classDefinition.declareMethod(a(PUBLIC), "filterPage", type(int[].class), session, page);
method.comment("Filter: %s rows in the page", filter.toString());
Scope scope = method.getScope();
Variable thisVariable = method.getThis();
BytecodeBlock body = method.getBody();
Variable positionCount = scope.declareVariable("positionCount", body, page.invoke("getPositionCount", int.class));
Variable selectedPositions = scope.declareVariable("selectedPositions", body, newArray(type(int[].class), positionCount));
List<Integer> filterChannels = getInputChannels(filter);
// extract block variables
ImmutableList.Builder<Variable> blockVariablesBuilder = ImmutableList.<Variable>builder();
for (int channel : filterChannels) {
Variable blockVariable = scope.declareVariable("block_" + channel, body, page.invoke("getBlock", Block.class, constantInt(channel)));
blockVariablesBuilder.add(blockVariable);
}
List<Variable> blockVariables = blockVariablesBuilder.build();
Variable selectedCount = scope.declareVariable("selectedCount", body, constantInt(0));
Variable position = scope.declareVariable(int.class, "position");
IfStatement ifStatement = new IfStatement();
ifStatement.condition(invokeFilter(thisVariable, session, blockVariables, position))
.ifTrue()
.append(selectedPositions.setElement(selectedCount, position))
.append(selectedCount.increment());
body.append(new ForLoop()
.initialize(position.set(constantInt(0)))
.condition(lessThan(position, positionCount))
.update(position.increment())
.body(ifStatement));
body.append(invokeStatic(Arrays.class, "copyOf", int[].class, selectedPositions, selectedCount).ret());
}
private void generateFilterMethod(ClassDefinition classDefinition, CallSiteBinder callSiteBinder, CachedInstanceBinder cachedInstanceBinder, RowExpression filter)
{
Parameter session = arg("session", ConnectorSession.class);
Parameter position = arg("position", int.class);
List<Parameter> blocks = toBlockParameters(getInputChannels(filter));
MethodDefinition method = classDefinition.declareMethod(
a(PUBLIC),
"filter",
type(boolean.class),
ImmutableList.<Parameter>builder()
.add(session)
.addAll(blocks)
.add(position)
.build());
method.comment("Filter: %s", filter.toString());
BytecodeBlock body = method.getBody();
Scope scope = method.getScope();
Variable wasNullVariable = scope.declareVariable("wasNull", body, constantFalse());
BytecodeExpressionVisitor visitor = new BytecodeExpressionVisitor(
callSiteBinder,
cachedInstanceBinder,
fieldReferenceCompiler(callSiteBinder, position, wasNullVariable),
metadata.getFunctionRegistry());
BytecodeNode visitorBody = filter.accept(visitor, scope);
Variable result = scope.declareVariable(boolean.class, "result");
body.append(visitorBody)
.putVariable(result)
.append(new IfStatement()
.condition(wasNullVariable)
.ifTrue(constantFalse().ret())
.ifFalse(result.ret()));
}
private MethodDefinition generateProjectMethod(ClassDefinition classDefinition, CallSiteBinder callSiteBinder, CachedInstanceBinder cachedInstanceBinder, String methodName, RowExpression projection)
{
Parameter session = arg("session", ConnectorSession.class);
List<Parameter> inputs = toBlockParameters(getInputChannels(projection));
Parameter position = arg("position", int.class);
Parameter output = arg("output", BlockBuilder.class);
MethodDefinition method = classDefinition.declareMethod(
a(PUBLIC),
methodName,
type(void.class),
ImmutableList.<Parameter>builder()
.add(session)
.addAll(inputs)
.add(position)
.add(output)
.build());
method.comment("Projection: %s", projection.toString());
Scope scope = method.getScope();
BytecodeBlock body = method.getBody();
Variable wasNullVariable = scope.declareVariable("wasNull", body, constantFalse());
BytecodeExpressionVisitor visitor = new BytecodeExpressionVisitor(callSiteBinder, cachedInstanceBinder, fieldReferenceCompiler(callSiteBinder, position, wasNullVariable), metadata.getFunctionRegistry());
body.getVariable(output)
.comment("evaluate projection: " + projection.toString())
.append(projection.accept(visitor, scope))
.append(generateWrite(callSiteBinder, scope, wasNullVariable, projection.getType()))
.ret();
return method;
}
private static boolean isIdentityExpression(RowExpression expression)
{
List<RowExpression> rowExpressions = Expressions.subExpressions(ImmutableList.of(expression));
return rowExpressions.size() == 1 && Iterables.getOnlyElement(rowExpressions) instanceof InputReferenceExpression;
}
private static boolean isConstantExpression(RowExpression expression)
{
List<RowExpression> rowExpressions = Expressions.subExpressions(ImmutableList.of(expression));
return rowExpressions.size() == 1 &&
Iterables.getOnlyElement(rowExpressions) instanceof ConstantExpression &&
((ConstantExpression) Iterables.getOnlyElement(rowExpressions)).getValue() != null;
}
private static List<Integer> getInputChannels(Iterable<RowExpression> expressions)
{
TreeSet<Integer> channels = new TreeSet<>();
for (RowExpression expression : Expressions.subExpressions(expressions)) {
if (expression instanceof InputReferenceExpression) {
channels.add(((InputReferenceExpression) expression).getField());
}
}
return ImmutableList.copyOf(channels);
}
private static List<Integer> getInputChannels(RowExpression expression)
{
return getInputChannels(ImmutableList.of(expression));
}
private static List<Parameter> toBlockParameters(List<Integer> inputChannels)
{
ImmutableList.Builder<Parameter> parameters = ImmutableList.builder();
for (int channel : inputChannels) {
parameters.add(arg("block_" + channel, Block.class));
}
return parameters.build();
}
private static RowExpressionVisitor<Scope, BytecodeNode> fieldReferenceCompiler(final CallSiteBinder callSiteBinder, final Variable positionVariable, final Variable wasNullVariable)
{
return new RowExpressionVisitor<Scope, BytecodeNode>()
{
@Override
public BytecodeNode visitInputReference(InputReferenceExpression node, Scope scope)
{
int field = node.getField();
Type type = node.getType();
Variable block = scope.getVariable("block_" + field);
Class<?> javaType = type.getJavaType();
if (!javaType.isPrimitive() && javaType != Slice.class) {
javaType = Object.class;
}
IfStatement ifStatement = new IfStatement();
ifStatement.condition()
.setDescription(format("block_%d.get%s()", field, type))
.append(block)
.getVariable(positionVariable)
.invokeInterface(Block.class, "isNull", boolean.class, int.class);
ifStatement.ifTrue()
.putVariable(wasNullVariable, true)
.pushJavaDefault(javaType);
String methodName = "get" + Primitives.wrap(javaType).getSimpleName();
ifStatement.ifFalse()
.append(loadConstant(callSiteBinder.bind(type, Type.class)))
.append(block)
.getVariable(positionVariable)
.invokeInterface(Type.class, methodName, javaType, Block.class, int.class);
return ifStatement;
}
@Override
public BytecodeNode visitCall(CallExpression call, Scope scope)
{
throw new UnsupportedOperationException("not yet implemented");
}
@Override
public BytecodeNode visitConstant(ConstantExpression literal, Scope scope)
{
throw new UnsupportedOperationException("not yet implemented");
}
};
}
private static Map<RowExpression, List<Variable>> getExpressionInputBlocks(List<RowExpression> projections, RowExpression filter, Map<Integer, Variable> channelBlock)
{
Map<RowExpression, List<Variable>> inputBlocksBuilder = new HashMap<>();
for (RowExpression projection : projections) {
List<Variable> inputBlocks = getInputChannels(projection).stream()
.map(channelBlock::get)
.collect(toList());
List<Variable> existingVariables = inputBlocksBuilder.get(projection);
// Constant expressions or expressions that are reused, should reference the same input blocks
checkState(existingVariables == null || existingVariables.equals(inputBlocks), "malformed RowExpression");
inputBlocksBuilder.put(projection, inputBlocks);
}
List<Variable> filterBlocks = getInputChannels(filter).stream()
.map(channelBlock::get)
.collect(toList());
inputBlocksBuilder.put(filter, filterBlocks);
return inputBlocksBuilder;
}
private static BytecodeExpression invokeFilter(BytecodeExpression objRef, BytecodeExpression session, List<? extends BytecodeExpression> blockVariables, BytecodeExpression position)
{
List<BytecodeExpression> params = ImmutableList.<BytecodeExpression>builder()
.add(session)
.addAll(blockVariables)
.add(position)
.build();
return objRef.invoke("filter", boolean.class, params);
}
private static BytecodeNode invokeProject(
Variable objRef,
Variable session,
List<? extends Variable> blockVariables,
BytecodeExpression position,
Variable pageBuilder,
BytecodeExpression projectionIndex,
MethodDefinition projectionMethod)
{
BytecodeExpression blockBuilder = pageBuilder.invoke("getBlockBuilder", BlockBuilder.class, projectionIndex);
List<BytecodeExpression> params = ImmutableList.<BytecodeExpression>builder()
.add(session)
.addAll(blockVariables)
.add(position)
.add(blockBuilder)
.build();
return new BytecodeBlock().append(objRef.invoke(projectionMethod, params));
}
}
|
presto-main/src/main/java/com/facebook/presto/sql/gen/PageProcessorCompiler.java
|
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.sql.gen;
import com.facebook.presto.bytecode.BytecodeBlock;
import com.facebook.presto.bytecode.BytecodeNode;
import com.facebook.presto.bytecode.ClassDefinition;
import com.facebook.presto.bytecode.FieldDefinition;
import com.facebook.presto.bytecode.MethodDefinition;
import com.facebook.presto.bytecode.Parameter;
import com.facebook.presto.bytecode.Scope;
import com.facebook.presto.bytecode.Variable;
import com.facebook.presto.bytecode.control.ForLoop;
import com.facebook.presto.bytecode.control.IfStatement;
import com.facebook.presto.bytecode.expression.BytecodeExpression;
import com.facebook.presto.bytecode.instruction.LabelNode;
import com.facebook.presto.metadata.Metadata;
import com.facebook.presto.operator.PageProcessor;
import com.facebook.presto.spi.ConnectorSession;
import com.facebook.presto.spi.Page;
import com.facebook.presto.spi.PageBuilder;
import com.facebook.presto.spi.block.Block;
import com.facebook.presto.spi.block.BlockBuilder;
import com.facebook.presto.spi.block.DictionaryBlock;
import com.facebook.presto.spi.block.LazyBlock;
import com.facebook.presto.spi.block.RunLengthEncodedBlock;
import com.facebook.presto.spi.type.Type;
import com.facebook.presto.sql.relational.CallExpression;
import com.facebook.presto.sql.relational.ConstantExpression;
import com.facebook.presto.sql.relational.Expressions;
import com.facebook.presto.sql.relational.InputReferenceExpression;
import com.facebook.presto.sql.relational.RowExpression;
import com.facebook.presto.sql.relational.RowExpressionVisitor;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.primitives.Primitives;
import io.airlift.slice.Slice;
import io.airlift.slice.Slices;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import static com.facebook.presto.bytecode.Access.FINAL;
import static com.facebook.presto.bytecode.Access.PRIVATE;
import static com.facebook.presto.bytecode.Access.PUBLIC;
import static com.facebook.presto.bytecode.Access.a;
import static com.facebook.presto.bytecode.Parameter.arg;
import static com.facebook.presto.bytecode.ParameterizedType.type;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.add;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.constantFalse;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.constantInt;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.constantNull;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.constantTrue;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.equal;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.invokeStatic;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.lessThan;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.multiply;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.newArray;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.newInstance;
import static com.facebook.presto.bytecode.instruction.JumpInstruction.jump;
import static com.facebook.presto.sql.gen.BytecodeUtils.generateWrite;
import static com.facebook.presto.sql.gen.BytecodeUtils.loadConstant;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Verify.verify;
import static com.google.common.collect.Iterables.concat;
import static io.airlift.slice.SizeOf.SIZE_OF_INT;
import static java.lang.String.format;
import static java.util.stream.Collectors.toList;
public class PageProcessorCompiler
implements BodyCompiler<PageProcessor>
{
private final Metadata metadata;
public PageProcessorCompiler(Metadata metadata)
{
this.metadata = metadata;
}
@Override
public void generateMethods(ClassDefinition classDefinition, CallSiteBinder callSiteBinder, RowExpression filter, List<RowExpression> projections)
{
CachedInstanceBinder cachedInstanceBinder = new CachedInstanceBinder(classDefinition, callSiteBinder);
ImmutableList.Builder<MethodDefinition> projectMethods = ImmutableList.builder();
ImmutableList.Builder<MethodDefinition> projectColumnarMethods = ImmutableList.builder();
ImmutableList.Builder<MethodDefinition> projectDictionaryMethods = ImmutableList.builder();
for (int i = 0; i < projections.size(); i++) {
MethodDefinition project = generateProjectMethod(classDefinition, callSiteBinder, cachedInstanceBinder, "project_" + i, projections.get(i));
MethodDefinition projectColumnar = generateProjectColumnarMethod(classDefinition, callSiteBinder, "projectColumnar_" + i, projections.get(i), project);
MethodDefinition projectDictionary = generateProjectDictionaryMethod(classDefinition, "projectDictionary_" + i, projections.get(i), project, projectColumnar);
projectMethods.add(project);
projectColumnarMethods.add(projectColumnar);
projectDictionaryMethods.add(projectDictionary);
}
List<MethodDefinition> projectMethodDefinitions = projectMethods.build();
List<MethodDefinition> projectColumnarMethodDefinitions = projectColumnarMethods.build();
List<MethodDefinition> projectDictionaryMethodDefinitions = projectDictionaryMethods.build();
generateProcessMethod(classDefinition, filter, projections, projectMethodDefinitions);
generateGetNonLazyPageMethod(classDefinition, filter, projections);
generateProcessColumnarMethod(classDefinition, projections, projectColumnarMethodDefinitions);
generateProcessColumnarDictionaryMethod(classDefinition, projections, projectColumnarMethodDefinitions, projectDictionaryMethodDefinitions);
generateFilterPageMethod(classDefinition, filter);
generateFilterMethod(classDefinition, callSiteBinder, cachedInstanceBinder, filter);
generateConstructor(classDefinition, cachedInstanceBinder, projections.size());
}
private static void generateConstructor(ClassDefinition classDefinition, CachedInstanceBinder cachedInstanceBinder, int projectionCount)
{
MethodDefinition constructorDefinition = classDefinition.declareConstructor(a(PUBLIC));
FieldDefinition inputDictionaries = classDefinition.declareField(a(PRIVATE, FINAL), "inputDictionaries", Block[].class);
FieldDefinition outputDictionaries = classDefinition.declareField(a(PRIVATE, FINAL), "outputDictionaries", Block[].class);
BytecodeBlock body = constructorDefinition.getBody();
Variable thisVariable = constructorDefinition.getThis();
body.comment("super();")
.append(thisVariable)
.invokeConstructor(Object.class);
body.append(thisVariable.setField(inputDictionaries, newArray(type(Block[].class), projectionCount)));
body.append(thisVariable.setField(outputDictionaries, newArray(type(Block[].class), projectionCount)));
cachedInstanceBinder.generateInitializations(thisVariable, body);
body.ret();
}
private static void generateProcessMethod(ClassDefinition classDefinition, RowExpression filter, List<RowExpression> projections, List<MethodDefinition> projectionMethods)
{
Parameter session = arg("session", ConnectorSession.class);
Parameter page = arg("page", Page.class);
Parameter start = arg("start", int.class);
Parameter end = arg("end", int.class);
Parameter pageBuilder = arg("pageBuilder", PageBuilder.class);
MethodDefinition method = classDefinition.declareMethod(a(PUBLIC), "process", type(int.class), session, page, start, end, pageBuilder);
Scope scope = method.getScope();
BytecodeBlock body = method.getBody();
Variable thisVariable = method.getThis();
// extract blocks
List<Integer> allInputChannels = getInputChannels(concat(projections, ImmutableList.of(filter)));
ImmutableMap.Builder<Integer, Variable> builder = ImmutableMap.builder();
for (int channel : allInputChannels) {
Variable blockVariable = scope.declareVariable("block_" + channel, body, page.invoke("getBlock", Block.class, constantInt(channel)));
builder.put(channel, blockVariable);
}
Map<Integer, Variable> channelBlocks = builder.build();
Map<RowExpression, List<Variable>> expressionInputBlocks = getExpressionInputBlocks(projections, filter, channelBlocks);
// extract block builders
ImmutableList.Builder<Variable> variableBuilder = ImmutableList.<Variable>builder();
for (int projectionIndex = 0; projectionIndex < projections.size(); projectionIndex++) {
Variable blockBuilder = scope.declareVariable("blockBuilder_" + projectionIndex, body, pageBuilder.invoke("getBlockBuilder", BlockBuilder.class, constantInt(projectionIndex)));
variableBuilder.add(blockBuilder);
}
List<Variable> blockBuilders = variableBuilder.build();
// projection body
Variable position = scope.declareVariable(int.class, "position");
BytecodeBlock project = new BytecodeBlock()
.append(pageBuilder.invoke("declarePosition", void.class));
for (int projectionIndex = 0; projectionIndex < projections.size(); projectionIndex++) {
RowExpression projection = projections.get(projectionIndex);
project.append(invokeProject(thisVariable, session, expressionInputBlocks.get(projection), position, blockBuilders.get(projectionIndex), projectionMethods.get(projectionIndex)));
}
LabelNode done = new LabelNode("done");
// for loop loop body
ForLoop loop = new ForLoop()
.initialize(position.set(start))
.condition(lessThan(position, end))
.update(position.set(add(position, constantInt(1))))
.body(new BytecodeBlock()
.append(new IfStatement()
.condition(pageBuilder.invoke("isFull", boolean.class))
.ifTrue(jump(done)))
.append(new IfStatement()
.condition(invokeFilter(thisVariable, session, expressionInputBlocks.get(filter), position))
.ifTrue(project)));
body
.append(loop)
.visitLabel(done)
.append(position.ret());
}
private static void generateProcessColumnarMethod(
ClassDefinition classDefinition,
List<RowExpression> projections,
List<MethodDefinition> projectColumnarMethods)
{
Parameter session = arg("session", ConnectorSession.class);
Parameter page = arg("page", Page.class);
Parameter types = arg("types", List.class);
MethodDefinition method = classDefinition.declareMethod(a(PUBLIC), "processColumnar", type(Page.class), session, page, types);
Scope scope = method.getScope();
BytecodeBlock body = method.getBody();
Variable thisVariable = method.getThis();
Variable selectedPositions = scope.declareVariable("selectedPositions", body, thisVariable.invoke("filterPage", int[].class, session, page));
Variable cardinality = scope.declareVariable("cardinality", body, selectedPositions.length());
body.comment("if no rows selected return null")
.append(new IfStatement()
.condition(equal(cardinality, constantInt(0)))
.ifTrue(constantNull(Page.class).ret()));
if (projections.isEmpty()) {
// if no projections, return new page with selected rows
body.append(newInstance(Page.class, cardinality, newArray(type(Block[].class), 0)).ret());
return;
}
Variable pageBuilder = scope.declareVariable("pageBuilder", body, newInstance(PageBuilder.class, cardinality, types));
Variable outputBlocks = scope.declareVariable("outputBlocks", body, newArray(type(Block[].class), projections.size()));
for (int projectionIndex = 0; projectionIndex < projections.size(); projectionIndex++) {
List<BytecodeExpression> params = ImmutableList.<BytecodeExpression>builder()
.add(session)
.add(page)
.add(selectedPositions)
.add(pageBuilder)
.add(constantInt(projectionIndex))
.build();
body.append(outputBlocks.setElement(projectionIndex, thisVariable.invoke(projectColumnarMethods.get(projectionIndex), params)));
}
// create new page from outputBlocks
body.append(newInstance(Page.class, cardinality, outputBlocks).ret());
}
private static MethodDefinition generateProjectColumnarMethod(
ClassDefinition classDefinition,
CallSiteBinder callSiteBinder,
String methodName,
RowExpression projection,
MethodDefinition projectionMethod)
{
Parameter session = arg("session", ConnectorSession.class);
Parameter page = arg("page", Page.class);
Parameter selectedPositions = arg("selectedPositions", int[].class);
Parameter pageBuilder = arg("pageBuilder", PageBuilder.class);
Parameter projectionIndex = arg("projectionIndex", int.class);
List<Parameter> params = ImmutableList.<Parameter>builder()
.add(session)
.add(page)
.add(selectedPositions)
.add(pageBuilder)
.add(projectionIndex)
.build();
MethodDefinition method = classDefinition.declareMethod(a(PRIVATE), methodName, type(Block.class), params);
BytecodeBlock body = method.getBody();
Scope scope = method.getScope();
Variable thisVariable = method.getThis();
ImmutableList.Builder<Variable> builder = ImmutableList.<Variable>builder();
for (int channel : getInputChannels(projection)) {
Variable blockVariable = scope.declareVariable("block_" + channel, body, page.invoke("getBlock", Block.class, constantInt(channel)));
builder.add(blockVariable);
}
List<Variable> inputs = builder.build();
Variable positionCount = scope.declareVariable("positionCount", body, page.invoke("getPositionCount", int.class));
Variable position = scope.declareVariable("position", body, constantInt(0));
Variable cardinality = scope.declareVariable("cardinality", body, selectedPositions.length());
Variable outputBlock = scope.declareVariable(Block.class, "outputBlock");
Variable blockBuilder = scope.declareVariable("blockBuilder", body, pageBuilder.invoke("getBlockBuilder", BlockBuilder.class, projectionIndex));
Variable type = scope.declareVariable("type", body, pageBuilder.invoke("getType", Type.class, projectionIndex));
BytecodeBlock projectBlock = new BytecodeBlock()
.append(new ForLoop()
.initialize(position.set(constantInt(0)))
.condition(lessThan(position, cardinality))
.update(position.increment())
.body(invokeProject(
thisVariable,
session,
inputs,
selectedPositions.getElement(position),
blockBuilder,
projectionMethod)))
.append(outputBlock.set(blockBuilder.invoke("build", Block.class)));
if (isIdentityExpression(projection)) {
// if nothing is filtered out, copy the entire block, else project it
body.append(new IfStatement()
.condition(equal(cardinality, positionCount))
.ifTrue(outputBlock.set(inputs.get(0)))
.ifFalse(projectBlock));
}
else if (isConstantExpression(projection)) {
// if projection is a constant, create RLE block of constant expression with cardinality positions
ConstantExpression constantExpression = (ConstantExpression) projection;
verify(getInputChannels(projection).isEmpty());
BytecodeExpression value = loadConstant(callSiteBinder, constantExpression.getValue(), Object.class);
body.append(outputBlock.set(invokeStatic(RunLengthEncodedBlock.class, "create", Block.class, type, value, cardinality)));
}
else {
body.append(projectBlock);
}
body.append(outputBlock.ret());
return method;
}
private static MethodDefinition generateProjectDictionaryMethod(
ClassDefinition classDefinition,
String methodName,
RowExpression projection,
MethodDefinition project,
MethodDefinition projectColumnar)
{
Parameter session = arg("session", ConnectorSession.class);
Parameter page = arg("page", Page.class);
Parameter selectedPositions = arg("selectedPositions", int[].class);
Parameter pageBuilder = arg("pageBuilder", PageBuilder.class);
Parameter projectionIndex = arg("projectionIndex", int.class);
List<Parameter> params = ImmutableList.<Parameter>builder()
.add(session)
.add(page)
.add(selectedPositions)
.add(pageBuilder)
.add(projectionIndex)
.build();
MethodDefinition method = classDefinition.declareMethod(a(PRIVATE), methodName, type(Block.class), params);
BytecodeBlock body = method.getBody();
Scope scope = method.getScope();
Variable thisVariable = method.getThis();
List<Integer> inputChannels = getInputChannels(projection);
if (inputChannels.size() != 1) {
body.append(thisVariable.invoke(projectColumnar, params).ret());
return method;
}
Variable inputBlock = scope.declareVariable("inputBlock", body, page.invoke("getBlock", Block.class, constantInt(Iterables.getOnlyElement(inputChannels))));
IfStatement ifStatement = new IfStatement()
.condition(inputBlock.instanceOf(DictionaryBlock.class))
.ifFalse(thisVariable.invoke(projectColumnar, params).ret());
body.append(ifStatement);
Variable blockBuilder = scope.declareVariable("blockBuilder", body, pageBuilder.invoke("getBlockBuilder", BlockBuilder.class, projectionIndex));
Variable cardinality = scope.declareVariable("cardinality", body, selectedPositions.length());
Variable dictionary = scope.declareVariable(Block.class, "dictionary");
Variable ids = scope.declareVariable(Slice.class, "ids");
Variable dictionaryCount = scope.declareVariable(int.class, "dictionaryCount");
Variable outputDictionary = scope.declareVariable(Block.class, "outputDictionary");
Variable outputIds = scope.declareVariable(int[].class, "outputIds");
BytecodeExpression inputDictionaries = thisVariable.getField("inputDictionaries", Block[].class);
BytecodeExpression outputDictionaries = thisVariable.getField("outputDictionaries", Block[].class);
Variable position = scope.declareVariable("position", body, constantInt(0));
body.comment("Extract dictionary and ids")
.append(dictionary.set(inputBlock.cast(DictionaryBlock.class).invoke("getDictionary", Block.class)))
.append(ids.set(inputBlock.cast(DictionaryBlock.class).invoke("getIds", Slice.class)))
.append(dictionaryCount.set(dictionary.invoke("getPositionCount", int.class)));
BytecodeBlock projectDictionary = new BytecodeBlock()
.comment("Project dictionary")
.append(new ForLoop()
.initialize(position.set(constantInt(0)))
.condition(lessThan(position, dictionaryCount))
.update(position.increment())
.body(invokeProject(thisVariable, session, ImmutableList.of(dictionary), position, blockBuilder, project)))
.append(outputDictionary.set(blockBuilder.invoke("build", Block.class)))
.append(inputDictionaries.setElement(projectionIndex, dictionary))
.append(outputDictionaries.setElement(projectionIndex, outputDictionary));
body.comment("Use processed dictionary, if available, else project it")
.append(
new IfStatement()
.condition(equal(inputDictionaries.getElement(projectionIndex), dictionary))
.ifTrue(outputDictionary.set(outputDictionaries.getElement(projectionIndex)))
.ifFalse(projectDictionary));
body.comment("Filter ids")
.append(outputIds.set(newArray(type(int[].class), cardinality)))
.append(new ForLoop()
.initialize(position.set(constantInt(0)))
.condition(lessThan(position, cardinality))
.update(position.increment())
.body(outputIds.setElement(position, ids.invoke("getInt", int.class, multiply(selectedPositions.getElement(position), constantInt(SIZE_OF_INT))))));
body.append(newInstance(DictionaryBlock.class, cardinality, outputDictionary, invokeStatic(Slices.class, "wrappedIntArray", Slice.class, outputIds)).cast(Block.class).ret());
return method;
}
private static void generateProcessColumnarDictionaryMethod(
ClassDefinition classDefinition,
List<RowExpression> projections,
List<MethodDefinition> projectColumnarMethods,
List<MethodDefinition> projectDictionaryMethods)
{
Parameter session = arg("session", ConnectorSession.class);
Parameter page = arg("page", Page.class);
Parameter types = arg("types", List.class);
MethodDefinition method = classDefinition.declareMethod(a(PUBLIC), "processColumnarDictionary", type(Page.class), session, page, types);
Scope scope = method.getScope();
BytecodeBlock body = method.getBody();
Variable thisVariable = method.getThis();
Variable selectedPositions = scope.declareVariable("selectedPositions", body, thisVariable.invoke("filterPage", int[].class, session, page));
Variable cardinality = scope.declareVariable("cardinality", body, selectedPositions.length());
body.comment("if no rows selected return null")
.append(new IfStatement()
.condition(equal(cardinality, constantInt(0)))
.ifTrue(constantNull(Page.class).ret()));
if (projectColumnarMethods.isEmpty()) {
// if no projections, return new page with selected rows
body.append(newInstance(Page.class, cardinality, newArray(type(Block[].class), 0)).ret());
return;
}
// create PageBuilder
Variable pageBuilder = scope.declareVariable("pageBuilder", body, newInstance(PageBuilder.class, cardinality, types));
body.append(page.set(thisVariable.invoke("getNonLazyPage", Page.class, page)));
// create outputBlocks
Variable outputBlocks = scope.declareVariable("outputBlocks", body, newArray(type(Block[].class), projections.size()));
for (int projectionIndex = 0; projectionIndex < projections.size(); projectionIndex++) {
List<BytecodeExpression> params = ImmutableList.<BytecodeExpression>builder()
.add(session)
.add(page)
.add(selectedPositions)
.add(pageBuilder)
.add(constantInt(projectionIndex))
.build();
body.append(outputBlocks.setElement(projectionIndex, thisVariable.invoke(projectDictionaryMethods.get(projectionIndex), params)));
}
body.append(newInstance(Page.class, cardinality, outputBlocks).ret());
}
private static void generateGetNonLazyPageMethod(ClassDefinition classDefinition, RowExpression filter, List<RowExpression> projections)
{
Parameter page = arg("page", Page.class);
MethodDefinition method = classDefinition.declareMethod(a(PRIVATE), "getNonLazyPage", type(Page.class), page);
Scope scope = method.getScope();
BytecodeBlock body = method.getBody();
List<Integer> allInputChannels = getInputChannels(concat(projections, ImmutableList.of(filter)));
if (allInputChannels.isEmpty()) {
body.append(page.ret());
return;
}
ImmutableMap.Builder<Integer, Variable> builder = ImmutableMap.builder();
for (int channel : allInputChannels) {
Variable blockVariable = scope.declareVariable("block_" + channel, body, page.invoke("getBlock", Block.class, constantInt(channel)));
builder.put(channel, blockVariable);
}
Map<Integer, Variable> channelBlocks = builder.build();
Variable blocks = scope.declareVariable("blocks", body, page.invoke("getBlocks", Block[].class));
Variable positionCount = scope.declareVariable("positionCount", body, page.invoke("getPositionCount", int.class));
Variable createNewPage = scope.declareVariable("createNewPage", body, constantFalse());
for (Map.Entry<Integer, Variable> entry : channelBlocks.entrySet()) {
int channel = entry.getKey();
Variable inputBlock = entry.getValue();
IfStatement ifStmt = new IfStatement();
ifStmt.condition(inputBlock.instanceOf(LazyBlock.class))
.ifTrue()
.append(blocks.setElement(channel, inputBlock.cast(LazyBlock.class).invoke("getBlock", Block.class)))
.append(createNewPage.set(constantTrue()));
body.append(ifStmt);
}
body.append(new IfStatement()
.condition(createNewPage)
.ifTrue(page.set(newInstance(Page.class, positionCount, blocks))));
body.append(page.ret());
}
private static void generateFilterPageMethod(ClassDefinition classDefinition, RowExpression filter)
{
Parameter session = arg("session", ConnectorSession.class);
Parameter page = arg("page", Page.class);
MethodDefinition method = classDefinition.declareMethod(a(PUBLIC), "filterPage", type(int[].class), session, page);
method.comment("Filter: %s rows in the page", filter.toString());
Scope scope = method.getScope();
Variable thisVariable = method.getThis();
BytecodeBlock body = method.getBody();
Variable positionCount = scope.declareVariable("positionCount", body, page.invoke("getPositionCount", int.class));
Variable selectedPositions = scope.declareVariable("selectedPositions", body, newArray(type(int[].class), positionCount));
List<Integer> filterChannels = getInputChannels(filter);
// extract block variables
ImmutableList.Builder<Variable> blockVariablesBuilder = ImmutableList.<Variable>builder();
for (int channel : filterChannels) {
Variable blockVariable = scope.declareVariable("block_" + channel, body, page.invoke("getBlock", Block.class, constantInt(channel)));
blockVariablesBuilder.add(blockVariable);
}
List<Variable> blockVariables = blockVariablesBuilder.build();
Variable selectedCount = scope.declareVariable("selectedCount", body, constantInt(0));
Variable position = scope.declareVariable(int.class, "position");
IfStatement ifStatement = new IfStatement();
ifStatement.condition(invokeFilter(thisVariable, session, blockVariables, position))
.ifTrue()
.append(selectedPositions.setElement(selectedCount, position))
.append(selectedCount.increment());
body.append(new ForLoop()
.initialize(position.set(constantInt(0)))
.condition(lessThan(position, positionCount))
.update(position.increment())
.body(ifStatement));
body.append(invokeStatic(Arrays.class, "copyOf", int[].class, selectedPositions, selectedCount).ret());
}
private void generateFilterMethod(ClassDefinition classDefinition, CallSiteBinder callSiteBinder, CachedInstanceBinder cachedInstanceBinder, RowExpression filter)
{
Parameter session = arg("session", ConnectorSession.class);
Parameter position = arg("position", int.class);
List<Parameter> blocks = toBlockParameters(getInputChannels(filter));
MethodDefinition method = classDefinition.declareMethod(
a(PUBLIC),
"filter",
type(boolean.class),
ImmutableList.<Parameter>builder()
.add(session)
.addAll(blocks)
.add(position)
.build());
method.comment("Filter: %s", filter.toString());
BytecodeBlock body = method.getBody();
Scope scope = method.getScope();
Variable wasNullVariable = scope.declareVariable("wasNull", body, constantFalse());
BytecodeExpressionVisitor visitor = new BytecodeExpressionVisitor(
callSiteBinder,
cachedInstanceBinder,
fieldReferenceCompiler(callSiteBinder, position, wasNullVariable),
metadata.getFunctionRegistry());
BytecodeNode visitorBody = filter.accept(visitor, scope);
Variable result = scope.declareVariable(boolean.class, "result");
body.append(visitorBody)
.putVariable(result)
.append(new IfStatement()
.condition(wasNullVariable)
.ifTrue(constantFalse().ret())
.ifFalse(result.ret()));
}
private MethodDefinition generateProjectMethod(ClassDefinition classDefinition, CallSiteBinder callSiteBinder, CachedInstanceBinder cachedInstanceBinder, String methodName, RowExpression projection)
{
Parameter session = arg("session", ConnectorSession.class);
List<Parameter> inputs = toBlockParameters(getInputChannels(projection));
Parameter position = arg("position", int.class);
Parameter output = arg("output", BlockBuilder.class);
MethodDefinition method = classDefinition.declareMethod(
a(PUBLIC),
methodName,
type(void.class),
ImmutableList.<Parameter>builder()
.add(session)
.addAll(inputs)
.add(position)
.add(output)
.build());
method.comment("Projection: %s", projection.toString());
Scope scope = method.getScope();
BytecodeBlock body = method.getBody();
Variable wasNullVariable = scope.declareVariable("wasNull", body, constantFalse());
BytecodeExpressionVisitor visitor = new BytecodeExpressionVisitor(callSiteBinder, cachedInstanceBinder, fieldReferenceCompiler(callSiteBinder, position, wasNullVariable), metadata.getFunctionRegistry());
body.getVariable(output)
.comment("evaluate projection: " + projection.toString())
.append(projection.accept(visitor, scope))
.append(generateWrite(callSiteBinder, scope, wasNullVariable, projection.getType()))
.ret();
return method;
}
private static boolean isIdentityExpression(RowExpression expression)
{
List<RowExpression> rowExpressions = Expressions.subExpressions(ImmutableList.of(expression));
return rowExpressions.size() == 1 && Iterables.getOnlyElement(rowExpressions) instanceof InputReferenceExpression;
}
private static boolean isConstantExpression(RowExpression expression)
{
List<RowExpression> rowExpressions = Expressions.subExpressions(ImmutableList.of(expression));
return rowExpressions.size() == 1 &&
Iterables.getOnlyElement(rowExpressions) instanceof ConstantExpression &&
((ConstantExpression) Iterables.getOnlyElement(rowExpressions)).getValue() != null;
}
private static List<Integer> getInputChannels(Iterable<RowExpression> expressions)
{
TreeSet<Integer> channels = new TreeSet<>();
for (RowExpression expression : Expressions.subExpressions(expressions)) {
if (expression instanceof InputReferenceExpression) {
channels.add(((InputReferenceExpression) expression).getField());
}
}
return ImmutableList.copyOf(channels);
}
private static List<Integer> getInputChannels(RowExpression expression)
{
return getInputChannels(ImmutableList.of(expression));
}
private static List<Parameter> toBlockParameters(List<Integer> inputChannels)
{
ImmutableList.Builder<Parameter> parameters = ImmutableList.builder();
for (int channel : inputChannels) {
parameters.add(arg("block_" + channel, Block.class));
}
return parameters.build();
}
private static RowExpressionVisitor<Scope, BytecodeNode> fieldReferenceCompiler(final CallSiteBinder callSiteBinder, final Variable positionVariable, final Variable wasNullVariable)
{
return new RowExpressionVisitor<Scope, BytecodeNode>()
{
@Override
public BytecodeNode visitInputReference(InputReferenceExpression node, Scope scope)
{
int field = node.getField();
Type type = node.getType();
Variable block = scope.getVariable("block_" + field);
Class<?> javaType = type.getJavaType();
if (!javaType.isPrimitive() && javaType != Slice.class) {
javaType = Object.class;
}
IfStatement ifStatement = new IfStatement();
ifStatement.condition()
.setDescription(format("block_%d.get%s()", field, type))
.append(block)
.getVariable(positionVariable)
.invokeInterface(Block.class, "isNull", boolean.class, int.class);
ifStatement.ifTrue()
.putVariable(wasNullVariable, true)
.pushJavaDefault(javaType);
String methodName = "get" + Primitives.wrap(javaType).getSimpleName();
ifStatement.ifFalse()
.append(loadConstant(callSiteBinder.bind(type, Type.class)))
.append(block)
.getVariable(positionVariable)
.invokeInterface(Type.class, methodName, javaType, Block.class, int.class);
return ifStatement;
}
@Override
public BytecodeNode visitCall(CallExpression call, Scope scope)
{
throw new UnsupportedOperationException("not yet implemented");
}
@Override
public BytecodeNode visitConstant(ConstantExpression literal, Scope scope)
{
throw new UnsupportedOperationException("not yet implemented");
}
};
}
private static Map<RowExpression, List<Variable>> getExpressionInputBlocks(List<RowExpression> projections, RowExpression filter, Map<Integer, Variable> channelBlock)
{
Map<RowExpression, List<Variable>> inputBlocksBuilder = new HashMap<>();
for (RowExpression projection : projections) {
List<Variable> inputBlocks = getInputChannels(projection).stream()
.map(channelBlock::get)
.collect(toList());
List<Variable> existingVariables = inputBlocksBuilder.get(projection);
// Constant expressions or expressions that are reused, should reference the same input blocks
checkState(existingVariables == null || existingVariables.equals(inputBlocks), "malformed RowExpression");
inputBlocksBuilder.put(projection, inputBlocks);
}
List<Variable> filterBlocks = getInputChannels(filter).stream()
.map(channelBlock::get)
.collect(toList());
inputBlocksBuilder.put(filter, filterBlocks);
return inputBlocksBuilder;
}
private static BytecodeExpression invokeFilter(BytecodeExpression objRef, BytecodeExpression session, List<? extends BytecodeExpression> blockVariables, BytecodeExpression position)
{
List<BytecodeExpression> params = ImmutableList.<BytecodeExpression>builder()
.add(session)
.addAll(blockVariables)
.add(position)
.build();
return objRef.invoke("filter", boolean.class, params);
}
private static BytecodeNode invokeProject(Variable objRef, Variable session, List<? extends Variable> blockVariables, BytecodeExpression position, Variable blockBuilder, MethodDefinition projectionMethod)
{
List<BytecodeExpression> params = ImmutableList.<BytecodeExpression>builder()
.add(session)
.addAll(blockVariables)
.add(position)
.add(blockBuilder)
.build();
return new BytecodeBlock().append(objRef.invoke(projectionMethod, params));
}
}
|
Reduce the size of generated code for PageProcessor
We saw Method too large for some really large queries. Refactor the code
so that we generate smallar methods.
|
presto-main/src/main/java/com/facebook/presto/sql/gen/PageProcessorCompiler.java
|
Reduce the size of generated code for PageProcessor
|
|
Java
|
apache-2.0
|
a9f5bfb6c6026ee7b5f87726e7e12f7cfa5d2ff1
| 0
|
arrowli/RsyncHadoop,arrowli/RsyncHadoop,arrowli/RsyncHadoop,arrowli/RsyncHadoop,arrowli/RsyncHadoop,arrowli/RsyncHadoop,arrowli/RsyncHadoop
|
/**
* 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.hdfs.server.datanode;
import static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.Status.ERROR;
import static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.Status.ERROR_UNSUPPORTED;
import static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.Status.ERROR_ACCESS_TOKEN;
import static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.Status.SUCCESS;
import static org.apache.hadoop.util.Time.now;
import static org.apache.hadoop.hdfs.server.datanode.DataNode.DN_CLIENTTRACE_FORMAT;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
import java.nio.channels.ClosedChannelException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.hadoop.hdfs.net.Peer;
import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
import org.apache.hadoop.hdfs.protocol.ExtendedBlock;
import org.apache.hadoop.hdfs.protocol.HdfsConstants;
import org.apache.hadoop.hdfs.protocol.datatransfer.BlockConstructionStage;
import org.apache.hadoop.hdfs.protocol.datatransfer.DataTransferEncryptor.InvalidMagicNumberException;
import org.apache.hadoop.hdfs.protocol.datatransfer.DataTransferProtoUtil;
import org.apache.hadoop.hdfs.protocol.datatransfer.DataTransferEncryptor;
import org.apache.hadoop.hdfs.protocol.datatransfer.IOStreamPair;
import org.apache.hadoop.hdfs.protocol.datatransfer.Op;
import org.apache.hadoop.hdfs.protocol.datatransfer.Receiver;
import org.apache.hadoop.hdfs.protocol.datatransfer.Sender;
import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BlockOpResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.ClientReadStatusProto;
import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpBlockChecksumResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpChunksChecksumResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.ReadOpChecksumInfoProto;
import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.Status;
import org.apache.hadoop.hdfs.protocolPB.PBHelper;
import org.apache.hadoop.hdfs.security.token.block.BlockTokenIdentifier;
import org.apache.hadoop.hdfs.security.token.block.BlockTokenSecretManager;
import org.apache.hadoop.hdfs.server.common.HdfsServerConstants;
import org.apache.hadoop.hdfs.server.datanode.DataNode.ShortCircuitFdsUnsupportedException;
import org.apache.hadoop.hdfs.server.datanode.DataNode.ShortCircuitFdsVersionException;
import org.apache.hadoop.hdfs.server.datanode.fsdataset.LengthInputStream;
import org.apache.hadoop.hdfs.server.protocol.DatanodeRegistration;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.MD5Hash;
import org.apache.hadoop.net.NetUtils;
import org.apache.hadoop.security.token.SecretManager.InvalidToken;
import org.apache.hadoop.security.token.Token;
import org.apache.hadoop.util.DataChecksum;
import com.google.protobuf.ByteString;
/**
* Thread for processing incoming/outgoing data stream.
*/
class DataXceiver extends Receiver implements Runnable {
public static final Log LOG = DataNode.LOG;
static final Log ClientTraceLog = DataNode.ClientTraceLog;
private final Peer peer;
private final String remoteAddress; // address of remote side
private final String localAddress; // local address of this daemon
private final DataNode datanode;
private final DNConf dnConf;
private final DataXceiverServer dataXceiverServer;
private final boolean connectToDnViaHostname;
private long opStartTime; // the start time of receiving an Op
private final InputStream socketIn;
private OutputStream socketOut;
/**
* Client Name used in previous operation. Not available on first request on
* the socket.
*/
private String previousOpClientName;
public static DataXceiver create(Peer peer, DataNode dn,
DataXceiverServer dataXceiverServer) throws IOException {
return new DataXceiver(peer, dn, dataXceiverServer);
}
private DataXceiver(Peer peer, DataNode datanode,
DataXceiverServer dataXceiverServer) throws IOException {
this.peer = peer;
this.dnConf = datanode.getDnConf();
this.socketIn = peer.getInputStream();
this.socketOut = peer.getOutputStream();
this.datanode = datanode;
this.dataXceiverServer = dataXceiverServer;
this.connectToDnViaHostname = datanode.getDnConf().connectToDnViaHostname;
remoteAddress = peer.getRemoteAddressString();
localAddress = peer.getLocalAddressString();
if (LOG.isDebugEnabled()) {
LOG.debug("Number of active connections is: "
+ datanode.getXceiverCount());
}
}
/**
* Update the current thread's name to contain the current status. Use this
* only after this receiver has started on its thread, i.e., outside the
* constructor.
*/
private void updateCurrentThreadName(String status) {
StringBuilder sb = new StringBuilder();
sb.append("DataXceiver for client ");
if (previousOpClientName != null) {
sb.append(previousOpClientName).append(" at ");
}
sb.append(remoteAddress);
if (status != null) {
sb.append(" [").append(status).append("]");
}
Thread.currentThread().setName(sb.toString());
}
/** Return the datanode object. */
DataNode getDataNode() {
return datanode;
}
private OutputStream getOutputStream() {
return socketOut;
}
/**
* Read/write data from/to the DataXceiverServer.
*/
@Override
public void run() {
int opsProcessed = 0;
Op op = null;
dataXceiverServer.addPeer(peer);
try {
peer.setWriteTimeout(datanode.getDnConf().socketWriteTimeout);
InputStream input = socketIn;
if (dnConf.encryptDataTransfer) {
IOStreamPair encryptedStreams = null;
try {
encryptedStreams = DataTransferEncryptor
.getEncryptedStreams(socketOut, socketIn,
datanode.blockPoolTokenSecretManager,
dnConf.encryptionAlgorithm);
} catch (InvalidMagicNumberException imne) {
LOG.info("Failed to read expected encryption handshake from client "
+ "at "
+ peer.getRemoteAddressString()
+ ". Perhaps the client "
+ "is running an older version of Hadoop which does not support "
+ "encryption");
return;
}
input = encryptedStreams.in;
socketOut = encryptedStreams.out;
}
input = new BufferedInputStream(input,
HdfsConstants.SMALL_BUFFER_SIZE);
super.initialize(new DataInputStream(input));
// We process requests in a loop, and stay around for a short
// timeout.
// This optimistic behaviour allows the other end to reuse
// connections.
// Setting keepalive timeout to 0 disable this behavior.
do {
updateCurrentThreadName("Waiting for operation #"
+ (opsProcessed + 1));
try {
if (opsProcessed != 0) {
assert dnConf.socketKeepaliveTimeout > 0;
peer.setReadTimeout(dnConf.socketKeepaliveTimeout);
} else {
peer.setReadTimeout(dnConf.socketTimeout);
}
op = readOp();
} catch (InterruptedIOException ignored) {
// Time out while we wait for client rpc
break;
} catch (IOException err) {
// Since we optimistically expect the next op, it's quite
// normal to get EOF here.
if (opsProcessed > 0
&& (err instanceof EOFException || err instanceof ClosedChannelException)) {
if (LOG.isDebugEnabled()) {
LOG.debug("Cached " + peer + " closing after "
+ opsProcessed + " ops");
}
} else {
throw err;
}
break;
}
// restore normal timeout
if (opsProcessed != 0) {
peer.setReadTimeout(dnConf.socketTimeout);
}
opStartTime = now();
processOp(op);
++opsProcessed;
} while (!peer.isClosed() && dnConf.socketKeepaliveTimeout > 0);
} catch (Throwable t) {
LOG.error(datanode.getDisplayName()
+ ":DataXceiver error processing "
+ ((op == null) ? "unknown" : op.name()) + " operation "
+ " src: " + remoteAddress + " dest: " + localAddress, t);
} finally {
if (LOG.isDebugEnabled()) {
LOG.debug(datanode.getDisplayName()
+ ":Number of active connections is: "
+ datanode.getXceiverCount());
}
updateCurrentThreadName("Cleaning up");
dataXceiverServer.closePeer(peer);
IOUtils.closeStream(in);
}
}
@Override
public void requestShortCircuitFds(final ExtendedBlock blk,
final Token<BlockTokenIdentifier> token, int maxVersion)
throws IOException {
updateCurrentThreadName("Passing file descriptors for block " + blk);
BlockOpResponseProto.Builder bld = BlockOpResponseProto.newBuilder();
FileInputStream fis[] = null;
try {
if (peer.getDomainSocket() == null) {
throw new IOException("You cannot pass file descriptors over "
+ "anything but a UNIX domain socket.");
}
fis = datanode
.requestShortCircuitFdsForRead(blk, token, maxVersion);
bld.setStatus(SUCCESS);
bld.setShortCircuitAccessVersion(DataNode.CURRENT_BLOCK_FORMAT_VERSION);
} catch (ShortCircuitFdsVersionException e) {
bld.setStatus(ERROR_UNSUPPORTED);
bld.setShortCircuitAccessVersion(DataNode.CURRENT_BLOCK_FORMAT_VERSION);
bld.setMessage(e.getMessage());
} catch (ShortCircuitFdsUnsupportedException e) {
bld.setStatus(ERROR_UNSUPPORTED);
bld.setMessage(e.getMessage());
} catch (InvalidToken e) {
bld.setStatus(ERROR_ACCESS_TOKEN);
bld.setMessage(e.getMessage());
} catch (IOException e) {
bld.setStatus(ERROR);
bld.setMessage(e.getMessage());
}
try {
bld.build().writeDelimitedTo(socketOut);
if (fis != null) {
FileDescriptor fds[] = new FileDescriptor[fis.length];
for (int i = 0; i < fds.length; i++) {
fds[i] = fis[i].getFD();
}
byte buf[] = new byte[] { (byte) 0 };
peer.getDomainSocket().sendFileDescriptors(fds, buf, 0,
buf.length);
}
} finally {
if (ClientTraceLog.isInfoEnabled()) {
DatanodeRegistration dnR = datanode.getDNRegistrationForBP(blk
.getBlockPoolId());
BlockSender.ClientTraceLog.info(String.format(
"src: 127.0.0.1, dest: 127.0.0.1, op: REQUEST_SHORT_CIRCUIT_FDS,"
+ " blockid: %s, srvID: %s, success: %b",
blk.getBlockId(), dnR.getStorageID(), (fis != null)));
}
if (fis != null) {
IOUtils.cleanup(LOG, fis);
}
}
}
@Override
public void readBlock(final ExtendedBlock block,
final Token<BlockTokenIdentifier> blockToken,
final String clientName, final long blockOffset, final long length,
final boolean sendChecksum, final CachingStrategy cachingStrategy)
throws IOException {
previousOpClientName = clientName;
OutputStream baseStream = getOutputStream();
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(
baseStream, HdfsConstants.SMALL_BUFFER_SIZE));
checkAccess(out, true, block, blockToken, Op.READ_BLOCK,
BlockTokenSecretManager.AccessMode.READ);
// send the block
BlockSender blockSender = null;
DatanodeRegistration dnR = datanode.getDNRegistrationForBP(block
.getBlockPoolId());
final String clientTraceFmt = clientName.length() > 0
&& ClientTraceLog.isInfoEnabled() ? String.format(
DN_CLIENTTRACE_FORMAT, localAddress, remoteAddress, "%d",
"HDFS_READ", clientName, "%d", dnR.getStorageID(), block, "%d")
: dnR + " Served block " + block + " to " + remoteAddress;
updateCurrentThreadName("Sending block " + block);
try {
try {
blockSender = new BlockSender(block, blockOffset, length, true,
false, sendChecksum, datanode, clientTraceFmt,
cachingStrategy);
} catch (IOException e) {
String msg = "opReadBlock " + block + " received exception "
+ e;
LOG.info(msg);
sendResponse(ERROR, msg);
throw e;
}
// send op status
writeSuccessWithChecksumInfo(blockSender, new DataOutputStream(
getOutputStream()));
long read = blockSender.sendBlock(out, baseStream, null); // send
// data
if (blockSender.didSendEntireByteRange()) {
// If we sent the entire range, then we should expect the client
// to respond with a Status enum.
try {
ClientReadStatusProto stat = ClientReadStatusProto
.parseFrom(PBHelper.vintPrefixed(in));
if (!stat.hasStatus()) {
LOG.warn("Client "
+ peer.getRemoteAddressString()
+ " did not send a valid status code after reading. "
+ "Will close connection.");
IOUtils.closeStream(out);
}
} catch (IOException ioe) {
LOG.debug(
"Error reading client status response. Will close connection.",
ioe);
IOUtils.closeStream(out);
}
} else {
IOUtils.closeStream(out);
}
datanode.metrics.incrBytesRead((int) read);
datanode.metrics.incrBlocksRead();
} catch (SocketException ignored) {
if (LOG.isTraceEnabled()) {
LOG.trace(dnR + ":Ignoring exception while serving " + block
+ " to " + remoteAddress, ignored);
}
// Its ok for remote side to close the connection anytime.
datanode.metrics.incrBlocksRead();
IOUtils.closeStream(out);
} catch (IOException ioe) {
/*
* What exactly should we do here? Earlier version shutdown()
* datanode if there is disk error.
*/
LOG.warn(dnR + ":Got exception while serving " + block + " to "
+ remoteAddress, ioe);
throw ioe;
} finally {
IOUtils.closeStream(blockSender);
}
// update metrics
datanode.metrics.addReadBlockOp(elapsed());
datanode.metrics.incrReadsFromClient(peer.isLocal());
}
@Override
public void writeBlock(final ExtendedBlock block,
final Token<BlockTokenIdentifier> blockToken,
final String clientname, final DatanodeInfo[] targets,
final DatanodeInfo srcDataNode, final BlockConstructionStage stage,
final int pipelineSize, final long minBytesRcvd,
final long maxBytesRcvd, final long latestGenerationStamp,
DataChecksum requestedChecksum, CachingStrategy cachingStrategy)
throws IOException {
previousOpClientName = clientname;
updateCurrentThreadName("Receiving block " + block);
final boolean isDatanode = clientname.length() == 0;
final boolean isClient = !isDatanode;
final boolean isTransfer = stage == BlockConstructionStage.TRANSFER_RBW
|| stage == BlockConstructionStage.TRANSFER_FINALIZED;
// check single target for transfer-RBW/Finalized
if (isTransfer && targets.length > 0) {
throw new IOException(stage + " does not support multiple targets "
+ Arrays.asList(targets));
}
if (LOG.isDebugEnabled()) {
LOG.debug("opWriteBlock: stage=" + stage + ", clientname="
+ clientname + "\n block =" + block + ", newGs="
+ latestGenerationStamp + ", bytesRcvd=[" + minBytesRcvd
+ ", " + maxBytesRcvd + "]" + "\n targets="
+ Arrays.asList(targets) + "; pipelineSize=" + pipelineSize
+ ", srcDataNode=" + srcDataNode);
LOG.debug("isDatanode=" + isDatanode + ", isClient=" + isClient
+ ", isTransfer=" + isTransfer);
LOG.debug("writeBlock receive buf size "
+ peer.getReceiveBufferSize() + " tcp no delay "
+ peer.getTcpNoDelay());
}
// We later mutate block's generation stamp and length, but we need to
// forward the original version of the block to downstream mirrors, so
// make a copy here.
final ExtendedBlock originalBlock = new ExtendedBlock(block);
block.setNumBytes(dataXceiverServer.estimateBlockSize);
LOG.info("Receiving " + block + " src: " + remoteAddress + " dest: "
+ localAddress);
// reply to upstream datanode or client
final DataOutputStream replyOut = new DataOutputStream(
new BufferedOutputStream(getOutputStream(),
HdfsConstants.SMALL_BUFFER_SIZE));
checkAccess(replyOut, isClient, block, blockToken, Op.WRITE_BLOCK,
BlockTokenSecretManager.AccessMode.WRITE);
DataOutputStream mirrorOut = null; // stream to next target
DataInputStream mirrorIn = null; // reply from next target
Socket mirrorSock = null; // socket to next target
BlockReceiver blockReceiver = null; // responsible for data handling
String mirrorNode = null; // the name:port of next target
String firstBadLink = ""; // first datanode that failed in connection
// setup
Status mirrorInStatus = SUCCESS;
try {
if (isDatanode
|| stage != BlockConstructionStage.PIPELINE_CLOSE_RECOVERY) {
// open a block receiver
blockReceiver = new BlockReceiver(block, in,
peer.getRemoteAddressString(),
peer.getLocalAddressString(), stage,
latestGenerationStamp, minBytesRcvd, maxBytesRcvd,
clientname, srcDataNode, datanode, requestedChecksum,
cachingStrategy);
} else {
datanode.data.recoverClose(block, latestGenerationStamp,
minBytesRcvd);
}
//
// Connect to downstream machine, if appropriate
//
if (targets.length > 0) {
InetSocketAddress mirrorTarget = null;
// Connect to backup machine
mirrorNode = targets[0].getXferAddr(connectToDnViaHostname);
if (LOG.isDebugEnabled()) {
LOG.debug("Connecting to datanode " + mirrorNode);
}
mirrorTarget = NetUtils.createSocketAddr(mirrorNode);
mirrorSock = datanode.newSocket();
try {
int timeoutValue = dnConf.socketTimeout
+ (HdfsServerConstants.READ_TIMEOUT_EXTENSION * targets.length);
int writeTimeout = dnConf.socketWriteTimeout
+ (HdfsServerConstants.WRITE_TIMEOUT_EXTENSION * targets.length);
NetUtils.connect(mirrorSock, mirrorTarget, timeoutValue);
mirrorSock.setSoTimeout(timeoutValue);
mirrorSock
.setSendBufferSize(HdfsConstants.DEFAULT_DATA_SOCKET_SIZE);
OutputStream unbufMirrorOut = NetUtils.getOutputStream(
mirrorSock, writeTimeout);
InputStream unbufMirrorIn = NetUtils
.getInputStream(mirrorSock);
if (dnConf.encryptDataTransfer) {
IOStreamPair encryptedStreams = DataTransferEncryptor
.getEncryptedStreams(
unbufMirrorOut,
unbufMirrorIn,
datanode.blockPoolTokenSecretManager
.generateDataEncryptionKey(block
.getBlockPoolId()));
unbufMirrorOut = encryptedStreams.out;
unbufMirrorIn = encryptedStreams.in;
}
mirrorOut = new DataOutputStream(new BufferedOutputStream(
unbufMirrorOut, HdfsConstants.SMALL_BUFFER_SIZE));
mirrorIn = new DataInputStream(unbufMirrorIn);
new Sender(mirrorOut).writeBlock(originalBlock, blockToken,
clientname, targets, srcDataNode, stage,
pipelineSize, minBytesRcvd, maxBytesRcvd,
latestGenerationStamp, requestedChecksum,
cachingStrategy);
mirrorOut.flush();
// read connect ack (only for clients, not for replication
// req)
if (isClient) {
BlockOpResponseProto connectAck = BlockOpResponseProto
.parseFrom(PBHelper.vintPrefixed(mirrorIn));
mirrorInStatus = connectAck.getStatus();
firstBadLink = connectAck.getFirstBadLink();
if (LOG.isDebugEnabled() || mirrorInStatus != SUCCESS) {
LOG.info("Datanode "
+ targets.length
+ " got response for connect ack "
+ " from downstream datanode with firstbadlink as "
+ firstBadLink);
}
}
} catch (IOException e) {
if (isClient) {
BlockOpResponseProto.newBuilder().setStatus(ERROR)
// NB: Unconditionally using the xfer addr w/o
// hostname
.setFirstBadLink(targets[0].getXferAddr())
.build().writeDelimitedTo(replyOut);
replyOut.flush();
}
IOUtils.closeStream(mirrorOut);
mirrorOut = null;
IOUtils.closeStream(mirrorIn);
mirrorIn = null;
IOUtils.closeSocket(mirrorSock);
mirrorSock = null;
if (isClient) {
LOG.error(datanode + ":Exception transfering block "
+ block + " to mirror " + mirrorNode + ": " + e);
throw e;
} else {
LOG.info(datanode + ":Exception transfering " + block
+ " to mirror " + mirrorNode
+ "- continuing without the mirror", e);
}
}
}
// send connect-ack to source for clients and not
// transfer-RBW/Finalized
if (isClient && !isTransfer) {
if (LOG.isDebugEnabled() || mirrorInStatus != SUCCESS) {
LOG.info("Datanode "
+ targets.length
+ " forwarding connect ack to upstream firstbadlink is "
+ firstBadLink);
}
BlockOpResponseProto.newBuilder().setStatus(mirrorInStatus)
.setFirstBadLink(firstBadLink).build()
.writeDelimitedTo(replyOut);
replyOut.flush();
}
// receive the block and mirror to the next target
if (blockReceiver != null) {
String mirrorAddr = (mirrorSock == null) ? null : mirrorNode;
blockReceiver.receiveBlock(mirrorOut, mirrorIn, replyOut,
mirrorAddr, null, targets);
// send close-ack for transfer-RBW/Finalized
if (isTransfer) {
if (LOG.isTraceEnabled()) {
LOG.trace("TRANSFER: send close-ack");
}
writeResponse(SUCCESS, null, replyOut);
}
}
// update its generation stamp
if (isClient
&& stage == BlockConstructionStage.PIPELINE_CLOSE_RECOVERY) {
block.setGenerationStamp(latestGenerationStamp);
block.setNumBytes(minBytesRcvd);
}
// if this write is for a replication request or recovering
// a failed close for client, then confirm block. For other
// client-writes,
// the block is finalized in the PacketResponder.
if (isDatanode
|| stage == BlockConstructionStage.PIPELINE_CLOSE_RECOVERY) {
datanode.closeBlock(block, DataNode.EMPTY_DEL_HINT);
LOG.info("Received " + block + " src: " + remoteAddress
+ " dest: " + localAddress + " of size "
+ block.getNumBytes());
}
} catch (IOException ioe) {
LOG.info("opWriteBlock " + block + " received exception " + ioe);
throw ioe;
} finally {
// close all opened streams
IOUtils.closeStream(mirrorOut);
IOUtils.closeStream(mirrorIn);
IOUtils.closeStream(replyOut);
IOUtils.closeSocket(mirrorSock);
IOUtils.closeStream(blockReceiver);
}
// update metrics
datanode.metrics.addWriteBlockOp(elapsed());
datanode.metrics.incrWritesFromClient(peer.isLocal());
}
@Override
public void transferBlock(final ExtendedBlock blk,
final Token<BlockTokenIdentifier> blockToken,
final String clientName, final DatanodeInfo[] targets)
throws IOException {
checkAccess(socketOut, true, blk, blockToken, Op.TRANSFER_BLOCK,
BlockTokenSecretManager.AccessMode.COPY);
previousOpClientName = clientName;
updateCurrentThreadName(Op.TRANSFER_BLOCK + " " + blk);
final DataOutputStream out = new DataOutputStream(getOutputStream());
try {
datanode.transferReplicaForPipelineRecovery(blk, targets,
clientName);
writeResponse(Status.SUCCESS, null, out);
} finally {
IOUtils.closeStream(out);
}
}
@Override
public void chunksChecksum(final ExtendedBlock block,
final Token<BlockTokenIdentifier> blockToken) throws IOException {
final DataOutputStream out = new DataOutputStream(getOutputStream());
checkAccess(out, true, block, blockToken, Op.RSYNC_CHUNKS_CHECKSUM,
BlockTokenSecretManager.AccessMode.READ);
updateCurrentThreadName("Reading metadata for block " + block);
final LengthInputStream metadataIn = datanode.data
.getMetaDataInputStream(block);
final DataInputStream checksumIn = new DataInputStream(
new BufferedInputStream(metadataIn,
HdfsConstants.IO_FILE_BUFFER_SIZE));
updateCurrentThreadName("Getting checksums for block " + block);
try {
// read metadata file
final BlockMetadataHeader header = BlockMetadataHeader
.readHeader(checksumIn);
final DataChecksum checksum = header.getChecksum();
final int bytesPerCRC = checksum.getBytesPerChecksum();
final long crcPerBlock = (metadataIn.getLength() - BlockMetadataHeader
.getHeaderSize()) / checksum.getChecksumSize();
final int bytesPerChunk = checksum.getChecksumSize();
final long chunksPerBlock = (metadataIn.getLength() - BlockMetadataHeader
.getHeaderSize()) / checksum.getChecksumSize();
final List<Integer> checksums = new LinkedList<Integer>();
for (int i = 0; i < chunksPerBlock; i++) {
checksums.add(checksumIn.readInt());
}
// compute block checksum
final MD5Hash md5 = MD5Hash.digest(checksumIn);
if (LOG.isDebugEnabled()) {
LOG.debug("block=" + block + ", bytesPerCRC=" + bytesPerCRC
+ ", crcPerBlock=" + crcPerBlock + ", md5=" + md5);
}
LOG.warn("chunkPerBlock %d"+chunksPerBlock);
LOG.warn("bytesPerChunk %d"+bytesPerChunk);
LOG.warn("checksums[0] %x"+checksums.get(0));
// write reply
BlockOpResponseProto.newBuilder().setStatus(SUCCESS)
.setChunksChecksumResponse(OpChunksChecksumResponseProto
.newBuilder().setBytesPerCrc(bytesPerCRC)
.setCrcPerBlock(crcPerBlock)
.setBytesPerChunk(bytesPerChunk)
.setChunksPerBlock(chunksPerBlock)
//.addAllChecksums(checksums)
.setMd5(ByteString.copyFrom(md5.getDigest()))
.setCrcType(PBHelper.convert(checksum.getChecksumType()))
)
.build()
.writeDelimitedTo(out);
out.flush();
} finally {
IOUtils.closeStream(out);
IOUtils.closeStream(checksumIn);
IOUtils.closeStream(metadataIn);
}
// update metrics
datanode.metrics.addBlockChecksumOp(elapsed());
}
@Override
public void blockChecksum(final ExtendedBlock block,
final Token<BlockTokenIdentifier> blockToken) throws IOException {
final DataOutputStream out = new DataOutputStream(getOutputStream());
checkAccess(out, true, block, blockToken, Op.BLOCK_CHECKSUM,
BlockTokenSecretManager.AccessMode.READ);
updateCurrentThreadName("Reading metadata for block " + block);
final LengthInputStream metadataIn = datanode.data
.getMetaDataInputStream(block);
final DataInputStream checksumIn = new DataInputStream(
new BufferedInputStream(metadataIn,
HdfsConstants.IO_FILE_BUFFER_SIZE));
updateCurrentThreadName("Getting checksum for block " + block);
try {
// read metadata file
final BlockMetadataHeader header = BlockMetadataHeader
.readHeader(checksumIn);
final DataChecksum checksum = header.getChecksum();
final int bytesPerCRC = checksum.getBytesPerChecksum();
final long crcPerBlock = (metadataIn.getLength() - BlockMetadataHeader
.getHeaderSize()) / checksum.getChecksumSize();
// compute block checksum
final MD5Hash md5 = MD5Hash.digest(checksumIn);
if (LOG.isDebugEnabled()) {
LOG.debug("block=" + block + ", bytesPerCRC=" + bytesPerCRC
+ ", crcPerBlock=" + crcPerBlock + ", md5=" + md5);
}
// write reply
BlockOpResponseProto
.newBuilder()
.setStatus(SUCCESS)
.setChecksumResponse(
OpBlockChecksumResponseProto
.newBuilder()
.setBytesPerCrc(bytesPerCRC)
.setCrcPerBlock(crcPerBlock)
.setMd5(ByteString.copyFrom(md5.getDigest()))
.setCrcType(
PBHelper.convert(checksum
.getChecksumType())))
.build().writeDelimitedTo(out);
out.flush();
} finally {
IOUtils.closeStream(out);
IOUtils.closeStream(checksumIn);
IOUtils.closeStream(metadataIn);
}
// update metrics
datanode.metrics.addBlockChecksumOp(elapsed());
}
@Override
public void copyBlock(final ExtendedBlock block,
final Token<BlockTokenIdentifier> blockToken) throws IOException {
updateCurrentThreadName("Copying block " + block);
// Read in the header
if (datanode.isBlockTokenEnabled) {
try {
datanode.blockPoolTokenSecretManager.checkAccess(blockToken,
null, block, BlockTokenSecretManager.AccessMode.COPY);
} catch (InvalidToken e) {
LOG.warn("Invalid access token in request from "
+ remoteAddress + " for OP_COPY_BLOCK for block "
+ block + " : " + e.getLocalizedMessage());
sendResponse(ERROR_ACCESS_TOKEN, "Invalid access token");
return;
}
}
if (!dataXceiverServer.balanceThrottler.acquire()) { // not able to
// start
String msg = "Not able to copy block " + block.getBlockId() + " "
+ "to " + peer.getRemoteAddressString()
+ " because threads " + "quota is exceeded.";
LOG.info(msg);
sendResponse(ERROR, msg);
return;
}
BlockSender blockSender = null;
DataOutputStream reply = null;
boolean isOpSuccess = true;
try {
// check if the block exists or not
blockSender = new BlockSender(block, 0, -1, false, false, true,
datanode, null, CachingStrategy.newDropBehind());
// set up response stream
OutputStream baseStream = getOutputStream();
reply = new DataOutputStream(new BufferedOutputStream(baseStream,
HdfsConstants.SMALL_BUFFER_SIZE));
// send status first
writeSuccessWithChecksumInfo(blockSender, reply);
// send block content to the target
long read = blockSender.sendBlock(reply, baseStream,
dataXceiverServer.balanceThrottler);
datanode.metrics.incrBytesRead((int) read);
datanode.metrics.incrBlocksRead();
LOG.info("Copied " + block + " to " + peer.getRemoteAddressString());
} catch (IOException ioe) {
isOpSuccess = false;
LOG.info("opCopyBlock " + block + " received exception " + ioe);
throw ioe;
} finally {
dataXceiverServer.balanceThrottler.release();
if (isOpSuccess) {
try {
// send one last byte to indicate that the resource is
// cleaned.
reply.writeChar('d');
} catch (IOException ignored) {
}
}
IOUtils.closeStream(reply);
IOUtils.closeStream(blockSender);
}
// update metrics
datanode.metrics.addCopyBlockOp(elapsed());
}
@Override
public void replaceBlock(final ExtendedBlock block,
final Token<BlockTokenIdentifier> blockToken, final String delHint,
final DatanodeInfo proxySource) throws IOException {
updateCurrentThreadName("Replacing block " + block + " from " + delHint);
/* read header */
block.setNumBytes(dataXceiverServer.estimateBlockSize);
if (datanode.isBlockTokenEnabled) {
try {
datanode.blockPoolTokenSecretManager
.checkAccess(blockToken, null, block,
BlockTokenSecretManager.AccessMode.REPLACE);
} catch (InvalidToken e) {
LOG.warn("Invalid access token in request from "
+ remoteAddress + " for OP_REPLACE_BLOCK for block "
+ block + " : " + e.getLocalizedMessage());
sendResponse(ERROR_ACCESS_TOKEN, "Invalid access token");
return;
}
}
if (!dataXceiverServer.balanceThrottler.acquire()) { // not able to
// start
String msg = "Not able to receive block " + block.getBlockId()
+ " from " + peer.getRemoteAddressString()
+ " because threads " + "quota is exceeded.";
LOG.warn(msg);
sendResponse(ERROR, msg);
return;
}
Socket proxySock = null;
DataOutputStream proxyOut = null;
Status opStatus = SUCCESS;
String errMsg = null;
BlockReceiver blockReceiver = null;
DataInputStream proxyReply = null;
try {
// get the output stream to the proxy
final String dnAddr = proxySource
.getXferAddr(connectToDnViaHostname);
if (LOG.isDebugEnabled()) {
LOG.debug("Connecting to datanode " + dnAddr);
}
InetSocketAddress proxyAddr = NetUtils.createSocketAddr(dnAddr);
proxySock = datanode.newSocket();
NetUtils.connect(proxySock, proxyAddr, dnConf.socketTimeout);
proxySock.setSoTimeout(dnConf.socketTimeout);
OutputStream unbufProxyOut = NetUtils.getOutputStream(proxySock,
dnConf.socketWriteTimeout);
InputStream unbufProxyIn = NetUtils.getInputStream(proxySock);
if (dnConf.encryptDataTransfer) {
IOStreamPair encryptedStreams = DataTransferEncryptor
.getEncryptedStreams(unbufProxyOut, unbufProxyIn,
datanode.blockPoolTokenSecretManager
.generateDataEncryptionKey(block
.getBlockPoolId()));
unbufProxyOut = encryptedStreams.out;
unbufProxyIn = encryptedStreams.in;
}
proxyOut = new DataOutputStream(new BufferedOutputStream(
unbufProxyOut, HdfsConstants.SMALL_BUFFER_SIZE));
proxyReply = new DataInputStream(new BufferedInputStream(
unbufProxyIn, HdfsConstants.IO_FILE_BUFFER_SIZE));
/* send request to the proxy */
new Sender(proxyOut).copyBlock(block, blockToken);
// receive the response from the proxy
BlockOpResponseProto copyResponse = BlockOpResponseProto
.parseFrom(PBHelper.vintPrefixed(proxyReply));
if (copyResponse.getStatus() != SUCCESS) {
if (copyResponse.getStatus() == ERROR_ACCESS_TOKEN) {
throw new IOException("Copy block " + block + " from "
+ proxySock.getRemoteSocketAddress()
+ " failed due to access token error");
}
throw new IOException("Copy block " + block + " from "
+ proxySock.getRemoteSocketAddress() + " failed");
}
// get checksum info about the block we're copying
ReadOpChecksumInfoProto checksumInfo = copyResponse
.getReadOpChecksumInfo();
DataChecksum remoteChecksum = DataTransferProtoUtil
.fromProto(checksumInfo.getChecksum());
// open a block receiver and check if the block does not exist
blockReceiver = new BlockReceiver(block, proxyReply, proxySock
.getRemoteSocketAddress().toString(), proxySock
.getLocalSocketAddress().toString(), null, 0, 0, 0, "",
null, datanode, remoteChecksum,
CachingStrategy.newDropBehind());
// receive a block
blockReceiver.receiveBlock(null, null, null, null,
dataXceiverServer.balanceThrottler, null);
// notify name node
datanode.notifyNamenodeReceivedBlock(block, delHint);
LOG.info("Moved " + block + " from "
+ peer.getRemoteAddressString());
} catch (IOException ioe) {
opStatus = ERROR;
errMsg = "opReplaceBlock " + block + " received exception " + ioe;
LOG.info(errMsg);
throw ioe;
} finally {
// receive the last byte that indicates the proxy released its
// thread resource
if (opStatus == SUCCESS) {
try {
proxyReply.readChar();
} catch (IOException ignored) {
}
}
// now release the thread resource
dataXceiverServer.balanceThrottler.release();
// send response back
try {
sendResponse(opStatus, errMsg);
} catch (IOException ioe) {
LOG.warn("Error writing reply back to "
+ peer.getRemoteAddressString());
}
IOUtils.closeStream(proxyOut);
IOUtils.closeStream(blockReceiver);
IOUtils.closeStream(proxyReply);
}
// update metrics
datanode.metrics.addReplaceBlockOp(elapsed());
}
private long elapsed() {
return now() - opStartTime;
}
/**
* Utility function for sending a response.
*
* @param opStatus
* status message to write
* @param message
* message to send to the client or other DN
*/
private void sendResponse(Status status, String message) throws IOException {
writeResponse(status, message, getOutputStream());
}
private static void writeResponse(Status status, String message,
OutputStream out) throws IOException {
BlockOpResponseProto.Builder response = BlockOpResponseProto
.newBuilder().setStatus(status);
if (message != null) {
response.setMessage(message);
}
response.build().writeDelimitedTo(out);
out.flush();
}
private void writeSuccessWithChecksumInfo(BlockSender blockSender,
DataOutputStream out) throws IOException {
ReadOpChecksumInfoProto ckInfo = ReadOpChecksumInfoProto
.newBuilder()
.setChecksum(
DataTransferProtoUtil.toProto(blockSender.getChecksum()))
.setChunkOffset(blockSender.getOffset()).build();
BlockOpResponseProto response = BlockOpResponseProto.newBuilder()
.setStatus(SUCCESS).setReadOpChecksumInfo(ckInfo).build();
response.writeDelimitedTo(out);
out.flush();
}
private void checkAccess(OutputStream out, final boolean reply,
final ExtendedBlock blk, final Token<BlockTokenIdentifier> t,
final Op op, final BlockTokenSecretManager.AccessMode mode)
throws IOException {
if (datanode.isBlockTokenEnabled) {
if (LOG.isDebugEnabled()) {
LOG.debug("Checking block access token for block '"
+ blk.getBlockId() + "' with mode '" + mode + "'");
}
try {
datanode.blockPoolTokenSecretManager.checkAccess(t, null, blk,
mode);
} catch (InvalidToken e) {
try {
if (reply) {
BlockOpResponseProto.Builder resp = BlockOpResponseProto
.newBuilder().setStatus(ERROR_ACCESS_TOKEN);
if (mode == BlockTokenSecretManager.AccessMode.WRITE) {
DatanodeRegistration dnR = datanode
.getDNRegistrationForBP(blk
.getBlockPoolId());
// NB: Unconditionally using the xfer addr w/o
// hostname
resp.setFirstBadLink(dnR.getXferAddr());
}
resp.build().writeDelimitedTo(out);
out.flush();
}
LOG.warn("Block token verification failed: op=" + op
+ ", remoteAddress=" + remoteAddress + ", message="
+ e.getLocalizedMessage());
throw e;
} finally {
IOUtils.closeStream(out);
}
}
}
}
}
|
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataXceiver.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.hdfs.server.datanode;
import static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.Status.ERROR;
import static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.Status.ERROR_UNSUPPORTED;
import static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.Status.ERROR_ACCESS_TOKEN;
import static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.Status.SUCCESS;
import static org.apache.hadoop.util.Time.now;
import static org.apache.hadoop.hdfs.server.datanode.DataNode.DN_CLIENTTRACE_FORMAT;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
import java.nio.channels.ClosedChannelException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.hadoop.hdfs.net.Peer;
import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
import org.apache.hadoop.hdfs.protocol.ExtendedBlock;
import org.apache.hadoop.hdfs.protocol.HdfsConstants;
import org.apache.hadoop.hdfs.protocol.datatransfer.BlockConstructionStage;
import org.apache.hadoop.hdfs.protocol.datatransfer.DataTransferEncryptor.InvalidMagicNumberException;
import org.apache.hadoop.hdfs.protocol.datatransfer.DataTransferProtoUtil;
import org.apache.hadoop.hdfs.protocol.datatransfer.DataTransferEncryptor;
import org.apache.hadoop.hdfs.protocol.datatransfer.IOStreamPair;
import org.apache.hadoop.hdfs.protocol.datatransfer.Op;
import org.apache.hadoop.hdfs.protocol.datatransfer.Receiver;
import org.apache.hadoop.hdfs.protocol.datatransfer.Sender;
import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BlockOpResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.ClientReadStatusProto;
import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpBlockChecksumResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpChunksChecksumResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.ReadOpChecksumInfoProto;
import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.Status;
import org.apache.hadoop.hdfs.protocolPB.PBHelper;
import org.apache.hadoop.hdfs.security.token.block.BlockTokenIdentifier;
import org.apache.hadoop.hdfs.security.token.block.BlockTokenSecretManager;
import org.apache.hadoop.hdfs.server.common.HdfsServerConstants;
import org.apache.hadoop.hdfs.server.datanode.DataNode.ShortCircuitFdsUnsupportedException;
import org.apache.hadoop.hdfs.server.datanode.DataNode.ShortCircuitFdsVersionException;
import org.apache.hadoop.hdfs.server.datanode.fsdataset.LengthInputStream;
import org.apache.hadoop.hdfs.server.protocol.DatanodeRegistration;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.MD5Hash;
import org.apache.hadoop.net.NetUtils;
import org.apache.hadoop.security.token.SecretManager.InvalidToken;
import org.apache.hadoop.security.token.Token;
import org.apache.hadoop.util.DataChecksum;
import com.google.protobuf.ByteString;
/**
* Thread for processing incoming/outgoing data stream.
*/
class DataXceiver extends Receiver implements Runnable {
public static final com.sun.tools.javac.util.Log LOG = DataNode.LOG;
static final Log ClientTraceLog = DataNode.ClientTraceLog;
private final Peer peer;
private final String remoteAddress; // address of remote side
private final String localAddress; // local address of this daemon
private final DataNode datanode;
private final DNConf dnConf;
private final DataXceiverServer dataXceiverServer;
private final boolean connectToDnViaHostname;
private long opStartTime; // the start time of receiving an Op
private final InputStream socketIn;
private OutputStream socketOut;
/**
* Client Name used in previous operation. Not available on first request on
* the socket.
*/
private String previousOpClientName;
public static DataXceiver create(Peer peer, DataNode dn,
DataXceiverServer dataXceiverServer) throws IOException {
return new DataXceiver(peer, dn, dataXceiverServer);
}
private DataXceiver(Peer peer, DataNode datanode,
DataXceiverServer dataXceiverServer) throws IOException {
this.peer = peer;
this.dnConf = datanode.getDnConf();
this.socketIn = peer.getInputStream();
this.socketOut = peer.getOutputStream();
this.datanode = datanode;
this.dataXceiverServer = dataXceiverServer;
this.connectToDnViaHostname = datanode.getDnConf().connectToDnViaHostname;
remoteAddress = peer.getRemoteAddressString();
localAddress = peer.getLocalAddressString();
if (LOG.isDebugEnabled()) {
LOG.debug("Number of active connections is: "
+ datanode.getXceiverCount());
}
}
/**
* Update the current thread's name to contain the current status. Use this
* only after this receiver has started on its thread, i.e., outside the
* constructor.
*/
private void updateCurrentThreadName(String status) {
StringBuilder sb = new StringBuilder();
sb.append("DataXceiver for client ");
if (previousOpClientName != null) {
sb.append(previousOpClientName).append(" at ");
}
sb.append(remoteAddress);
if (status != null) {
sb.append(" [").append(status).append("]");
}
Thread.currentThread().setName(sb.toString());
}
/** Return the datanode object. */
DataNode getDataNode() {
return datanode;
}
private OutputStream getOutputStream() {
return socketOut;
}
/**
* Read/write data from/to the DataXceiverServer.
*/
@Override
public void run() {
int opsProcessed = 0;
Op op = null;
dataXceiverServer.addPeer(peer);
try {
peer.setWriteTimeout(datanode.getDnConf().socketWriteTimeout);
InputStream input = socketIn;
if (dnConf.encryptDataTransfer) {
IOStreamPair encryptedStreams = null;
try {
encryptedStreams = DataTransferEncryptor
.getEncryptedStreams(socketOut, socketIn,
datanode.blockPoolTokenSecretManager,
dnConf.encryptionAlgorithm);
} catch (InvalidMagicNumberException imne) {
LOG.info("Failed to read expected encryption handshake from client "
+ "at "
+ peer.getRemoteAddressString()
+ ". Perhaps the client "
+ "is running an older version of Hadoop which does not support "
+ "encryption");
return;
}
input = encryptedStreams.in;
socketOut = encryptedStreams.out;
}
input = new BufferedInputStream(input,
HdfsConstants.SMALL_BUFFER_SIZE);
super.initialize(new DataInputStream(input));
// We process requests in a loop, and stay around for a short
// timeout.
// This optimistic behaviour allows the other end to reuse
// connections.
// Setting keepalive timeout to 0 disable this behavior.
do {
updateCurrentThreadName("Waiting for operation #"
+ (opsProcessed + 1));
try {
if (opsProcessed != 0) {
assert dnConf.socketKeepaliveTimeout > 0;
peer.setReadTimeout(dnConf.socketKeepaliveTimeout);
} else {
peer.setReadTimeout(dnConf.socketTimeout);
}
op = readOp();
} catch (InterruptedIOException ignored) {
// Time out while we wait for client rpc
break;
} catch (IOException err) {
// Since we optimistically expect the next op, it's quite
// normal to get EOF here.
if (opsProcessed > 0
&& (err instanceof EOFException || err instanceof ClosedChannelException)) {
if (LOG.isDebugEnabled()) {
LOG.debug("Cached " + peer + " closing after "
+ opsProcessed + " ops");
}
} else {
throw err;
}
break;
}
// restore normal timeout
if (opsProcessed != 0) {
peer.setReadTimeout(dnConf.socketTimeout);
}
opStartTime = now();
processOp(op);
++opsProcessed;
} while (!peer.isClosed() && dnConf.socketKeepaliveTimeout > 0);
} catch (Throwable t) {
LOG.error(datanode.getDisplayName()
+ ":DataXceiver error processing "
+ ((op == null) ? "unknown" : op.name()) + " operation "
+ " src: " + remoteAddress + " dest: " + localAddress, t);
} finally {
if (LOG.isDebugEnabled()) {
LOG.debug(datanode.getDisplayName()
+ ":Number of active connections is: "
+ datanode.getXceiverCount());
}
updateCurrentThreadName("Cleaning up");
dataXceiverServer.closePeer(peer);
IOUtils.closeStream(in);
}
}
@Override
public void requestShortCircuitFds(final ExtendedBlock blk,
final Token<BlockTokenIdentifier> token, int maxVersion)
throws IOException {
updateCurrentThreadName("Passing file descriptors for block " + blk);
BlockOpResponseProto.Builder bld = BlockOpResponseProto.newBuilder();
FileInputStream fis[] = null;
try {
if (peer.getDomainSocket() == null) {
throw new IOException("You cannot pass file descriptors over "
+ "anything but a UNIX domain socket.");
}
fis = datanode
.requestShortCircuitFdsForRead(blk, token, maxVersion);
bld.setStatus(SUCCESS);
bld.setShortCircuitAccessVersion(DataNode.CURRENT_BLOCK_FORMAT_VERSION);
} catch (ShortCircuitFdsVersionException e) {
bld.setStatus(ERROR_UNSUPPORTED);
bld.setShortCircuitAccessVersion(DataNode.CURRENT_BLOCK_FORMAT_VERSION);
bld.setMessage(e.getMessage());
} catch (ShortCircuitFdsUnsupportedException e) {
bld.setStatus(ERROR_UNSUPPORTED);
bld.setMessage(e.getMessage());
} catch (InvalidToken e) {
bld.setStatus(ERROR_ACCESS_TOKEN);
bld.setMessage(e.getMessage());
} catch (IOException e) {
bld.setStatus(ERROR);
bld.setMessage(e.getMessage());
}
try {
bld.build().writeDelimitedTo(socketOut);
if (fis != null) {
FileDescriptor fds[] = new FileDescriptor[fis.length];
for (int i = 0; i < fds.length; i++) {
fds[i] = fis[i].getFD();
}
byte buf[] = new byte[] { (byte) 0 };
peer.getDomainSocket().sendFileDescriptors(fds, buf, 0,
buf.length);
}
} finally {
if (ClientTraceLog.isInfoEnabled()) {
DatanodeRegistration dnR = datanode.getDNRegistrationForBP(blk
.getBlockPoolId());
BlockSender.ClientTraceLog.info(String.format(
"src: 127.0.0.1, dest: 127.0.0.1, op: REQUEST_SHORT_CIRCUIT_FDS,"
+ " blockid: %s, srvID: %s, success: %b",
blk.getBlockId(), dnR.getStorageID(), (fis != null)));
}
if (fis != null) {
IOUtils.cleanup(LOG, fis);
}
}
}
@Override
public void readBlock(final ExtendedBlock block,
final Token<BlockTokenIdentifier> blockToken,
final String clientName, final long blockOffset, final long length,
final boolean sendChecksum, final CachingStrategy cachingStrategy)
throws IOException {
previousOpClientName = clientName;
OutputStream baseStream = getOutputStream();
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(
baseStream, HdfsConstants.SMALL_BUFFER_SIZE));
checkAccess(out, true, block, blockToken, Op.READ_BLOCK,
BlockTokenSecretManager.AccessMode.READ);
// send the block
BlockSender blockSender = null;
DatanodeRegistration dnR = datanode.getDNRegistrationForBP(block
.getBlockPoolId());
final String clientTraceFmt = clientName.length() > 0
&& ClientTraceLog.isInfoEnabled() ? String.format(
DN_CLIENTTRACE_FORMAT, localAddress, remoteAddress, "%d",
"HDFS_READ", clientName, "%d", dnR.getStorageID(), block, "%d")
: dnR + " Served block " + block + " to " + remoteAddress;
updateCurrentThreadName("Sending block " + block);
try {
try {
blockSender = new BlockSender(block, blockOffset, length, true,
false, sendChecksum, datanode, clientTraceFmt,
cachingStrategy);
} catch (IOException e) {
String msg = "opReadBlock " + block + " received exception "
+ e;
LOG.info(msg);
sendResponse(ERROR, msg);
throw e;
}
// send op status
writeSuccessWithChecksumInfo(blockSender, new DataOutputStream(
getOutputStream()));
long read = blockSender.sendBlock(out, baseStream, null); // send
// data
if (blockSender.didSendEntireByteRange()) {
// If we sent the entire range, then we should expect the client
// to respond with a Status enum.
try {
ClientReadStatusProto stat = ClientReadStatusProto
.parseFrom(PBHelper.vintPrefixed(in));
if (!stat.hasStatus()) {
LOG.warn("Client "
+ peer.getRemoteAddressString()
+ " did not send a valid status code after reading. "
+ "Will close connection.");
IOUtils.closeStream(out);
}
} catch (IOException ioe) {
LOG.debug(
"Error reading client status response. Will close connection.",
ioe);
IOUtils.closeStream(out);
}
} else {
IOUtils.closeStream(out);
}
datanode.metrics.incrBytesRead((int) read);
datanode.metrics.incrBlocksRead();
} catch (SocketException ignored) {
if (LOG.isTraceEnabled()) {
LOG.trace(dnR + ":Ignoring exception while serving " + block
+ " to " + remoteAddress, ignored);
}
// Its ok for remote side to close the connection anytime.
datanode.metrics.incrBlocksRead();
IOUtils.closeStream(out);
} catch (IOException ioe) {
/*
* What exactly should we do here? Earlier version shutdown()
* datanode if there is disk error.
*/
LOG.warn(dnR + ":Got exception while serving " + block + " to "
+ remoteAddress, ioe);
throw ioe;
} finally {
IOUtils.closeStream(blockSender);
}
// update metrics
datanode.metrics.addReadBlockOp(elapsed());
datanode.metrics.incrReadsFromClient(peer.isLocal());
}
@Override
public void writeBlock(final ExtendedBlock block,
final Token<BlockTokenIdentifier> blockToken,
final String clientname, final DatanodeInfo[] targets,
final DatanodeInfo srcDataNode, final BlockConstructionStage stage,
final int pipelineSize, final long minBytesRcvd,
final long maxBytesRcvd, final long latestGenerationStamp,
DataChecksum requestedChecksum, CachingStrategy cachingStrategy)
throws IOException {
previousOpClientName = clientname;
updateCurrentThreadName("Receiving block " + block);
final boolean isDatanode = clientname.length() == 0;
final boolean isClient = !isDatanode;
final boolean isTransfer = stage == BlockConstructionStage.TRANSFER_RBW
|| stage == BlockConstructionStage.TRANSFER_FINALIZED;
// check single target for transfer-RBW/Finalized
if (isTransfer && targets.length > 0) {
throw new IOException(stage + " does not support multiple targets "
+ Arrays.asList(targets));
}
if (LOG.isDebugEnabled()) {
LOG.debug("opWriteBlock: stage=" + stage + ", clientname="
+ clientname + "\n block =" + block + ", newGs="
+ latestGenerationStamp + ", bytesRcvd=[" + minBytesRcvd
+ ", " + maxBytesRcvd + "]" + "\n targets="
+ Arrays.asList(targets) + "; pipelineSize=" + pipelineSize
+ ", srcDataNode=" + srcDataNode);
LOG.debug("isDatanode=" + isDatanode + ", isClient=" + isClient
+ ", isTransfer=" + isTransfer);
LOG.debug("writeBlock receive buf size "
+ peer.getReceiveBufferSize() + " tcp no delay "
+ peer.getTcpNoDelay());
}
// We later mutate block's generation stamp and length, but we need to
// forward the original version of the block to downstream mirrors, so
// make a copy here.
final ExtendedBlock originalBlock = new ExtendedBlock(block);
block.setNumBytes(dataXceiverServer.estimateBlockSize);
LOG.info("Receiving " + block + " src: " + remoteAddress + " dest: "
+ localAddress);
// reply to upstream datanode or client
final DataOutputStream replyOut = new DataOutputStream(
new BufferedOutputStream(getOutputStream(),
HdfsConstants.SMALL_BUFFER_SIZE));
checkAccess(replyOut, isClient, block, blockToken, Op.WRITE_BLOCK,
BlockTokenSecretManager.AccessMode.WRITE);
DataOutputStream mirrorOut = null; // stream to next target
DataInputStream mirrorIn = null; // reply from next target
Socket mirrorSock = null; // socket to next target
BlockReceiver blockReceiver = null; // responsible for data handling
String mirrorNode = null; // the name:port of next target
String firstBadLink = ""; // first datanode that failed in connection
// setup
Status mirrorInStatus = SUCCESS;
try {
if (isDatanode
|| stage != BlockConstructionStage.PIPELINE_CLOSE_RECOVERY) {
// open a block receiver
blockReceiver = new BlockReceiver(block, in,
peer.getRemoteAddressString(),
peer.getLocalAddressString(), stage,
latestGenerationStamp, minBytesRcvd, maxBytesRcvd,
clientname, srcDataNode, datanode, requestedChecksum,
cachingStrategy);
} else {
datanode.data.recoverClose(block, latestGenerationStamp,
minBytesRcvd);
}
//
// Connect to downstream machine, if appropriate
//
if (targets.length > 0) {
InetSocketAddress mirrorTarget = null;
// Connect to backup machine
mirrorNode = targets[0].getXferAddr(connectToDnViaHostname);
if (LOG.isDebugEnabled()) {
LOG.debug("Connecting to datanode " + mirrorNode);
}
mirrorTarget = NetUtils.createSocketAddr(mirrorNode);
mirrorSock = datanode.newSocket();
try {
int timeoutValue = dnConf.socketTimeout
+ (HdfsServerConstants.READ_TIMEOUT_EXTENSION * targets.length);
int writeTimeout = dnConf.socketWriteTimeout
+ (HdfsServerConstants.WRITE_TIMEOUT_EXTENSION * targets.length);
NetUtils.connect(mirrorSock, mirrorTarget, timeoutValue);
mirrorSock.setSoTimeout(timeoutValue);
mirrorSock
.setSendBufferSize(HdfsConstants.DEFAULT_DATA_SOCKET_SIZE);
OutputStream unbufMirrorOut = NetUtils.getOutputStream(
mirrorSock, writeTimeout);
InputStream unbufMirrorIn = NetUtils
.getInputStream(mirrorSock);
if (dnConf.encryptDataTransfer) {
IOStreamPair encryptedStreams = DataTransferEncryptor
.getEncryptedStreams(
unbufMirrorOut,
unbufMirrorIn,
datanode.blockPoolTokenSecretManager
.generateDataEncryptionKey(block
.getBlockPoolId()));
unbufMirrorOut = encryptedStreams.out;
unbufMirrorIn = encryptedStreams.in;
}
mirrorOut = new DataOutputStream(new BufferedOutputStream(
unbufMirrorOut, HdfsConstants.SMALL_BUFFER_SIZE));
mirrorIn = new DataInputStream(unbufMirrorIn);
new Sender(mirrorOut).writeBlock(originalBlock, blockToken,
clientname, targets, srcDataNode, stage,
pipelineSize, minBytesRcvd, maxBytesRcvd,
latestGenerationStamp, requestedChecksum,
cachingStrategy);
mirrorOut.flush();
// read connect ack (only for clients, not for replication
// req)
if (isClient) {
BlockOpResponseProto connectAck = BlockOpResponseProto
.parseFrom(PBHelper.vintPrefixed(mirrorIn));
mirrorInStatus = connectAck.getStatus();
firstBadLink = connectAck.getFirstBadLink();
if (LOG.isDebugEnabled() || mirrorInStatus != SUCCESS) {
LOG.info("Datanode "
+ targets.length
+ " got response for connect ack "
+ " from downstream datanode with firstbadlink as "
+ firstBadLink);
}
}
} catch (IOException e) {
if (isClient) {
BlockOpResponseProto.newBuilder().setStatus(ERROR)
// NB: Unconditionally using the xfer addr w/o
// hostname
.setFirstBadLink(targets[0].getXferAddr())
.build().writeDelimitedTo(replyOut);
replyOut.flush();
}
IOUtils.closeStream(mirrorOut);
mirrorOut = null;
IOUtils.closeStream(mirrorIn);
mirrorIn = null;
IOUtils.closeSocket(mirrorSock);
mirrorSock = null;
if (isClient) {
LOG.error(datanode + ":Exception transfering block "
+ block + " to mirror " + mirrorNode + ": " + e);
throw e;
} else {
LOG.info(datanode + ":Exception transfering " + block
+ " to mirror " + mirrorNode
+ "- continuing without the mirror", e);
}
}
}
// send connect-ack to source for clients and not
// transfer-RBW/Finalized
if (isClient && !isTransfer) {
if (LOG.isDebugEnabled() || mirrorInStatus != SUCCESS) {
LOG.info("Datanode "
+ targets.length
+ " forwarding connect ack to upstream firstbadlink is "
+ firstBadLink);
}
BlockOpResponseProto.newBuilder().setStatus(mirrorInStatus)
.setFirstBadLink(firstBadLink).build()
.writeDelimitedTo(replyOut);
replyOut.flush();
}
// receive the block and mirror to the next target
if (blockReceiver != null) {
String mirrorAddr = (mirrorSock == null) ? null : mirrorNode;
blockReceiver.receiveBlock(mirrorOut, mirrorIn, replyOut,
mirrorAddr, null, targets);
// send close-ack for transfer-RBW/Finalized
if (isTransfer) {
if (LOG.isTraceEnabled()) {
LOG.trace("TRANSFER: send close-ack");
}
writeResponse(SUCCESS, null, replyOut);
}
}
// update its generation stamp
if (isClient
&& stage == BlockConstructionStage.PIPELINE_CLOSE_RECOVERY) {
block.setGenerationStamp(latestGenerationStamp);
block.setNumBytes(minBytesRcvd);
}
// if this write is for a replication request or recovering
// a failed close for client, then confirm block. For other
// client-writes,
// the block is finalized in the PacketResponder.
if (isDatanode
|| stage == BlockConstructionStage.PIPELINE_CLOSE_RECOVERY) {
datanode.closeBlock(block, DataNode.EMPTY_DEL_HINT);
LOG.info("Received " + block + " src: " + remoteAddress
+ " dest: " + localAddress + " of size "
+ block.getNumBytes());
}
} catch (IOException ioe) {
LOG.info("opWriteBlock " + block + " received exception " + ioe);
throw ioe;
} finally {
// close all opened streams
IOUtils.closeStream(mirrorOut);
IOUtils.closeStream(mirrorIn);
IOUtils.closeStream(replyOut);
IOUtils.closeSocket(mirrorSock);
IOUtils.closeStream(blockReceiver);
}
// update metrics
datanode.metrics.addWriteBlockOp(elapsed());
datanode.metrics.incrWritesFromClient(peer.isLocal());
}
@Override
public void transferBlock(final ExtendedBlock blk,
final Token<BlockTokenIdentifier> blockToken,
final String clientName, final DatanodeInfo[] targets)
throws IOException {
checkAccess(socketOut, true, blk, blockToken, Op.TRANSFER_BLOCK,
BlockTokenSecretManager.AccessMode.COPY);
previousOpClientName = clientName;
updateCurrentThreadName(Op.TRANSFER_BLOCK + " " + blk);
final DataOutputStream out = new DataOutputStream(getOutputStream());
try {
datanode.transferReplicaForPipelineRecovery(blk, targets,
clientName);
writeResponse(Status.SUCCESS, null, out);
} finally {
IOUtils.closeStream(out);
}
}
@Override
public void chunksChecksum(final ExtendedBlock block,
final Token<BlockTokenIdentifier> blockToken) throws IOException {
final DataOutputStream out = new DataOutputStream(getOutputStream());
checkAccess(out, true, block, blockToken, Op.RSYNC_CHUNKS_CHECKSUM,
BlockTokenSecretManager.AccessMode.READ);
updateCurrentThreadName("Reading metadata for block " + block);
final LengthInputStream metadataIn = datanode.data
.getMetaDataInputStream(block);
final DataInputStream checksumIn = new DataInputStream(
new BufferedInputStream(metadataIn,
HdfsConstants.IO_FILE_BUFFER_SIZE));
updateCurrentThreadName("Getting checksums for block " + block);
try {
// read metadata file
final BlockMetadataHeader header = BlockMetadataHeader
.readHeader(checksumIn);
final DataChecksum checksum = header.getChecksum();
final int bytesPerCRC = checksum.getBytesPerChecksum();
final long crcPerBlock = (metadataIn.getLength() - BlockMetadataHeader
.getHeaderSize()) / checksum.getChecksumSize();
final int bytesPerChunk = checksum.getChecksumSize();
final long chunksPerBlock = (metadataIn.getLength() - BlockMetadataHeader
.getHeaderSize()) / checksum.getChecksumSize();
final List<Integer> checksums = new LinkedList<Integer>();
for (int i = 0; i < chunksPerBlock; i++) {
checksums.add(checksumIn.readInt());
}
// compute block checksum
final MD5Hash md5 = MD5Hash.digest(checksumIn);
if (LOG.isDebugEnabled()) {
LOG.debug("block=" + block + ", bytesPerCRC=" + bytesPerCRC
+ ", crcPerBlock=" + crcPerBlock + ", md5=" + md5);
}
LOG.printNoteLines("chunkPerBlock %d", chunksPerBlock);
LOG.printNoteLines("bytesPerChunk %d", bytesPerChunk);
LOG.printNoteLines("checksums[0] %x", checksums.get(0));
// write reply
BlockOpResponseProto.newBuilder().setStatus(SUCCESS)
.setChunksChecksumResponse(OpChunksChecksumResponseProto
.newBuilder().setBytesPerCrc(bytesPerCRC)
.setCrcPerBlock(crcPerBlock)
.setBytesPerChunk(bytesPerChunk)
.setChunksPerBlock(chunksPerBlock)
//.addAllChecksums(checksums)
.setMd5(ByteString.copyFrom(md5.getDigest()))
.setCrcType(PBHelper.convert(checksum.getChecksumType()))
)
.build()
.writeDelimitedTo(out);
out.flush();
} finally {
IOUtils.closeStream(out);
IOUtils.closeStream(checksumIn);
IOUtils.closeStream(metadataIn);
}
// update metrics
datanode.metrics.addBlockChecksumOp(elapsed());
}
@Override
public void blockChecksum(final ExtendedBlock block,
final Token<BlockTokenIdentifier> blockToken) throws IOException {
final DataOutputStream out = new DataOutputStream(getOutputStream());
checkAccess(out, true, block, blockToken, Op.BLOCK_CHECKSUM,
BlockTokenSecretManager.AccessMode.READ);
updateCurrentThreadName("Reading metadata for block " + block);
final LengthInputStream metadataIn = datanode.data
.getMetaDataInputStream(block);
final DataInputStream checksumIn = new DataInputStream(
new BufferedInputStream(metadataIn,
HdfsConstants.IO_FILE_BUFFER_SIZE));
updateCurrentThreadName("Getting checksum for block " + block);
try {
// read metadata file
final BlockMetadataHeader header = BlockMetadataHeader
.readHeader(checksumIn);
final DataChecksum checksum = header.getChecksum();
final int bytesPerCRC = checksum.getBytesPerChecksum();
final long crcPerBlock = (metadataIn.getLength() - BlockMetadataHeader
.getHeaderSize()) / checksum.getChecksumSize();
// compute block checksum
final MD5Hash md5 = MD5Hash.digest(checksumIn);
if (LOG.isDebugEnabled()) {
LOG.debug("block=" + block + ", bytesPerCRC=" + bytesPerCRC
+ ", crcPerBlock=" + crcPerBlock + ", md5=" + md5);
}
// write reply
BlockOpResponseProto
.newBuilder()
.setStatus(SUCCESS)
.setChecksumResponse(
OpBlockChecksumResponseProto
.newBuilder()
.setBytesPerCrc(bytesPerCRC)
.setCrcPerBlock(crcPerBlock)
.setMd5(ByteString.copyFrom(md5.getDigest()))
.setCrcType(
PBHelper.convert(checksum
.getChecksumType())))
.build().writeDelimitedTo(out);
out.flush();
} finally {
IOUtils.closeStream(out);
IOUtils.closeStream(checksumIn);
IOUtils.closeStream(metadataIn);
}
// update metrics
datanode.metrics.addBlockChecksumOp(elapsed());
}
@Override
public void copyBlock(final ExtendedBlock block,
final Token<BlockTokenIdentifier> blockToken) throws IOException {
updateCurrentThreadName("Copying block " + block);
// Read in the header
if (datanode.isBlockTokenEnabled) {
try {
datanode.blockPoolTokenSecretManager.checkAccess(blockToken,
null, block, BlockTokenSecretManager.AccessMode.COPY);
} catch (InvalidToken e) {
LOG.warn("Invalid access token in request from "
+ remoteAddress + " for OP_COPY_BLOCK for block "
+ block + " : " + e.getLocalizedMessage());
sendResponse(ERROR_ACCESS_TOKEN, "Invalid access token");
return;
}
}
if (!dataXceiverServer.balanceThrottler.acquire()) { // not able to
// start
String msg = "Not able to copy block " + block.getBlockId() + " "
+ "to " + peer.getRemoteAddressString()
+ " because threads " + "quota is exceeded.";
LOG.info(msg);
sendResponse(ERROR, msg);
return;
}
BlockSender blockSender = null;
DataOutputStream reply = null;
boolean isOpSuccess = true;
try {
// check if the block exists or not
blockSender = new BlockSender(block, 0, -1, false, false, true,
datanode, null, CachingStrategy.newDropBehind());
// set up response stream
OutputStream baseStream = getOutputStream();
reply = new DataOutputStream(new BufferedOutputStream(baseStream,
HdfsConstants.SMALL_BUFFER_SIZE));
// send status first
writeSuccessWithChecksumInfo(blockSender, reply);
// send block content to the target
long read = blockSender.sendBlock(reply, baseStream,
dataXceiverServer.balanceThrottler);
datanode.metrics.incrBytesRead((int) read);
datanode.metrics.incrBlocksRead();
LOG.info("Copied " + block + " to " + peer.getRemoteAddressString());
} catch (IOException ioe) {
isOpSuccess = false;
LOG.info("opCopyBlock " + block + " received exception " + ioe);
throw ioe;
} finally {
dataXceiverServer.balanceThrottler.release();
if (isOpSuccess) {
try {
// send one last byte to indicate that the resource is
// cleaned.
reply.writeChar('d');
} catch (IOException ignored) {
}
}
IOUtils.closeStream(reply);
IOUtils.closeStream(blockSender);
}
// update metrics
datanode.metrics.addCopyBlockOp(elapsed());
}
@Override
public void replaceBlock(final ExtendedBlock block,
final Token<BlockTokenIdentifier> blockToken, final String delHint,
final DatanodeInfo proxySource) throws IOException {
updateCurrentThreadName("Replacing block " + block + " from " + delHint);
/* read header */
block.setNumBytes(dataXceiverServer.estimateBlockSize);
if (datanode.isBlockTokenEnabled) {
try {
datanode.blockPoolTokenSecretManager
.checkAccess(blockToken, null, block,
BlockTokenSecretManager.AccessMode.REPLACE);
} catch (InvalidToken e) {
LOG.warn("Invalid access token in request from "
+ remoteAddress + " for OP_REPLACE_BLOCK for block "
+ block + " : " + e.getLocalizedMessage());
sendResponse(ERROR_ACCESS_TOKEN, "Invalid access token");
return;
}
}
if (!dataXceiverServer.balanceThrottler.acquire()) { // not able to
// start
String msg = "Not able to receive block " + block.getBlockId()
+ " from " + peer.getRemoteAddressString()
+ " because threads " + "quota is exceeded.";
LOG.warn(msg);
sendResponse(ERROR, msg);
return;
}
Socket proxySock = null;
DataOutputStream proxyOut = null;
Status opStatus = SUCCESS;
String errMsg = null;
BlockReceiver blockReceiver = null;
DataInputStream proxyReply = null;
try {
// get the output stream to the proxy
final String dnAddr = proxySource
.getXferAddr(connectToDnViaHostname);
if (LOG.isDebugEnabled()) {
LOG.debug("Connecting to datanode " + dnAddr);
}
InetSocketAddress proxyAddr = NetUtils.createSocketAddr(dnAddr);
proxySock = datanode.newSocket();
NetUtils.connect(proxySock, proxyAddr, dnConf.socketTimeout);
proxySock.setSoTimeout(dnConf.socketTimeout);
OutputStream unbufProxyOut = NetUtils.getOutputStream(proxySock,
dnConf.socketWriteTimeout);
InputStream unbufProxyIn = NetUtils.getInputStream(proxySock);
if (dnConf.encryptDataTransfer) {
IOStreamPair encryptedStreams = DataTransferEncryptor
.getEncryptedStreams(unbufProxyOut, unbufProxyIn,
datanode.blockPoolTokenSecretManager
.generateDataEncryptionKey(block
.getBlockPoolId()));
unbufProxyOut = encryptedStreams.out;
unbufProxyIn = encryptedStreams.in;
}
proxyOut = new DataOutputStream(new BufferedOutputStream(
unbufProxyOut, HdfsConstants.SMALL_BUFFER_SIZE));
proxyReply = new DataInputStream(new BufferedInputStream(
unbufProxyIn, HdfsConstants.IO_FILE_BUFFER_SIZE));
/* send request to the proxy */
new Sender(proxyOut).copyBlock(block, blockToken);
// receive the response from the proxy
BlockOpResponseProto copyResponse = BlockOpResponseProto
.parseFrom(PBHelper.vintPrefixed(proxyReply));
if (copyResponse.getStatus() != SUCCESS) {
if (copyResponse.getStatus() == ERROR_ACCESS_TOKEN) {
throw new IOException("Copy block " + block + " from "
+ proxySock.getRemoteSocketAddress()
+ " failed due to access token error");
}
throw new IOException("Copy block " + block + " from "
+ proxySock.getRemoteSocketAddress() + " failed");
}
// get checksum info about the block we're copying
ReadOpChecksumInfoProto checksumInfo = copyResponse
.getReadOpChecksumInfo();
DataChecksum remoteChecksum = DataTransferProtoUtil
.fromProto(checksumInfo.getChecksum());
// open a block receiver and check if the block does not exist
blockReceiver = new BlockReceiver(block, proxyReply, proxySock
.getRemoteSocketAddress().toString(), proxySock
.getLocalSocketAddress().toString(), null, 0, 0, 0, "",
null, datanode, remoteChecksum,
CachingStrategy.newDropBehind());
// receive a block
blockReceiver.receiveBlock(null, null, null, null,
dataXceiverServer.balanceThrottler, null);
// notify name node
datanode.notifyNamenodeReceivedBlock(block, delHint);
LOG.info("Moved " + block + " from "
+ peer.getRemoteAddressString());
} catch (IOException ioe) {
opStatus = ERROR;
errMsg = "opReplaceBlock " + block + " received exception " + ioe;
LOG.info(errMsg);
throw ioe;
} finally {
// receive the last byte that indicates the proxy released its
// thread resource
if (opStatus == SUCCESS) {
try {
proxyReply.readChar();
} catch (IOException ignored) {
}
}
// now release the thread resource
dataXceiverServer.balanceThrottler.release();
// send response back
try {
sendResponse(opStatus, errMsg);
} catch (IOException ioe) {
LOG.warn("Error writing reply back to "
+ peer.getRemoteAddressString());
}
IOUtils.closeStream(proxyOut);
IOUtils.closeStream(blockReceiver);
IOUtils.closeStream(proxyReply);
}
// update metrics
datanode.metrics.addReplaceBlockOp(elapsed());
}
private long elapsed() {
return now() - opStartTime;
}
/**
* Utility function for sending a response.
*
* @param opStatus
* status message to write
* @param message
* message to send to the client or other DN
*/
private void sendResponse(Status status, String message) throws IOException {
writeResponse(status, message, getOutputStream());
}
private static void writeResponse(Status status, String message,
OutputStream out) throws IOException {
BlockOpResponseProto.Builder response = BlockOpResponseProto
.newBuilder().setStatus(status);
if (message != null) {
response.setMessage(message);
}
response.build().writeDelimitedTo(out);
out.flush();
}
private void writeSuccessWithChecksumInfo(BlockSender blockSender,
DataOutputStream out) throws IOException {
ReadOpChecksumInfoProto ckInfo = ReadOpChecksumInfoProto
.newBuilder()
.setChecksum(
DataTransferProtoUtil.toProto(blockSender.getChecksum()))
.setChunkOffset(blockSender.getOffset()).build();
BlockOpResponseProto response = BlockOpResponseProto.newBuilder()
.setStatus(SUCCESS).setReadOpChecksumInfo(ckInfo).build();
response.writeDelimitedTo(out);
out.flush();
}
private void checkAccess(OutputStream out, final boolean reply,
final ExtendedBlock blk, final Token<BlockTokenIdentifier> t,
final Op op, final BlockTokenSecretManager.AccessMode mode)
throws IOException {
if (datanode.isBlockTokenEnabled) {
if (LOG.isDebugEnabled()) {
LOG.debug("Checking block access token for block '"
+ blk.getBlockId() + "' with mode '" + mode + "'");
}
try {
datanode.blockPoolTokenSecretManager.checkAccess(t, null, blk,
mode);
} catch (InvalidToken e) {
try {
if (reply) {
BlockOpResponseProto.Builder resp = BlockOpResponseProto
.newBuilder().setStatus(ERROR_ACCESS_TOKEN);
if (mode == BlockTokenSecretManager.AccessMode.WRITE) {
DatanodeRegistration dnR = datanode
.getDNRegistrationForBP(blk
.getBlockPoolId());
// NB: Unconditionally using the xfer addr w/o
// hostname
resp.setFirstBadLink(dnR.getXferAddr());
}
resp.build().writeDelimitedTo(out);
out.flush();
}
LOG.warn("Block token verification failed: op=" + op
+ ", remoteAddress=" + remoteAddress + ", message="
+ e.getLocalizedMessage());
throw e;
} finally {
IOUtils.closeStream(out);
}
}
}
}
}
|
patch
|
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataXceiver.java
|
patch
|
|
Java
|
apache-2.0
|
b6ea3fdd88afc551f279847d0a61060be875ab39
| 0
|
ilscipio/scipio-erp,ilscipio/scipio-erp,ilscipio/scipio-erp,ilscipio/scipio-erp,ilscipio/scipio-erp
|
/*******************************************************************************
* 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.ofbiz.base.util;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import javolution.util.FastMap;
import com.ibm.icu.util.Calendar;
/**
* Utility class for handling java.util.Date, the java.sql data/time classes and related
*/
public class UtilDateTime {
public static final String[] months = {// // to be translated over CommonMonthName, see example in accounting
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November",
"December"
};
public static final String[] days = {// to be translated over CommonDayName, see example in accounting
"Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday", "Sunday"
};
public static final String[][] timevals = {
{"1000", "millisecond"},
{"60", "second"},
{"60", "minute"},
{"24", "hour"},
{"168", "week"}
};
public static final String[] TIME_INTERVALS = {"hour", "day", "week", "month", "quarter", "semester", "year"};
public static final DecimalFormat df = new DecimalFormat("0.00;-0.00");
/**
* JDBC escape format for java.sql.Date conversions.
*/
public static final String DATE_FORMAT = "yyyy-MM-dd";
/**
* JDBC escape format for java.sql.Timestamp conversions.
*/
public static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS";
/**
* JDBC escape format for java.sql.Time conversions.
*/
public static final String TIME_FORMAT = "HH:mm:ss";
public static double getInterval(Date from, Date thru) {
return thru != null ? thru.getTime() - from.getTime() : 0;
}
public static int getIntervalInDays(Timestamp from, Timestamp thru) {
return thru != null ? (int) ((thru.getTime() - from.getTime()) / (24*60*60*1000)) : 0;
}
public static Timestamp addDaysToTimestamp(Timestamp start, int days) {
return new Timestamp(start.getTime() + (24L*60L*60L*1000L*days));
}
public static Timestamp addDaysToTimestamp(Timestamp start, Double days) {
return new Timestamp(start.getTime() + ((int) (24L*60L*60L*1000L*days)));
}
public static double getInterval(Timestamp from, Timestamp thru) {
return thru != null ? thru.getTime() - from.getTime() + (thru.getNanos() - from.getNanos()) / 1000000 : 0;
}
public static String formatInterval(Date from, Date thru, int count, Locale locale) {
return formatInterval(getInterval(from, thru), count, locale);
}
public static String formatInterval(Date from, Date thru, Locale locale) {
return formatInterval(from, thru, 2, locale);
}
public static String formatInterval(Timestamp from, Timestamp thru, int count, Locale locale) {
return formatInterval(getInterval(from, thru), count, locale);
}
public static String formatInterval(Timestamp from, Timestamp thru, Locale locale) {
return formatInterval(from, thru, 2, locale);
}
public static String formatInterval(long interval, int count, Locale locale) {
return formatInterval((double) interval, count, locale);
}
public static String formatInterval(long interval, Locale locale) {
return formatInterval(interval, 2, locale);
}
public static String formatInterval(double interval, Locale locale) {
return formatInterval(interval, 2, locale);
}
public static String formatInterval(double interval, int count, Locale locale) {
ArrayList<Double> parts = new ArrayList<Double>(timevals.length);
for (String[] timeval: timevals) {
int value = Integer.valueOf(timeval[0]);
double remainder = interval % value;
interval = interval / value;
parts.add(remainder);
}
Map<String, Object> uiDateTimeMap = UtilProperties.getResourceBundleMap("DateTimeLabels", locale);
StringBuilder sb = new StringBuilder();
for (int i = parts.size() - 1; i >= 0 && count > 0; i--) {
Double D = parts.get(i);
double d = D.doubleValue();
if (d < 1) continue;
if (sb.length() > 0) sb.append(", ");
count--;
sb.append(count == 0 ? df.format(d) : Integer.toString(D.intValue()));
sb.append(' ');
Object label;
if (D.intValue() == 1) {
label = uiDateTimeMap.get(timevals[i][1] + ".singular");
} else {
label = uiDateTimeMap.get(timevals[i][1] + ".plural");
}
sb.append(label);
}
return sb.toString();
}
/**
* Return a Timestamp for right now
*
* @return Timestamp for right now
*/
public static java.sql.Timestamp nowTimestamp() {
return getTimestamp(System.currentTimeMillis());
}
/**
* Convert a millisecond value to a Timestamp.
* @param time millsecond value
* @return Timestamp
*/
public static java.sql.Timestamp getTimestamp(long time) {
return new java.sql.Timestamp(time);
}
/**
* Convert a millisecond value to a Timestamp.
* @param milliSecs millsecond value
* @return Timestamp
*/
public static Timestamp getTimestamp(String milliSecs) throws NumberFormatException {
return new Timestamp(Long.parseLong(milliSecs));
}
/**
* Returns currentTimeMillis as String
*
* @return String(currentTimeMillis)
*/
public static String nowAsString() {
return Long.toString(System.currentTimeMillis());
}
/**
* Return a string formatted as yyyyMMddHHmmss
*
* @return String formatted for right now
*/
public static String nowDateString() {
return nowDateString("yyyyMMddHHmmss");
}
/**
* Return a string formatted as format
*
* @return String formatted for right now
*/
public static String nowDateString(String format) {
SimpleDateFormat df = new SimpleDateFormat(format);
return df.format(new Date());
}
/**
* Return a Date for right now
*
* @return Date for right now
*/
public static java.util.Date nowDate() {
return new java.util.Date();
}
public static java.sql.Timestamp getDayStart(java.sql.Timestamp stamp) {
return getDayStart(stamp, 0);
}
public static java.sql.Timestamp getDayStart(java.sql.Timestamp stamp, int daysLater) {
return getDayStart(stamp, daysLater, TimeZone.getDefault(), Locale.getDefault());
}
public static java.sql.Timestamp getNextDayStart(java.sql.Timestamp stamp) {
return getDayStart(stamp, 1);
}
public static java.sql.Timestamp getDayEnd(java.sql.Timestamp stamp) {
return getDayEnd(stamp, Long.valueOf(0));
}
public static java.sql.Timestamp getDayEnd(java.sql.Timestamp stamp, Long daysLater) {
return getDayEnd(stamp, daysLater, TimeZone.getDefault(), Locale.getDefault());
}
/**
* Return the date for the first day of the year
*
* @param stamp
* @return java.sql.Timestamp
*/
public static java.sql.Timestamp getYearStart(java.sql.Timestamp stamp) {
return getYearStart(stamp, 0, 0, 0);
}
public static java.sql.Timestamp getYearStart(java.sql.Timestamp stamp, int daysLater) {
return getYearStart(stamp, daysLater, 0, 0);
}
public static java.sql.Timestamp getYearStart(java.sql.Timestamp stamp, int daysLater, int yearsLater) {
return getYearStart(stamp, daysLater, 0, yearsLater);
}
public static java.sql.Timestamp getYearStart(java.sql.Timestamp stamp, int daysLater, int monthsLater, int yearsLater) {
return getYearStart(stamp, daysLater, monthsLater, yearsLater, TimeZone.getDefault(), Locale.getDefault());
}
public static java.sql.Timestamp getYearStart(java.sql.Timestamp stamp, Number daysLater, Number monthsLater, Number yearsLater) {
return getYearStart(stamp, (daysLater == null ? 0 : daysLater.intValue()),
(monthsLater == null ? 0 : monthsLater.intValue()), (yearsLater == null ? 0 : yearsLater.intValue()));
}
/**
* Return the date for the first day of the month
*
* @param stamp
* @return java.sql.Timestamp
*/
public static java.sql.Timestamp getMonthStart(java.sql.Timestamp stamp) {
return getMonthStart(stamp, 0, 0);
}
public static java.sql.Timestamp getMonthStart(java.sql.Timestamp stamp, int daysLater) {
return getMonthStart(stamp, daysLater, 0);
}
public static java.sql.Timestamp getMonthStart(java.sql.Timestamp stamp, int daysLater, int monthsLater) {
return getMonthStart(stamp, daysLater, monthsLater, TimeZone.getDefault(), Locale.getDefault());
}
/**
* Return the date for the first day of the week
*
* @param stamp
* @return java.sql.Timestamp
*/
public static java.sql.Timestamp getWeekStart(java.sql.Timestamp stamp) {
return getWeekStart(stamp, 0, 0);
}
public static java.sql.Timestamp getWeekStart(java.sql.Timestamp stamp, int daysLater) {
return getWeekStart(stamp, daysLater, 0);
}
public static java.sql.Timestamp getWeekStart(java.sql.Timestamp stamp, int daysLater, int weeksLater) {
return getWeekStart(stamp, daysLater, weeksLater, TimeZone.getDefault(), Locale.getDefault());
}
public static java.sql.Timestamp getWeekEnd(java.sql.Timestamp stamp) {
return getWeekEnd(stamp, TimeZone.getDefault(), Locale.getDefault());
}
public static Calendar toCalendar(java.sql.Timestamp stamp) {
Calendar cal = Calendar.getInstance();
if (stamp != null) {
cal.setTimeInMillis(stamp.getTime());
}
return cal;
}
/**
* Converts a date String into a java.sql.Date
*
* @param date The date String: MM/DD/YYYY
* @return A java.sql.Date made from the date String
*/
public static java.sql.Date toSqlDate(String date) {
java.util.Date newDate = toDate(date, "00:00:00");
if (newDate != null) {
return new java.sql.Date(newDate.getTime());
} else {
return null;
}
}
/**
* Makes a java.sql.Date from separate Strings for month, day, year
*
* @param monthStr The month String
* @param dayStr The day String
* @param yearStr The year String
* @return A java.sql.Date made from separate Strings for month, day, year
*/
public static java.sql.Date toSqlDate(String monthStr, String dayStr, String yearStr) {
java.util.Date newDate = toDate(monthStr, dayStr, yearStr, "0", "0", "0");
if (newDate != null) {
return new java.sql.Date(newDate.getTime());
} else {
return null;
}
}
/**
* Makes a java.sql.Date from separate ints for month, day, year
*
* @param month The month int
* @param day The day int
* @param year The year int
* @return A java.sql.Date made from separate ints for month, day, year
*/
public static java.sql.Date toSqlDate(int month, int day, int year) {
java.util.Date newDate = toDate(month, day, year, 0, 0, 0);
if (newDate != null) {
return new java.sql.Date(newDate.getTime());
} else {
return null;
}
}
/**
* Converts a time String into a java.sql.Time
*
* @param time The time String: either HH:MM or HH:MM:SS
* @return A java.sql.Time made from the time String
*/
public static java.sql.Time toSqlTime(String time) {
java.util.Date newDate = toDate("1/1/1970", time);
if (newDate != null) {
return new java.sql.Time(newDate.getTime());
} else {
return null;
}
}
/**
* Makes a java.sql.Time from separate Strings for hour, minute, and second.
*
* @param hourStr The hour String
* @param minuteStr The minute String
* @param secondStr The second String
* @return A java.sql.Time made from separate Strings for hour, minute, and second.
*/
public static java.sql.Time toSqlTime(String hourStr, String minuteStr, String secondStr) {
java.util.Date newDate = toDate("0", "0", "0", hourStr, minuteStr, secondStr);
if (newDate != null) {
return new java.sql.Time(newDate.getTime());
} else {
return null;
}
}
/**
* Makes a java.sql.Time from separate ints for hour, minute, and second.
*
* @param hour The hour int
* @param minute The minute int
* @param second The second int
* @return A java.sql.Time made from separate ints for hour, minute, and second.
*/
public static java.sql.Time toSqlTime(int hour, int minute, int second) {
java.util.Date newDate = toDate(0, 0, 0, hour, minute, second);
if (newDate != null) {
return new java.sql.Time(newDate.getTime());
} else {
return null;
}
}
/**
* Converts a date and time String into a Timestamp
*
* @param dateTime A combined data and time string in the format "MM/DD/YYYY HH:MM:SS", the seconds are optional
* @return The corresponding Timestamp
*/
public static java.sql.Timestamp toTimestamp(String dateTime) {
java.util.Date newDate = toDate(dateTime);
if (newDate != null) {
return new java.sql.Timestamp(newDate.getTime());
} else {
return null;
}
}
/**
* Converts a date String and a time String into a Timestamp
*
* @param date The date String: MM/DD/YYYY
* @param time The time String: either HH:MM or HH:MM:SS
* @return A Timestamp made from the date and time Strings
*/
public static java.sql.Timestamp toTimestamp(String date, String time) {
java.util.Date newDate = toDate(date, time);
if (newDate != null) {
return new java.sql.Timestamp(newDate.getTime());
} else {
return null;
}
}
/**
* Makes a Timestamp from separate Strings for month, day, year, hour, minute, and second.
*
* @param monthStr The month String
* @param dayStr The day String
* @param yearStr The year String
* @param hourStr The hour String
* @param minuteStr The minute String
* @param secondStr The second String
* @return A Timestamp made from separate Strings for month, day, year, hour, minute, and second.
*/
public static java.sql.Timestamp toTimestamp(String monthStr, String dayStr, String yearStr, String hourStr,
String minuteStr, String secondStr) {
java.util.Date newDate = toDate(monthStr, dayStr, yearStr, hourStr, minuteStr, secondStr);
if (newDate != null) {
return new java.sql.Timestamp(newDate.getTime());
} else {
return null;
}
}
/**
* Makes a Timestamp from separate ints for month, day, year, hour, minute, and second.
*
* @param month The month int
* @param day The day int
* @param year The year int
* @param hour The hour int
* @param minute The minute int
* @param second The second int
* @return A Timestamp made from separate ints for month, day, year, hour, minute, and second.
*/
public static java.sql.Timestamp toTimestamp(int month, int day, int year, int hour, int minute, int second) {
java.util.Date newDate = toDate(month, day, year, hour, minute, second);
if (newDate != null) {
return new java.sql.Timestamp(newDate.getTime());
} else {
return null;
}
}
public static java.sql.Timestamp toTimestamp(Date date) {
if (date == null) return null;
return new Timestamp(date.getTime());
}
/**
* SCIPIO: Converts a timestamp into a Date
*
* @param dateTime a Timestamp
* @return The corresponding Date
*/
public static java.util.Date toDate(Timestamp timestamp) {
if (timestamp == null) {
return null;
}
long milliseconds = timestamp.getTime() + (timestamp.getNanos() / 1000000);
return new Date(milliseconds);
}
/**
* Converts a date and time String into a Date
*
* @param dateTime A combined data and time string in the format "MM/DD/YYYY HH:MM:SS", the seconds are optional
* @return The corresponding Date
*/
public static java.util.Date toDate(String dateTime) {
if (dateTime == null) {
return null;
}
// dateTime must have one space between the date and time...
String date = dateTime.substring(0, dateTime.indexOf(" "));
String time = dateTime.substring(dateTime.indexOf(" ") + 1);
return toDate(date, time);
}
/**
* Converts a date String and a time String into a Date
*
* @param date The date String: MM/DD/YYYY
* @param time The time String: either HH:MM or HH:MM:SS
* @return A Date made from the date and time Strings
*/
public static java.util.Date toDate(String date, String time) {
if (date == null || time == null) return null;
String month;
String day;
String year;
String hour;
String minute;
String second;
int dateSlash1 = date.indexOf("/");
int dateSlash2 = date.lastIndexOf("/");
if (dateSlash1 <= 0 || dateSlash1 == dateSlash2) return null;
int timeColon1 = time.indexOf(":");
int timeColon2 = time.lastIndexOf(":");
if (timeColon1 <= 0) return null;
month = date.substring(0, dateSlash1);
day = date.substring(dateSlash1 + 1, dateSlash2);
year = date.substring(dateSlash2 + 1);
hour = time.substring(0, timeColon1);
if (timeColon1 == timeColon2) {
minute = time.substring(timeColon1 + 1);
second = "0";
} else {
minute = time.substring(timeColon1 + 1, timeColon2);
second = time.substring(timeColon2 + 1);
}
return toDate(month, day, year, hour, minute, second);
}
/**
* Makes a Date from separate Strings for month, day, year, hour, minute, and second.
*
* @param monthStr The month String
* @param dayStr The day String
* @param yearStr The year String
* @param hourStr The hour String
* @param minuteStr The minute String
* @param secondStr The second String
* @return A Date made from separate Strings for month, day, year, hour, minute, and second.
*/
public static java.util.Date toDate(String monthStr, String dayStr, String yearStr, String hourStr,
String minuteStr, String secondStr) {
int month, day, year, hour, minute, second;
try {
month = Integer.parseInt(monthStr);
day = Integer.parseInt(dayStr);
year = Integer.parseInt(yearStr);
hour = Integer.parseInt(hourStr);
minute = Integer.parseInt(minuteStr);
second = Integer.parseInt(secondStr);
} catch (Exception e) {
return null;
}
return toDate(month, day, year, hour, minute, second);
}
/**
* Makes a Date from separate ints for month, day, year, hour, minute, and second.
*
* @param month The month int
* @param day The day int
* @param year The year int
* @param hour The hour int
* @param minute The minute int
* @param second The second int
* @return A Date made from separate ints for month, day, year, hour, minute, and second.
*/
public static java.util.Date toDate(int month, int day, int year, int hour, int minute, int second) {
Calendar calendar = Calendar.getInstance();
try {
calendar.set(year, month - 1, day, hour, minute, second);
calendar.set(Calendar.MILLISECOND, 0);
} catch (Exception e) {
return null;
}
return new java.util.Date(calendar.getTime().getTime());
}
/**
* Makes a date String in the given from a Date
*
* @param date The Date
* @return A date String in the given format
*/
public static String toDateString(java.util.Date date, String format) {
if (date == null) return "";
SimpleDateFormat dateFormat = null;
if (format != null) {
dateFormat = new SimpleDateFormat(format);
} else {
dateFormat = new SimpleDateFormat();
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return dateFormat.format(date);
}
/**
* Makes a date String in the format MM/DD/YYYY from a Date
*
* @param date The Date
* @return A date String in the format MM/DD/YYYY
*/
public static String toDateString(java.util.Date date) {
return toDateString(date, "MM/dd/yyyy");
}
/**
* Makes a time String in the format HH:MM:SS from a Date. If the seconds are 0, then the output is in HH:MM.
*
* @param date The Date
* @return A time String in the format HH:MM:SS or HH:MM
*/
public static String toTimeString(java.util.Date date) {
if (date == null) return "";
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return (toTimeString(calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND)));
}
/**
* Makes a time String in the format HH:MM:SS from a separate ints for hour, minute, and second. If the seconds are 0, then the output is in HH:MM.
*
* @param hour The hour int
* @param minute The minute int
* @param second The second int
* @return A time String in the format HH:MM:SS or HH:MM
*/
public static String toTimeString(int hour, int minute, int second) {
String hourStr;
String minuteStr;
String secondStr;
if (hour < 10) {
hourStr = "0" + hour;
} else {
hourStr = "" + hour;
}
if (minute < 10) {
minuteStr = "0" + minute;
} else {
minuteStr = "" + minute;
}
if (second < 10) {
secondStr = "0" + second;
} else {
secondStr = "" + second;
}
if (second == 0) {
return hourStr + ":" + minuteStr;
} else {
return hourStr + ":" + minuteStr + ":" + secondStr;
}
}
/**
* Makes a combined data and time string in the format "MM/DD/YYYY HH:MM:SS" from a Date. If the seconds are 0 they are left off.
*
* @param date The Date
* @return A combined data and time string in the format "MM/DD/YYYY HH:MM:SS" where the seconds are left off if they are 0.
*/
public static String toDateTimeString(java.util.Date date) {
if (date == null) return "";
String dateString = toDateString(date);
String timeString = toTimeString(date);
if (dateString != null && timeString != null) {
return dateString + " " + timeString;
} else {
return "";
}
}
public static String toGmtTimestampString(Timestamp timestamp) {
DateFormat df = DateFormat.getDateTimeInstance();
df.setTimeZone(TimeZone.getTimeZone("GMT"));
return df.format(timestamp);
}
/**
* Makes a Timestamp for the beginning of the month
*
* @return A Timestamp of the beginning of the month
*/
public static java.sql.Timestamp monthBegin() {
Calendar mth = Calendar.getInstance();
mth.set(Calendar.DAY_OF_MONTH, 1);
mth.set(Calendar.HOUR_OF_DAY, 0);
mth.set(Calendar.MINUTE, 0);
mth.set(Calendar.SECOND, 0);
mth.set(Calendar.MILLISECOND, 0);
mth.set(Calendar.AM_PM, Calendar.AM);
return new java.sql.Timestamp(mth.getTime().getTime());
}
/**
* returns a week number in a year for a Timestamp input
*
* @param input Timestamp date
* @return A int containing the week number
*/
public static int weekNumber(Timestamp input) {
return weekNumber(input, TimeZone.getDefault(), Locale.getDefault());
}
/**
* returns a day number in a week for a Timestamp input
*
* @param stamp Timestamp date
* @return A int containing the day number (sunday = 1, saturday = 7)
*/
public static int dayNumber(Timestamp stamp) {
Calendar tempCal = toCalendar(stamp, TimeZone.getDefault(), Locale.getDefault());
return tempCal.get(Calendar.DAY_OF_WEEK);
}
public static int weekNumber(Timestamp input, int startOfWeek) {
Calendar calendar = Calendar.getInstance();
calendar.setFirstDayOfWeek(startOfWeek);
if (startOfWeek == Calendar.MONDAY) {
calendar.setMinimalDaysInFirstWeek(4);
} else if (startOfWeek == Calendar.SUNDAY) {
calendar.setMinimalDaysInFirstWeek(3);
}
calendar.setTime(new java.util.Date(input.getTime()));
return calendar.get(Calendar.WEEK_OF_YEAR);
}
// ----- New methods that take a timezone and locale -- //
public static Calendar getCalendarInstance(TimeZone timeZone, Locale locale) {
return Calendar.getInstance(com.ibm.icu.util.TimeZone.getTimeZone(timeZone.getID()), locale);
}
/**
* Returns a Calendar object initialized to the specified date/time, time zone,
* and locale.
*
* @param date date/time to use
* @param timeZone
* @param locale
* @return Calendar object
* @see java.util.Calendar
*/
public static Calendar toCalendar(Date date, TimeZone timeZone, Locale locale) {
Calendar cal = getCalendarInstance(timeZone, locale);
if (date != null) {
cal.setTime(date);
}
return cal;
}
/**
* Perform date/time arithmetic on a Timestamp. This is the only accurate way to
* perform date/time arithmetic across locales and time zones.
*
* @param stamp date/time to perform arithmetic on
* @param adjType the adjustment type to perform. Use one of the java.util.Calendar fields.
* @param adjQuantity the adjustment quantity.
* @param timeZone
* @param locale
* @return adjusted Timestamp
* @see java.util.Calendar
*/
public static Timestamp adjustTimestamp(Timestamp stamp, int adjType, int adjQuantity, TimeZone timeZone, Locale locale) {
Calendar tempCal = toCalendar(stamp, timeZone, locale);
tempCal.add(adjType, adjQuantity);
return new Timestamp(tempCal.getTimeInMillis());
}
public static Timestamp adjustTimestamp(Timestamp stamp, Integer adjType, Integer adjQuantity) {
Calendar tempCal = toCalendar(stamp);
tempCal.add(adjType, adjQuantity);
return new Timestamp(tempCal.getTimeInMillis());
}
public static Timestamp getHourStart(Timestamp stamp, TimeZone timeZone, Locale locale) {
return getHourStart(stamp, 0, timeZone, locale);
}
public static Timestamp getHourStart(Timestamp stamp, int hoursLater, TimeZone timeZone, Locale locale) {
Calendar tempCal = toCalendar(stamp, timeZone, locale);
tempCal.set(tempCal.get(Calendar.YEAR), tempCal.get(Calendar.MONTH), tempCal.get(Calendar.DAY_OF_MONTH), tempCal.get(Calendar.HOUR_OF_DAY), 0, 0);
tempCal.add(Calendar.HOUR_OF_DAY, hoursLater);
Timestamp retStamp = new Timestamp(tempCal.getTimeInMillis());
retStamp.setNanos(0);
return retStamp;
}
public static Timestamp getHourEnd(Timestamp stamp, TimeZone timeZone, Locale locale) {
return getHourEnd(stamp, Long.valueOf(0), timeZone, locale);
}
public static Timestamp getHourEnd(Timestamp stamp, Long hoursLater, TimeZone timeZone, Locale locale) {
Calendar tempCal = toCalendar(stamp, timeZone, locale);
tempCal.set(tempCal.get(Calendar.YEAR), tempCal.get(Calendar.MONTH), tempCal.get(Calendar.DAY_OF_MONTH), tempCal.get(Calendar.HOUR_OF_DAY), 59, 59);
tempCal.add(Calendar.HOUR_OF_DAY, hoursLater.intValue());
Timestamp retStamp = new Timestamp(tempCal.getTimeInMillis());
retStamp.setNanos(0);
return retStamp;
}
public static Timestamp getDayStart(Timestamp stamp, TimeZone timeZone, Locale locale) {
return getDayStart(stamp, 0, timeZone, locale);
}
public static Timestamp getDayStart(Timestamp stamp, int daysLater, TimeZone timeZone, Locale locale) {
Calendar tempCal = toCalendar(stamp, timeZone, locale);
tempCal.set(tempCal.get(Calendar.YEAR), tempCal.get(Calendar.MONTH), tempCal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
tempCal.add(Calendar.DAY_OF_MONTH, daysLater);
Timestamp retStamp = new Timestamp(tempCal.getTimeInMillis());
retStamp.setNanos(0);
return retStamp;
}
public static Timestamp getDayEnd(Timestamp stamp, TimeZone timeZone, Locale locale) {
return getDayEnd(stamp, Long.valueOf(0), timeZone, locale);
}
public static Timestamp getDayEnd(Timestamp stamp, Long daysLater, TimeZone timeZone, Locale locale) {
Calendar tempCal = toCalendar(stamp, timeZone, locale);
tempCal.set(tempCal.get(Calendar.YEAR), tempCal.get(Calendar.MONTH), tempCal.get(Calendar.DAY_OF_MONTH), 23, 59, 59);
tempCal.add(Calendar.DAY_OF_MONTH, daysLater.intValue());
Timestamp retStamp = new Timestamp(tempCal.getTimeInMillis());
retStamp.setNanos(0);
//MSSQL datetime field has accuracy of 3 milliseconds and setting the nano seconds cause the date to be rounded to next day
//retStamp.setNanos(999999999);
return retStamp;
}
public static Timestamp getWeekStart(Timestamp stamp, TimeZone timeZone, Locale locale) {
return getWeekStart(stamp, 0, 0, timeZone, locale);
}
public static Timestamp getWeekStart(Timestamp stamp, int daysLater, TimeZone timeZone, Locale locale) {
return getWeekStart(stamp, daysLater, 0, timeZone, locale);
}
public static Timestamp getWeekStart(Timestamp stamp, int daysLater, int weeksLater, TimeZone timeZone, Locale locale) {
Calendar tempCal = toCalendar(stamp, timeZone, locale);
tempCal.set(tempCal.get(Calendar.YEAR), tempCal.get(Calendar.MONTH), tempCal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
tempCal.add(Calendar.DAY_OF_MONTH, daysLater);
tempCal.set(Calendar.DAY_OF_WEEK, tempCal.getFirstDayOfWeek());
tempCal.add(Calendar.WEEK_OF_MONTH, weeksLater);
Timestamp retStamp = new Timestamp(tempCal.getTimeInMillis());
retStamp.setNanos(0);
return retStamp;
}
public static Timestamp getWeekEnd(Timestamp stamp, TimeZone timeZone, Locale locale) {
Timestamp weekStart = getWeekStart(stamp, timeZone, locale);
Calendar tempCal = toCalendar(weekStart, timeZone, locale);
tempCal.add(Calendar.DAY_OF_MONTH, 6);
return getDayEnd(new Timestamp(tempCal.getTimeInMillis()), timeZone, locale);
}
public static Timestamp getMonthStart(Timestamp stamp, TimeZone timeZone, Locale locale) {
return getMonthStart(stamp, 0, 0, timeZone, locale);
}
public static Timestamp getMonthStart(Timestamp stamp, int daysLater, TimeZone timeZone, Locale locale) {
return getMonthStart(stamp, daysLater, 0, timeZone, locale);
}
public static Timestamp getMonthStart(Timestamp stamp, int daysLater, int monthsLater, TimeZone timeZone, Locale locale) {
Calendar tempCal = toCalendar(stamp, timeZone, locale);
tempCal.set(tempCal.get(Calendar.YEAR), tempCal.get(Calendar.MONTH), 1, 0, 0, 0);
tempCal.add(Calendar.MONTH, monthsLater);
tempCal.add(Calendar.DAY_OF_MONTH, daysLater);
Timestamp retStamp = new Timestamp(tempCal.getTimeInMillis());
retStamp.setNanos(0);
return retStamp;
}
public static Timestamp getMonthEnd(Timestamp stamp, TimeZone timeZone, Locale locale) {
Calendar tempCal = toCalendar(stamp, timeZone, locale);
tempCal.set(tempCal.get(Calendar.YEAR), tempCal.get(Calendar.MONTH), tempCal.getActualMaximum(Calendar.DAY_OF_MONTH), 0, 0, 0);
return getDayEnd(new Timestamp(tempCal.getTimeInMillis()), timeZone, locale);
}
public static Timestamp getYearStart(Timestamp stamp, TimeZone timeZone, Locale locale) {
return getYearStart(stamp, 0, 0, 0, timeZone, locale);
}
public static Timestamp getYearStart(Timestamp stamp, int daysLater, TimeZone timeZone, Locale locale) {
return getYearStart(stamp, daysLater, 0, 0, timeZone, locale);
}
public static Timestamp getYearStart(Timestamp stamp, int daysLater, int yearsLater, TimeZone timeZone, Locale locale) {
return getYearStart(stamp, daysLater, 0, yearsLater, timeZone, locale);
}
public static Timestamp getYearStart(Timestamp stamp, Number daysLater, Number monthsLater, Number yearsLater, TimeZone timeZone, Locale locale) {
return getYearStart(stamp, (daysLater == null ? 0 : daysLater.intValue()),
(monthsLater == null ? 0 : monthsLater.intValue()), (yearsLater == null ? 0 : yearsLater.intValue()), timeZone, locale);
}
public static Timestamp getYearStart(Timestamp stamp, int daysLater, int monthsLater, int yearsLater, TimeZone timeZone, Locale locale) {
Calendar tempCal = toCalendar(stamp, timeZone, locale);
tempCal.set(tempCal.get(Calendar.YEAR), Calendar.JANUARY, 1, 0, 0, 0);
tempCal.add(Calendar.YEAR, yearsLater);
tempCal.add(Calendar.MONTH, monthsLater);
tempCal.add(Calendar.DAY_OF_MONTH, daysLater);
Timestamp retStamp = new Timestamp(tempCal.getTimeInMillis());
retStamp.setNanos(0);
return retStamp;
}
public static Timestamp getYearEnd(Timestamp stamp, TimeZone timeZone, Locale locale) {
Calendar tempCal = toCalendar(stamp, timeZone, locale);
tempCal.set(tempCal.get(Calendar.YEAR), tempCal.getActualMaximum(Calendar.MONTH) + 1, 0, 0, 0, 0);
return getMonthEnd(new Timestamp(tempCal.getTimeInMillis()), timeZone, locale);
}
public static int weekNumber(Timestamp stamp, TimeZone timeZone, Locale locale) {
Calendar tempCal = toCalendar(stamp, timeZone, locale);
return tempCal.get(Calendar.WEEK_OF_YEAR);
}
/**
* Returns a List of day name Strings - suitable for calendar headings.
* @param locale
* @return List of day name Strings
*/
public static List<String> getDayNames(Locale locale) {
Calendar tempCal = Calendar.getInstance(locale);
tempCal.set(Calendar.DAY_OF_WEEK, tempCal.getFirstDayOfWeek());
SimpleDateFormat dateFormat = new SimpleDateFormat("EEEE", locale);
List<String> resultList = new ArrayList<String>();
for (int i = 0; i < 7; i++) {
resultList.add(dateFormat.format(tempCal.getTime()));
tempCal.roll(Calendar.DAY_OF_WEEK, 1);
}
return resultList;
}
/**
* Returns a List of month name Strings - suitable for calendar headings.
*
* @param locale
* @return List of month name Strings
*/
public static List<String> getMonthNames(Locale locale) {
Calendar tempCal = Calendar.getInstance(locale);
tempCal.set(Calendar.MONTH, Calendar.JANUARY);
SimpleDateFormat dateFormat = new SimpleDateFormat("MMMM", locale);
List<String> resultList = new ArrayList<String>();
for (int i = Calendar.JANUARY; i <= tempCal.getActualMaximum(Calendar.MONTH); i++) {
resultList.add(dateFormat.format(tempCal.getTime()));
tempCal.roll(Calendar.MONTH, 1);
}
return resultList;
}
/**
* Returns an initialized DateFormat object.
*
* @param dateFormat
* optional format string
* @param tz
* @param locale
* can be null if dateFormat is not null
* @return DateFormat object
*/
public static DateFormat toDateFormat(String dateFormat, TimeZone tz, Locale locale) {
DateFormat df = null;
if (UtilValidate.isEmpty(dateFormat)) {
df = DateFormat.getDateInstance(DateFormat.SHORT, locale);
} else {
df = new SimpleDateFormat(dateFormat, locale == null ? Locale.getDefault() : locale);
}
df.setTimeZone(tz);
return df;
}
/**
* Returns an initialized DateFormat object.
* @param dateTimeFormat optional format string
* @param tz
* @param locale can be null if dateTimeFormat is not null
* @return DateFormat object
*/
public static DateFormat toDateTimeFormat(String dateTimeFormat, TimeZone tz, Locale locale) {
DateFormat df = null;
if (UtilValidate.isEmpty(dateTimeFormat)) {
df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM, locale);
} else {
df = new SimpleDateFormat(dateTimeFormat, locale == null ? Locale.getDefault() : locale);
}
df.setTimeZone(tz);
return df;
}
/**
* Returns an initialized DateFormat object.
* @param timeFormat optional format string
* @param tz
* @param locale can be null if timeFormat is not null
* @return DateFormat object
*/
public static DateFormat toTimeFormat(String timeFormat, TimeZone tz, Locale locale) {
DateFormat df = null;
if (UtilValidate.isEmpty(timeFormat)) {
df = DateFormat.getTimeInstance(DateFormat.MEDIUM, locale);
} else {
df = new SimpleDateFormat(timeFormat, locale == null ? Locale.getDefault() : locale);
}
df.setTimeZone(tz);
return df;
}
/**
* Localized String to Timestamp conversion. To be used in tandem with timeStampToString().
*/
public static Timestamp stringToTimeStamp(String dateTimeString, TimeZone tz, Locale locale) throws ParseException {
return stringToTimeStamp(dateTimeString, null, tz, locale);
}
/**
* Localized String to Timestamp conversion. To be used in tandem with timeStampToString().
*/
public static Timestamp stringToTimeStamp(String dateTimeString, String dateTimeFormat, TimeZone tz, Locale locale) throws ParseException {
DateFormat dateFormat = toDateTimeFormat(dateTimeFormat, tz, locale);
Date parsedDate = dateFormat.parse(dateTimeString);
return new Timestamp(parsedDate.getTime());
}
/**
* Localized Timestamp to String conversion. To be used in tandem with stringToTimeStamp().
*/
public static String timeStampToString(Timestamp stamp, TimeZone tz, Locale locale) {
return timeStampToString(stamp, null, tz, locale);
}
/**
* Localized Timestamp to String conversion. To be used in tandem with stringToTimeStamp().
*/
public static String timeStampToString(Timestamp stamp, String dateTimeFormat, TimeZone tz, Locale locale) {
DateFormat dateFormat = toDateTimeFormat(dateTimeFormat, tz, locale);
return dateFormat.format(stamp);
}
// Private lazy-initializer class
private static class TimeZoneHolder {
private static final List<TimeZone> availableTimeZoneList = getTimeZones();
private static List<TimeZone> getTimeZones() {
ArrayList<TimeZone> availableTimeZoneList = new ArrayList<TimeZone>();
List<String> idList = null;
String tzString = UtilProperties.getPropertyValue("general", "timeZones.available");
if (UtilValidate.isNotEmpty(tzString)) {
idList = StringUtil.split(tzString, ",");
} else {
idList = Arrays.asList(TimeZone.getAvailableIDs());
}
for (String id : idList) {
TimeZone curTz = TimeZone.getTimeZone(id);
availableTimeZoneList.add(curTz);
}
availableTimeZoneList.trimToSize();
return Collections.unmodifiableList(availableTimeZoneList);
}
}
/** Returns a List of available TimeZone objects.
* @see java.util.TimeZone
*/
public static List<TimeZone> availableTimeZones() {
return TimeZoneHolder.availableTimeZoneList;
}
/** Returns a TimeZone object based upon a time zone ID. Method defaults to
* server's time zone if tzID is null or empty.
* @see java.util.TimeZone
*/
public static TimeZone toTimeZone(String tzId) {
if (UtilValidate.isEmpty(tzId)) {
return TimeZone.getDefault();
} else {
return TimeZone.getTimeZone(tzId);
}
}
/** Returns a TimeZone object based upon an hour offset from GMT.
* @see java.util.TimeZone
*/
public static TimeZone toTimeZone(int gmtOffset) {
if (gmtOffset > 12 || gmtOffset < -14) {
throw new IllegalArgumentException("Invalid GMT offset");
}
String tzId = gmtOffset > 0 ? "Etc/GMT+" : "Etc/GMT";
return TimeZone.getTimeZone(tzId + gmtOffset);
}
public static int getSecond(Timestamp stamp, TimeZone timeZone, Locale locale) {
Calendar cal = toCalendar(stamp, timeZone, locale);
return cal.get(Calendar.SECOND);
}
public static int getMinute(Timestamp stamp, TimeZone timeZone, Locale locale) {
Calendar cal = toCalendar(stamp, timeZone, locale);
return cal.get(Calendar.MINUTE);
}
public static int getHour(Timestamp stamp, TimeZone timeZone, Locale locale) {
Calendar cal = toCalendar(stamp, timeZone, locale);
return cal.get(Calendar.HOUR_OF_DAY);
}
public static int getDayOfWeek(Timestamp stamp, TimeZone timeZone, Locale locale) {
Calendar cal = toCalendar(stamp, timeZone, locale);
return cal.get(Calendar.DAY_OF_WEEK);
}
public static int getDayOfMonth(Timestamp stamp, TimeZone timeZone, Locale locale) {
Calendar cal = toCalendar(stamp, timeZone, locale);
return cal.get(Calendar.DAY_OF_MONTH);
}
public static int getDayOfYear(Timestamp stamp, TimeZone timeZone, Locale locale) {
Calendar cal = toCalendar(stamp, timeZone, locale);
return cal.get(Calendar.DAY_OF_YEAR);
}
public static int getWeek(Timestamp stamp, TimeZone timeZone, Locale locale) {
Calendar cal = toCalendar(stamp, timeZone, locale);
return cal.get(Calendar.WEEK_OF_YEAR);
}
public static int getMonth(Timestamp stamp, TimeZone timeZone, Locale locale) {
Calendar cal = toCalendar(stamp, timeZone, locale);
return cal.get(Calendar.MONTH);
}
public static int getYear(Timestamp stamp, TimeZone timeZone, Locale locale) {
Calendar cal = toCalendar(stamp, timeZone, locale);
return cal.get(Calendar.YEAR);
}
public static Date getEarliestDate() {
Calendar cal = getCalendarInstance(TimeZone.getTimeZone("GMT"), Locale.getDefault());
cal.set(Calendar.YEAR, cal.getActualMinimum(Calendar.YEAR));
cal.set(Calendar.MONTH, cal.getActualMinimum(Calendar.MONTH));
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
public static Date getLatestDate() {
Calendar cal = getCalendarInstance(TimeZone.getTimeZone("GMT"), Locale.getDefault());
cal.set(Calendar.YEAR, cal.getActualMaximum(Calendar.YEAR));
cal.set(Calendar.MONTH, cal.getActualMaximum(Calendar.MONTH));
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
cal.set(Calendar.MILLISECOND, 999);
return cal.getTime();
}
/**
* Returns a copy of <code>date</code> that cannot be modified.
* Attempts to modify the returned date will result in an
* <tt>UnsupportedOperationException</tt>.
*
* @param date
*/
public static Date unmodifiableDate(Date date) {
if (date instanceof ImmutableDate) {
return date;
}
return new ImmutableDate(date.getTime());
}
@SuppressWarnings("serial")
private static class ImmutableDate extends Date {
private ImmutableDate(long date) {
super(date);
}
@Override
public Object clone() {
// No need to clone an immutable object.
return this;
}
@Override
public void setYear(int year) {
throw new UnsupportedOperationException();
}
@Override
public void setMonth(int month) {
throw new UnsupportedOperationException();
}
@Override
public void setDate(int date) {
throw new UnsupportedOperationException();
}
@Override
public void setHours(int hours) {
throw new UnsupportedOperationException();
}
@Override
public void setMinutes(int minutes) {
throw new UnsupportedOperationException();
}
@Override
public void setSeconds(int seconds) {
throw new UnsupportedOperationException();
}
@Override
public void setTime(long time) {
throw new UnsupportedOperationException();
}
}
/**
* Scipio: Returns a map with begin/end timestamp for a given period. Defaults to month.
* @param period
* @param fromDate
* @param locale
* @param timezone
* @return a map with two fixed keys, dateBegin & dateEnd, representing the beginning and the end of the given period
*/
public static TimeInterval getPeriodInterval(String period, Timestamp fromDate, Locale locale, TimeZone timezone) {
return getPeriodInterval(period, 0, fromDate, locale, timezone);
}
public static TimeInterval getPeriodInterval(String period, int timeShift, Timestamp fromDate, Locale locale, TimeZone timezone) {
// Map<String, Timestamp> result = FastMap.newInstance();
Timestamp dateBegin = null;
Timestamp dateEnd = null;
if (!checkValidInterval(period))
return null;
Timestamp date = (UtilValidate.isNotEmpty(fromDate)) ? fromDate : UtilDateTime.nowTimestamp();
switch (period) {
case "hour":
dateBegin = getHourStart(date, timeShift, timezone, locale);
dateEnd = getHourEnd(dateBegin, timezone, locale);
break;
case "day":
dateBegin = getDayStart(date, timeShift);
dateEnd = getDayEnd(dateBegin);
break;
case "week":
dateBegin = getWeekStart(date, 0, timeShift);
dateEnd = getWeekEnd(dateBegin);
break;
case "month":
dateBegin = getMonthStart(date, 0, timeShift);
dateEnd = getMonthEnd(dateBegin, timezone, locale);
break;
case "quarter":
Calendar calendar = toCalendar(date);
calendar.set(Calendar.DAY_OF_MONTH, 1);
int month = UtilDateTime.getMonth(date, timezone, locale);
int quarter = 0;
if (month >= 2 && month < 5)
quarter = 3;
else if (month >= 5 && month < 8)
quarter = 6;
else if (month >= 8 && month < 11)
quarter = 9;
else if (month == 11)
quarter = 12;
calendar.set(Calendar.MONTH, quarter);
Timestamp monthStart = getMonthStart(toTimestamp(calendar.getTime()));
dateBegin = monthStart;
dateEnd = getMonthEnd(UtilDateTime.getMonthStart(monthStart, 0, 2), timezone, locale);
break;
case "semester":
calendar = toCalendar(date);
calendar.set(Calendar.DAY_OF_MONTH, 1);
month = UtilDateTime.getMonth(date, timezone, locale);
int semester = 0;
if (month >= 0 && month < 5)
semester = 5;
else if (month >= 5)
semester = 12;
calendar.set(Calendar.MONTH, semester);
monthStart = UtilDateTime.getMonthStart(toTimestamp(calendar.getTime()));
dateBegin = monthStart;
dateEnd = getMonthEnd(UtilDateTime.getMonthStart(monthStart, 0, 4), timezone, locale);
break;
case "year":
dateBegin = getYearStart(date, 0, timeShift);
dateEnd = getYearEnd(dateBegin, timezone, locale);
break;
default:
dateBegin = getMonthStart(date);
dateEnd = getMonthEnd(dateBegin, timezone, locale);
break;
}
return new TimeInterval(dateBegin, dateEnd);
}
/**
* Scipio: Enhanced version of getPeriodInterval that returns also a date formatter for a given period.
* @param period
* @param locale
* @param timezone
* @return a map with three fixed keys, dateBegin & dateEnd & dateFormatter, representing the beginning and the end of the given period
* and the date formatter needed to display the date.
*/
public static TimeInterval getPeriodIntervalAndFormatter(String period, Timestamp fromDate, Locale locale, TimeZone timezone) {
return getPeriodIntervalAndFormatter(period, 0, fromDate, locale, timezone);
}
public static TimeInterval getPeriodIntervalAndFormatter(String period, int timeShift, Timestamp fromDate, Locale locale, TimeZone timezone) {
if (!checkValidInterval(period))
return null;
TimeInterval timeInterval = getPeriodInterval(period, timeShift, fromDate, locale, timezone);
switch (period) {
case "hour":
timeInterval.setDateFormatter(new SimpleDateFormat("yyyy-MM-dd hha"));
break;
case "day":
timeInterval.setDateFormatter(new SimpleDateFormat("yyyy-MM-dd"));
break;
case "week":
timeInterval.setDateFormatter(new SimpleDateFormat("YYYY-'W'ww"));
break;
case "month":
timeInterval.setDateFormatter(new SimpleDateFormat("yyyy-MM"));
break;
case "quarter":
int month = UtilDateTime.getMonth(timeInterval.getDateBegin(), timezone, locale);
int quarter = 1;
if (month >= 3 && month < 6)
quarter = 2;
if (month >= 6 && month < 9)
quarter = 3;
if (month >= 9)
quarter = 4;
timeInterval.setDateFormatter(new SimpleDateFormat("yyyy-'" + quarter + "T'"));
break;
case "semester":
month = UtilDateTime.getMonth(timeInterval.getDateBegin(), timezone, locale);
int semester = 1;
if (month >= 5)
semester = 2;
timeInterval.setDateFormatter(new SimpleDateFormat("yyyy-'" + semester + "S'"));
break;
case "year":
timeInterval.setDateFormatter(new SimpleDateFormat("yyyy"));
break;
default:
timeInterval.setDateFormatter(new SimpleDateFormat("yyyy-MM"));
break;
}
return timeInterval;
}
/**
* Scipio: Checks if the interval passed is a valid one
*
* @param interval
* @return true or false depending on the result of evaluating the given
* interval against the valid list of intervals represented by the
* constant TIME_INTERVALS
*/
public static boolean checkValidInterval(String interval) {
return Arrays.asList(TIME_INTERVALS).contains(interval);
}
public static Timestamp getTimeStampFromIntervalScope(String iScope) {
return getTimeStampFromIntervalScope(iScope, -1);
}
public static Timestamp getTimeStampFromIntervalScope(String iScope, int iCount) {
iCount--;
if (iCount < 0)
iCount = getIntervalDefaultCount(iScope);
Calendar calendar = Calendar.getInstance();
if (iScope.equals("hour")) {
calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) - iCount);
} else if (iScope.equals("day")) {
calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - iCount);
} else if (iScope.equals("week")) {
calendar.set(Calendar.DAY_OF_WEEK, 1);
calendar.set(Calendar.WEEK_OF_YEAR, calendar.get(Calendar.WEEK_OF_YEAR) - iCount);
} else if (iScope.equals("month") || iScope.equals("quarter") || iScope.equals("semester")) {
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - iCount);
} else if (iScope.equals("year")) {
calendar.set(Calendar.DAY_OF_YEAR, 1);
calendar.set(Calendar.MONTH, 1);
calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR) - iCount);
}
return UtilDateTime.toTimestamp(calendar.getTime());
}
public static int getIntervalDefaultCount(String iScope) {
int iCount = 0;
if (iScope.equals("hour")) {
iCount = 12;
} else if (iScope.equals("day")) {
iCount = 30;
} else if (iScope.equals("week")) {
iCount = 4;
} else if (iScope.equals("month")) {
iCount = 12;
} else if (iScope.equals("quarter")) {
iCount = 16;
} else if (iScope.equals("semester")) {
iCount = 24;
} else if (iScope.equals("year")) {
iCount = 5;
}
return iCount;
}
public static class TimeInterval {
private final Timestamp dateBegin;
private final Timestamp dateEnd;
private DateFormat dateFormatter;
TimeInterval(Timestamp dateBegin, Timestamp dateEnd) {
this.dateBegin = dateBegin;
this.dateEnd = dateEnd;
}
TimeInterval(Timestamp dateBegin, Timestamp dateEnd, DateFormat dateFormatter) {
this(dateBegin, dateEnd);
this.setDateFormatter(dateFormatter);
}
public Timestamp getDateBegin() {
return dateBegin;
}
public Timestamp getDateEnd() {
return dateEnd;
}
public DateFormat getDateFormatter() {
return dateFormatter;
}
public void setDateFormatter(DateFormat dateFormatter) {
this.dateFormatter = dateFormatter;
}
}
}
|
framework/base/src/org/ofbiz/base/util/UtilDateTime.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.ofbiz.base.util;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import javolution.util.FastMap;
import com.ibm.icu.util.Calendar;
/**
* Utility class for handling java.util.Date, the java.sql data/time classes and related
*/
public class UtilDateTime {
public static final String[] months = {// // to be translated over CommonMonthName, see example in accounting
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November",
"December"
};
public static final String[] days = {// to be translated over CommonDayName, see example in accounting
"Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday", "Sunday"
};
public static final String[][] timevals = {
{"1000", "millisecond"},
{"60", "second"},
{"60", "minute"},
{"24", "hour"},
{"168", "week"}
};
public static final String[] TIME_INTERVALS = {"hour", "day", "week", "month", "quarter", "semester", "year"};
public static final DecimalFormat df = new DecimalFormat("0.00;-0.00");
/**
* JDBC escape format for java.sql.Date conversions.
*/
public static final String DATE_FORMAT = "yyyy-MM-dd";
/**
* JDBC escape format for java.sql.Timestamp conversions.
*/
public static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS";
/**
* JDBC escape format for java.sql.Time conversions.
*/
public static final String TIME_FORMAT = "HH:mm:ss";
public static double getInterval(Date from, Date thru) {
return thru != null ? thru.getTime() - from.getTime() : 0;
}
public static int getIntervalInDays(Timestamp from, Timestamp thru) {
return thru != null ? (int) ((thru.getTime() - from.getTime()) / (24*60*60*1000)) : 0;
}
public static Timestamp addDaysToTimestamp(Timestamp start, int days) {
return new Timestamp(start.getTime() + (24L*60L*60L*1000L*days));
}
public static Timestamp addDaysToTimestamp(Timestamp start, Double days) {
return new Timestamp(start.getTime() + ((int) (24L*60L*60L*1000L*days)));
}
public static double getInterval(Timestamp from, Timestamp thru) {
return thru != null ? thru.getTime() - from.getTime() + (thru.getNanos() - from.getNanos()) / 1000000 : 0;
}
public static String formatInterval(Date from, Date thru, int count, Locale locale) {
return formatInterval(getInterval(from, thru), count, locale);
}
public static String formatInterval(Date from, Date thru, Locale locale) {
return formatInterval(from, thru, 2, locale);
}
public static String formatInterval(Timestamp from, Timestamp thru, int count, Locale locale) {
return formatInterval(getInterval(from, thru), count, locale);
}
public static String formatInterval(Timestamp from, Timestamp thru, Locale locale) {
return formatInterval(from, thru, 2, locale);
}
public static String formatInterval(long interval, int count, Locale locale) {
return formatInterval((double) interval, count, locale);
}
public static String formatInterval(long interval, Locale locale) {
return formatInterval(interval, 2, locale);
}
public static String formatInterval(double interval, Locale locale) {
return formatInterval(interval, 2, locale);
}
public static String formatInterval(double interval, int count, Locale locale) {
ArrayList<Double> parts = new ArrayList<Double>(timevals.length);
for (String[] timeval: timevals) {
int value = Integer.valueOf(timeval[0]);
double remainder = interval % value;
interval = interval / value;
parts.add(remainder);
}
Map<String, Object> uiDateTimeMap = UtilProperties.getResourceBundleMap("DateTimeLabels", locale);
StringBuilder sb = new StringBuilder();
for (int i = parts.size() - 1; i >= 0 && count > 0; i--) {
Double D = parts.get(i);
double d = D.doubleValue();
if (d < 1) continue;
if (sb.length() > 0) sb.append(", ");
count--;
sb.append(count == 0 ? df.format(d) : Integer.toString(D.intValue()));
sb.append(' ');
Object label;
if (D.intValue() == 1) {
label = uiDateTimeMap.get(timevals[i][1] + ".singular");
} else {
label = uiDateTimeMap.get(timevals[i][1] + ".plural");
}
sb.append(label);
}
return sb.toString();
}
/**
* Return a Timestamp for right now
*
* @return Timestamp for right now
*/
public static java.sql.Timestamp nowTimestamp() {
return getTimestamp(System.currentTimeMillis());
}
/**
* Convert a millisecond value to a Timestamp.
* @param time millsecond value
* @return Timestamp
*/
public static java.sql.Timestamp getTimestamp(long time) {
return new java.sql.Timestamp(time);
}
/**
* Convert a millisecond value to a Timestamp.
* @param milliSecs millsecond value
* @return Timestamp
*/
public static Timestamp getTimestamp(String milliSecs) throws NumberFormatException {
return new Timestamp(Long.parseLong(milliSecs));
}
/**
* Returns currentTimeMillis as String
*
* @return String(currentTimeMillis)
*/
public static String nowAsString() {
return Long.toString(System.currentTimeMillis());
}
/**
* Return a string formatted as yyyyMMddHHmmss
*
* @return String formatted for right now
*/
public static String nowDateString() {
return nowDateString("yyyyMMddHHmmss");
}
/**
* Return a string formatted as format
*
* @return String formatted for right now
*/
public static String nowDateString(String format) {
SimpleDateFormat df = new SimpleDateFormat(format);
return df.format(new Date());
}
/**
* Return a Date for right now
*
* @return Date for right now
*/
public static java.util.Date nowDate() {
return new java.util.Date();
}
public static java.sql.Timestamp getDayStart(java.sql.Timestamp stamp) {
return getDayStart(stamp, 0);
}
public static java.sql.Timestamp getDayStart(java.sql.Timestamp stamp, int daysLater) {
return getDayStart(stamp, daysLater, TimeZone.getDefault(), Locale.getDefault());
}
public static java.sql.Timestamp getNextDayStart(java.sql.Timestamp stamp) {
return getDayStart(stamp, 1);
}
public static java.sql.Timestamp getDayEnd(java.sql.Timestamp stamp) {
return getDayEnd(stamp, Long.valueOf(0));
}
public static java.sql.Timestamp getDayEnd(java.sql.Timestamp stamp, Long daysLater) {
return getDayEnd(stamp, daysLater, TimeZone.getDefault(), Locale.getDefault());
}
/**
* Return the date for the first day of the year
*
* @param stamp
* @return java.sql.Timestamp
*/
public static java.sql.Timestamp getYearStart(java.sql.Timestamp stamp) {
return getYearStart(stamp, 0, 0, 0);
}
public static java.sql.Timestamp getYearStart(java.sql.Timestamp stamp, int daysLater) {
return getYearStart(stamp, daysLater, 0, 0);
}
public static java.sql.Timestamp getYearStart(java.sql.Timestamp stamp, int daysLater, int yearsLater) {
return getYearStart(stamp, daysLater, 0, yearsLater);
}
public static java.sql.Timestamp getYearStart(java.sql.Timestamp stamp, int daysLater, int monthsLater, int yearsLater) {
return getYearStart(stamp, daysLater, monthsLater, yearsLater, TimeZone.getDefault(), Locale.getDefault());
}
public static java.sql.Timestamp getYearStart(java.sql.Timestamp stamp, Number daysLater, Number monthsLater, Number yearsLater) {
return getYearStart(stamp, (daysLater == null ? 0 : daysLater.intValue()),
(monthsLater == null ? 0 : monthsLater.intValue()), (yearsLater == null ? 0 : yearsLater.intValue()));
}
/**
* Return the date for the first day of the month
*
* @param stamp
* @return java.sql.Timestamp
*/
public static java.sql.Timestamp getMonthStart(java.sql.Timestamp stamp) {
return getMonthStart(stamp, 0, 0);
}
public static java.sql.Timestamp getMonthStart(java.sql.Timestamp stamp, int daysLater) {
return getMonthStart(stamp, daysLater, 0);
}
public static java.sql.Timestamp getMonthStart(java.sql.Timestamp stamp, int daysLater, int monthsLater) {
return getMonthStart(stamp, daysLater, monthsLater, TimeZone.getDefault(), Locale.getDefault());
}
/**
* Return the date for the first day of the week
*
* @param stamp
* @return java.sql.Timestamp
*/
public static java.sql.Timestamp getWeekStart(java.sql.Timestamp stamp) {
return getWeekStart(stamp, 0, 0);
}
public static java.sql.Timestamp getWeekStart(java.sql.Timestamp stamp, int daysLater) {
return getWeekStart(stamp, daysLater, 0);
}
public static java.sql.Timestamp getWeekStart(java.sql.Timestamp stamp, int daysLater, int weeksLater) {
return getWeekStart(stamp, daysLater, weeksLater, TimeZone.getDefault(), Locale.getDefault());
}
public static java.sql.Timestamp getWeekEnd(java.sql.Timestamp stamp) {
return getWeekEnd(stamp, TimeZone.getDefault(), Locale.getDefault());
}
public static Calendar toCalendar(java.sql.Timestamp stamp) {
Calendar cal = Calendar.getInstance();
if (stamp != null) {
cal.setTimeInMillis(stamp.getTime());
}
return cal;
}
/**
* Converts a date String into a java.sql.Date
*
* @param date The date String: MM/DD/YYYY
* @return A java.sql.Date made from the date String
*/
public static java.sql.Date toSqlDate(String date) {
java.util.Date newDate = toDate(date, "00:00:00");
if (newDate != null) {
return new java.sql.Date(newDate.getTime());
} else {
return null;
}
}
/**
* Makes a java.sql.Date from separate Strings for month, day, year
*
* @param monthStr The month String
* @param dayStr The day String
* @param yearStr The year String
* @return A java.sql.Date made from separate Strings for month, day, year
*/
public static java.sql.Date toSqlDate(String monthStr, String dayStr, String yearStr) {
java.util.Date newDate = toDate(monthStr, dayStr, yearStr, "0", "0", "0");
if (newDate != null) {
return new java.sql.Date(newDate.getTime());
} else {
return null;
}
}
/**
* Makes a java.sql.Date from separate ints for month, day, year
*
* @param month The month int
* @param day The day int
* @param year The year int
* @return A java.sql.Date made from separate ints for month, day, year
*/
public static java.sql.Date toSqlDate(int month, int day, int year) {
java.util.Date newDate = toDate(month, day, year, 0, 0, 0);
if (newDate != null) {
return new java.sql.Date(newDate.getTime());
} else {
return null;
}
}
/**
* Converts a time String into a java.sql.Time
*
* @param time The time String: either HH:MM or HH:MM:SS
* @return A java.sql.Time made from the time String
*/
public static java.sql.Time toSqlTime(String time) {
java.util.Date newDate = toDate("1/1/1970", time);
if (newDate != null) {
return new java.sql.Time(newDate.getTime());
} else {
return null;
}
}
/**
* Makes a java.sql.Time from separate Strings for hour, minute, and second.
*
* @param hourStr The hour String
* @param minuteStr The minute String
* @param secondStr The second String
* @return A java.sql.Time made from separate Strings for hour, minute, and second.
*/
public static java.sql.Time toSqlTime(String hourStr, String minuteStr, String secondStr) {
java.util.Date newDate = toDate("0", "0", "0", hourStr, minuteStr, secondStr);
if (newDate != null) {
return new java.sql.Time(newDate.getTime());
} else {
return null;
}
}
/**
* Makes a java.sql.Time from separate ints for hour, minute, and second.
*
* @param hour The hour int
* @param minute The minute int
* @param second The second int
* @return A java.sql.Time made from separate ints for hour, minute, and second.
*/
public static java.sql.Time toSqlTime(int hour, int minute, int second) {
java.util.Date newDate = toDate(0, 0, 0, hour, minute, second);
if (newDate != null) {
return new java.sql.Time(newDate.getTime());
} else {
return null;
}
}
/**
* Converts a date and time String into a Timestamp
*
* @param dateTime A combined data and time string in the format "MM/DD/YYYY HH:MM:SS", the seconds are optional
* @return The corresponding Timestamp
*/
public static java.sql.Timestamp toTimestamp(String dateTime) {
java.util.Date newDate = toDate(dateTime);
if (newDate != null) {
return new java.sql.Timestamp(newDate.getTime());
} else {
return null;
}
}
/**
* Converts a date String and a time String into a Timestamp
*
* @param date The date String: MM/DD/YYYY
* @param time The time String: either HH:MM or HH:MM:SS
* @return A Timestamp made from the date and time Strings
*/
public static java.sql.Timestamp toTimestamp(String date, String time) {
java.util.Date newDate = toDate(date, time);
if (newDate != null) {
return new java.sql.Timestamp(newDate.getTime());
} else {
return null;
}
}
/**
* Makes a Timestamp from separate Strings for month, day, year, hour, minute, and second.
*
* @param monthStr The month String
* @param dayStr The day String
* @param yearStr The year String
* @param hourStr The hour String
* @param minuteStr The minute String
* @param secondStr The second String
* @return A Timestamp made from separate Strings for month, day, year, hour, minute, and second.
*/
public static java.sql.Timestamp toTimestamp(String monthStr, String dayStr, String yearStr, String hourStr,
String minuteStr, String secondStr) {
java.util.Date newDate = toDate(monthStr, dayStr, yearStr, hourStr, minuteStr, secondStr);
if (newDate != null) {
return new java.sql.Timestamp(newDate.getTime());
} else {
return null;
}
}
/**
* Makes a Timestamp from separate ints for month, day, year, hour, minute, and second.
*
* @param month The month int
* @param day The day int
* @param year The year int
* @param hour The hour int
* @param minute The minute int
* @param second The second int
* @return A Timestamp made from separate ints for month, day, year, hour, minute, and second.
*/
public static java.sql.Timestamp toTimestamp(int month, int day, int year, int hour, int minute, int second) {
java.util.Date newDate = toDate(month, day, year, hour, minute, second);
if (newDate != null) {
return new java.sql.Timestamp(newDate.getTime());
} else {
return null;
}
}
public static java.sql.Timestamp toTimestamp(Date date) {
if (date == null) return null;
return new Timestamp(date.getTime());
}
/**
* SCIPIO: Converts a timestamp into a Date
*
* @param dateTime a Timestamp
* @return The corresponding Date
*/
public static java.util.Date toDate(Timestamp timestamp) {
if (timestamp == null) {
return null;
}
long milliseconds = timestamp.getTime() + (timestamp.getNanos() / 1000000);
return new Date(milliseconds);
}
/**
* Converts a date and time String into a Date
*
* @param dateTime A combined data and time string in the format "MM/DD/YYYY HH:MM:SS", the seconds are optional
* @return The corresponding Date
*/
public static java.util.Date toDate(String dateTime) {
if (dateTime == null) {
return null;
}
// dateTime must have one space between the date and time...
String date = dateTime.substring(0, dateTime.indexOf(" "));
String time = dateTime.substring(dateTime.indexOf(" ") + 1);
return toDate(date, time);
}
/**
* Converts a date String and a time String into a Date
*
* @param date The date String: MM/DD/YYYY
* @param time The time String: either HH:MM or HH:MM:SS
* @return A Date made from the date and time Strings
*/
public static java.util.Date toDate(String date, String time) {
if (date == null || time == null) return null;
String month;
String day;
String year;
String hour;
String minute;
String second;
int dateSlash1 = date.indexOf("/");
int dateSlash2 = date.lastIndexOf("/");
if (dateSlash1 <= 0 || dateSlash1 == dateSlash2) return null;
int timeColon1 = time.indexOf(":");
int timeColon2 = time.lastIndexOf(":");
if (timeColon1 <= 0) return null;
month = date.substring(0, dateSlash1);
day = date.substring(dateSlash1 + 1, dateSlash2);
year = date.substring(dateSlash2 + 1);
hour = time.substring(0, timeColon1);
if (timeColon1 == timeColon2) {
minute = time.substring(timeColon1 + 1);
second = "0";
} else {
minute = time.substring(timeColon1 + 1, timeColon2);
second = time.substring(timeColon2 + 1);
}
return toDate(month, day, year, hour, minute, second);
}
/**
* Makes a Date from separate Strings for month, day, year, hour, minute, and second.
*
* @param monthStr The month String
* @param dayStr The day String
* @param yearStr The year String
* @param hourStr The hour String
* @param minuteStr The minute String
* @param secondStr The second String
* @return A Date made from separate Strings for month, day, year, hour, minute, and second.
*/
public static java.util.Date toDate(String monthStr, String dayStr, String yearStr, String hourStr,
String minuteStr, String secondStr) {
int month, day, year, hour, minute, second;
try {
month = Integer.parseInt(monthStr);
day = Integer.parseInt(dayStr);
year = Integer.parseInt(yearStr);
hour = Integer.parseInt(hourStr);
minute = Integer.parseInt(minuteStr);
second = Integer.parseInt(secondStr);
} catch (Exception e) {
return null;
}
return toDate(month, day, year, hour, minute, second);
}
/**
* Makes a Date from separate ints for month, day, year, hour, minute, and second.
*
* @param month The month int
* @param day The day int
* @param year The year int
* @param hour The hour int
* @param minute The minute int
* @param second The second int
* @return A Date made from separate ints for month, day, year, hour, minute, and second.
*/
public static java.util.Date toDate(int month, int day, int year, int hour, int minute, int second) {
Calendar calendar = Calendar.getInstance();
try {
calendar.set(year, month - 1, day, hour, minute, second);
calendar.set(Calendar.MILLISECOND, 0);
} catch (Exception e) {
return null;
}
return new java.util.Date(calendar.getTime().getTime());
}
/**
* Makes a date String in the given from a Date
*
* @param date The Date
* @return A date String in the given format
*/
public static String toDateString(java.util.Date date, String format) {
if (date == null) return "";
SimpleDateFormat dateFormat = null;
if (format != null) {
dateFormat = new SimpleDateFormat(format);
} else {
dateFormat = new SimpleDateFormat();
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return dateFormat.format(date);
}
/**
* Makes a date String in the format MM/DD/YYYY from a Date
*
* @param date The Date
* @return A date String in the format MM/DD/YYYY
*/
public static String toDateString(java.util.Date date) {
return toDateString(date, "MM/dd/yyyy");
}
/**
* Makes a time String in the format HH:MM:SS from a Date. If the seconds are 0, then the output is in HH:MM.
*
* @param date The Date
* @return A time String in the format HH:MM:SS or HH:MM
*/
public static String toTimeString(java.util.Date date) {
if (date == null) return "";
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return (toTimeString(calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND)));
}
/**
* Makes a time String in the format HH:MM:SS from a separate ints for hour, minute, and second. If the seconds are 0, then the output is in HH:MM.
*
* @param hour The hour int
* @param minute The minute int
* @param second The second int
* @return A time String in the format HH:MM:SS or HH:MM
*/
public static String toTimeString(int hour, int minute, int second) {
String hourStr;
String minuteStr;
String secondStr;
if (hour < 10) {
hourStr = "0" + hour;
} else {
hourStr = "" + hour;
}
if (minute < 10) {
minuteStr = "0" + minute;
} else {
minuteStr = "" + minute;
}
if (second < 10) {
secondStr = "0" + second;
} else {
secondStr = "" + second;
}
if (second == 0) {
return hourStr + ":" + minuteStr;
} else {
return hourStr + ":" + minuteStr + ":" + secondStr;
}
}
/**
* Makes a combined data and time string in the format "MM/DD/YYYY HH:MM:SS" from a Date. If the seconds are 0 they are left off.
*
* @param date The Date
* @return A combined data and time string in the format "MM/DD/YYYY HH:MM:SS" where the seconds are left off if they are 0.
*/
public static String toDateTimeString(java.util.Date date) {
if (date == null) return "";
String dateString = toDateString(date);
String timeString = toTimeString(date);
if (dateString != null && timeString != null) {
return dateString + " " + timeString;
} else {
return "";
}
}
public static String toGmtTimestampString(Timestamp timestamp) {
DateFormat df = DateFormat.getDateTimeInstance();
df.setTimeZone(TimeZone.getTimeZone("GMT"));
return df.format(timestamp);
}
/**
* Makes a Timestamp for the beginning of the month
*
* @return A Timestamp of the beginning of the month
*/
public static java.sql.Timestamp monthBegin() {
Calendar mth = Calendar.getInstance();
mth.set(Calendar.DAY_OF_MONTH, 1);
mth.set(Calendar.HOUR_OF_DAY, 0);
mth.set(Calendar.MINUTE, 0);
mth.set(Calendar.SECOND, 0);
mth.set(Calendar.MILLISECOND, 0);
mth.set(Calendar.AM_PM, Calendar.AM);
return new java.sql.Timestamp(mth.getTime().getTime());
}
/**
* returns a week number in a year for a Timestamp input
*
* @param input Timestamp date
* @return A int containing the week number
*/
public static int weekNumber(Timestamp input) {
return weekNumber(input, TimeZone.getDefault(), Locale.getDefault());
}
/**
* returns a day number in a week for a Timestamp input
*
* @param stamp Timestamp date
* @return A int containing the day number (sunday = 1, saturday = 7)
*/
public static int dayNumber(Timestamp stamp) {
Calendar tempCal = toCalendar(stamp, TimeZone.getDefault(), Locale.getDefault());
return tempCal.get(Calendar.DAY_OF_WEEK);
}
public static int weekNumber(Timestamp input, int startOfWeek) {
Calendar calendar = Calendar.getInstance();
calendar.setFirstDayOfWeek(startOfWeek);
if (startOfWeek == Calendar.MONDAY) {
calendar.setMinimalDaysInFirstWeek(4);
} else if (startOfWeek == Calendar.SUNDAY) {
calendar.setMinimalDaysInFirstWeek(3);
}
calendar.setTime(new java.util.Date(input.getTime()));
return calendar.get(Calendar.WEEK_OF_YEAR);
}
// ----- New methods that take a timezone and locale -- //
public static Calendar getCalendarInstance(TimeZone timeZone, Locale locale) {
return Calendar.getInstance(com.ibm.icu.util.TimeZone.getTimeZone(timeZone.getID()), locale);
}
/**
* Returns a Calendar object initialized to the specified date/time, time zone,
* and locale.
*
* @param date date/time to use
* @param timeZone
* @param locale
* @return Calendar object
* @see java.util.Calendar
*/
public static Calendar toCalendar(Date date, TimeZone timeZone, Locale locale) {
Calendar cal = getCalendarInstance(timeZone, locale);
if (date != null) {
cal.setTime(date);
}
return cal;
}
/**
* Perform date/time arithmetic on a Timestamp. This is the only accurate way to
* perform date/time arithmetic across locales and time zones.
*
* @param stamp date/time to perform arithmetic on
* @param adjType the adjustment type to perform. Use one of the java.util.Calendar fields.
* @param adjQuantity the adjustment quantity.
* @param timeZone
* @param locale
* @return adjusted Timestamp
* @see java.util.Calendar
*/
public static Timestamp adjustTimestamp(Timestamp stamp, int adjType, int adjQuantity, TimeZone timeZone, Locale locale) {
Calendar tempCal = toCalendar(stamp, timeZone, locale);
tempCal.add(adjType, adjQuantity);
return new Timestamp(tempCal.getTimeInMillis());
}
public static Timestamp adjustTimestamp(Timestamp stamp, Integer adjType, Integer adjQuantity) {
Calendar tempCal = toCalendar(stamp);
tempCal.add(adjType, adjQuantity);
return new Timestamp(tempCal.getTimeInMillis());
}
public static Timestamp getHourStart(Timestamp stamp, TimeZone timeZone, Locale locale) {
return getHourStart(stamp, 0, timeZone, locale);
}
public static Timestamp getHourStart(Timestamp stamp, int hoursLater, TimeZone timeZone, Locale locale) {
Calendar tempCal = toCalendar(stamp, timeZone, locale);
tempCal.set(tempCal.get(Calendar.YEAR), tempCal.get(Calendar.MONTH), tempCal.get(Calendar.DAY_OF_MONTH), tempCal.get(Calendar.HOUR_OF_DAY), 0, 0);
tempCal.add(Calendar.HOUR_OF_DAY, hoursLater);
Timestamp retStamp = new Timestamp(tempCal.getTimeInMillis());
retStamp.setNanos(0);
return retStamp;
}
public static Timestamp getHourEnd(Timestamp stamp, TimeZone timeZone, Locale locale) {
return getHourEnd(stamp, Long.valueOf(0), timeZone, locale);
}
public static Timestamp getHourEnd(Timestamp stamp, Long hoursLater, TimeZone timeZone, Locale locale) {
Calendar tempCal = toCalendar(stamp, timeZone, locale);
tempCal.set(tempCal.get(Calendar.YEAR), tempCal.get(Calendar.MONTH), tempCal.get(Calendar.DAY_OF_MONTH), tempCal.get(Calendar.HOUR_OF_DAY), 59, 59);
tempCal.add(Calendar.HOUR_OF_DAY, hoursLater.intValue());
Timestamp retStamp = new Timestamp(tempCal.getTimeInMillis());
retStamp.setNanos(0);
return retStamp;
}
public static Timestamp getDayStart(Timestamp stamp, TimeZone timeZone, Locale locale) {
return getDayStart(stamp, 0, timeZone, locale);
}
public static Timestamp getDayStart(Timestamp stamp, int daysLater, TimeZone timeZone, Locale locale) {
Calendar tempCal = toCalendar(stamp, timeZone, locale);
tempCal.set(tempCal.get(Calendar.YEAR), tempCal.get(Calendar.MONTH), tempCal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
tempCal.add(Calendar.DAY_OF_MONTH, daysLater);
Timestamp retStamp = new Timestamp(tempCal.getTimeInMillis());
retStamp.setNanos(0);
return retStamp;
}
public static Timestamp getDayEnd(Timestamp stamp, TimeZone timeZone, Locale locale) {
return getDayEnd(stamp, Long.valueOf(0), timeZone, locale);
}
public static Timestamp getDayEnd(Timestamp stamp, Long daysLater, TimeZone timeZone, Locale locale) {
Calendar tempCal = toCalendar(stamp, timeZone, locale);
tempCal.set(tempCal.get(Calendar.YEAR), tempCal.get(Calendar.MONTH), tempCal.get(Calendar.DAY_OF_MONTH), 23, 59, 59);
tempCal.add(Calendar.DAY_OF_MONTH, daysLater.intValue());
Timestamp retStamp = new Timestamp(tempCal.getTimeInMillis());
retStamp.setNanos(0);
//MSSQL datetime field has accuracy of 3 milliseconds and setting the nano seconds cause the date to be rounded to next day
//retStamp.setNanos(999999999);
return retStamp;
}
public static Timestamp getWeekStart(Timestamp stamp, TimeZone timeZone, Locale locale) {
return getWeekStart(stamp, 0, 0, timeZone, locale);
}
public static Timestamp getWeekStart(Timestamp stamp, int daysLater, TimeZone timeZone, Locale locale) {
return getWeekStart(stamp, daysLater, 0, timeZone, locale);
}
public static Timestamp getWeekStart(Timestamp stamp, int daysLater, int weeksLater, TimeZone timeZone, Locale locale) {
Calendar tempCal = toCalendar(stamp, timeZone, locale);
tempCal.set(tempCal.get(Calendar.YEAR), tempCal.get(Calendar.MONTH), tempCal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
tempCal.add(Calendar.DAY_OF_MONTH, daysLater);
tempCal.set(Calendar.DAY_OF_WEEK, tempCal.getFirstDayOfWeek());
tempCal.add(Calendar.WEEK_OF_MONTH, weeksLater);
Timestamp retStamp = new Timestamp(tempCal.getTimeInMillis());
retStamp.setNanos(0);
return retStamp;
}
public static Timestamp getWeekEnd(Timestamp stamp, TimeZone timeZone, Locale locale) {
Timestamp weekStart = getWeekStart(stamp, timeZone, locale);
Calendar tempCal = toCalendar(weekStart, timeZone, locale);
tempCal.add(Calendar.DAY_OF_MONTH, 6);
return getDayEnd(new Timestamp(tempCal.getTimeInMillis()), timeZone, locale);
}
public static Timestamp getMonthStart(Timestamp stamp, TimeZone timeZone, Locale locale) {
return getMonthStart(stamp, 0, 0, timeZone, locale);
}
public static Timestamp getMonthStart(Timestamp stamp, int daysLater, TimeZone timeZone, Locale locale) {
return getMonthStart(stamp, daysLater, 0, timeZone, locale);
}
public static Timestamp getMonthStart(Timestamp stamp, int daysLater, int monthsLater, TimeZone timeZone, Locale locale) {
Calendar tempCal = toCalendar(stamp, timeZone, locale);
tempCal.set(tempCal.get(Calendar.YEAR), tempCal.get(Calendar.MONTH), 1, 0, 0, 0);
tempCal.add(Calendar.MONTH, monthsLater);
tempCal.add(Calendar.DAY_OF_MONTH, daysLater);
Timestamp retStamp = new Timestamp(tempCal.getTimeInMillis());
retStamp.setNanos(0);
return retStamp;
}
public static Timestamp getMonthEnd(Timestamp stamp, TimeZone timeZone, Locale locale) {
Calendar tempCal = toCalendar(stamp, timeZone, locale);
tempCal.set(tempCal.get(Calendar.YEAR), tempCal.get(Calendar.MONTH), tempCal.getActualMaximum(Calendar.DAY_OF_MONTH), 0, 0, 0);
return getDayEnd(new Timestamp(tempCal.getTimeInMillis()), timeZone, locale);
}
public static Timestamp getYearStart(Timestamp stamp, TimeZone timeZone, Locale locale) {
return getYearStart(stamp, 0, 0, 0, timeZone, locale);
}
public static Timestamp getYearStart(Timestamp stamp, int daysLater, TimeZone timeZone, Locale locale) {
return getYearStart(stamp, daysLater, 0, 0, timeZone, locale);
}
public static Timestamp getYearStart(Timestamp stamp, int daysLater, int yearsLater, TimeZone timeZone, Locale locale) {
return getYearStart(stamp, daysLater, 0, yearsLater, timeZone, locale);
}
public static Timestamp getYearStart(Timestamp stamp, Number daysLater, Number monthsLater, Number yearsLater, TimeZone timeZone, Locale locale) {
return getYearStart(stamp, (daysLater == null ? 0 : daysLater.intValue()),
(monthsLater == null ? 0 : monthsLater.intValue()), (yearsLater == null ? 0 : yearsLater.intValue()), timeZone, locale);
}
public static Timestamp getYearStart(Timestamp stamp, int daysLater, int monthsLater, int yearsLater, TimeZone timeZone, Locale locale) {
Calendar tempCal = toCalendar(stamp, timeZone, locale);
tempCal.set(tempCal.get(Calendar.YEAR), Calendar.JANUARY, 1, 0, 0, 0);
tempCal.add(Calendar.YEAR, yearsLater);
tempCal.add(Calendar.MONTH, monthsLater);
tempCal.add(Calendar.DAY_OF_MONTH, daysLater);
Timestamp retStamp = new Timestamp(tempCal.getTimeInMillis());
retStamp.setNanos(0);
return retStamp;
}
public static Timestamp getYearEnd(Timestamp stamp, TimeZone timeZone, Locale locale) {
Calendar tempCal = toCalendar(stamp, timeZone, locale);
tempCal.set(tempCal.get(Calendar.YEAR), tempCal.getActualMaximum(Calendar.MONTH) + 1, 0, 0, 0, 0);
return getMonthEnd(new Timestamp(tempCal.getTimeInMillis()), timeZone, locale);
}
public static int weekNumber(Timestamp stamp, TimeZone timeZone, Locale locale) {
Calendar tempCal = toCalendar(stamp, timeZone, locale);
return tempCal.get(Calendar.WEEK_OF_YEAR);
}
/**
* Returns a List of day name Strings - suitable for calendar headings.
* @param locale
* @return List of day name Strings
*/
public static List<String> getDayNames(Locale locale) {
Calendar tempCal = Calendar.getInstance(locale);
tempCal.set(Calendar.DAY_OF_WEEK, tempCal.getFirstDayOfWeek());
SimpleDateFormat dateFormat = new SimpleDateFormat("EEEE", locale);
List<String> resultList = new ArrayList<String>();
for (int i = 0; i < 7; i++) {
resultList.add(dateFormat.format(tempCal.getTime()));
tempCal.roll(Calendar.DAY_OF_WEEK, 1);
}
return resultList;
}
/**
* Returns a List of month name Strings - suitable for calendar headings.
*
* @param locale
* @return List of month name Strings
*/
public static List<String> getMonthNames(Locale locale) {
Calendar tempCal = Calendar.getInstance(locale);
tempCal.set(Calendar.MONTH, Calendar.JANUARY);
SimpleDateFormat dateFormat = new SimpleDateFormat("MMMM", locale);
List<String> resultList = new ArrayList<String>();
for (int i = Calendar.JANUARY; i <= tempCal.getActualMaximum(Calendar.MONTH); i++) {
resultList.add(dateFormat.format(tempCal.getTime()));
tempCal.roll(Calendar.MONTH, 1);
}
return resultList;
}
/**
* Returns an initialized DateFormat object.
*
* @param dateFormat
* optional format string
* @param tz
* @param locale
* can be null if dateFormat is not null
* @return DateFormat object
*/
public static DateFormat toDateFormat(String dateFormat, TimeZone tz, Locale locale) {
DateFormat df = null;
if (UtilValidate.isEmpty(dateFormat)) {
df = DateFormat.getDateInstance(DateFormat.SHORT, locale);
} else {
df = new SimpleDateFormat(dateFormat, locale == null ? Locale.getDefault() : locale);
}
df.setTimeZone(tz);
return df;
}
/**
* Returns an initialized DateFormat object.
* @param dateTimeFormat optional format string
* @param tz
* @param locale can be null if dateTimeFormat is not null
* @return DateFormat object
*/
public static DateFormat toDateTimeFormat(String dateTimeFormat, TimeZone tz, Locale locale) {
DateFormat df = null;
if (UtilValidate.isEmpty(dateTimeFormat)) {
df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM, locale);
} else {
df = new SimpleDateFormat(dateTimeFormat, locale == null ? Locale.getDefault() : locale);
}
df.setTimeZone(tz);
return df;
}
/**
* Returns an initialized DateFormat object.
* @param timeFormat optional format string
* @param tz
* @param locale can be null if timeFormat is not null
* @return DateFormat object
*/
public static DateFormat toTimeFormat(String timeFormat, TimeZone tz, Locale locale) {
DateFormat df = null;
if (UtilValidate.isEmpty(timeFormat)) {
df = DateFormat.getTimeInstance(DateFormat.MEDIUM, locale);
} else {
df = new SimpleDateFormat(timeFormat, locale == null ? Locale.getDefault() : locale);
}
df.setTimeZone(tz);
return df;
}
/**
* Localized String to Timestamp conversion. To be used in tandem with timeStampToString().
*/
public static Timestamp stringToTimeStamp(String dateTimeString, TimeZone tz, Locale locale) throws ParseException {
return stringToTimeStamp(dateTimeString, null, tz, locale);
}
/**
* Localized String to Timestamp conversion. To be used in tandem with timeStampToString().
*/
public static Timestamp stringToTimeStamp(String dateTimeString, String dateTimeFormat, TimeZone tz, Locale locale) throws ParseException {
DateFormat dateFormat = toDateTimeFormat(dateTimeFormat, tz, locale);
Date parsedDate = dateFormat.parse(dateTimeString);
return new Timestamp(parsedDate.getTime());
}
/**
* Localized Timestamp to String conversion. To be used in tandem with stringToTimeStamp().
*/
public static String timeStampToString(Timestamp stamp, TimeZone tz, Locale locale) {
return timeStampToString(stamp, null, tz, locale);
}
/**
* Localized Timestamp to String conversion. To be used in tandem with stringToTimeStamp().
*/
public static String timeStampToString(Timestamp stamp, String dateTimeFormat, TimeZone tz, Locale locale) {
DateFormat dateFormat = toDateTimeFormat(dateTimeFormat, tz, locale);
return dateFormat.format(stamp);
}
// Private lazy-initializer class
private static class TimeZoneHolder {
private static final List<TimeZone> availableTimeZoneList = getTimeZones();
private static List<TimeZone> getTimeZones() {
ArrayList<TimeZone> availableTimeZoneList = new ArrayList<TimeZone>();
List<String> idList = null;
String tzString = UtilProperties.getPropertyValue("general", "timeZones.available");
if (UtilValidate.isNotEmpty(tzString)) {
idList = StringUtil.split(tzString, ",");
} else {
idList = Arrays.asList(TimeZone.getAvailableIDs());
}
for (String id : idList) {
TimeZone curTz = TimeZone.getTimeZone(id);
availableTimeZoneList.add(curTz);
}
availableTimeZoneList.trimToSize();
return Collections.unmodifiableList(availableTimeZoneList);
}
}
/** Returns a List of available TimeZone objects.
* @see java.util.TimeZone
*/
public static List<TimeZone> availableTimeZones() {
return TimeZoneHolder.availableTimeZoneList;
}
/** Returns a TimeZone object based upon a time zone ID. Method defaults to
* server's time zone if tzID is null or empty.
* @see java.util.TimeZone
*/
public static TimeZone toTimeZone(String tzId) {
if (UtilValidate.isEmpty(tzId)) {
return TimeZone.getDefault();
} else {
return TimeZone.getTimeZone(tzId);
}
}
/** Returns a TimeZone object based upon an hour offset from GMT.
* @see java.util.TimeZone
*/
public static TimeZone toTimeZone(int gmtOffset) {
if (gmtOffset > 12 || gmtOffset < -14) {
throw new IllegalArgumentException("Invalid GMT offset");
}
String tzId = gmtOffset > 0 ? "Etc/GMT+" : "Etc/GMT";
return TimeZone.getTimeZone(tzId + gmtOffset);
}
public static int getSecond(Timestamp stamp, TimeZone timeZone, Locale locale) {
Calendar cal = toCalendar(stamp, timeZone, locale);
return cal.get(Calendar.SECOND);
}
public static int getMinute(Timestamp stamp, TimeZone timeZone, Locale locale) {
Calendar cal = toCalendar(stamp, timeZone, locale);
return cal.get(Calendar.MINUTE);
}
public static int getHour(Timestamp stamp, TimeZone timeZone, Locale locale) {
Calendar cal = toCalendar(stamp, timeZone, locale);
return cal.get(Calendar.HOUR_OF_DAY);
}
public static int getDayOfWeek(Timestamp stamp, TimeZone timeZone, Locale locale) {
Calendar cal = toCalendar(stamp, timeZone, locale);
return cal.get(Calendar.DAY_OF_WEEK);
}
public static int getDayOfMonth(Timestamp stamp, TimeZone timeZone, Locale locale) {
Calendar cal = toCalendar(stamp, timeZone, locale);
return cal.get(Calendar.DAY_OF_MONTH);
}
public static int getDayOfYear(Timestamp stamp, TimeZone timeZone, Locale locale) {
Calendar cal = toCalendar(stamp, timeZone, locale);
return cal.get(Calendar.DAY_OF_YEAR);
}
public static int getWeek(Timestamp stamp, TimeZone timeZone, Locale locale) {
Calendar cal = toCalendar(stamp, timeZone, locale);
return cal.get(Calendar.WEEK_OF_YEAR);
}
public static int getMonth(Timestamp stamp, TimeZone timeZone, Locale locale) {
Calendar cal = toCalendar(stamp, timeZone, locale);
return cal.get(Calendar.MONTH);
}
public static int getYear(Timestamp stamp, TimeZone timeZone, Locale locale) {
Calendar cal = toCalendar(stamp, timeZone, locale);
return cal.get(Calendar.YEAR);
}
public static Date getEarliestDate() {
Calendar cal = getCalendarInstance(TimeZone.getTimeZone("GMT"), Locale.getDefault());
cal.set(Calendar.YEAR, cal.getActualMinimum(Calendar.YEAR));
cal.set(Calendar.MONTH, cal.getActualMinimum(Calendar.MONTH));
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
public static Date getLatestDate() {
Calendar cal = getCalendarInstance(TimeZone.getTimeZone("GMT"), Locale.getDefault());
cal.set(Calendar.YEAR, cal.getActualMaximum(Calendar.YEAR));
cal.set(Calendar.MONTH, cal.getActualMaximum(Calendar.MONTH));
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
cal.set(Calendar.MILLISECOND, 999);
return cal.getTime();
}
/**
* Returns a copy of <code>date</code> that cannot be modified.
* Attempts to modify the returned date will result in an
* <tt>UnsupportedOperationException</tt>.
*
* @param date
*/
public static Date unmodifiableDate(Date date) {
if (date instanceof ImmutableDate) {
return date;
}
return new ImmutableDate(date.getTime());
}
@SuppressWarnings("serial")
private static class ImmutableDate extends Date {
private ImmutableDate(long date) {
super(date);
}
@Override
public Object clone() {
// No need to clone an immutable object.
return this;
}
@Override
public void setYear(int year) {
throw new UnsupportedOperationException();
}
@Override
public void setMonth(int month) {
throw new UnsupportedOperationException();
}
@Override
public void setDate(int date) {
throw new UnsupportedOperationException();
}
@Override
public void setHours(int hours) {
throw new UnsupportedOperationException();
}
@Override
public void setMinutes(int minutes) {
throw new UnsupportedOperationException();
}
@Override
public void setSeconds(int seconds) {
throw new UnsupportedOperationException();
}
@Override
public void setTime(long time) {
throw new UnsupportedOperationException();
}
}
/**
* Scipio: Returns a map with begin/end timestamp for a given period. Defaults to month.
* @param period
* @param fromDate
* @param locale
* @param timezone
* @return a map with two fixed keys, dateBegin & dateEnd, representing the beginning and the end of the given period
*/
public static TimeInterval getPeriodInterval(String period, Timestamp fromDate, Locale locale, TimeZone timezone) {
return getPeriodInterval(period, 0, fromDate, locale, timezone);
}
public static TimeInterval getPeriodInterval(String period, int timeShift, Timestamp fromDate, Locale locale, TimeZone timezone) {
// Map<String, Timestamp> result = FastMap.newInstance();
Timestamp dateBegin = null;
Timestamp dateEnd = null;
if (!checkValidInterval(period))
return null;
Timestamp date = (UtilValidate.isNotEmpty(fromDate)) ? fromDate : UtilDateTime.nowTimestamp();
switch (period) {
case "hour":
dateBegin = getHourStart(date, timeShift, timezone, locale);
dateEnd = getHourEnd(dateBegin, timezone, locale);
break;
case "day":
dateBegin = getDayStart(date, timeShift);
dateEnd = getDayEnd(dateBegin);
break;
case "week":
dateBegin = getWeekStart(date, 0, timeShift);
dateEnd = getWeekEnd(dateBegin);
break;
case "month":
dateBegin = getMonthStart(date, 0, timeShift);
dateEnd = getMonthEnd(dateBegin, timezone, locale);
break;
case "quarter":
Calendar calendar = toCalendar(date);
calendar.set(Calendar.DAY_OF_MONTH, 1);
int month = UtilDateTime.getMonth(date, timezone, locale);
int quarter = 0;
if (month >= 2 && month < 5)
quarter = 3;
else if (month >= 5 && month < 8)
quarter = 6;
else if (month >= 8 && month < 11)
quarter = 9;
else if (month == 11)
quarter = 12;
calendar.set(Calendar.MONTH, quarter);
Timestamp monthStart = getMonthStart(toTimestamp(calendar.getTime()));
dateBegin = monthStart;
dateEnd = getMonthEnd(UtilDateTime.getMonthStart(monthStart, 0, 2), timezone, locale);
break;
case "semester":
calendar = toCalendar(date);
calendar.set(Calendar.DAY_OF_MONTH, 1);
month = UtilDateTime.getMonth(date, timezone, locale);
int semester = 0;
if (month >= 0 && month < 5)
semester = 5;
else if (month >= 5)
semester = 12;
calendar.set(Calendar.MONTH, semester);
monthStart = UtilDateTime.getMonthStart(toTimestamp(calendar.getTime()));
dateBegin = monthStart;
dateEnd = getMonthEnd(UtilDateTime.getMonthStart(monthStart, 0, 4), timezone, locale);
break;
case "year":
dateBegin = getYearStart(date, 0, timeShift);
dateEnd = getYearEnd(dateBegin, timezone, locale);
break;
default:
dateBegin = getMonthStart(date);
dateEnd = getMonthEnd(dateBegin, timezone, locale);
break;
}
return new TimeInterval(dateBegin, dateEnd);
}
/**
* Scipio: Enhanced version of getPeriodInterval that returns also a date formatter for a given period.
* @param period
* @param locale
* @param timezone
* @return a map with three fixed keys, dateBegin & dateEnd & dateFormatter, representing the beginning and the end of the given period
* and the date formatter needed to display the date.
*/
public static TimeInterval getPeriodIntervalAndFormatter(String period, Timestamp fromDate, Locale locale, TimeZone timezone) {
return getPeriodIntervalAndFormatter(period, 0, fromDate, locale, timezone);
}
public static TimeInterval getPeriodIntervalAndFormatter(String period, int timeShift, Timestamp fromDate, Locale locale, TimeZone timezone) {
Map<String, Object> result = FastMap.newInstance();
if (!checkValidInterval(period))
return null;
TimeInterval timeInterval = getPeriodInterval(period, timeShift, fromDate, locale, timezone);
switch (period) {
case "hour":
timeInterval.setDateFormatter(new SimpleDateFormat("yyyy-MM-dd hha"));
break;
case "day":
timeInterval.setDateFormatter(new SimpleDateFormat("yyyy-MM-dd"));
break;
case "week":
timeInterval.setDateFormatter(new SimpleDateFormat("YYYY-'W'ww"));
break;
case "month":
timeInterval.setDateFormatter(new SimpleDateFormat("yyyy-MM"));
break;
case "quarter":
int month = UtilDateTime.getMonth((Timestamp) result.get("dateBegin"), timezone, locale);
int quarter = 1;
if (month >= 3 && month < 6)
quarter = 2;
if (month >= 6 && month < 9)
quarter = 3;
if (month >= 9)
quarter = 4;
timeInterval.setDateFormatter(new SimpleDateFormat("yyyy-'" + quarter + "T'"));
break;
case "semester":
month = UtilDateTime.getMonth((Timestamp) result.get("dateBegin"), timezone, locale);
int semester = 1;
if (month >= 5)
semester = 2;
timeInterval.setDateFormatter(new SimpleDateFormat("yyyy-'" + semester + "S'"));
break;
case "year":
timeInterval.setDateFormatter(new SimpleDateFormat("yyyy"));
break;
default:
timeInterval.setDateFormatter(new SimpleDateFormat("yyyy-MM"));
break;
}
return timeInterval;
}
/**
* Scipio: Checks if the interval passed is a valid one
*
* @param interval
* @return true or false depending on the result of evaluating the given
* interval against the valid list of intervals represented by the
* constant TIME_INTERVALS
*/
public static boolean checkValidInterval(String interval) {
return Arrays.asList(TIME_INTERVALS).contains(interval);
}
public static Timestamp getTimeStampFromIntervalScope(String iScope) {
return getTimeStampFromIntervalScope(iScope, -1);
}
public static Timestamp getTimeStampFromIntervalScope(String iScope, int iCount) {
iCount--;
if (iCount < 0)
iCount = getIntervalDefaultCount(iScope);
Calendar calendar = Calendar.getInstance();
if (iScope.equals("hour")) {
calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) - iCount);
} else if (iScope.equals("day")) {
calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - iCount);
} else if (iScope.equals("week")) {
calendar.set(Calendar.DAY_OF_WEEK, 1);
calendar.set(Calendar.WEEK_OF_YEAR, calendar.get(Calendar.WEEK_OF_YEAR) - iCount);
} else if (iScope.equals("month") || iScope.equals("quarter") || iScope.equals("semester")) {
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - iCount);
} else if (iScope.equals("year")) {
calendar.set(Calendar.DAY_OF_YEAR, 1);
calendar.set(Calendar.MONTH, 1);
calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR) - iCount);
}
return UtilDateTime.toTimestamp(calendar.getTime());
}
public static int getIntervalDefaultCount(String iScope) {
int iCount = 0;
if (iScope.equals("hour")) {
iCount = 12;
} else if (iScope.equals("day")) {
iCount = 30;
} else if (iScope.equals("week")) {
iCount = 4;
} else if (iScope.equals("month")) {
iCount = 12;
} else if (iScope.equals("quarter")) {
iCount = 16;
} else if (iScope.equals("semester")) {
iCount = 18;
} else if (iScope.equals("year")) {
iCount = 5;
}
return iCount;
}
public static class TimeInterval {
private final Timestamp dateBegin;
private final Timestamp dateEnd;
private DateFormat dateFormatter;
TimeInterval(Timestamp dateBegin, Timestamp dateEnd) {
this.dateBegin = dateBegin;
this.dateEnd = dateEnd;
}
TimeInterval(Timestamp dateBegin, Timestamp dateEnd, DateFormat dateFormatter) {
this(dateBegin, dateEnd);
this.setDateFormatter(dateFormatter);
}
public Timestamp getDateBegin() {
return dateBegin;
}
public Timestamp getDateEnd() {
return dateEnd;
}
public DateFormat getDateFormatter() {
return dateFormatter;
}
public void setDateFormatter(DateFormat dateFormatter) {
this.dateFormatter = dateFormatter;
}
}
}
|
NoRef/OFBIZ patch: Fixed issue in time interval calculation
git-svn-id: 6c0edb9fdd085beb7f3b78cf385b6ddede550bd9@11193 55bbc10b-e964-4c8f-a844-a62c6f7d3c80
|
framework/base/src/org/ofbiz/base/util/UtilDateTime.java
|
NoRef/OFBIZ patch: Fixed issue in time interval calculation
|
|
Java
|
apache-2.0
|
fafeb68da33d531bcf83ecfc1399b4770ada6e4b
| 0
|
korealerts1/gitblit,vitalif/gitblit,vitalif/gitblit,RainerW/gitblit,fuero/gitblit,gitblit/gitblit,mrjoel/gitblit,mystygage/gitblit,yonglehou/gitblit,two-ack/gitblit,two-ack/gitblit,paulsputer/gitblit,fzs/gitblit,fuero/gitblit,paulsputer/gitblit,RainerW/gitblit,two-ack/gitblit,gzsombor/gitblit,paulsputer/gitblit,dispositional/gitblit,gitblit/gitblit,cesarmarinhorj/gitblit,yonglehou/gitblit,vitalif/gitblit,two-ack/gitblit,gitblit/gitblit,ahnjune881214/gitblit,gzsombor/gitblit,fuero/gitblit,fzs/gitblit,paladox/gitblit,lucamilanesio/gitblit,mystygage/gitblit,lucamilanesio/gitblit,paladox/gitblit,vitalif/gitblit,ahnjune881214/gitblit,RainerW/gitblit,yonglehou/gitblit,lucamilanesio/gitblit,fzs/gitblit,lucamilanesio/gitblit,paladox/gitblit,two-ack/gitblit,mystygage/gitblit,paulsputer/gitblit,dispositional/gitblit,cesarmarinhorj/gitblit,gitblit/gitblit,gzsombor/gitblit,mrjoel/gitblit,fzs/gitblit,paladox/gitblit,lucamilanesio/gitblit,paulsputer/gitblit,gzsombor/gitblit,mystygage/gitblit,korealerts1/gitblit,mystygage/gitblit,mrjoel/gitblit,fuero/gitblit,RainerW/gitblit,paladox/gitblit,dispositional/gitblit,korealerts1/gitblit,gitblit/gitblit,yonglehou/gitblit,cesarmarinhorj/gitblit,dispositional/gitblit,fuero/gitblit,fzs/gitblit,ahnjune881214/gitblit,ahnjune881214/gitblit,mrjoel/gitblit,vitalif/gitblit,cesarmarinhorj/gitblit,yonglehou/gitblit,RainerW/gitblit,cesarmarinhorj/gitblit,mrjoel/gitblit,dispositional/gitblit,korealerts1/gitblit,korealerts1/gitblit,ahnjune881214/gitblit
|
/*
* Copyright 2014 gitblit.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gitblit.models;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.jgit.util.RelativeDateFormatter;
/**
* The Gitblit Ticket model, its component classes, and enums.
*
* @author James Moger
*
*/
public class TicketModel implements Serializable, Comparable<TicketModel> {
private static final long serialVersionUID = 1L;
public String project;
public String repository;
public long number;
public Date created;
public String createdBy;
public Date updated;
public String updatedBy;
public String title;
public String body;
public String topic;
public Type type;
public Status status;
public String responsible;
public String milestone;
public String mergeSha;
public String mergeTo;
public List<Change> changes;
public Integer insertions;
public Integer deletions;
/**
* Builds an effective ticket from the collection of changes. A change may
* Add or Subtract information from a ticket, but the collection of changes
* is only additive.
*
* @param changes
* @return the effective ticket
*/
public static TicketModel buildTicket(Collection<Change> changes) {
TicketModel ticket;
List<Change> effectiveChanges = new ArrayList<Change>();
Map<String, Change> comments = new HashMap<String, Change>();
for (Change change : changes) {
if (change.comment != null) {
if (comments.containsKey(change.comment.id)) {
Change original = comments.get(change.comment.id);
Change clone = copy(original);
clone.comment.text = change.comment.text;
clone.comment.deleted = change.comment.deleted;
int idx = effectiveChanges.indexOf(original);
effectiveChanges.remove(original);
effectiveChanges.add(idx, clone);
comments.put(clone.comment.id, clone);
} else {
effectiveChanges.add(change);
comments.put(change.comment.id, change);
}
} else {
effectiveChanges.add(change);
}
}
// effective ticket
ticket = new TicketModel();
for (Change change : effectiveChanges) {
if (!change.hasComment()) {
// ensure we do not include a deleted comment
change.comment = null;
}
ticket.applyChange(change);
}
return ticket;
}
public TicketModel() {
// the first applied change set the date appropriately
created = new Date(0);
changes = new ArrayList<Change>();
status = Status.New;
type = Type.defaultType;
}
public boolean isOpen() {
return !status.isClosed();
}
public boolean isClosed() {
return status.isClosed();
}
public boolean isMerged() {
return isClosed() && !isEmpty(mergeSha);
}
public boolean isProposal() {
return Type.Proposal == type;
}
public boolean isBug() {
return Type.Bug == type;
}
public Date getLastUpdated() {
return updated == null ? created : updated;
}
public boolean hasPatchsets() {
return getPatchsets().size() > 0;
}
/**
* Returns true if multiple participants are involved in discussing a ticket.
* The ticket creator is excluded from this determination because a
* discussion requires more than one participant.
*
* @return true if this ticket has a discussion
*/
public boolean hasDiscussion() {
for (Change change : getComments()) {
if (!change.author.equals(createdBy)) {
return true;
}
}
return false;
}
/**
* Returns the list of changes with comments.
*
* @return
*/
public List<Change> getComments() {
List<Change> list = new ArrayList<Change>();
for (Change change : changes) {
if (change.hasComment()) {
list.add(change);
}
}
return list;
}
/**
* Returns the list of participants for the ticket.
*
* @return the list of participants
*/
public List<String> getParticipants() {
Set<String> set = new LinkedHashSet<String>();
for (Change change : changes) {
if (change.isParticipantChange()) {
set.add(change.author);
}
}
if (responsible != null && responsible.length() > 0) {
set.add(responsible);
}
return new ArrayList<String>(set);
}
public boolean hasLabel(String label) {
return getLabels().contains(label);
}
public List<String> getLabels() {
return getList(Field.labels);
}
public boolean isResponsible(String username) {
return username.equals(responsible);
}
public boolean isAuthor(String username) {
return username.equals(createdBy);
}
public boolean isReviewer(String username) {
return getReviewers().contains(username);
}
public List<String> getReviewers() {
return getList(Field.reviewers);
}
public boolean isWatching(String username) {
return getWatchers().contains(username);
}
public List<String> getWatchers() {
return getList(Field.watchers);
}
public boolean isVoter(String username) {
return getVoters().contains(username);
}
public List<String> getVoters() {
return getList(Field.voters);
}
public List<String> getMentions() {
return getList(Field.mentions);
}
protected List<String> getList(Field field) {
Set<String> set = new TreeSet<String>();
for (Change change : changes) {
if (change.hasField(field)) {
String values = change.getString(field);
for (String value : values.split(",")) {
switch (value.charAt(0)) {
case '+':
set.add(value.substring(1));
break;
case '-':
set.remove(value.substring(1));
break;
default:
set.add(value);
}
}
}
}
if (!set.isEmpty()) {
return new ArrayList<String>(set);
}
return Collections.emptyList();
}
public Attachment getAttachment(String name) {
Attachment attachment = null;
for (Change change : changes) {
if (change.hasAttachments()) {
Attachment a = change.getAttachment(name);
if (a != null) {
attachment = a;
}
}
}
return attachment;
}
public boolean hasAttachments() {
for (Change change : changes) {
if (change.hasAttachments()) {
return true;
}
}
return false;
}
public List<Attachment> getAttachments() {
List<Attachment> list = new ArrayList<Attachment>();
for (Change change : changes) {
if (change.hasAttachments()) {
list.addAll(change.attachments);
}
}
return list;
}
public List<Patchset> getPatchsets() {
List<Patchset> list = new ArrayList<Patchset>();
for (Change change : changes) {
if (change.patchset != null) {
list.add(change.patchset);
}
}
return list;
}
public List<Patchset> getPatchsetRevisions(int number) {
List<Patchset> list = new ArrayList<Patchset>();
for (Change change : changes) {
if (change.patchset != null) {
if (number == change.patchset.number) {
list.add(change.patchset);
}
}
}
return list;
}
public Patchset getPatchset(String sha) {
for (Change change : changes) {
if (change.patchset != null) {
if (sha.equals(change.patchset.tip)) {
return change.patchset;
}
}
}
return null;
}
public Patchset getPatchset(int number, int rev) {
for (Change change : changes) {
if (change.patchset != null) {
if (number == change.patchset.number && rev == change.patchset.rev) {
return change.patchset;
}
}
}
return null;
}
public Patchset getCurrentPatchset() {
Patchset patchset = null;
for (Change change : changes) {
if (change.patchset != null) {
if (patchset == null) {
patchset = change.patchset;
} else if (patchset.compareTo(change.patchset) == 1) {
patchset = change.patchset;
}
}
}
return patchset;
}
public boolean isCurrent(Patchset patchset) {
if (patchset == null) {
return false;
}
Patchset curr = getCurrentPatchset();
if (curr == null) {
return false;
}
return curr.equals(patchset);
}
public List<Change> getReviews(Patchset patchset) {
if (patchset == null) {
return Collections.emptyList();
}
// collect the patchset reviews by author
// the last review by the author is the
// official review
Map<String, Change> reviews = new LinkedHashMap<String, TicketModel.Change>();
for (Change change : changes) {
if (change.hasReview()) {
if (change.review.isReviewOf(patchset)) {
reviews.put(change.author, change);
}
}
}
return new ArrayList<Change>(reviews.values());
}
public boolean isApproved(Patchset patchset) {
if (patchset == null) {
return false;
}
boolean approved = false;
boolean vetoed = false;
for (Change change : getReviews(patchset)) {
if (change.hasReview()) {
if (change.review.isReviewOf(patchset)) {
if (Score.approved == change.review.score) {
approved = true;
} else if (Score.vetoed == change.review.score) {
vetoed = true;
}
}
}
}
return approved && !vetoed;
}
public boolean isVetoed(Patchset patchset) {
if (patchset == null) {
return false;
}
for (Change change : getReviews(patchset)) {
if (change.hasReview()) {
if (change.review.isReviewOf(patchset)) {
if (Score.vetoed == change.review.score) {
return true;
}
}
}
}
return false;
}
public Review getReviewBy(String username) {
for (Change change : getReviews(getCurrentPatchset())) {
if (change.author.equals(username)) {
return change.review;
}
}
return null;
}
public boolean isPatchsetAuthor(String username) {
for (Change change : changes) {
if (change.hasPatchset()) {
if (change.author.equals(username)) {
return true;
}
}
}
return false;
}
public void applyChange(Change change) {
if (changes.size() == 0) {
// first change created the ticket
created = change.date;
createdBy = change.author;
status = Status.New;
} else if (created == null || change.date.after(created)) {
// track last ticket update
updated = change.date;
updatedBy = change.author;
}
if (change.isMerge()) {
// identify merge patchsets
if (isEmpty(responsible)) {
responsible = change.author;
}
status = Status.Merged;
}
if (change.hasFieldChanges()) {
for (Map.Entry<Field, String> entry : change.fields.entrySet()) {
Field field = entry.getKey();
Object value = entry.getValue();
switch (field) {
case type:
type = TicketModel.Type.fromObject(value, type);
break;
case status:
status = TicketModel.Status.fromObject(value, status);
break;
case title:
title = toString(value);
break;
case body:
body = toString(value);
break;
case topic:
topic = toString(value);
break;
case responsible:
responsible = toString(value);
break;
case milestone:
milestone = toString(value);
break;
case mergeTo:
mergeTo = toString(value);
break;
case mergeSha:
mergeSha = toString(value);
break;
default:
// unknown
break;
}
}
}
// add the change to the ticket
changes.add(change);
}
protected String toString(Object value) {
if (value == null) {
return null;
}
return value.toString();
}
public String toIndexableString() {
StringBuilder sb = new StringBuilder();
if (!isEmpty(title)) {
sb.append(title).append('\n');
}
if (!isEmpty(body)) {
sb.append(body).append('\n');
}
for (Change change : changes) {
if (change.hasComment()) {
sb.append(change.comment.text);
sb.append('\n');
}
}
return sb.toString();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("#");
sb.append(number);
sb.append(": " + title + "\n");
for (Change change : changes) {
sb.append(change);
sb.append('\n');
}
return sb.toString();
}
@Override
public int compareTo(TicketModel o) {
return o.created.compareTo(created);
}
@Override
public boolean equals(Object o) {
if (o instanceof TicketModel) {
return number == ((TicketModel) o).number;
}
return super.equals(o);
}
@Override
public int hashCode() {
return (repository + number).hashCode();
}
/**
* Encapsulates a ticket change
*/
public static class Change implements Serializable, Comparable<Change> {
private static final long serialVersionUID = 1L;
public final Date date;
public final String author;
public Comment comment;
public Map<Field, String> fields;
public Set<Attachment> attachments;
public Patchset patchset;
public Review review;
private transient String id;
public Change(String author) {
this(author, new Date());
}
public Change(String author, Date date) {
this.date = date;
this.author = author;
}
public boolean isStatusChange() {
return hasField(Field.status);
}
public Status getStatus() {
Status state = Status.fromObject(getField(Field.status), null);
return state;
}
public boolean isMerge() {
return hasField(Field.status) && hasField(Field.mergeSha);
}
public boolean hasPatchset() {
return patchset != null;
}
public boolean hasReview() {
return review != null;
}
public boolean hasComment() {
return comment != null && !comment.isDeleted() && comment.text != null;
}
public Comment comment(String text) {
comment = new Comment(text);
comment.id = TicketModel.getSHA1(date.toString() + author + text);
try {
Pattern mentions = Pattern.compile("\\s@([A-Za-z0-9-_]+)");
Matcher m = mentions.matcher(text);
while (m.find()) {
String username = m.group(1);
plusList(Field.mentions, username);
}
} catch (Exception e) {
// ignore
}
return comment;
}
public Review review(Patchset patchset, Score score, boolean addReviewer) {
if (addReviewer) {
plusList(Field.reviewers, author);
}
review = new Review(patchset.number, patchset.rev);
review.score = score;
return review;
}
public boolean hasAttachments() {
return !TicketModel.isEmpty(attachments);
}
public void addAttachment(Attachment attachment) {
if (attachments == null) {
attachments = new LinkedHashSet<Attachment>();
}
attachments.add(attachment);
}
public Attachment getAttachment(String name) {
if (attachments != null) {
for (Attachment attachment : attachments) {
if (attachment.name.equalsIgnoreCase(name)) {
return attachment;
}
}
}
return null;
}
public boolean isParticipantChange() {
if (hasComment()
|| hasReview()
|| hasPatchset()
|| hasAttachments()) {
return true;
}
if (TicketModel.isEmpty(fields)) {
return false;
}
// identify real ticket field changes
Map<Field, String> map = new HashMap<Field, String>(fields);
map.remove(Field.watchers);
map.remove(Field.voters);
return !map.isEmpty();
}
public boolean hasField(Field field) {
return !TicketModel.isEmpty(getString(field));
}
public boolean hasFieldChanges() {
return !TicketModel.isEmpty(fields);
}
public String getField(Field field) {
if (fields != null) {
return fields.get(field);
}
return null;
}
public void setField(Field field, Object value) {
if (fields == null) {
fields = new LinkedHashMap<Field, String>();
}
if (value == null) {
fields.put(field, null);
} else if (Enum.class.isAssignableFrom(value.getClass())) {
fields.put(field, ((Enum<?>) value).name());
} else {
fields.put(field, value.toString());
}
}
public void remove(Field field) {
if (fields != null) {
fields.remove(field);
}
}
public String getString(Field field) {
String value = getField(field);
if (value == null) {
return null;
}
return value;
}
public void watch(String... username) {
plusList(Field.watchers, username);
}
public void unwatch(String... username) {
minusList(Field.watchers, username);
}
public void vote(String... username) {
plusList(Field.voters, username);
}
public void unvote(String... username) {
minusList(Field.voters, username);
}
public void label(String... label) {
plusList(Field.labels, label);
}
public void unlabel(String... label) {
minusList(Field.labels, label);
}
protected void plusList(Field field, String... items) {
modList(field, "+", items);
}
protected void minusList(Field field, String... items) {
modList(field, "-", items);
}
private void modList(Field field, String prefix, String... items) {
List<String> list = new ArrayList<String>();
for (String item : items) {
list.add(prefix + item);
}
if (hasField(field)) {
String flat = getString(field);
if (isEmpty(flat)) {
// field is empty, use this list
setField(field, join(list, ","));
} else {
// merge this list into the existing field list
Set<String> set = new TreeSet<String>(Arrays.asList(flat.split(",")));
set.addAll(list);
setField(field, join(set, ","));
}
} else {
// does not have a list for this field
setField(field, join(list, ","));
}
}
public String getId() {
if (id == null) {
id = getSHA1(Long.toHexString(date.getTime()) + author);
}
return id;
}
@Override
public int compareTo(Change c) {
return date.compareTo(c.date);
}
@Override
public int hashCode() {
return getId().hashCode();
}
@Override
public boolean equals(Object o) {
if (o instanceof Change) {
return getId().equals(((Change) o).getId());
}
return false;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(RelativeDateFormatter.format(date));
if (hasComment()) {
sb.append(" commented on by ");
} else if (hasPatchset()) {
sb.append(MessageFormat.format(" {0} uploaded by ", patchset));
} else {
sb.append(" changed by ");
}
sb.append(author).append(" - ");
if (hasComment()) {
if (comment.isDeleted()) {
sb.append("(deleted) ");
}
sb.append(comment.text).append(" ");
}
if (hasFieldChanges()) {
for (Map.Entry<Field, String> entry : fields.entrySet()) {
sb.append("\n ");
sb.append(entry.getKey().name());
sb.append(':');
sb.append(entry.getValue());
}
}
return sb.toString();
}
}
/**
* Returns true if the string is null or empty.
*
* @param value
* @return true if string is null or empty
*/
static boolean isEmpty(String value) {
return value == null || value.trim().length() == 0;
}
/**
* Returns true if the collection is null or empty
*
* @param collection
* @return
*/
static boolean isEmpty(Collection<?> collection) {
return collection == null || collection.size() == 0;
}
/**
* Returns true if the map is null or empty
*
* @param map
* @return
*/
static boolean isEmpty(Map<?, ?> map) {
return map == null || map.size() == 0;
}
/**
* Calculates the SHA1 of the string.
*
* @param text
* @return sha1 of the string
*/
static String getSHA1(String text) {
try {
byte[] bytes = text.getBytes("iso-8859-1");
return getSHA1(bytes);
} catch (UnsupportedEncodingException u) {
throw new RuntimeException(u);
}
}
/**
* Calculates the SHA1 of the byte array.
*
* @param bytes
* @return sha1 of the byte array
*/
static String getSHA1(byte[] bytes) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(bytes, 0, bytes.length);
byte[] digest = md.digest();
return toHex(digest);
} catch (NoSuchAlgorithmException t) {
throw new RuntimeException(t);
}
}
/**
* Returns the hex representation of the byte array.
*
* @param bytes
* @return byte array as hex string
*/
static String toHex(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (int i = 0; i < bytes.length; i++) {
if ((bytes[i] & 0xff) < 0x10) {
sb.append('0');
}
sb.append(Long.toString(bytes[i] & 0xff, 16));
}
return sb.toString();
}
/**
* Join the list of strings into a single string with a space separator.
*
* @param values
* @return joined list
*/
static String join(Collection<String> values) {
return join(values, " ");
}
/**
* Join the list of strings into a single string with the specified
* separator.
*
* @param values
* @param separator
* @return joined list
*/
static String join(String[] values, String separator) {
return join(Arrays.asList(values), separator);
}
/**
* Join the list of strings into a single string with the specified
* separator.
*
* @param values
* @param separator
* @return joined list
*/
static String join(Collection<String> values, String separator) {
StringBuilder sb = new StringBuilder();
for (String value : values) {
sb.append(value).append(separator);
}
if (sb.length() > 0) {
// truncate trailing separator
sb.setLength(sb.length() - separator.length());
}
return sb.toString().trim();
}
/**
* Produce a deep copy of the given object. Serializes the entire object to
* a byte array in memory. Recommended for relatively small objects.
*/
@SuppressWarnings("unchecked")
static <T> T copy(T original) {
T o = null;
try {
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(byteOut);
oos.writeObject(original);
ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
ObjectInputStream ois = new ObjectInputStream(byteIn);
try {
o = (T) ois.readObject();
} catch (ClassNotFoundException cex) {
// actually can not happen in this instance
}
} catch (IOException iox) {
// doesn't seem likely to happen as these streams are in memory
throw new RuntimeException(iox);
}
return o;
}
public static class Patchset implements Serializable, Comparable<Patchset> {
private static final long serialVersionUID = 1L;
public int number;
public int rev;
public String tip;
public String parent;
public String base;
public int insertions;
public int deletions;
public int commits;
public int added;
public PatchsetType type;
public boolean isFF() {
return PatchsetType.FastForward == type;
}
@Override
public int hashCode() {
return toString().hashCode();
}
@Override
public boolean equals(Object o) {
if (o instanceof Patchset) {
return hashCode() == o.hashCode();
}
return false;
}
@Override
public int compareTo(Patchset p) {
if (number > p.number) {
return -1;
} else if (p.number > number) {
return 1;
} else {
// same patchset, different revision
if (rev > p.rev) {
return -1;
} else if (p.rev > rev) {
return 1;
} else {
// same patchset & revision
return 0;
}
}
}
@Override
public String toString() {
return "patchset " + number + " revision " + rev;
}
}
public static class Comment implements Serializable {
private static final long serialVersionUID = 1L;
public String text;
public String id;
public Boolean deleted;
public CommentSource src;
public String replyTo;
Comment(String text) {
this.text = text;
}
public boolean isDeleted() {
return deleted != null && deleted;
}
@Override
public String toString() {
return text;
}
}
public static class Attachment implements Serializable {
private static final long serialVersionUID = 1L;
public final String name;
public long size;
public byte[] content;
public Boolean deleted;
public Attachment(String name) {
this.name = name;
}
public boolean isDeleted() {
return deleted != null && deleted;
}
@Override
public int hashCode() {
return name.hashCode();
}
@Override
public boolean equals(Object o) {
if (o instanceof Attachment) {
return name.equalsIgnoreCase(((Attachment) o).name);
}
return false;
}
@Override
public String toString() {
return name;
}
}
public static class Review implements Serializable {
private static final long serialVersionUID = 1L;
public final int patchset;
public final int rev;
public Score score;
public Review(int patchset, int revision) {
this.patchset = patchset;
this.rev = revision;
}
public boolean isReviewOf(Patchset p) {
return patchset == p.number && rev == p.rev;
}
@Override
public String toString() {
return "review of patchset " + patchset + " rev " + rev + ":" + score;
}
}
public static enum Score {
approved(2), looks_good(1), not_reviewed(0), needs_improvement(-1), vetoed(
-2);
final int value;
Score(int value) {
this.value = value;
}
public int getValue() {
return value;
}
@Override
public String toString() {
return name().toLowerCase().replace('_', ' ');
}
public static Score fromScore(int score) {
for (Score s : values()) {
if (s.getValue() == score) {
return s;
}
}
throw new NoSuchElementException(String.valueOf(score));
}
}
public static enum Field {
title, body, responsible, type, status, milestone, mergeSha, mergeTo,
topic, labels, watchers, reviewers, voters, mentions;
}
public static enum Type {
Enhancement, Task, Bug, Proposal, Question;
public static Type defaultType = Task;
public static Type [] choices() {
return new Type [] { Enhancement, Task, Bug, Question };
}
@Override
public String toString() {
return name().toLowerCase().replace('_', ' ');
}
public static Type fromObject(Object o, Type defaultType) {
if (o instanceof Type) {
// cast and return
return (Type) o;
} else if (o instanceof String) {
// find by name
for (Type type : values()) {
String str = o.toString();
if (type.name().equalsIgnoreCase(str)
|| type.toString().equalsIgnoreCase(str)) {
return type;
}
}
} else if (o instanceof Number) {
// by ordinal
int id = ((Number) o).intValue();
if (id >= 0 && id < values().length) {
return values()[id];
}
}
return defaultType;
}
}
public static enum Status {
New, Open, Closed, Resolved, Fixed, Merged, Wontfix, Declined, Duplicate, Invalid, Abandoned, On_Hold;
public static Status [] requestWorkflow = { Open, Resolved, Declined, Duplicate, Invalid, Abandoned, On_Hold };
public static Status [] bugWorkflow = { Open, Fixed, Wontfix, Duplicate, Invalid, Abandoned, On_Hold };
public static Status [] proposalWorkflow = { Open, Resolved, Declined, Abandoned, On_Hold };
public static Status [] milestoneWorkflow = { Open, Closed, Abandoned, On_Hold };
@Override
public String toString() {
return name().toLowerCase().replace('_', ' ');
}
public static Status fromObject(Object o, Status defaultStatus) {
if (o instanceof Status) {
// cast and return
return (Status) o;
} else if (o instanceof String) {
// find by name
String name = o.toString();
for (Status state : values()) {
if (state.name().equalsIgnoreCase(name)
|| state.toString().equalsIgnoreCase(name)) {
return state;
}
}
} else if (o instanceof Number) {
// by ordinal
int id = ((Number) o).intValue();
if (id >= 0 && id < values().length) {
return values()[id];
}
}
return defaultStatus;
}
public boolean isClosed() {
return ordinal() > Open.ordinal();
}
}
public static enum CommentSource {
Comment, Email
}
public static enum PatchsetType {
Proposal, FastForward, Rebase, Squash, Rebase_Squash, Amend;
public boolean isRewrite() {
return (this != FastForward) && (this != Proposal);
}
@Override
public String toString() {
return name().toLowerCase().replace('_', '+');
}
public static PatchsetType fromObject(Object o) {
if (o instanceof PatchsetType) {
// cast and return
return (PatchsetType) o;
} else if (o instanceof String) {
// find by name
String name = o.toString();
for (PatchsetType type : values()) {
if (type.name().equalsIgnoreCase(name)
|| type.toString().equalsIgnoreCase(name)) {
return type;
}
}
} else if (o instanceof Number) {
// by ordinal
int id = ((Number) o).intValue();
if (id >= 0 && id < values().length) {
return values()[id];
}
}
return null;
}
}
}
|
src/main/java/com/gitblit/models/TicketModel.java
|
/*
* Copyright 2014 gitblit.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gitblit.models;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.jgit.util.RelativeDateFormatter;
/**
* The Gitblit Ticket model, its component classes, and enums.
*
* @author James Moger
*
*/
public class TicketModel implements Serializable, Comparable<TicketModel> {
private static final long serialVersionUID = 1L;
public String project;
public String repository;
public long number;
public Date created;
public String createdBy;
public Date updated;
public String updatedBy;
public String title;
public String body;
public String topic;
public Type type;
public Status status;
public String responsible;
public String milestone;
public String mergeSha;
public String mergeTo;
public List<Change> changes;
public Integer insertions;
public Integer deletions;
/**
* Builds an effective ticket from the collection of changes. A change may
* Add or Subtract information from a ticket, but the collection of changes
* is only additive.
*
* @param changes
* @return the effective ticket
*/
public static TicketModel buildTicket(Collection<Change> changes) {
TicketModel ticket;
List<Change> effectiveChanges = new ArrayList<Change>();
Map<String, Change> comments = new HashMap<String, Change>();
for (Change change : changes) {
if (change.comment != null) {
if (comments.containsKey(change.comment.id)) {
Change original = comments.get(change.comment.id);
Change clone = copy(original);
clone.comment.text = change.comment.text;
clone.comment.deleted = change.comment.deleted;
int idx = effectiveChanges.indexOf(original);
effectiveChanges.remove(original);
effectiveChanges.add(idx, clone);
comments.put(clone.comment.id, clone);
} else {
effectiveChanges.add(change);
comments.put(change.comment.id, change);
}
} else {
effectiveChanges.add(change);
}
}
// effective ticket
ticket = new TicketModel();
for (Change change : effectiveChanges) {
if (!change.hasComment()) {
// ensure we do not include a deleted comment
change.comment = null;
}
ticket.applyChange(change);
}
return ticket;
}
public TicketModel() {
// the first applied change set the date appropriately
created = new Date(0);
changes = new ArrayList<Change>();
status = Status.New;
type = Type.defaultType;
}
public boolean isOpen() {
return !status.isClosed();
}
public boolean isClosed() {
return status.isClosed();
}
public boolean isMerged() {
return isClosed() && !isEmpty(mergeSha);
}
public boolean isProposal() {
return Type.Proposal == type;
}
public boolean isBug() {
return Type.Bug == type;
}
public Date getLastUpdated() {
return updated == null ? created : updated;
}
public boolean hasPatchsets() {
return getPatchsets().size() > 0;
}
/**
* Returns true if multiple participants are involved in discussing a ticket.
* The ticket creator is excluded from this determination because a
* discussion requires more than one participant.
*
* @return true if this ticket has a discussion
*/
public boolean hasDiscussion() {
for (Change change : getComments()) {
if (!change.author.equals(createdBy)) {
return true;
}
}
return false;
}
/**
* Returns the list of changes with comments.
*
* @return
*/
public List<Change> getComments() {
List<Change> list = new ArrayList<Change>();
for (Change change : changes) {
if (change.hasComment()) {
list.add(change);
}
}
return list;
}
/**
* Returns the list of participants for the ticket.
*
* @return the list of participants
*/
public List<String> getParticipants() {
Set<String> set = new LinkedHashSet<String>();
for (Change change : changes) {
if (change.isParticipantChange()) {
set.add(change.author);
}
}
if (responsible != null && responsible.length() > 0) {
set.add(responsible);
}
return new ArrayList<String>(set);
}
public boolean hasLabel(String label) {
return getLabels().contains(label);
}
public List<String> getLabels() {
return getList(Field.labels);
}
public boolean isResponsible(String username) {
return username.equals(responsible);
}
public boolean isAuthor(String username) {
return username.equals(createdBy);
}
public boolean isReviewer(String username) {
return getReviewers().contains(username);
}
public List<String> getReviewers() {
return getList(Field.reviewers);
}
public boolean isWatching(String username) {
return getWatchers().contains(username);
}
public List<String> getWatchers() {
return getList(Field.watchers);
}
public boolean isVoter(String username) {
return getVoters().contains(username);
}
public List<String> getVoters() {
return getList(Field.voters);
}
public List<String> getMentions() {
return getList(Field.mentions);
}
protected List<String> getList(Field field) {
Set<String> set = new TreeSet<String>();
for (Change change : changes) {
if (change.hasField(field)) {
String values = change.getString(field);
for (String value : values.split(",")) {
switch (value.charAt(0)) {
case '+':
set.add(value.substring(1));
break;
case '-':
set.remove(value.substring(1));
break;
default:
set.add(value);
}
}
}
}
if (!set.isEmpty()) {
return new ArrayList<String>(set);
}
return Collections.emptyList();
}
public Attachment getAttachment(String name) {
Attachment attachment = null;
for (Change change : changes) {
if (change.hasAttachments()) {
Attachment a = change.getAttachment(name);
if (a != null) {
attachment = a;
}
}
}
return attachment;
}
public boolean hasAttachments() {
for (Change change : changes) {
if (change.hasAttachments()) {
return true;
}
}
return false;
}
public List<Attachment> getAttachments() {
List<Attachment> list = new ArrayList<Attachment>();
for (Change change : changes) {
if (change.hasAttachments()) {
list.addAll(change.attachments);
}
}
return list;
}
public List<Patchset> getPatchsets() {
List<Patchset> list = new ArrayList<Patchset>();
for (Change change : changes) {
if (change.patchset != null) {
list.add(change.patchset);
}
}
return list;
}
public List<Patchset> getPatchsetRevisions(int number) {
List<Patchset> list = new ArrayList<Patchset>();
for (Change change : changes) {
if (change.patchset != null) {
if (number == change.patchset.number) {
list.add(change.patchset);
}
}
}
return list;
}
public Patchset getPatchset(String sha) {
for (Change change : changes) {
if (change.patchset != null) {
if (sha.equals(change.patchset.tip)) {
return change.patchset;
}
}
}
return null;
}
public Patchset getPatchset(int number, int rev) {
for (Change change : changes) {
if (change.patchset != null) {
if (number == change.patchset.number && rev == change.patchset.rev) {
return change.patchset;
}
}
}
return null;
}
public Patchset getCurrentPatchset() {
Patchset patchset = null;
for (Change change : changes) {
if (change.patchset != null) {
if (patchset == null) {
patchset = change.patchset;
} else if (patchset.compareTo(change.patchset) == 1) {
patchset = change.patchset;
}
}
}
return patchset;
}
public boolean isCurrent(Patchset patchset) {
if (patchset == null) {
return false;
}
Patchset curr = getCurrentPatchset();
if (curr == null) {
return false;
}
return curr.equals(patchset);
}
public List<Change> getReviews(Patchset patchset) {
if (patchset == null) {
return Collections.emptyList();
}
// collect the patchset reviews by author
// the last review by the author is the
// official review
Map<String, Change> reviews = new LinkedHashMap<String, TicketModel.Change>();
for (Change change : changes) {
if (change.hasReview()) {
if (change.review.isReviewOf(patchset)) {
reviews.put(change.author, change);
}
}
}
return new ArrayList<Change>(reviews.values());
}
public boolean isApproved(Patchset patchset) {
if (patchset == null) {
return false;
}
boolean approved = false;
boolean vetoed = false;
for (Change change : getReviews(patchset)) {
if (change.hasReview()) {
if (change.review.isReviewOf(patchset)) {
if (Score.approved == change.review.score) {
approved = true;
} else if (Score.vetoed == change.review.score) {
vetoed = true;
}
}
}
}
return approved && !vetoed;
}
public boolean isVetoed(Patchset patchset) {
if (patchset == null) {
return false;
}
for (Change change : getReviews(patchset)) {
if (change.hasReview()) {
if (change.review.isReviewOf(patchset)) {
if (Score.vetoed == change.review.score) {
return true;
}
}
}
}
return false;
}
public Review getReviewBy(String username) {
for (Change change : getReviews(getCurrentPatchset())) {
if (change.author.equals(username)) {
return change.review;
}
}
return null;
}
public boolean isPatchsetAuthor(String username) {
for (Change change : changes) {
if (change.hasPatchset()) {
if (change.author.equals(username)) {
return true;
}
}
}
return false;
}
public void applyChange(Change change) {
if (changes.size() == 0) {
// first change created the ticket
created = change.date;
createdBy = change.author;
status = Status.New;
} else if (created == null || change.date.after(created)) {
// track last ticket update
updated = change.date;
updatedBy = change.author;
}
if (change.isMerge()) {
// identify merge patchsets
if (isEmpty(responsible)) {
responsible = change.author;
}
status = Status.Merged;
}
if (change.hasFieldChanges()) {
for (Map.Entry<Field, String> entry : change.fields.entrySet()) {
Field field = entry.getKey();
Object value = entry.getValue();
switch (field) {
case type:
type = TicketModel.Type.fromObject(value, type);
break;
case status:
status = TicketModel.Status.fromObject(value, status);
break;
case title:
title = toString(value);
break;
case body:
body = toString(value);
break;
case topic:
topic = toString(value);
break;
case responsible:
responsible = toString(value);
break;
case milestone:
milestone = toString(value);
break;
case mergeTo:
mergeTo = toString(value);
break;
case mergeSha:
mergeSha = toString(value);
break;
default:
// unknown
break;
}
}
}
// add the change to the ticket
changes.add(change);
}
protected String toString(Object value) {
if (value == null) {
return null;
}
return value.toString();
}
public String toIndexableString() {
StringBuilder sb = new StringBuilder();
if (!isEmpty(title)) {
sb.append(title).append('\n');
}
if (!isEmpty(body)) {
sb.append(body).append('\n');
}
for (Change change : changes) {
if (change.hasComment()) {
sb.append(change.comment.text);
sb.append('\n');
}
}
return sb.toString();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("#");
sb.append(number);
sb.append(": " + title + "\n");
for (Change change : changes) {
sb.append(change);
sb.append('\n');
}
return sb.toString();
}
@Override
public int compareTo(TicketModel o) {
return o.created.compareTo(created);
}
@Override
public boolean equals(Object o) {
if (o instanceof TicketModel) {
return number == ((TicketModel) o).number;
}
return super.equals(o);
}
@Override
public int hashCode() {
return (repository + number).hashCode();
}
/**
* Encapsulates a ticket change
*/
public static class Change implements Serializable, Comparable<Change> {
private static final long serialVersionUID = 1L;
public final Date date;
public final String author;
public Comment comment;
public Map<Field, String> fields;
public Set<Attachment> attachments;
public Patchset patchset;
public Review review;
private transient String id;
public Change(String author) {
this(author, new Date());
}
public Change(String author, Date date) {
this.date = date;
this.author = author;
}
public boolean isStatusChange() {
return hasField(Field.status);
}
public Status getStatus() {
Status state = Status.fromObject(getField(Field.status), null);
return state;
}
public boolean isMerge() {
return hasField(Field.status) && hasField(Field.mergeSha);
}
public boolean hasPatchset() {
return patchset != null;
}
public boolean hasReview() {
return review != null;
}
public boolean hasComment() {
return comment != null && !comment.isDeleted();
}
public Comment comment(String text) {
comment = new Comment(text);
comment.id = TicketModel.getSHA1(date.toString() + author + text);
try {
Pattern mentions = Pattern.compile("\\s@([A-Za-z0-9-_]+)");
Matcher m = mentions.matcher(text);
while (m.find()) {
String username = m.group(1);
plusList(Field.mentions, username);
}
} catch (Exception e) {
// ignore
}
return comment;
}
public Review review(Patchset patchset, Score score, boolean addReviewer) {
if (addReviewer) {
plusList(Field.reviewers, author);
}
review = new Review(patchset.number, patchset.rev);
review.score = score;
return review;
}
public boolean hasAttachments() {
return !TicketModel.isEmpty(attachments);
}
public void addAttachment(Attachment attachment) {
if (attachments == null) {
attachments = new LinkedHashSet<Attachment>();
}
attachments.add(attachment);
}
public Attachment getAttachment(String name) {
if (attachments != null) {
for (Attachment attachment : attachments) {
if (attachment.name.equalsIgnoreCase(name)) {
return attachment;
}
}
}
return null;
}
public boolean isParticipantChange() {
if (hasComment()
|| hasReview()
|| hasPatchset()
|| hasAttachments()) {
return true;
}
if (TicketModel.isEmpty(fields)) {
return false;
}
// identify real ticket field changes
Map<Field, String> map = new HashMap<Field, String>(fields);
map.remove(Field.watchers);
map.remove(Field.voters);
return !map.isEmpty();
}
public boolean hasField(Field field) {
return !TicketModel.isEmpty(getString(field));
}
public boolean hasFieldChanges() {
return !TicketModel.isEmpty(fields);
}
public String getField(Field field) {
if (fields != null) {
return fields.get(field);
}
return null;
}
public void setField(Field field, Object value) {
if (fields == null) {
fields = new LinkedHashMap<Field, String>();
}
if (value == null) {
fields.put(field, null);
} else if (Enum.class.isAssignableFrom(value.getClass())) {
fields.put(field, ((Enum<?>) value).name());
} else {
fields.put(field, value.toString());
}
}
public void remove(Field field) {
if (fields != null) {
fields.remove(field);
}
}
public String getString(Field field) {
String value = getField(field);
if (value == null) {
return null;
}
return value;
}
public void watch(String... username) {
plusList(Field.watchers, username);
}
public void unwatch(String... username) {
minusList(Field.watchers, username);
}
public void vote(String... username) {
plusList(Field.voters, username);
}
public void unvote(String... username) {
minusList(Field.voters, username);
}
public void label(String... label) {
plusList(Field.labels, label);
}
public void unlabel(String... label) {
minusList(Field.labels, label);
}
protected void plusList(Field field, String... items) {
modList(field, "+", items);
}
protected void minusList(Field field, String... items) {
modList(field, "-", items);
}
private void modList(Field field, String prefix, String... items) {
List<String> list = new ArrayList<String>();
for (String item : items) {
list.add(prefix + item);
}
if (hasField(field)) {
String flat = getString(field);
if (isEmpty(flat)) {
// field is empty, use this list
setField(field, join(list, ","));
} else {
// merge this list into the existing field list
Set<String> set = new TreeSet<String>(Arrays.asList(flat.split(",")));
set.addAll(list);
setField(field, join(set, ","));
}
} else {
// does not have a list for this field
setField(field, join(list, ","));
}
}
public String getId() {
if (id == null) {
id = getSHA1(Long.toHexString(date.getTime()) + author);
}
return id;
}
@Override
public int compareTo(Change c) {
return date.compareTo(c.date);
}
@Override
public int hashCode() {
return getId().hashCode();
}
@Override
public boolean equals(Object o) {
if (o instanceof Change) {
return getId().equals(((Change) o).getId());
}
return false;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(RelativeDateFormatter.format(date));
if (hasComment()) {
sb.append(" commented on by ");
} else if (hasPatchset()) {
sb.append(MessageFormat.format(" {0} uploaded by ", patchset));
} else {
sb.append(" changed by ");
}
sb.append(author).append(" - ");
if (hasComment()) {
if (comment.isDeleted()) {
sb.append("(deleted) ");
}
sb.append(comment.text).append(" ");
}
if (hasFieldChanges()) {
for (Map.Entry<Field, String> entry : fields.entrySet()) {
sb.append("\n ");
sb.append(entry.getKey().name());
sb.append(':');
sb.append(entry.getValue());
}
}
return sb.toString();
}
}
/**
* Returns true if the string is null or empty.
*
* @param value
* @return true if string is null or empty
*/
static boolean isEmpty(String value) {
return value == null || value.trim().length() == 0;
}
/**
* Returns true if the collection is null or empty
*
* @param collection
* @return
*/
static boolean isEmpty(Collection<?> collection) {
return collection == null || collection.size() == 0;
}
/**
* Returns true if the map is null or empty
*
* @param map
* @return
*/
static boolean isEmpty(Map<?, ?> map) {
return map == null || map.size() == 0;
}
/**
* Calculates the SHA1 of the string.
*
* @param text
* @return sha1 of the string
*/
static String getSHA1(String text) {
try {
byte[] bytes = text.getBytes("iso-8859-1");
return getSHA1(bytes);
} catch (UnsupportedEncodingException u) {
throw new RuntimeException(u);
}
}
/**
* Calculates the SHA1 of the byte array.
*
* @param bytes
* @return sha1 of the byte array
*/
static String getSHA1(byte[] bytes) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(bytes, 0, bytes.length);
byte[] digest = md.digest();
return toHex(digest);
} catch (NoSuchAlgorithmException t) {
throw new RuntimeException(t);
}
}
/**
* Returns the hex representation of the byte array.
*
* @param bytes
* @return byte array as hex string
*/
static String toHex(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (int i = 0; i < bytes.length; i++) {
if ((bytes[i] & 0xff) < 0x10) {
sb.append('0');
}
sb.append(Long.toString(bytes[i] & 0xff, 16));
}
return sb.toString();
}
/**
* Join the list of strings into a single string with a space separator.
*
* @param values
* @return joined list
*/
static String join(Collection<String> values) {
return join(values, " ");
}
/**
* Join the list of strings into a single string with the specified
* separator.
*
* @param values
* @param separator
* @return joined list
*/
static String join(String[] values, String separator) {
return join(Arrays.asList(values), separator);
}
/**
* Join the list of strings into a single string with the specified
* separator.
*
* @param values
* @param separator
* @return joined list
*/
static String join(Collection<String> values, String separator) {
StringBuilder sb = new StringBuilder();
for (String value : values) {
sb.append(value).append(separator);
}
if (sb.length() > 0) {
// truncate trailing separator
sb.setLength(sb.length() - separator.length());
}
return sb.toString().trim();
}
/**
* Produce a deep copy of the given object. Serializes the entire object to
* a byte array in memory. Recommended for relatively small objects.
*/
@SuppressWarnings("unchecked")
static <T> T copy(T original) {
T o = null;
try {
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(byteOut);
oos.writeObject(original);
ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
ObjectInputStream ois = new ObjectInputStream(byteIn);
try {
o = (T) ois.readObject();
} catch (ClassNotFoundException cex) {
// actually can not happen in this instance
}
} catch (IOException iox) {
// doesn't seem likely to happen as these streams are in memory
throw new RuntimeException(iox);
}
return o;
}
public static class Patchset implements Serializable, Comparable<Patchset> {
private static final long serialVersionUID = 1L;
public int number;
public int rev;
public String tip;
public String parent;
public String base;
public int insertions;
public int deletions;
public int commits;
public int added;
public PatchsetType type;
public boolean isFF() {
return PatchsetType.FastForward == type;
}
@Override
public int hashCode() {
return toString().hashCode();
}
@Override
public boolean equals(Object o) {
if (o instanceof Patchset) {
return hashCode() == o.hashCode();
}
return false;
}
@Override
public int compareTo(Patchset p) {
if (number > p.number) {
return -1;
} else if (p.number > number) {
return 1;
} else {
// same patchset, different revision
if (rev > p.rev) {
return -1;
} else if (p.rev > rev) {
return 1;
} else {
// same patchset & revision
return 0;
}
}
}
@Override
public String toString() {
return "patchset " + number + " revision " + rev;
}
}
public static class Comment implements Serializable {
private static final long serialVersionUID = 1L;
public String text;
public String id;
public Boolean deleted;
public CommentSource src;
public String replyTo;
Comment(String text) {
this.text = text;
}
public boolean isDeleted() {
return deleted != null && deleted;
}
@Override
public String toString() {
return text;
}
}
public static class Attachment implements Serializable {
private static final long serialVersionUID = 1L;
public final String name;
public long size;
public byte[] content;
public Boolean deleted;
public Attachment(String name) {
this.name = name;
}
public boolean isDeleted() {
return deleted != null && deleted;
}
@Override
public int hashCode() {
return name.hashCode();
}
@Override
public boolean equals(Object o) {
if (o instanceof Attachment) {
return name.equalsIgnoreCase(((Attachment) o).name);
}
return false;
}
@Override
public String toString() {
return name;
}
}
public static class Review implements Serializable {
private static final long serialVersionUID = 1L;
public final int patchset;
public final int rev;
public Score score;
public Review(int patchset, int revision) {
this.patchset = patchset;
this.rev = revision;
}
public boolean isReviewOf(Patchset p) {
return patchset == p.number && rev == p.rev;
}
@Override
public String toString() {
return "review of patchset " + patchset + " rev " + rev + ":" + score;
}
}
public static enum Score {
approved(2), looks_good(1), not_reviewed(0), needs_improvement(-1), vetoed(
-2);
final int value;
Score(int value) {
this.value = value;
}
public int getValue() {
return value;
}
@Override
public String toString() {
return name().toLowerCase().replace('_', ' ');
}
public static Score fromScore(int score) {
for (Score s : values()) {
if (s.getValue() == score) {
return s;
}
}
throw new NoSuchElementException(String.valueOf(score));
}
}
public static enum Field {
title, body, responsible, type, status, milestone, mergeSha, mergeTo,
topic, labels, watchers, reviewers, voters, mentions;
}
public static enum Type {
Enhancement, Task, Bug, Proposal, Question;
public static Type defaultType = Task;
public static Type [] choices() {
return new Type [] { Enhancement, Task, Bug, Question };
}
@Override
public String toString() {
return name().toLowerCase().replace('_', ' ');
}
public static Type fromObject(Object o, Type defaultType) {
if (o instanceof Type) {
// cast and return
return (Type) o;
} else if (o instanceof String) {
// find by name
for (Type type : values()) {
String str = o.toString();
if (type.name().equalsIgnoreCase(str)
|| type.toString().equalsIgnoreCase(str)) {
return type;
}
}
} else if (o instanceof Number) {
// by ordinal
int id = ((Number) o).intValue();
if (id >= 0 && id < values().length) {
return values()[id];
}
}
return defaultType;
}
}
public static enum Status {
New, Open, Closed, Resolved, Fixed, Merged, Wontfix, Declined, Duplicate, Invalid, Abandoned, On_Hold;
public static Status [] requestWorkflow = { Open, Resolved, Declined, Duplicate, Invalid, Abandoned, On_Hold };
public static Status [] bugWorkflow = { Open, Fixed, Wontfix, Duplicate, Invalid, Abandoned, On_Hold };
public static Status [] proposalWorkflow = { Open, Resolved, Declined, Abandoned, On_Hold };
public static Status [] milestoneWorkflow = { Open, Closed, Abandoned, On_Hold };
@Override
public String toString() {
return name().toLowerCase().replace('_', ' ');
}
public static Status fromObject(Object o, Status defaultStatus) {
if (o instanceof Status) {
// cast and return
return (Status) o;
} else if (o instanceof String) {
// find by name
String name = o.toString();
for (Status state : values()) {
if (state.name().equalsIgnoreCase(name)
|| state.toString().equalsIgnoreCase(name)) {
return state;
}
}
} else if (o instanceof Number) {
// by ordinal
int id = ((Number) o).intValue();
if (id >= 0 && id < values().length) {
return values()[id];
}
}
return defaultStatus;
}
public boolean isClosed() {
return ordinal() > Open.ordinal();
}
}
public static enum CommentSource {
Comment, Email
}
public static enum PatchsetType {
Proposal, FastForward, Rebase, Squash, Rebase_Squash, Amend;
public boolean isRewrite() {
return (this != FastForward) && (this != Proposal);
}
@Override
public String toString() {
return name().toLowerCase().replace('_', '+');
}
public static PatchsetType fromObject(Object o) {
if (o instanceof PatchsetType) {
// cast and return
return (PatchsetType) o;
} else if (o instanceof String) {
// find by name
String name = o.toString();
for (PatchsetType type : values()) {
if (type.name().equalsIgnoreCase(name)
|| type.toString().equalsIgnoreCase(name)) {
return type;
}
}
} else if (o instanceof Number) {
// by ordinal
int id = ((Number) o).intValue();
if (id >= 0 && id < values().length) {
return values()[id];
}
}
return null;
}
}
}
|
Ensure TicketModel comment text is not null in hasComment() test
|
src/main/java/com/gitblit/models/TicketModel.java
|
Ensure TicketModel comment text is not null in hasComment() test
|
|
Java
|
apache-2.0
|
79c2cf26e812b319f190e83c22b21dfe81bd2786
| 0
|
mtvweb/BootsFaces-OSP,TheCoder4eu/BootsFaces-OSP,mtvweb/BootsFaces-OSP,TheCoder4eu/BootsFaces-OSP
|
/**
* Copyright 2014-2017 Riccardo Massera (TheCoder4.Eu) and Stephan Rauh (http://www.beyondjava.net).
*
* This file is part of BootsFaces.
*
* 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.bootsfaces.component.dataTable;
import javax.faces.context.FacesContext;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ComponentSystemEvent;
import javax.faces.event.ListenerFor;
import javax.faces.event.ListenersFor;
import javax.faces.event.PostAddToViewEvent;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.el.ValueExpression;
import javax.faces.component.FacesComponent;
import javax.faces.component.UIComponent;
import javax.faces.component.UIComponentBase;
import javax.faces.component.UIViewRoot;
import javax.faces.component.behavior.ClientBehaviorHolder;
import javax.faces.context.FacesContext;
import javax.faces.event.FacesEvent;
import net.bootsfaces.C;
import net.bootsfaces.component.ajax.IAJAXComponent;
import net.bootsfaces.component.ajax.IAJAXComponent2;
import net.bootsfaces.listeners.AddResourcesListener;
import net.bootsfaces.render.IContentDisabled;
import net.bootsfaces.render.IResponsive;
import net.bootsfaces.render.Tooltip;
import net.bootsfaces.utils.BsfUtils;
/** This class holds the attributes of <b:dataTable />. */
@ListenersFor({ @ListenerFor(systemEventClass = PostAddToViewEvent.class) })
@FacesComponent(DataTable.COMPONENT_TYPE)
public class DataTable extends DataTableCore implements IAJAXComponent, IAJAXComponent2, ClientBehaviorHolder,
net.bootsfaces.render.IHasTooltip, IResponsive, IContentDisabled {
public static final String COMPONENT_TYPE = C.BSFCOMPONENT + ".dataTable.DataTable";
public static final String COMPONENT_FAMILY = C.BSFCOMPONENT;
public static final String DEFAULT_RENDERER = "net.bootsfaces.component.dataTable.DataTable";
private static final Collection<String> EVENT_NAMES = Collections.unmodifiableCollection(Arrays.asList("click",
"dblclick", "dragstart", "dragover", "drop", "mousedown", "mousemove", "mouseout", "mouseover", "mouseup"));
/**
* This map is used to store the column sort information gathered during
* rendering.
*/
private Map<Integer, String> columnSortOrder;
/**
* This array is used to store the columnDef property used to
* initialize the columns using the columns attribute of datatables.net
*/
private List<String> columnDefinition;
/**
* internal attribute used for b:dataTableColumn selectionMode="multiple"
*/
private String selectionMode2;
/**
* This array is used to store the column information bits that are used to
* initialize the columns using the columns attribute of datatables.net
*/
private List<String> columnInfo;
public enum DataTablePropertyType {
pageLength, searchTerm, currentPage
}
public DataTable() {
setRendererType(DEFAULT_RENDERER);
Tooltip.addResourceFiles();
AddResourcesListener.addThemedCSSResource("core.css");
AddResourcesListener.addDatatablesResourceIfNecessary("https://cdn.datatables.net/v/bs/jszip-2.5.0/dt-1.10.18/af-2.3.2/b-1.5.4/b-colvis-1.5.4/b-html5-1.5.4/b-print-1.5.4/fc-3.2.5/fh-3.1.4/r-2.2.2/rr-1.2.4/sc-1.5.0/sl-1.2.6/datatables.min.css", "css");
AddResourcesListener.addDatatablesResourceIfNecessary("https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/pdfmake.min.js", "css");
AddResourcesListener.addDatatablesResourceIfNecessary("https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/vfs_fonts.js", "css");
AddResourcesListener.addDatatablesResourceIfNecessary("https://cdn.datatables.net/v/bs/jszip-2.5.0/dt-1.10.18/af-2.3.2/b-1.5.4/b-colvis-1.5.4/b-html5-1.5.4/b-print-1.5.4/fc-3.2.5/fh-3.1.4/r-2.2.2/rr-1.2.4/sc-1.5.0/sl-1.2.6/datatables.min.js", "js");
}
public void setValueExpression(String name, ValueExpression binding) {
name = BsfUtils.snakeCaseToCamelCase(name);
super.setValueExpression(name, binding);
}
@Override
public boolean getRendersChildren() {
return true;
}
/**
* returns the subset of AJAX requests that are implemented by jQuery callback
* or other non-standard means (such as the onclick event of b:tabView, which
* has to be implemented manually).
*
* @return
*/
public Map<String, String> getJQueryEvents() {
Map<String, String> result = new HashMap<String, String>();
result.put("order", "order.dt");
result.put("page", "page.dt");
result.put("search", "search.dt");
result.put("select", "select.dt");
result.put("deselect", "deselect.dt");
return result;
}
/**
* Returns the parameter list of jQuery and other non-standard JS callbacks. If
* there's no parameter list for a certain event, the default is simply "event".
*
* @return A hash map containing the events. May be null.
*/
@Override
public Map<String, String> getJQueryEventParameterLists() {
Map<String, String> result = new HashMap<String, String>();
result.put("select", "event, datatable, typeOfSelection, indexes");
result.put("deselect", "event, datatable, typeOfSelection, indexes");
return result;
}
/**
* Returns the subset of the parameter list of jQuery and other non-standard JS
* callbacks which is sent to the server via AJAX. If there's no parameter list
* for a certain event, the default is simply null.
*
* @return A hash map containing the events. May be null.
*/
@Override
public Map<String, String> getJQueryEventParameterListsForAjax() {
Map<String, String> result = new HashMap<String, String>();
result.put("select", "'typeOfSelection':typeOfSelection,'indexes':indexes");
result.put("deselect", "'typeOfSelection':typeOfSelection,'indexes':indexes");
return result;
}
public Collection<String> getEventNames() {
return EVENT_NAMES;
}
public String getDefaultEventName() {
return "click";
}
public void processEvent(ComponentSystemEvent event) throws AbortProcessingException {
if (isAutoUpdate()) {
if (FacesContext.getCurrentInstance().isPostback()) {
FacesContext.getCurrentInstance().getPartialViewContext().getRenderIds().add(getClientId());
}
super.processEvent(event);
}
List<UIComponent> columns = getChildren();
for (UIComponent column : columns) {
if (column.getAttributes().get("selectionMode") != null) {
String selectionMode = (String) column.getAttributes().get("selectionMode");
if ("multiple".equals(selectionMode)) {
importCheckboxColumnLib();
}
}
}
}
public String getFamily() {
return COMPONENT_FAMILY;
}
/**
* This map contains all of the default sorting for each column. This map is
* used to store the column sort information gathered during rendering.
*
* @return The map containing the column / sort type pairs
*/
public Map<Integer, String> getColumnSortOrderMap() {
return columnSortOrder;
}
/**
* Called in order to lazily initialize the map. This map is used to store the
* column sort information gathered during rendering.
*/
public void initColumnSortOrderMap() {
this.columnSortOrder = new HashMap<Integer, String>();
}
/**
* This array is used to store the columnDef attribute used to
* initialize the columns using the columns attribute of datatables.net
*/
public List<String> getColumnDefinition() {
return columnDefinition;
}
/**
* This array is used to store the columnDef attribute used to
* initialize the columns using the columns attribute of datatables.net
*/
public void setColumnDefinition(List<String> columnDefinition) {
this.columnDefinition = columnDefinition;
}
/**
* This array is used to store the column information bits that are used to
* initialize the columns using the columns attribute of datatables.net
*/
public List<String> getColumnInfo() {
return columnInfo;
}
/**
* This array is used to store the column information bits that are used to
* initialize the columns using the columns attribute of datatables.net
*/
public void setColumnInfo(List<String> columnInfo) {
this.columnInfo = columnInfo;
}
/**
* <p>
* Queue an event for broadcast at the end of the current request processing
* lifecycle phase. The default implementation in {@link UIComponentBase} must
* delegate this call to the <code>queueEvent()</code> method of the parent
* {@link UIComponent}.
* </p>
*
* @param event
* {@link FacesEvent} to be queued
*
* @throws IllegalStateException
* if this component is not a descendant of a {@link UIViewRoot}
* @throws NullPointerException
* if <code>event</code> is <code>null</code>
*/
public void queueEvent(FacesEvent event) {
FacesContext context = FacesContext.getCurrentInstance();
String indexes = (String) context.getExternalContext().getRequestParameterMap().get("indexes");
context.getELContext().getELResolver().setValue(context.getELContext(), null, "indexes", indexes);
String typeOfSelection = (String) context.getExternalContext().getRequestParameterMap().get("typeOfSelection");
context.getELContext().getELResolver().setValue(context.getELContext(), null, "typeOfSelection",
typeOfSelection);
try {
int oldIndex = getRowIndex();
int index = Integer.valueOf(indexes);
setRowIndex(index);
super.queueEvent(event);
setRowIndex(oldIndex);
} catch (Exception multipleIndexes) {
super.queueEvent(event);
}
}
@Override
public void setSelectedColumn(Object _selectedColumn) {
super.setSelectedColumn(_selectedColumn);
if (_selectedColumn != null) {
setSelect(true);
setSelectedItems("column");
}
}
@Override
public void setSelectedRow(Object _selectedRow) {
super.setSelectedRow(_selectedRow);
if (_selectedRow != null) {
setSelect(true);
setSelectedItems("row");
}
}
@Override
public void setSelectionMode(String _selectectionMode) {
super.setSelectionMode(_selectectionMode);
if (_selectectionMode != null) {
setSelect(true);
}
}
/**
* internal attribute used for b:dataTableColumn selectionMode="multiple"
*/
public String getSelectionMode2() {
return selectionMode2;
}
/**
* internal attribute used for b:dataTableColumn selectionMode="multiple"
*/
public void setSelectionMode2(String selectionMode2) {
this.selectionMode2 = selectionMode2;
}
@Override
public void setSelectedItems(String _selectedItems) {
super.setSelectedItems(_selectedItems);
if (_selectedItems != null) {
setSelect(true);
}
}
/**
* If true, search results are marked yellow as you type. Based on mark.js (see https://datatables.net/blog/2017-01-19). <P>
* Usually this method is called internally by the JSF engine.
*/
public void setMarkSearchResults(boolean _markSearchResults) {
if (_markSearchResults) {
AddResourcesListener.addResourceIfNecessary("https://cdn.datatables.net/plug-ins/1.10.18/features/mark.js/datatables.mark.min.css");
AddResourcesListener.addResourceIfNecessary("https://cdn.jsdelivr.net/g/mark.js(jquery.mark.min.js)");
AddResourcesListener.addResourceIfNecessary("https://cdn.datatables.net/plug-ins/1.10.18/features/mark.js/datatables.mark.js");
}
super.setMarkSearchResults(_markSearchResults);
}
/**
* Group the rows by a common column value. Can be a number or a Json-object, as documented at https://datatables.net/reference/option/#rowgroup. <P>
* Usually this method is called internally by the JSF engine.
*/
public void setRowGroup(String _rowGroup) {
AddResourcesListener.addResourceIfNecessary("https://cdn.datatables.net/rowgroup/1.1.0/js/dataTables.rowGroup.min.js");
super.setRowGroup(_rowGroup);
}
void importCheckboxColumnLib() {
AddResourcesListener.addBasicJSResource(C.BSF_LIBRARY, "js/dataTables.checkboxes.min.js");
AddResourcesListener.addExtCSSResource("dataTables.checkboxes.css");
}
}
|
src/main/java/net/bootsfaces/component/dataTable/DataTable.java
|
/**
* Copyright 2014-2017 Riccardo Massera (TheCoder4.Eu) and Stephan Rauh (http://www.beyondjava.net).
*
* This file is part of BootsFaces.
*
* 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.bootsfaces.component.dataTable;
import javax.faces.context.FacesContext;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ComponentSystemEvent;
import javax.faces.event.ListenerFor;
import javax.faces.event.ListenersFor;
import javax.faces.event.PostAddToViewEvent;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.el.ValueExpression;
import javax.faces.component.FacesComponent;
import javax.faces.component.UIComponent;
import javax.faces.component.UIComponentBase;
import javax.faces.component.UIViewRoot;
import javax.faces.component.behavior.ClientBehaviorHolder;
import javax.faces.context.FacesContext;
import javax.faces.event.FacesEvent;
import net.bootsfaces.C;
import net.bootsfaces.component.ajax.IAJAXComponent;
import net.bootsfaces.component.ajax.IAJAXComponent2;
import net.bootsfaces.listeners.AddResourcesListener;
import net.bootsfaces.render.IContentDisabled;
import net.bootsfaces.render.IResponsive;
import net.bootsfaces.render.Tooltip;
import net.bootsfaces.utils.BsfUtils;
/** This class holds the attributes of <b:dataTable />. */
@ListenersFor({ @ListenerFor(systemEventClass = PostAddToViewEvent.class) })
@FacesComponent(DataTable.COMPONENT_TYPE)
public class DataTable extends DataTableCore implements IAJAXComponent, IAJAXComponent2, ClientBehaviorHolder,
net.bootsfaces.render.IHasTooltip, IResponsive, IContentDisabled {
public static final String COMPONENT_TYPE = C.BSFCOMPONENT + ".dataTable.DataTable";
public static final String COMPONENT_FAMILY = C.BSFCOMPONENT;
public static final String DEFAULT_RENDERER = "net.bootsfaces.component.dataTable.DataTable";
private static final Collection<String> EVENT_NAMES = Collections.unmodifiableCollection(Arrays.asList("click",
"dblclick", "dragstart", "dragover", "drop", "mousedown", "mousemove", "mouseout", "mouseover", "mouseup"));
/**
* This map is used to store the column sort information gathered during
* rendering.
*/
private Map<Integer, String> columnSortOrder;
/**
* This array is used to store the columnDef property used to
* initialize the columns using the columns attribute of datatables.net
*/
private List<String> columnDefinition;
/**
* internal attribute used for b:dataTableColumn selectionMode="multiple"
*/
private String selectionMode2;
/**
* This array is used to store the column information bits that are used to
* initialize the columns using the columns attribute of datatables.net
*/
private List<String> columnInfo;
public enum DataTablePropertyType {
pageLength, searchTerm, currentPage
}
public DataTable() {
setRendererType(DEFAULT_RENDERER);
Tooltip.addResourceFiles();
AddResourcesListener.addThemedCSSResource("core.css");
AddResourcesListener.addDatatablesResourceIfNecessary("https://cdn.datatables.net/v/bs/jszip-2.5.0/dt-1.10.18/af-2.3.2/b-1.5.4/b-colvis-1.5.4/b-html5-1.5.4/b-print-1.5.4/fc-3.2.5/fh-3.1.4/r-2.2.2/rr-1.2.4/sc-1.5.0/sl-1.2.6/datatables.min.css", "css");
AddResourcesListener.addDatatablesResourceIfNecessary("https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/pdfmake.min.js", "css");
AddResourcesListener.addDatatablesResourceIfNecessary("https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/vfs_fonts.js", "css");
AddResourcesListener.addDatatablesResourceIfNecessary("https://cdn.datatables.net/v/bs/jszip-2.5.0/dt-1.10.18/af-2.3.2/b-1.5.4/b-colvis-1.5.4/b-html5-1.5.4/b-print-1.5.4/fc-3.2.5/fh-3.1.4/r-2.2.2/rr-1.2.4/sc-1.5.0/sl-1.2.6/datatables.min.js", "js");
}
public void setValueExpression(String name, ValueExpression binding) {
name = BsfUtils.snakeCaseToCamelCase(name);
super.setValueExpression(name, binding);
}
@Override
public boolean getRendersChildren() {
return true;
}
/**
* returns the subset of AJAX requests that are implemented by jQuery callback
* or other non-standard means (such as the onclick event of b:tabView, which
* has to be implemented manually).
*
* @return
*/
public Map<String, String> getJQueryEvents() {
Map<String, String> result = new HashMap<String, String>();
result.put("order", "order.dt");
result.put("page", "page.dt");
result.put("search", "search.dt");
result.put("select", "select.dt");
result.put("deselect", "deselect.dt");
return result;
}
/**
* Returns the parameter list of jQuery and other non-standard JS callbacks. If
* there's no parameter list for a certain event, the default is simply "event".
*
* @return A hash map containing the events. May be null.
*/
@Override
public Map<String, String> getJQueryEventParameterLists() {
Map<String, String> result = new HashMap<String, String>();
result.put("select", "event, datatable, typeOfSelection, indexes");
result.put("deselect", "event, datatable, typeOfSelection, indexes");
return result;
}
/**
* Returns the subset of the parameter list of jQuery and other non-standard JS
* callbacks which is sent to the server via AJAX. If there's no parameter list
* for a certain event, the default is simply null.
*
* @return A hash map containing the events. May be null.
*/
@Override
public Map<String, String> getJQueryEventParameterListsForAjax() {
Map<String, String> result = new HashMap<String, String>();
result.put("select", "'typeOfSelection':typeOfSelection,'indexes':indexes");
result.put("deselect", "'typeOfSelection':typeOfSelection,'indexes':indexes");
return result;
}
public Collection<String> getEventNames() {
return EVENT_NAMES;
}
public String getDefaultEventName() {
return "click";
}
public void processEvent(ComponentSystemEvent event) throws AbortProcessingException {
if (isAutoUpdate()) {
if (FacesContext.getCurrentInstance().isPostback()) {
FacesContext.getCurrentInstance().getPartialViewContext().getRenderIds().add(getClientId());
}
super.processEvent(event);
}
List<UIComponent> columns = getChildren();
for (UIComponent column : columns) {
if (column.getAttributes().get("selectionMode") != null) {
String selectionMode = (String) column.getAttributes().get("selectionMode");
if ("multiple".equals(selectionMode)) {
importCheckboxColumnLib();
}
}
}
}
public String getFamily() {
return COMPONENT_FAMILY;
}
/**
* This map contains all of the default sorting for each column. This map is
* used to store the column sort information gathered during rendering.
*
* @return The map containing the column / sort type pairs
*/
public Map<Integer, String> getColumnSortOrderMap() {
return columnSortOrder;
}
/**
* Called in order to lazily initialize the map. This map is used to store the
* column sort information gathered during rendering.
*/
public void initColumnSortOrderMap() {
this.columnSortOrder = new HashMap<Integer, String>();
}
/**
* This array is used to store the columnDef attribute used to
* initialize the columns using the columns attribute of datatables.net
*/
public List<String> getColumnDefinition() {
return columnDefinition;
}
/**
* This array is used to store the columnDef attribute used to
* initialize the columns using the columns attribute of datatables.net
*/
public void setColumnDefinition(List<String> columnDefinition) {
this.columnDefinition = columnDefinition;
}
/**
* This array is used to store the column information bits that are used to
* initialize the columns using the columns attribute of datatables.net
*/
public List<String> getColumnInfo() {
return columnInfo;
}
/**
* This array is used to store the column information bits that are used to
* initialize the columns using the columns attribute of datatables.net
*/
public void setColumnInfo(List<String> columnInfo) {
this.columnInfo = columnInfo;
}
/**
* <p>
* Queue an event for broadcast at the end of the current request processing
* lifecycle phase. The default implementation in {@link UIComponentBase} must
* delegate this call to the <code>queueEvent()</code> method of the parent
* {@link UIComponent}.
* </p>
*
* @param event
* {@link FacesEvent} to be queued
*
* @throws IllegalStateException
* if this component is not a descendant of a {@link UIViewRoot}
* @throws NullPointerException
* if <code>event</code> is <code>null</code>
*/
public void queueEvent(FacesEvent event) {
FacesContext context = FacesContext.getCurrentInstance();
String indexes = (String) context.getExternalContext().getRequestParameterMap().get("indexes");
context.getELContext().getELResolver().setValue(context.getELContext(), null, "indexes", indexes);
String typeOfSelection = (String) context.getExternalContext().getRequestParameterMap().get("typeOfSelection");
context.getELContext().getELResolver().setValue(context.getELContext(), null, "typeOfSelection",
typeOfSelection);
try {
int oldIndex = getRowIndex();
int index = Integer.valueOf(indexes);
setRowIndex(index);
super.queueEvent(event);
setRowIndex(oldIndex);
} catch (Exception multipleIndexes) {
super.queueEvent(event);
}
}
@Override
public void setSelectedColumn(Object _selectedColumn) {
super.setSelectedColumn(_selectedColumn);
if (_selectedColumn != null) {
setSelect(true);
setSelectedItems("column");
}
}
@Override
public void setSelectedRow(Object _selectedRow) {
super.setSelectedRow(_selectedRow);
if (_selectedRow != null) {
setSelect(true);
setSelectedItems("row");
}
}
@Override
public void setSelectionMode(String _selectectionMode) {
super.setSelectionMode(_selectectionMode);
if (_selectectionMode != null) {
setSelect(true);
}
}
/**
* internal attribute used for b:dataTableColumn selectionMode="multiple"
*/
public String getSelectionMode2() {
return selectionMode2;
}
/**
* internal attribute used for b:dataTableColumn selectionMode="multiple"
*/
public void setSelectionMode2(String selectionMode2) {
this.selectionMode2 = selectionMode2;
}
@Override
public void setSelectedItems(String _selectedItems) {
super.setSelectedItems(_selectedItems);
if (_selectedItems != null) {
setSelect(true);
}
}
/**
* If true, search results are marked yellow as you type. Based on mark.js (see https://datatables.net/blog/2017-01-19). <P>
* Usually this method is called internally by the JSF engine.
*/
public void setMarkSearchResults(boolean _markSearchResults) {
if (_markSearchResults) {
AddResourcesListener.addResourceIfNecessary("https://cdn.datatables.net/plug-ins/1.10.13/features/mark.js/datatables.mark.min.css");
AddResourcesListener.addResourceIfNecessary("https://cdn.jsdelivr.net/g/mark.js(jquery.mark.min.js)");
AddResourcesListener.addResourceIfNecessary("https://cdn.datatables.net/plug-ins/1.10.13/features/mark.js/datatables.mark.js");
}
super.setMarkSearchResults(_markSearchResults);
}
/**
* Group the rows by a common column value. Can be a number or a Json-object, as documented at https://datatables.net/reference/option/#rowgroup. <P>
* Usually this method is called internally by the JSF engine.
*/
public void setRowGroup(String _rowGroup) {
AddResourcesListener.addResourceIfNecessary("https://cdn.datatables.net/rowgroup/1.0.2/js/dataTables.rowGroup.min.js");
super.setRowGroup(_rowGroup);
}
void importCheckboxColumnLib() {
AddResourcesListener.addBasicJSResource(C.BSF_LIBRARY, "js/dataTables.checkboxes.min.js");
AddResourcesListener.addExtCSSResource("dataTables.checkboxes.css");
}
}
|
updated the mark.js plugin
|
src/main/java/net/bootsfaces/component/dataTable/DataTable.java
|
updated the mark.js plugin
|
|
Java
|
apache-2.0
|
441a471b90bccb707862d5f42df58635543eac41
| 0
|
google/conscrypt,google/conscrypt,google/conscrypt,google/conscrypt,google/conscrypt,google/conscrypt
|
/*
* Copyright (C) 2009 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 org.apache.harmony.xnet.provider.jsse;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.logging.Level;
import javax.net.ssl.SSLSession;
import libcore.io.IoUtils;
/**
* File-based cache implementation. Only one process should access the
* underlying directory at a time.
*/
public class FileClientSessionCache {
static final int MAX_SIZE = 12; // ~72k
static final java.util.logging.Logger logger
= java.util.logging.Logger.getLogger(
FileClientSessionCache.class.getName());
private FileClientSessionCache() {}
/**
* This cache creates one file per SSL session using "host.port" for
* the file name. Files are created or replaced when session data is put
* in the cache (see {@link #putSessionData}). Files are read on
* cache hits, but not on cache misses.
*
* <p>When the number of session files exceeds MAX_SIZE, we delete the
* least-recently-used file. We don't current persist the last access time,
* so the ordering actually ends up being least-recently-modified in some
* cases and even just "not accessed in this process" if the filesystem
* doesn't track last modified times.
*/
static class Impl implements SSLClientSessionCache {
/** Directory to store session files in. */
final File directory;
/**
* Map of name -> File. Keeps track of the order files were accessed in.
*/
Map<String, File> accessOrder = newAccessOrder();
/** The number of files on disk. */
int size;
/**
* The initial set of files. We use this to defer adding information
* about all files to accessOrder until necessary.
*/
String[] initialFiles;
/**
* Constructs a new cache backed by the given directory.
*/
Impl(File directory) throws IOException {
boolean exists = directory.exists();
if (exists && !directory.isDirectory()) {
throw new IOException(directory + " exists but is not a directory.");
}
if (exists) {
// Read and sort initial list of files. We defer adding
// information about these files to accessOrder until necessary
// (see indexFiles()). Sorting the list enables us to detect
// cache misses in getSessionData().
// Note: Sorting an array here was faster than creating a
// HashSet on Dalvik.
initialFiles = directory.list();
if (initialFiles == null) {
// File.list() will return null in error cases without throwing IOException
// http://b/3363561
throw new IOException(directory + " exists but cannot list contents.");
}
Arrays.sort(initialFiles);
size = initialFiles.length;
} else {
// Create directory.
if (!directory.mkdirs()) {
throw new IOException("Creation of " + directory + " directory failed.");
}
size = 0;
}
this.directory = directory;
}
/**
* Creates a new access-ordered linked hash map.
*/
private static Map<String, File> newAccessOrder() {
return new LinkedHashMap<String, File>(
MAX_SIZE, 0.75f, true /* access order */);
}
/**
* Gets the file name for the given host and port.
*/
private static String fileName(String host, int port) {
if (host == null) {
throw new NullPointerException("host");
}
return host + "." + port;
}
public synchronized byte[] getSessionData(String host, int port) {
/*
* Note: This method is only called when the in-memory cache
* in SSLSessionContext misses, so it would be unnecesarily
* rendundant for this cache to store data in memory.
*/
String name = fileName(host, port);
File file = accessOrder.get(name);
if (file == null) {
// File wasn't in access order. Check initialFiles...
if (initialFiles == null) {
// All files are in accessOrder, so it doesn't exist.
return null;
}
// Look in initialFiles.
if (Arrays.binarySearch(initialFiles, name) < 0) {
// Not found.
return null;
}
// The file is on disk but not in accessOrder yet.
file = new File(directory, name);
accessOrder.put(name, file);
}
FileInputStream in;
try {
in = new FileInputStream(file);
} catch (FileNotFoundException e) {
logReadError(host, e);
return null;
}
try {
int size = (int) file.length();
byte[] data = new byte[size];
new DataInputStream(in).readFully(data);
logger.log(Level.FINE, "Read session for " + host + ".");
return data;
} catch (IOException e) {
logReadError(host, e);
return null;
} finally {
IoUtils.closeQuietly(in);
}
}
static void logReadError(String host, Throwable t) {
logger.log(Level.INFO, "Error reading session data for " + host
+ ".", t);
}
public synchronized void putSessionData(SSLSession session,
byte[] sessionData) {
String host = session.getPeerHost();
if (sessionData == null) {
throw new NullPointerException("sessionData");
}
String name = fileName(host, session.getPeerPort());
File file = new File(directory, name);
// Used to keep track of whether or not we're expanding the cache.
boolean existedBefore = file.exists();
FileOutputStream out;
try {
out = new FileOutputStream(file);
} catch (FileNotFoundException e) {
// We can't write to the file.
logWriteError(host, e);
return;
}
// If we expanded the cache (by creating a new file)...
if (!existedBefore) {
size++;
// Delete an old file if necessary.
makeRoom();
}
boolean writeSuccessful = false;
try {
out.write(sessionData);
writeSuccessful = true;
} catch (IOException e) {
logWriteError(host, e);
} finally {
boolean closeSuccessful = false;
try {
out.close();
closeSuccessful = true;
} catch (IOException e) {
logWriteError(host, e);
} finally {
if (!writeSuccessful || !closeSuccessful) {
// Storage failed. Clean up.
delete(file);
} else {
// Success!
accessOrder.put(name, file);
logger.log(Level.FINE, "Stored session for " + host
+ ".");
}
}
}
}
/**
* Deletes old files if necessary.
*/
private void makeRoom() {
if (size <= MAX_SIZE) {
return;
}
indexFiles();
// Delete LRUed files.
int removals = size - MAX_SIZE;
Iterator<File> i = accessOrder.values().iterator();
do {
delete(i.next());
i.remove();
} while (--removals > 0);
}
/**
* Lazily updates accessOrder to know about all files as opposed to
* just the files accessed since this process started.
*/
private void indexFiles() {
String[] initialFiles = this.initialFiles;
if (initialFiles != null) {
this.initialFiles = null;
// Files on disk only, sorted by last modified time.
// TODO: Use last access time.
Set<CacheFile> diskOnly = new TreeSet<CacheFile>();
for (String name : initialFiles) {
// If the file hasn't been accessed in this process...
if (!accessOrder.containsKey(name)) {
diskOnly.add(new CacheFile(directory, name));
}
}
if (!diskOnly.isEmpty()) {
// Add files not accessed in this process to the beginning
// of accessOrder.
Map<String, File> newOrder = newAccessOrder();
for (CacheFile cacheFile : diskOnly) {
newOrder.put(cacheFile.name, cacheFile);
}
newOrder.putAll(accessOrder);
this.accessOrder = newOrder;
}
}
}
@SuppressWarnings("ThrowableInstanceNeverThrown")
private void delete(File file) {
if (!file.delete()) {
logger.log(Level.INFO, "Failed to delete " + file + ".",
new IOException());
}
size--;
}
static void logWriteError(String host, Throwable t) {
logger.log(Level.INFO, "Error writing session data for "
+ host + ".", t);
}
}
/**
* Maps directories to the cache instances that are backed by those
* directories. We synchronize access using the cache instance, so it's
* important that everyone shares the same instance.
*/
static final Map<File, FileClientSessionCache.Impl> caches
= new HashMap<File, FileClientSessionCache.Impl>();
/**
* Returns a cache backed by the given directory. Creates the directory
* (including parent directories) if necessary. This cache should have
* exclusive access to the given directory.
*
* @param directory to store files in
* @return a cache backed by the given directory
* @throws IOException if the file exists and is not a directory or if
* creating the directories fails
*/
public static synchronized SSLClientSessionCache usingDirectory(
File directory) throws IOException {
FileClientSessionCache.Impl cache = caches.get(directory);
if (cache == null) {
cache = new FileClientSessionCache.Impl(directory);
caches.put(directory, cache);
}
return cache;
}
/** For testing. */
static synchronized void reset() {
caches.clear();
}
/** A file containing a piece of cached data. */
static class CacheFile extends File {
final String name;
CacheFile(File dir, String name) {
super(dir, name);
this.name = name;
}
long lastModified = -1;
@Override
public long lastModified() {
long lastModified = this.lastModified;
if (lastModified == -1) {
lastModified = this.lastModified = super.lastModified();
}
return lastModified;
}
@Override
public int compareTo(File another) {
// Sort by last modified time.
long result = lastModified() - another.lastModified();
if (result == 0) {
return super.compareTo(another);
}
return result < 0 ? -1 : 1;
}
}
}
|
luni/src/main/java/org/apache/harmony/xnet/provider/jsse/FileClientSessionCache.java
|
/*
* Copyright (C) 2009 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 org.apache.harmony.xnet.provider.jsse;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.logging.Level;
import javax.net.ssl.SSLSession;
import libcore.io.IoUtils;
/**
* File-based cache implementation. Only one process should access the
* underlying directory at a time.
*/
public class FileClientSessionCache {
static final int MAX_SIZE = 12; // ~72k
static final java.util.logging.Logger logger
= java.util.logging.Logger.getLogger(
FileClientSessionCache.class.getName());
private FileClientSessionCache() {}
/**
* This cache creates one file per SSL session using "host.port" for
* the file name. Files are created or replaced when session data is put
* in the cache (see {@link #putSessionData}). Files are read on
* cache hits, but not on cache misses.
*
* <p>When the number of session files exceeds MAX_SIZE, we delete the
* least-recently-used file. We don't current persist the last access time,
* so the ordering actually ends up being least-recently-modified in some
* cases and even just "not accessed in this process" if the filesystem
* doesn't track last modified times.
*/
static class Impl implements SSLClientSessionCache {
/** Directory to store session files in. */
final File directory;
/**
* Map of name -> File. Keeps track of the order files were accessed in.
*/
Map<String, File> accessOrder = newAccessOrder();
/** The number of files on disk. */
int size;
/**
* The initial set of files. We use this to defer adding information
* about all files to accessOrder until necessary.
*/
String[] initialFiles;
/**
* Constructs a new cache backed by the given directory.
*/
Impl(File directory) throws IOException {
boolean exists = directory.exists();
if (exists && !directory.isDirectory()) {
throw new IOException(directory
+ " exists but is not a directory.");
}
if (exists) {
// Read and sort initial list of files. We defer adding
// information about these files to accessOrder until necessary
// (see indexFiles()). Sorting the list enables us to detect
// cache misses in getSessionData().
// Note: Sorting an array here was faster than creating a
// HashSet on Dalvik.
initialFiles = directory.list();
Arrays.sort(initialFiles);
size = initialFiles.length;
} else {
// Create directory.
if (!directory.mkdirs()) {
throw new IOException("Creation of " + directory
+ " directory failed.");
}
size = 0;
}
this.directory = directory;
}
/**
* Creates a new access-ordered linked hash map.
*/
private static Map<String, File> newAccessOrder() {
return new LinkedHashMap<String, File>(
MAX_SIZE, 0.75f, true /* access order */);
}
/**
* Gets the file name for the given host and port.
*/
private static String fileName(String host, int port) {
if (host == null) {
throw new NullPointerException("host");
}
return host + "." + port;
}
public synchronized byte[] getSessionData(String host, int port) {
/*
* Note: This method is only called when the in-memory cache
* in SSLSessionContext misses, so it would be unnecesarily
* rendundant for this cache to store data in memory.
*/
String name = fileName(host, port);
File file = accessOrder.get(name);
if (file == null) {
// File wasn't in access order. Check initialFiles...
if (initialFiles == null) {
// All files are in accessOrder, so it doesn't exist.
return null;
}
// Look in initialFiles.
if (Arrays.binarySearch(initialFiles, name) < 0) {
// Not found.
return null;
}
// The file is on disk but not in accessOrder yet.
file = new File(directory, name);
accessOrder.put(name, file);
}
FileInputStream in;
try {
in = new FileInputStream(file);
} catch (FileNotFoundException e) {
logReadError(host, e);
return null;
}
try {
int size = (int) file.length();
byte[] data = new byte[size];
new DataInputStream(in).readFully(data);
logger.log(Level.FINE, "Read session for " + host + ".");
return data;
} catch (IOException e) {
logReadError(host, e);
return null;
} finally {
IoUtils.closeQuietly(in);
}
}
static void logReadError(String host, Throwable t) {
logger.log(Level.INFO, "Error reading session data for " + host
+ ".", t);
}
public synchronized void putSessionData(SSLSession session,
byte[] sessionData) {
String host = session.getPeerHost();
if (sessionData == null) {
throw new NullPointerException("sessionData");
}
String name = fileName(host, session.getPeerPort());
File file = new File(directory, name);
// Used to keep track of whether or not we're expanding the cache.
boolean existedBefore = file.exists();
FileOutputStream out;
try {
out = new FileOutputStream(file);
} catch (FileNotFoundException e) {
// We can't write to the file.
logWriteError(host, e);
return;
}
// If we expanded the cache (by creating a new file)...
if (!existedBefore) {
size++;
// Delete an old file if necessary.
makeRoom();
}
boolean writeSuccessful = false;
try {
out.write(sessionData);
writeSuccessful = true;
} catch (IOException e) {
logWriteError(host, e);
} finally {
boolean closeSuccessful = false;
try {
out.close();
closeSuccessful = true;
} catch (IOException e) {
logWriteError(host, e);
} finally {
if (!writeSuccessful || !closeSuccessful) {
// Storage failed. Clean up.
delete(file);
} else {
// Success!
accessOrder.put(name, file);
logger.log(Level.FINE, "Stored session for " + host
+ ".");
}
}
}
}
/**
* Deletes old files if necessary.
*/
private void makeRoom() {
if (size <= MAX_SIZE) {
return;
}
indexFiles();
// Delete LRUed files.
int removals = size - MAX_SIZE;
Iterator<File> i = accessOrder.values().iterator();
do {
delete(i.next());
i.remove();
} while (--removals > 0);
}
/**
* Lazily updates accessOrder to know about all files as opposed to
* just the files accessed since this process started.
*/
private void indexFiles() {
String[] initialFiles = this.initialFiles;
if (initialFiles != null) {
this.initialFiles = null;
// Files on disk only, sorted by last modified time.
// TODO: Use last access time.
Set<CacheFile> diskOnly = new TreeSet<CacheFile>();
for (String name : initialFiles) {
// If the file hasn't been accessed in this process...
if (!accessOrder.containsKey(name)) {
diskOnly.add(new CacheFile(directory, name));
}
}
if (!diskOnly.isEmpty()) {
// Add files not accessed in this process to the beginning
// of accessOrder.
Map<String, File> newOrder = newAccessOrder();
for (CacheFile cacheFile : diskOnly) {
newOrder.put(cacheFile.name, cacheFile);
}
newOrder.putAll(accessOrder);
this.accessOrder = newOrder;
}
}
}
@SuppressWarnings("ThrowableInstanceNeverThrown")
private void delete(File file) {
if (!file.delete()) {
logger.log(Level.INFO, "Failed to delete " + file + ".",
new IOException());
}
size--;
}
static void logWriteError(String host, Throwable t) {
logger.log(Level.INFO, "Error writing session data for "
+ host + ".", t);
}
}
/**
* Maps directories to the cache instances that are backed by those
* directories. We synchronize access using the cache instance, so it's
* important that everyone shares the same instance.
*/
static final Map<File, FileClientSessionCache.Impl> caches
= new HashMap<File, FileClientSessionCache.Impl>();
/**
* Returns a cache backed by the given directory. Creates the directory
* (including parent directories) if necessary. This cache should have
* exclusive access to the given directory.
*
* @param directory to store files in
* @return a cache backed by the given directory
* @throws IOException if the file exists and is not a directory or if
* creating the directories fails
*/
public static synchronized SSLClientSessionCache usingDirectory(
File directory) throws IOException {
FileClientSessionCache.Impl cache = caches.get(directory);
if (cache == null) {
cache = new FileClientSessionCache.Impl(directory);
caches.put(directory, cache);
}
return cache;
}
/** For testing. */
static synchronized void reset() {
caches.clear();
}
/** A file containing a piece of cached data. */
static class CacheFile extends File {
final String name;
CacheFile(File dir, String name) {
super(dir, name);
this.name = name;
}
long lastModified = -1;
@Override
public long lastModified() {
long lastModified = this.lastModified;
if (lastModified == -1) {
lastModified = this.lastModified = super.lastModified();
}
return lastModified;
}
@Override
public int compareTo(File another) {
// Sort by last modified time.
long result = lastModified() - another.lastModified();
if (result == 0) {
return super.compareTo(another);
}
return result < 0 ? -1 : 1;
}
}
}
|
Defend against null directory list in FileClientSessionCache
Bug: 3363561
Change-Id: Idc45f7ed85d4e2a78078f06f4d9bbf903efdac69
|
luni/src/main/java/org/apache/harmony/xnet/provider/jsse/FileClientSessionCache.java
|
Defend against null directory list in FileClientSessionCache
|
|
Java
|
apache-2.0
|
d0a6d8998a87196a2f59d28ea70c0b4d22fed17e
| 0
|
mkambol/pentaho-kettle,pavel-sakun/pentaho-kettle,nanata1115/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,brosander/pentaho-kettle,YuryBY/pentaho-kettle,pavel-sakun/pentaho-kettle,dkincade/pentaho-kettle,EcoleKeine/pentaho-kettle,ma459006574/pentaho-kettle,airy-ict/pentaho-kettle,brosander/pentaho-kettle,emartin-pentaho/pentaho-kettle,skofra0/pentaho-kettle,ccaspanello/pentaho-kettle,wseyler/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,Advent51/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,marcoslarsen/pentaho-kettle,sajeetharan/pentaho-kettle,rfellows/pentaho-kettle,HiromuHota/pentaho-kettle,tmcsantos/pentaho-kettle,pavel-sakun/pentaho-kettle,HiromuHota/pentaho-kettle,sajeetharan/pentaho-kettle,denisprotopopov/pentaho-kettle,roboguy/pentaho-kettle,skofra0/pentaho-kettle,mattyb149/pentaho-kettle,wseyler/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,mattyb149/pentaho-kettle,wseyler/pentaho-kettle,ma459006574/pentaho-kettle,rmansoor/pentaho-kettle,bmorrise/pentaho-kettle,emartin-pentaho/pentaho-kettle,stevewillcock/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,ViswesvarSekar/pentaho-kettle,tmcsantos/pentaho-kettle,rfellows/pentaho-kettle,airy-ict/pentaho-kettle,pedrofvteixeira/pentaho-kettle,yshakhau/pentaho-kettle,jbrant/pentaho-kettle,roboguy/pentaho-kettle,stepanovdg/pentaho-kettle,ivanpogodin/pentaho-kettle,kurtwalker/pentaho-kettle,mbatchelor/pentaho-kettle,CapeSepias/pentaho-kettle,GauravAshara/pentaho-kettle,ddiroma/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,zlcnju/kettle,pminutillo/pentaho-kettle,tkafalas/pentaho-kettle,mkambol/pentaho-kettle,airy-ict/pentaho-kettle,DFieldFL/pentaho-kettle,matrix-stone/pentaho-kettle,mkambol/pentaho-kettle,cjsonger/pentaho-kettle,pminutillo/pentaho-kettle,YuryBY/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,mkambol/pentaho-kettle,lgrill-pentaho/pentaho-kettle,graimundo/pentaho-kettle,Advent51/pentaho-kettle,rmansoor/pentaho-kettle,dkincade/pentaho-kettle,hudak/pentaho-kettle,ViswesvarSekar/pentaho-kettle,nicoben/pentaho-kettle,bmorrise/pentaho-kettle,flbrino/pentaho-kettle,pymjer/pentaho-kettle,ddiroma/pentaho-kettle,wseyler/pentaho-kettle,denisprotopopov/pentaho-kettle,lgrill-pentaho/pentaho-kettle,pymjer/pentaho-kettle,matthewtckr/pentaho-kettle,nantunes/pentaho-kettle,aminmkhan/pentaho-kettle,stepanovdg/pentaho-kettle,ViswesvarSekar/pentaho-kettle,MikhailHubanau/pentaho-kettle,rmansoor/pentaho-kettle,SergeyTravin/pentaho-kettle,YuryBY/pentaho-kettle,aminmkhan/pentaho-kettle,aminmkhan/pentaho-kettle,mdamour1976/pentaho-kettle,nicoben/pentaho-kettle,dkincade/pentaho-kettle,mbatchelor/pentaho-kettle,ViswesvarSekar/pentaho-kettle,graimundo/pentaho-kettle,YuryBY/pentaho-kettle,marcoslarsen/pentaho-kettle,HiromuHota/pentaho-kettle,bmorrise/pentaho-kettle,stepanovdg/pentaho-kettle,GauravAshara/pentaho-kettle,GauravAshara/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,tkafalas/pentaho-kettle,graimundo/pentaho-kettle,nicoben/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,stevewillcock/pentaho-kettle,DFieldFL/pentaho-kettle,alina-ipatina/pentaho-kettle,pymjer/pentaho-kettle,EcoleKeine/pentaho-kettle,alina-ipatina/pentaho-kettle,gretchiemoran/pentaho-kettle,alina-ipatina/pentaho-kettle,ivanpogodin/pentaho-kettle,cjsonger/pentaho-kettle,MikhailHubanau/pentaho-kettle,kurtwalker/pentaho-kettle,yshakhau/pentaho-kettle,pedrofvteixeira/pentaho-kettle,EcoleKeine/pentaho-kettle,nantunes/pentaho-kettle,mattyb149/pentaho-kettle,ccaspanello/pentaho-kettle,eayoungs/pentaho-kettle,emartin-pentaho/pentaho-kettle,flbrino/pentaho-kettle,ccaspanello/pentaho-kettle,mbatchelor/pentaho-kettle,nicoben/pentaho-kettle,rfellows/pentaho-kettle,flbrino/pentaho-kettle,bmorrise/pentaho-kettle,yshakhau/pentaho-kettle,SergeyTravin/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,drndos/pentaho-kettle,pedrofvteixeira/pentaho-kettle,ivanpogodin/pentaho-kettle,GauravAshara/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,codek/pentaho-kettle,tkafalas/pentaho-kettle,akhayrutdinov/pentaho-kettle,tkafalas/pentaho-kettle,cjsonger/pentaho-kettle,hudak/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,e-cuellar/pentaho-kettle,andrei-viaryshka/pentaho-kettle,Advent51/pentaho-kettle,flbrino/pentaho-kettle,mdamour1976/pentaho-kettle,pminutillo/pentaho-kettle,airy-ict/pentaho-kettle,codek/pentaho-kettle,alina-ipatina/pentaho-kettle,jbrant/pentaho-kettle,drndos/pentaho-kettle,e-cuellar/pentaho-kettle,pminutillo/pentaho-kettle,pavel-sakun/pentaho-kettle,cjsonger/pentaho-kettle,nantunes/pentaho-kettle,ddiroma/pentaho-kettle,matrix-stone/pentaho-kettle,mdamour1976/pentaho-kettle,skofra0/pentaho-kettle,denisprotopopov/pentaho-kettle,matrix-stone/pentaho-kettle,nantunes/pentaho-kettle,aminmkhan/pentaho-kettle,birdtsai/pentaho-kettle,roboguy/pentaho-kettle,mdamour1976/pentaho-kettle,kurtwalker/pentaho-kettle,stepanovdg/pentaho-kettle,gretchiemoran/pentaho-kettle,DFieldFL/pentaho-kettle,SergeyTravin/pentaho-kettle,CapeSepias/pentaho-kettle,brosander/pentaho-kettle,matthewtckr/pentaho-kettle,birdtsai/pentaho-kettle,graimundo/pentaho-kettle,drndos/pentaho-kettle,pentaho/pentaho-kettle,drndos/pentaho-kettle,MikhailHubanau/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,ddiroma/pentaho-kettle,Advent51/pentaho-kettle,zlcnju/kettle,sajeetharan/pentaho-kettle,marcoslarsen/pentaho-kettle,zlcnju/kettle,eayoungs/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,roboguy/pentaho-kettle,kurtwalker/pentaho-kettle,pedrofvteixeira/pentaho-kettle,codek/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,akhayrutdinov/pentaho-kettle,stevewillcock/pentaho-kettle,CapeSepias/pentaho-kettle,skofra0/pentaho-kettle,e-cuellar/pentaho-kettle,emartin-pentaho/pentaho-kettle,andrei-viaryshka/pentaho-kettle,gretchiemoran/pentaho-kettle,tmcsantos/pentaho-kettle,matrix-stone/pentaho-kettle,andrei-viaryshka/pentaho-kettle,yshakhau/pentaho-kettle,stevewillcock/pentaho-kettle,lgrill-pentaho/pentaho-kettle,zlcnju/kettle,jbrant/pentaho-kettle,marcoslarsen/pentaho-kettle,denisprotopopov/pentaho-kettle,sajeetharan/pentaho-kettle,lgrill-pentaho/pentaho-kettle,ivanpogodin/pentaho-kettle,codek/pentaho-kettle,CapeSepias/pentaho-kettle,dkincade/pentaho-kettle,e-cuellar/pentaho-kettle,tmcsantos/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,birdtsai/pentaho-kettle,nanata1115/pentaho-kettle,akhayrutdinov/pentaho-kettle,brosander/pentaho-kettle,eayoungs/pentaho-kettle,mattyb149/pentaho-kettle,hudak/pentaho-kettle,ma459006574/pentaho-kettle,pentaho/pentaho-kettle,jbrant/pentaho-kettle,ma459006574/pentaho-kettle,rmansoor/pentaho-kettle,HiromuHota/pentaho-kettle,hudak/pentaho-kettle,ccaspanello/pentaho-kettle,mbatchelor/pentaho-kettle,matthewtckr/pentaho-kettle,nanata1115/pentaho-kettle,birdtsai/pentaho-kettle,eayoungs/pentaho-kettle,pentaho/pentaho-kettle,gretchiemoran/pentaho-kettle,akhayrutdinov/pentaho-kettle,pymjer/pentaho-kettle,pentaho/pentaho-kettle,matthewtckr/pentaho-kettle,DFieldFL/pentaho-kettle,EcoleKeine/pentaho-kettle,nanata1115/pentaho-kettle,SergeyTravin/pentaho-kettle
|
/* Copyright (c) 2007 Pentaho Corporation. All rights reserved.
* This software was developed by Pentaho Corporation and is provided under the terms
* of the GNU Lesser General Public License, Version 2.1. You may not use
* this file except in compliance with the license. If you need a copy of the license,
* please go to http://www.gnu.org/licenses/lgpl-2.1.txt. The Original Code is Pentaho
* Data Integration. The Initial Developer is Pentaho Corporation.
*
* Software distributed under the GNU Lesser Public License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to
* the license for the specific language governing your rights and limitations.
*/
package org.pentaho.di.trans.steps.randomvalue;
import java.util.List;
import java.util.Map;
import org.pentaho.di.core.CheckResult;
import org.pentaho.di.core.CheckResultInterface;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.Counter;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleStepException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMeta;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStepMeta;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;
import org.w3c.dom.Node;
/**
* Created on 08-07-2008
*/
public class RandomValueMeta extends BaseStepMeta implements StepMetaInterface {
public final static int TYPE_SYSTEM_INFO_NONE = 0;
public final static int TYPE_RANDOM_NUMBER = 1;
public final static int TYPE_RANDOM_INTEGER = 2;
public final static int TYPE_RANDOM_STRING = 3;
public final static int TYPE_RANDOM_UUID = 4;
public static final RandomValueMetaFunction functions[] = new RandomValueMetaFunction[] {
null,
new RandomValueMetaFunction(TYPE_RANDOM_NUMBER, "random number",
Messages.getString("RandomValueMeta.TypeDesc.RandomNumber")),
new RandomValueMetaFunction(
TYPE_RANDOM_INTEGER,
"random integer",
Messages.getString("RandomValueMeta.TypeDesc.RandomInteger")),
new RandomValueMetaFunction(TYPE_RANDOM_STRING, "random string",
Messages.getString("RandomValueMeta.TypeDesc.RandomString")),
new RandomValueMetaFunction(TYPE_RANDOM_UUID, "random string",
Messages.getString("RandomValueMeta.TypeDesc.RandomUUID")), };
private String fieldName[];
private int fieldType[];
public RandomValueMeta() {
super(); // allocate BaseStepMeta
}
/**
* @return Returns the fieldName.
*/
public String[] getFieldName() {
return fieldName;
}
/**
* @param fieldName
* The fieldName to set.
*/
public void setFieldName(String[] fieldName) {
this.fieldName = fieldName;
}
/**
* @return Returns the fieldType.
*/
public int[] getFieldType() {
return fieldType;
}
/**
* @param fieldType
* The fieldType to set.
*/
public void setFieldType(int[] fieldType) {
this.fieldType = fieldType;
}
public void loadXML(Node stepnode, List<DatabaseMeta> databases,
Map<String, Counter> counters) throws KettleXMLException {
readData(stepnode);
}
public void allocate(int count) {
fieldName = new String[count];
fieldType = new int[count];
}
public Object clone() {
RandomValueMeta retval = (RandomValueMeta) super.clone();
int count = fieldName.length;
retval.allocate(count);
for (int i = 0; i < count; i++) {
retval.fieldName[i] = fieldName[i];
retval.fieldType[i] = fieldType[i];
}
return retval;
}
private void readData(Node stepnode) throws KettleXMLException {
try {
Node fields = XMLHandler.getSubNode(stepnode, "fields");
int count = XMLHandler.countNodes(fields, "field");
String type;
allocate(count);
for (int i = 0; i < count; i++) {
Node fnode = XMLHandler.getSubNodeByNr(fields, "field", i);
fieldName[i] = XMLHandler.getTagValue(fnode, "name");
type = XMLHandler.getTagValue(fnode, "type");
fieldType[i] = getType(type);
}
} catch (Exception e) {
throw new KettleXMLException(
"Unable to read step information from XML", e);
}
}
public static final int getType(String type) {
for (int i = 1; i < functions.length; i++) {
if (functions[i].getCode().equalsIgnoreCase(type))
return i;
if (functions[i].getDescription().equalsIgnoreCase(type))
return i;
}
return 0;
}
public static final String getTypeDesc(int t) {
if (functions == null || functions.length == 0)
return null;
if (t < 0 || t >= functions.length || functions[t] == null)
return null;
return functions[t].getDescription();
}
public void setDefault() {
int count = 0;
allocate(count);
for (int i = 0; i < count; i++) {
fieldName[i] = "field" + i;
fieldType[i] = TYPE_RANDOM_NUMBER;
}
}
public void getFields(RowMetaInterface row, String name,
RowMetaInterface[] info, StepMeta nextStep, VariableSpace space)
throws KettleStepException {
for (int i = 0; i < fieldName.length; i++) {
ValueMetaInterface v;
switch (fieldType[i]) {
case TYPE_RANDOM_NUMBER: // All date values...
v = new ValueMeta(fieldName[i], ValueMetaInterface.TYPE_NUMBER);
break;
case TYPE_RANDOM_INTEGER: // All date values...
v = new ValueMeta(fieldName[i], ValueMetaInterface.TYPE_INTEGER);
// v.setLength(ValueMetaInterface.DEFAULT_INTEGER_LENGTH, 0);
break;
case TYPE_RANDOM_STRING: // All date values...
v = new ValueMeta(fieldName[i], ValueMetaInterface.TYPE_STRING);
// v.setLength(ValueMetaInterface.DEFAULT_INTEGER_LENGTH, 0);
break;
case TYPE_RANDOM_UUID: // All date values...
v = new ValueMeta(fieldName[i], ValueMetaInterface.TYPE_STRING);
// v.setLength(ValueMetaInterface.DEFAULT_INTEGER_LENGTH, 0);
break;
default:
v = new ValueMeta(fieldName[i], ValueMetaInterface.TYPE_NONE);
break;
}
v.setOrigin(name);
row.addValueMeta(v);
}
}
public String getXML() {
StringBuffer retval = new StringBuffer(200);
retval.append(" <fields>").append(Const.CR);
for (int i = 0; i < fieldName.length; i++) {
retval.append(" <field>").append(Const.CR);
retval.append(" ").append(
XMLHandler.addTagValue("name", fieldName[i]));
retval
.append(" ")
.append(
XMLHandler
.addTagValue(
"type",
functions[fieldType[i]] != null ? functions[fieldType[i]]
.getCode()
: ""));
retval.append(" </field>").append(Const.CR);
}
retval.append(" </fields>" + Const.CR);
return retval.toString();
}
public void readRep(Repository rep, long id_step,
List<DatabaseMeta> databases, Map<String, Counter> counters)
throws KettleException {
try {
int nrfields = rep.countNrStepAttributes(id_step, "field_name");
allocate(nrfields);
for (int i = 0; i < nrfields; i++) {
fieldName[i] = rep.getStepAttributeString(id_step, i,
"field_name");
fieldType[i] = getType(rep.getStepAttributeString(id_step, i,
"field_type"));
}
} catch (Exception e) {
throw new KettleException(
"Unexpected error reading step information from the repository",
e);
}
}
public void saveRep(Repository rep, long id_transformation, long id_step)
throws KettleException {
try {
for (int i = 0; i < fieldName.length; i++) {
rep.saveStepAttribute(id_transformation, id_step, i,
"field_name", fieldName[i]);
rep
.saveStepAttribute(
id_transformation,
id_step,
i,
"field_type",
functions[fieldType[i]] != null ? functions[fieldType[i]]
.getCode()
: "");
}
} catch (Exception e) {
throw new KettleException(
"Unable to save step information to the repository for id_step="
+ id_step, e);
}
}
public void check(List<CheckResultInterface> remarks, TransMeta transMeta,
StepMeta stepMeta, RowMetaInterface prev, String input[],
String output[], RowMetaInterface info) {
// See if we have input streams leading to this step!
int nrRemarks = remarks.size();
for (int i = 0; i < fieldName.length; i++) {
if (fieldType[i] <= TYPE_SYSTEM_INFO_NONE) {
CheckResult cr = new CheckResult(
CheckResultInterface.TYPE_RESULT_ERROR,
Messages.getString("RandomValueMeta.CheckResult.FieldHasNoType",fieldName[i]), stepMeta);
remarks.add(cr);
}
}
if (remarks.size() == nrRemarks) {
CheckResult cr = new CheckResult(
CheckResultInterface.TYPE_RESULT_OK,
Messages.getString("RandomValueMeta.CheckResult.AllTypesSpecified"),
stepMeta);
remarks.add(cr);
}
}
public StepInterface getStep(StepMeta stepMeta,
StepDataInterface stepDataInterface, int cnr, TransMeta transMeta,
Trans trans) {
return new RandomValue(stepMeta, stepDataInterface, cnr, transMeta,
trans);
}
public StepDataInterface getStepData() {
return new RandomValueData();
}
}
|
src/org/pentaho/di/trans/steps/randomvalue/RandomValueMeta.java
|
/* Copyright (c) 2007 Pentaho Corporation. All rights reserved.
* This software was developed by Pentaho Corporation and is provided under the terms
* of the GNU Lesser General Public License, Version 2.1. You may not use
* this file except in compliance with the license. If you need a copy of the license,
* please go to http://www.gnu.org/licenses/lgpl-2.1.txt. The Original Code is Pentaho
* Data Integration. The Initial Developer is Pentaho Corporation.
*
* Software distributed under the GNU Lesser Public License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to
* the license for the specific language governing your rights and limitations.
*/
package org.pentaho.di.trans.steps.randomvalue;
import java.util.List;
import java.util.Map;
import org.pentaho.di.core.CheckResult;
import org.pentaho.di.core.CheckResultInterface;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.Counter;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleStepException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMeta;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStepMeta;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;
import org.w3c.dom.Node;
/**
* Created on 08-07-2008
*/
public class RandomValueMeta extends BaseStepMeta implements StepMetaInterface {
public final static int TYPE_SYSTEM_INFO_NONE = 0;
public final static int TYPE_RANDOM_NUMBER = 1;
public final static int TYPE_RANDOM_INTEGER = 2;
public final static int TYPE_RANDOM_STRING = 3;
public final static int TYPE_RANDOM_UUID = 4;
public static final RandomValueMetaFunction functions[] = new RandomValueMetaFunction[] {
null,
new RandomValueMetaFunction(TYPE_RANDOM_NUMBER, "random number",
Messages.getString("RandomValueMeta.TypeDesc.RandomNumber")),
new RandomValueMetaFunction(
TYPE_RANDOM_INTEGER,
"random integer",
Messages.getString("RandomValueMeta.TypeDesc.RandomInteger")),
new RandomValueMetaFunction(TYPE_RANDOM_STRING, "random string",
Messages.getString("RandomValueMeta.TypeDesc.RandomString")),
new RandomValueMetaFunction(TYPE_RANDOM_UUID, "random string",
Messages.getString("RandomValueMeta.TypeDesc.RandomUUID")), };
private String fieldName[];
private int fieldType[];
public RandomValueMeta() {
super(); // allocate BaseStepMeta
}
/**
* @return Returns the fieldName.
*/
public String[] getFieldName() {
return fieldName;
}
/**
* @param fieldName
* The fieldName to set.
*/
public void setFieldName(String[] fieldName) {
this.fieldName = fieldName;
}
/**
* @return Returns the fieldType.
*/
public int[] getFieldType() {
return fieldType;
}
/**
* @param fieldType
* The fieldType to set.
*/
public void setFieldType(int[] fieldType) {
this.fieldType = fieldType;
}
public void loadXML(Node stepnode, List<DatabaseMeta> databases,
Map<String, Counter> counters) throws KettleXMLException {
readData(stepnode);
}
public void allocate(int count) {
fieldName = new String[count];
fieldType = new int[count];
}
public Object clone() {
RandomValueMeta retval = (RandomValueMeta) super.clone();
int count = fieldName.length;
retval.allocate(count);
for (int i = 0; i < count; i++) {
retval.fieldName[i] = fieldName[i];
retval.fieldType[i] = fieldType[i];
}
return retval;
}
private void readData(Node stepnode) throws KettleXMLException {
try {
Node fields = XMLHandler.getSubNode(stepnode, "fields");
int count = XMLHandler.countNodes(fields, "field");
String type;
allocate(count);
for (int i = 0; i < count; i++) {
Node fnode = XMLHandler.getSubNodeByNr(fields, "field", i);
fieldName[i] = XMLHandler.getTagValue(fnode, "name");
type = XMLHandler.getTagValue(fnode, "type");
fieldType[i] = getType(type);
}
} catch (Exception e) {
throw new KettleXMLException(
"Unable to read step information from XML", e);
}
}
public static final int getType(String type) {
for (int i = 1; i < functions.length; i++) {
if (functions[i].getCode().equalsIgnoreCase(type))
return i;
if (functions[i].getDescription().equalsIgnoreCase(type))
return i;
}
return 0;
}
public static final String getTypeDesc(int t) {
if (functions == null || functions.length == 0)
return null;
if (t < 0 || t >= functions.length || functions[t] == null)
return null;
return functions[t].getDescription();
}
public void setDefault() {
int count = 0;
allocate(count);
for (int i = 0; i < count; i++) {
fieldName[i] = "field" + i;
fieldType[i] = TYPE_RANDOM_NUMBER;
}
}
public void getFields(RowMetaInterface row, String name,
RowMetaInterface[] info, StepMeta nextStep, VariableSpace space)
throws KettleStepException {
for (int i = 0; i < fieldName.length; i++) {
ValueMetaInterface v;
switch (fieldType[i]) {
case TYPE_RANDOM_NUMBER: // All date values...
v = new ValueMeta(fieldName[i], ValueMetaInterface.TYPE_NUMBER);
break;
case TYPE_RANDOM_INTEGER: // All date values...
v = new ValueMeta(fieldName[i], ValueMetaInterface.TYPE_INTEGER);
// v.setLength(ValueMetaInterface.DEFAULT_INTEGER_LENGTH, 0);
break;
case TYPE_RANDOM_STRING: // All date values...
v = new ValueMeta(fieldName[i], ValueMetaInterface.TYPE_STRING);
// v.setLength(ValueMetaInterface.DEFAULT_INTEGER_LENGTH, 0);
break;
case TYPE_RANDOM_UUID: // All date values...
v = new ValueMeta(fieldName[i], ValueMetaInterface.TYPE_STRING);
// v.setLength(ValueMetaInterface.DEFAULT_INTEGER_LENGTH, 0);
break;
default:
v = new ValueMeta(fieldName[i], ValueMetaInterface.TYPE_NONE);
break;
}
v.setOrigin(name);
row.addValueMeta(v);
}
}
public String getXML() {
StringBuffer retval = new StringBuffer(200);
retval.append(" <fields>").append(Const.CR);
for (int i = 0; i < fieldName.length; i++) {
retval.append(" <field>").append(Const.CR);
retval.append(" ").append(
XMLHandler.addTagValue("name", fieldName[i]));
retval
.append(" ")
.append(
XMLHandler
.addTagValue(
"type",
functions[fieldType[i]] != null ? functions[fieldType[i]]
.getCode()
: ""));
retval.append(" </field>").append(Const.CR);
}
retval.append(" </fields>" + Const.CR);
return retval.toString();
}
public void readRep(Repository rep, long id_step,
List<DatabaseMeta> databases, Map<String, Counter> counters)
throws KettleException {
try {
int nrfields = rep.countNrStepAttributes(id_step, "field_name");
allocate(nrfields);
for (int i = 0; i < nrfields; i++) {
fieldName[i] = rep.getStepAttributeString(id_step, i,
"field_name");
fieldType[i] = getType(rep.getStepAttributeString(id_step, i,
"field_type"));
}
} catch (Exception e) {
throw new KettleException(
"Unexpected error reading step information from the repository",
e);
}
}
public void saveRep(Repository rep, long id_transformation, long id_step)
throws KettleException {
try {
for (int i = 0; i < fieldName.length; i++) {
rep.saveStepAttribute(id_transformation, id_step, i,
"field_name", fieldName[i]);
rep
.saveStepAttribute(
id_transformation,
id_step,
i,
"field_type",
functions[fieldType[i]] != null ? functions[fieldType[i]]
.getCode()
: "");
}
} catch (Exception e) {
throw new KettleException(
"Unable to save step information to the repository for id_step="
+ id_step, e);
}
}
public void check(List<CheckResultInterface> remarks, TransMeta transMeta,
StepMeta stepMeta, RowMetaInterface prev, String input[],
String output[], RowMetaInterface info) {
// See if we have input streams leading to this step!
int nrRemarks = remarks.size();
for (int i = 0; i < fieldName.length; i++) {
if (fieldType[i] <= TYPE_SYSTEM_INFO_NONE) {
CheckResult cr = new CheckResult(
CheckResultInterface.TYPE_RESULT_ERROR,
Messages.getString(
"RandomValueMeta.CheckResult.FieldHasNoType",
fieldName[i]), stepMeta);
remarks.add(cr);
}
}
if (remarks.size() == nrRemarks) {
CheckResult cr = new CheckResult(
CheckResultInterface.TYPE_RESULT_OK,
Messages
.getString("RandomValueMeta.CheckResult.AllTypesSpecified"),
stepMeta);
remarks.add(cr);
}
}
public StepInterface getStep(StepMeta stepMeta,
StepDataInterface stepDataInterface, int cnr, TransMeta transMeta,
Trans trans) {
return new RandomValue(stepMeta, stepDataInterface, cnr, transMeta,
trans);
}
public StepDataInterface getStepData() {
return new RandomValueData();
}
}
|
i18n fix
git-svn-id: 51b39fcfd0d3a6ea7caa15377cad4af13b9d2664@8484 5fb7f6ec-07c1-534a-b4ca-9155e429e800
|
src/org/pentaho/di/trans/steps/randomvalue/RandomValueMeta.java
|
i18n fix
|
|
Java
|
apache-2.0
|
1a9b28e7a25b1b47dfe0d603d0abb912541ae295
| 0
|
nate-rcl/irplus,nate-rcl/irplus
|
/**
Copyright 2008 University of Rochester
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 edu.ur.ir.institution.service;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;
import org.apache.log4j.Logger;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.MapFieldSelector;
import org.apache.lucene.document.NumberTools;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.misc.ChainedFilter;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.DocIdSet;
import org.apache.lucene.search.Filter;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.QueryWrapperFilter;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.util.OpenBitSet;
import org.apache.lucene.util.OpenBitSetDISI;
import edu.ur.ir.FacetSearchHelper;
import edu.ur.ir.SearchHelper;
import edu.ur.ir.institution.InstitutionalCollection;
import edu.ur.ir.institution.InstitutionalItemSearchService;
import edu.ur.ir.search.FacetFilter;
import edu.ur.ir.search.FacetResult;
import edu.ur.ir.search.FacetResultHitComparator;
/**
* Excecute the search and determine facets
*
* @author Nathan Sarr
*
*/
public class DefaultInstitutionalItemSearchService implements InstitutionalItemSearchService{
/** Analyzer to use for parsing the queries */
private Analyzer analyzer;
/** Logger for editing a file database. */
private static final Logger log = Logger.getLogger(DefaultInstitutionalItemSearchService.class);
/** max number of hits to retrieve */
private int maxNumberOfMainQueryHits = 10000;
/** fields to search in the index*/
private static final String[] fields =
{DefaultInstitutionalItemIndexService.ABSTRACT,
DefaultInstitutionalItemIndexService.NAME,
DefaultInstitutionalItemIndexService.DESCRIPTION,
DefaultInstitutionalItemIndexService.LINK_NAMES,
DefaultInstitutionalItemIndexService.FILE_TEXT,
DefaultInstitutionalItemIndexService.CONTRIBUTOR_NAMES,
DefaultInstitutionalItemIndexService.LANGUAGE,
DefaultInstitutionalItemIndexService.IDENTIFIERS,
DefaultInstitutionalItemIndexService.KEY_WORDS,
DefaultInstitutionalItemIndexService.SUB_TITLES,
DefaultInstitutionalItemIndexService.PUBLISHER,
DefaultInstitutionalItemIndexService.CITATION,
DefaultInstitutionalItemIndexService.CONTENT_TYPES,
DefaultInstitutionalItemIndexService.COLLECTION_LEFT_VALUE,
DefaultInstitutionalItemIndexService.COLLECTION_RIGHT_VALUE,
DefaultInstitutionalItemIndexService.COLLECTION_NAME};
/**
* Get the facets and results
* @see edu.ur.ir.institution.InstitutionalItemSearchService#executeSearchWithFacets(java.lang.String, java.lang.String, int, int, int, int)
*/
public FacetSearchHelper executeSearchWithFacets(
String mainQueryString,
String indexFolder,
int numberOfHitsToProcessForFacets,
int numberOfResultsToCollectForFacets,
int numberOfFactsToShow,
int numberOfIdsToCollect,
int idsToCollectStartPosition )
throws CorruptIndexException, IOException, ParseException
{
if( searchDirectoryIsEmpty(indexFolder) || isInvalidQuery(mainQueryString))
{
return new FacetSearchHelper(new HashSet<Long>(), 0, new HashMap<String, Collection<FacetResult>>(), mainQueryString);
}
IndexSearcher searcher = new IndexSearcher(indexFolder);
IndexReader reader = searcher.getIndexReader();
QueryParser parser = new MultiFieldQueryParser(fields, analyzer);
parser.setDefaultOperator(QueryParser.AND_OPERATOR);
HashMap<String, Collection<FacetResult>> facetResults = new HashMap<String, Collection<FacetResult>>();
// execute the main query - we will use this to extract data to determine the facet searches
String executedQuery = SearchHelper.prepareMainSearchString(mainQueryString, false);
Query mainQuery = parser.parse(executedQuery);
if( log.isDebugEnabled() )
{
log.debug("main query = " + executedQuery );
}
TopDocs topDocs = searcher.search(mainQuery, maxNumberOfMainQueryHits);
// determine the set of data we should use to determine facets
HashMap<String, HashMap<String, FacetResult>> possibleFacets = this.generateFacetSearches(
topDocs,
numberOfHitsToProcessForFacets,
numberOfResultsToCollectForFacets,
searcher);
QueryWrapperFilter mainQueryWrapper = new QueryWrapperFilter(mainQuery);
log.debug("executeSearchWithFacets 1 query = " + mainQuery);
DocIdSet mainQueryBits = mainQueryWrapper.getDocIdSet(reader);
OpenBitSetDISI mainQueryBitSet = new OpenBitSetDISI(mainQueryBits.iterator(), maxNumberOfMainQueryHits);
// process the data and determine the facets
FacetSearchHelper helper = processPossibleFacets(possibleFacets,
reader,
mainQueryBitSet,
facetResults,
topDocs,
numberOfIdsToCollect,
idsToCollectStartPosition,
numberOfFactsToShow,
mainQueryString,
searcher);
helper.setExecutedQuery(executedQuery);
searcher.close();
return helper;
}
/**
* Determine the number of hits based on the overall number of results the main search returned.
*
* @param baseBitSet
* @param filterBitSet
* @return
*/
private long getFacetHitCount(OpenBitSet baseBitSet, OpenBitSet filterBitSet)
{
filterBitSet.and(baseBitSet);
return filterBitSet.cardinality();
}
/**
* This determines the possible facets for each of the categories. For example - possible authors
* for the display. This does not care about counts later on counts will be important.
*
* @param topDocs - top doucment hits found
* @param numberOfHitsToProcess
* @return
* @throws CorruptIndexException
* @throws IOException
*/
private HashMap<String, HashMap<String, FacetResult>> generateFacetSearches(TopDocs topDocs,
int numberOfHitsToProcess,
int numberOfResultsToCollect,
IndexSearcher searcher) throws CorruptIndexException, IOException
{
String[] fieldsToLoad = {
DefaultInstitutionalItemIndexService.CONTRIBUTOR_NAMES,
DefaultInstitutionalItemIndexService.LANGUAGE,
DefaultInstitutionalItemIndexService.KEY_WORDS,
DefaultInstitutionalItemIndexService.CONTENT_TYPES,
DefaultInstitutionalItemIndexService.COLLECTION_NAME,
DefaultInstitutionalItemIndexService.CONTRIBUTOR_NAMES
};
MapFieldSelector fieldSelector= new MapFieldSelector(fieldsToLoad);
HashMap<String, HashMap<String, FacetResult>> facets = new HashMap<String, HashMap<String, FacetResult>>();
HashMap<String, FacetResult> authorsMap = new HashMap<String, FacetResult>();
HashMap<String, FacetResult> languagesMap = new HashMap<String, FacetResult>();
HashMap<String, FacetResult> subjectsMap = new HashMap<String, FacetResult>();
HashMap<String, FacetResult> formatsMap = new HashMap<String, FacetResult>();
HashMap<String, FacetResult> collectionMap = new HashMap<String, FacetResult>();
facets.put(AUTHOR_MAP, authorsMap);
facets.put(LANGUAGE_MAP, languagesMap);
facets.put(SUBJECT_MAP, subjectsMap);
facets.put(FORMAT_MAP, formatsMap);
facets.put(COLLECTION_MAP, collectionMap);
int length = topDocs.totalHits;
if (length <= numberOfHitsToProcess)
{
numberOfHitsToProcess = length;
}
for( int index = 0; index < numberOfHitsToProcess; index++)
{
Document doc = searcher.doc(topDocs.scoreDocs[index].doc, fieldSelector);
String names = doc.get(DefaultInstitutionalItemIndexService.CONTRIBUTOR_NAMES);
String language = doc.get(DefaultInstitutionalItemIndexService.LANGUAGE);
if( language != null )
{
language = language.trim();
}
String subjects = doc.get(DefaultInstitutionalItemIndexService.KEY_WORDS);
String formats = doc.get(DefaultInstitutionalItemIndexService.CONTENT_TYPES);
String collection = doc.get(DefaultInstitutionalItemIndexService.COLLECTION_NAME);
if( collection != null)
{
collection = collection.trim();
FacetResult f = collectionMap.get(collection);
if( f == null )
{
f = new FacetResult(1l, DefaultInstitutionalItemIndexService.COLLECTION_NAME, collection);
collectionMap.put(collection, f);
}
}
if( names != null && authorsMap.size() < numberOfResultsToCollect)
{
StringTokenizer tokenizer = new StringTokenizer(names, DefaultInstitutionalItemIndexService.SEPERATOR);
while(tokenizer.hasMoreElements() && authorsMap.size() < numberOfResultsToCollect)
{
String nextName = tokenizer.nextToken().trim();
FacetResult f = authorsMap.get(nextName);
if( f== null )
{
f = new FacetResult(1l, DefaultInstitutionalItemIndexService.CONTRIBUTOR_NAMES, nextName);
authorsMap.put(nextName, f);
}
}
}
if( language != null && languagesMap.size() < numberOfResultsToCollect )
{
FacetResult f = languagesMap.get(language);
if( f == null )
{
f = new FacetResult(1l, DefaultInstitutionalItemIndexService.LANGUAGE, language);
languagesMap.put(language, f);
}
}
if( subjects != null && subjectsMap.size() < numberOfResultsToCollect)
{
StringTokenizer tokenizer = new StringTokenizer(subjects, DefaultInstitutionalItemIndexService.SEPERATOR);
while(tokenizer.hasMoreElements() && languagesMap.size() < numberOfResultsToCollect)
{
String subject = tokenizer.nextToken().trim();
FacetResult f = subjectsMap.get(subject);
if( f == null )
{
f = new FacetResult(1l, DefaultInstitutionalItemIndexService.KEY_WORDS, subject);
subjectsMap.put(subject, f);
}
}
}
if( formats != null && formatsMap.size() < numberOfResultsToCollect)
{
StringTokenizer tokenizer = new StringTokenizer(formats, DefaultInstitutionalItemIndexService.SEPERATOR);
while(tokenizer.hasMoreElements() && formatsMap.size() < numberOfResultsToCollect)
{
String nextFormat = tokenizer.nextToken().trim();
FacetResult f = formatsMap.get(nextFormat);
if( f== null )
{
f = new FacetResult(1l, DefaultInstitutionalItemIndexService.CONTENT_TYPES, nextFormat);
formatsMap.put(nextFormat, f);
}
}
}
doc = null;
}
return facets;
}
/**
* Determines the number of hits for each facet across the main query.
*
* @param facets
* @param reader
* @param mainQueryBits
* @throws ParseException
* @throws IOException
*/
private void processFacetCategory(Collection<FacetResult> facets,
IndexReader reader,
OpenBitSetDISI mainQueryBitSet,
IndexSearcher searcher)
throws ParseException, IOException
{
for(FacetResult f : facets )
{
long count = 0;
String searchString = SearchHelper.prepareFacetSearchString(f.getFacetName(), false);
if( !searchString.trim().equals(""))
{
QueryParser subQueryParser = new QueryParser(f.getField(), analyzer);
subQueryParser.setDefaultOperator(QueryParser.AND_OPERATOR);
Query subQuery = subQueryParser.parse(searchString);
QueryWrapperFilter subQueryWrapper = new QueryWrapperFilter(subQuery);
DocIdSet subQueryBits = subQueryWrapper.getDocIdSet(reader);
OpenBitSetDISI subQuerybitSet = new OpenBitSetDISI(subQueryBits.iterator(), maxNumberOfMainQueryHits);
count = getFacetHitCount(mainQueryBitSet, subQuerybitSet);
}
else
{
log.error("bad search string " + searchString);
}
f.setHits(count);
}
}
public void setAnalyzer(Analyzer analyzer) {
this.analyzer = analyzer;
}
public String[] getFields() {
return fields;
}
/* (non-Javadoc)
* @see edu.ur.ir.repository.InstitutionalItemSearchService#executeSearchWithFacets(java.lang.String, java.util.Set, java.lang.String, int, int, int)
*/
public FacetSearchHelper executeSearchWithFacets(
String mainQueryString,
List<FacetFilter> filters,
String indexFolder,
int numberOfHitsToProcessForFacets,
int numberOfResultsToCollectForFacets,
int numberOfFactsToShow,
int numberOfIdsToCollect,
int idsToCollectStartPosition)
throws CorruptIndexException, IOException, ParseException {
if( searchDirectoryIsEmpty(indexFolder) || isInvalidQuery(mainQueryString))
{
return new FacetSearchHelper(new HashSet<Long>(), 0, new HashMap<String, Collection<FacetResult>>(), mainQueryString);
}
IndexSearcher searcher = new IndexSearcher(indexFolder);
IndexReader reader = searcher.getIndexReader();
QueryParser parser = new MultiFieldQueryParser(fields, analyzer);
parser.setDefaultOperator(QueryParser.AND_OPERATOR);
HashMap<String, Collection<FacetResult>> facetResults = new HashMap<String, Collection<FacetResult>>();
// execute the main query - we will use this to extract data to determine the facet searches
String executedQuery = SearchHelper.prepareMainSearchString(mainQueryString, false);
if( log.isDebugEnabled() )
{
log.debug("parsed query = " + executedQuery.trim());
}
Query mainQuery = parser.parse( executedQuery);
//create a filter for the main query
QueryWrapperFilter mainQueryWrapper = new QueryWrapperFilter(mainQuery);
// get the bitset for main query
DocIdSet mainQueryBits = mainQueryWrapper.getDocIdSet(reader);
OpenBitSetDISI mainQueryBitSet = new OpenBitSetDISI(mainQueryBits.iterator(), maxNumberOfMainQueryHits);
TopDocs hits = null;
if( filters.size() > 0 )
{
// create a filter that will match the main query plus all other filters
List<Filter> luceneFilters = getSubQueryFilters(filters, searcher);
Filter filter = new ChainedFilter(luceneFilters.toArray(new Filter[luceneFilters.size()]), ChainedFilter.AND);
if(log.isDebugEnabled())
{
log.debug("filter = " + filter);
}
// apply the facets and include them in the main query bit set
DocIdSet filterQueryBits = filter.getDocIdSet(reader);
OpenBitSetDISI filterBitSet = new OpenBitSetDISI(filterQueryBits.iterator(), maxNumberOfMainQueryHits);
mainQueryBitSet.and(filterBitSet);
hits = searcher.search(mainQuery, filter, maxNumberOfMainQueryHits);
log.debug(" executeSearchWithFacets 2 = mainQuery = " + executedQuery + " filter = " + filter);
}
else
{
hits = searcher.search(mainQuery, maxNumberOfMainQueryHits);
log.debug(" executeSearchWithFacets 3 = mainQuery = " + mainQuery);
}
// determine the set of data we should use to determine facets
HashMap<String, HashMap<String, FacetResult>> possibleFacets = this.generateFacetSearches(hits, numberOfHitsToProcessForFacets, numberOfResultsToCollectForFacets, searcher);
FacetSearchHelper helper = processPossibleFacets(possibleFacets,
reader,
mainQueryBitSet,
facetResults,
hits,
numberOfIdsToCollect,
idsToCollectStartPosition,
numberOfFactsToShow,
mainQueryString,
searcher);
helper.setExecutedQuery(executedQuery);
helper.setFacetTrail(filters);
searcher.close();
return helper;
}
/* (non-Javadoc)
* @see edu.ur.ir.institution.InstitutionalItemSearchService#executeSearchWithFacets(java.lang.String, java.util.List, java.lang.String, int, int, int, edu.ur.ir.institution.InstitutionalCollection)
*/
public FacetSearchHelper executeSearchWithFacets(
String mainQueryString,
List<FacetFilter> filters,
String indexFolder,
int numberOfHitsToProcessForFacets,
int numberOfResultsToCollectForFacets,
int numberOfFactsToShow,
int numberOfIdsToCollect,
int idsToCollectStartPosition,
InstitutionalCollection collection)
throws CorruptIndexException, IOException, ParseException {
if( searchDirectoryIsEmpty(indexFolder) || isInvalidQuery(mainQueryString))
{
return new FacetSearchHelper(new HashSet<Long>(), 0, new HashMap<String, Collection<FacetResult>>(), mainQueryString);
}
IndexSearcher searcher = new IndexSearcher(indexFolder);
IndexReader reader = searcher.getIndexReader();
QueryParser parser = new MultiFieldQueryParser(fields, analyzer);
parser.setDefaultOperator(QueryParser.AND_OPERATOR);
HashMap<String, Collection<FacetResult>> facetResults = new HashMap<String, Collection<FacetResult>>();
// execute the main query - we will use this to extract data to determine the facet searches
String executedQuery = SearchHelper.prepareMainSearchString(mainQueryString, false);
Query mainQuery = parser.parse(executedQuery);
if( log.isDebugEnabled() )
{
log.debug("parsed query = " + executedQuery);
}
//create a filter for the main query
QueryWrapperFilter mainQueryWrapper = new QueryWrapperFilter(mainQuery);
// get the bitset for main query
DocIdSet mainQueryBits = mainQueryWrapper.getDocIdSet(reader);
TopDocs hits = null;
List<Filter> luceneFilters = new LinkedList<Filter>();
if( filters.size() > 0 )
{
// create a filter that will match the main query plus all other filters
luceneFilters.addAll(getSubQueryFilters(filters, searcher));
}
// add filters for the collection first
luceneFilters.addAll(0, getCollectionFilters(collection));
Filter filter = new ChainedFilter(luceneFilters.toArray(new Filter[luceneFilters.size()]), ChainedFilter.AND);
if(log.isDebugEnabled())
{
log.debug("filter = " + filter);
}
// get the filter query doc id set
DocIdSet filterQueryBits = filter.getDocIdSet(reader);
// apply the facets and include them in the main query bit set
OpenBitSetDISI mainQueryBitSet = new OpenBitSetDISI(mainQueryBits.iterator(), maxNumberOfMainQueryHits);
OpenBitSetDISI filterBitSet = new OpenBitSetDISI(filterQueryBits.iterator(), maxNumberOfMainQueryHits);
mainQueryBitSet.and(filterBitSet);
hits = searcher.search(mainQuery, filter, maxNumberOfMainQueryHits);
log.debug(" executeSearchWithFacets 4 = mainQuery = " + mainQuery + " filter = " + filter);
// determine the set of data we should use to determine facets
HashMap<String, HashMap<String, FacetResult>> possibleFacets = this.generateFacetSearches(hits, numberOfHitsToProcessForFacets, numberOfResultsToCollectForFacets, searcher);
FacetSearchHelper helper = processPossibleFacets(possibleFacets,
reader,
mainQueryBitSet,
facetResults,
hits,
numberOfIdsToCollect,
idsToCollectStartPosition,
numberOfFactsToShow,
mainQueryString,
searcher);
helper.setFacetTrail(filters);
helper.setExecutedQuery(executedQuery);
searcher.close();
return helper;
}
/**
* Execute the sub query facets and return the search results
* @throws ParseException
* @throws IOException
*/
private List<Filter> getSubQueryFilters( List<FacetFilter> filters,
IndexSearcher searcher) throws ParseException, IOException
{
List<Filter> luceneFilters = new LinkedList<Filter>();
for(FacetFilter filter : filters)
{
if(log.isDebugEnabled())
{
log.debug("adding filter for field " + filter.getField() + " and query " + filter.getQuery());
}
QueryParser subQueryParser = new QueryParser(filter.getField(), analyzer);
subQueryParser.setDefaultOperator(QueryParser.AND_OPERATOR);
Query subQuery = subQueryParser.parse(SearchHelper.prepareFacetSearchString(filter.getQuery(), false));
if(log.isDebugEnabled())
{
log.debug("sub query is " + subQuery);
}
luceneFilters.add(new QueryWrapperFilter(subQuery));
}
return luceneFilters;
}
/**
* Process the possible facets and determine the number of hits for each facet accross the main query.
*
* @param possibleFacets - possible facets to show to the user
* @param reader - lucene reader
* @param mainQueryBits - bitset from the main query
* @param facetResults - set of facet results
* @param hits - number of hits
* @param numberOfIdsToCollect - number of ids to collect and show to user
* @param mainQueryString - main query
*
* @return - search helper
* @throws ParseException
* @throws IOException
*/
private FacetSearchHelper processPossibleFacets(HashMap<String, HashMap<String, FacetResult>> possibleFacets,
IndexReader reader,
OpenBitSetDISI mainQueryBits,
HashMap<String,
Collection<FacetResult>> facetResults,
TopDocs hits,
int numberOfIdsToCollect,
int idsToCollectStartPosition,
int numberOfFacetsToShow,
String mainQueryString,
IndexSearcher searcher) throws ParseException, IOException
{
FacetResultHitComparator facetResultHitComparator = new FacetResultHitComparator();
// get the authors and create a facet for each author
// determine the number of hits the author has in the main query
HashMap<String, FacetResult> authorFacetMap = possibleFacets.get(AUTHOR_MAP);
LinkedList<FacetResult> authorFacets = new LinkedList<FacetResult>();
authorFacets.addAll(authorFacetMap.values());
processFacetCategory(authorFacets, reader, mainQueryBits, searcher);
Collections.sort(authorFacets, facetResultHitComparator );
// final holder of facets
LinkedList<FacetResult> finalAuthorFacets;
if( authorFacets.size() < numberOfFacetsToShow )
{
finalAuthorFacets = authorFacets;
}
else
{
finalAuthorFacets = new LinkedList<FacetResult>();
for( int index = 0; index < numberOfFacetsToShow; index++ )
{
finalAuthorFacets.add(authorFacets.get(index));
}
}
facetResults.put(AUTHOR_MAP,finalAuthorFacets);
// get the subjects and create a facet for each subject
// determine the number of hits the subject has in the main query
HashMap<String, FacetResult> subjectFacetMap = possibleFacets.get(SUBJECT_MAP);
LinkedList<FacetResult> subjectFacets = new LinkedList<FacetResult>();
subjectFacets.addAll(subjectFacetMap.values());
processFacetCategory(subjectFacets, reader, mainQueryBits, searcher);
Collections.sort(subjectFacets, facetResultHitComparator);
// final holder of facets
LinkedList<FacetResult> finalSubjectFacets;
if( subjectFacets.size() < numberOfFacetsToShow )
{
finalSubjectFacets = subjectFacets;
}
else
{
finalSubjectFacets = new LinkedList<FacetResult>();
for( int index = 0; index < numberOfFacetsToShow; index++ )
{
finalSubjectFacets.add(subjectFacets.get(index));
}
}
facetResults.put(SUBJECT_MAP, finalSubjectFacets);
// get the language and create a facet for each language
// determine the number of hits the language has in the main query
HashMap<String, FacetResult> languageFacetMap = possibleFacets.get(LANGUAGE_MAP);
LinkedList<FacetResult> languageFacets = new LinkedList<FacetResult>();
languageFacets.addAll(languageFacetMap.values());
processFacetCategory(languageFacets, reader, mainQueryBits, searcher);
Collections.sort(languageFacets, facetResultHitComparator);
// final holder of facets
LinkedList<FacetResult> finalLanguageFacets;
if( languageFacets.size() < numberOfFacetsToShow )
{
finalLanguageFacets = languageFacets;
}
else
{
finalLanguageFacets = new LinkedList<FacetResult>();
for( int index = 0; index < numberOfFacetsToShow; index++ )
{
finalLanguageFacets.add(languageFacets.get(index));
}
}
facetResults.put(LANGUAGE_MAP, finalLanguageFacets);
// get the format and create a facet for each format
// determine the number of hits the format has in the main query
HashMap<String, FacetResult> formatFacetMap = possibleFacets.get(FORMAT_MAP);
LinkedList<FacetResult> formatFacets = new LinkedList<FacetResult>();
formatFacets.addAll(formatFacetMap.values());
processFacetCategory(formatFacets, reader, mainQueryBits, searcher);
Collections.sort(formatFacets, facetResultHitComparator);
// final holder of facets
LinkedList<FacetResult> finalFormatFacets;
if( formatFacets.size() < numberOfFacetsToShow )
{
finalFormatFacets = formatFacets;
}
else
{
finalFormatFacets = new LinkedList<FacetResult>();
for( int index = 0; index < numberOfFacetsToShow; index++ )
{
finalFormatFacets.add(formatFacets.get(index));
}
}
facetResults.put(FORMAT_MAP, finalFormatFacets);
// get the format and create a facet for each format
// determine the number of hits the format has in the main query
HashMap<String, FacetResult> collectionFacetMap = possibleFacets.get(COLLECTION_MAP);
LinkedList<FacetResult> collectionFacets = new LinkedList<FacetResult>();
collectionFacets.addAll(collectionFacetMap.values());
processFacetCategory(collectionFacets, reader, mainQueryBits, searcher);
Collections.sort(collectionFacets, facetResultHitComparator);
// final holder of facets
LinkedList<FacetResult> finalCollectionFacets;
if( collectionFacets.size() < numberOfFacetsToShow )
{
finalCollectionFacets = collectionFacets;
}
else
{
finalCollectionFacets = new LinkedList<FacetResult>();
for( int index = 0; index < numberOfFacetsToShow; index++ )
{
finalCollectionFacets.add(collectionFacets.get(index));
}
}
facetResults.put(COLLECTION_MAP, finalCollectionFacets);
HashSet<Long> ids = new HashSet<Long>();
// end position of id's to collect will be start position plus the number to collect
int endPosition = idsToCollectStartPosition + numberOfIdsToCollect;
// make sure that the end position is set up correctly
if(hits.totalHits < endPosition )
{
endPosition = hits.totalHits;
}
String[] fieldsToLoad = { DefaultInstitutionalItemIndexService.ID };
MapFieldSelector fieldSelector= new MapFieldSelector(fieldsToLoad);
for( int index = idsToCollectStartPosition; index < endPosition; index ++ )
{
Document doc = searcher.doc(hits.scoreDocs[index].doc,fieldSelector);
ids.add(NumberTools.stringToLong(doc.get(DefaultInstitutionalItemIndexService.ID)));
}
FacetSearchHelper helper = new FacetSearchHelper(ids, hits.totalHits, facetResults, mainQueryString);
return helper;
}
/**
* Determine if the search directory is empty.
*
* @param indexFolder
* @return
*/
private boolean searchDirectoryIsEmpty(String indexFolder )
{
File indexFolderLocation = new File(indexFolder);
if( indexFolderLocation.isDirectory() && indexFolderLocation.exists())
{
// do not search if the folder is empty
String[] files = indexFolderLocation.list();
if( files == null || files.length <= 0 )
{
log.debug("no index files found");
return true;
}
return false;
}
else
{
log.debug("search directory is not a directory or does not exist " + indexFolder);
return true;
}
}
private boolean isInvalidQuery(String mainQuery)
{
log.debug("check to see if problem with main query " + mainQuery);
return (mainQuery == null || mainQuery.trim().equals("") || mainQuery.trim().equals("*"));
}
/* (non-Javadoc)
* @see edu.ur.ir.institution.InstitutionalItemSearchService#executeSearchWithFacets(java.lang.String, java.lang.String, int, int, int, edu.ur.ir.institution.InstitutionalCollection)
*/
public FacetSearchHelper executeSearchWithFacets(
String mainQueryString,
String indexFolder,
int numberOfHitsToProcessForFacets,
int numberOfResultsToCollectForFacets,
int numberOfFactsToShow,
int numberOfIdsToCollect,
int idsToCollectStartPosition,
InstitutionalCollection collection) throws CorruptIndexException,
IOException, ParseException
{
log.debug("execute search with facets for a collection");
if( searchDirectoryIsEmpty(indexFolder) || isInvalidQuery(mainQueryString))
{
log.debug("problem with search!");
return new FacetSearchHelper(new HashSet<Long>(), 0, new HashMap<String, Collection<FacetResult>>(), mainQueryString);
}
IndexSearcher searcher = new IndexSearcher(indexFolder);
IndexReader reader = searcher.getIndexReader();
QueryParser parser = new MultiFieldQueryParser(fields, analyzer);
parser.setDefaultOperator(QueryParser.AND_OPERATOR);
HashMap<String, Collection<FacetResult>> facetResults = new HashMap<String, Collection<FacetResult>>();
// execute the main query - we will use this to extract data to determine the facet searches
String executedQuery = SearchHelper.prepareMainSearchString(mainQueryString, false);
Query mainQuery = parser.parse(executedQuery);
Filter[] aFilters = this.getCollectionFilters(collection).toArray(new Filter[2]);
Filter chainedFilter = new ChainedFilter(aFilters, ChainedFilter.AND);
//create a filter for the main query
QueryWrapperFilter mainQueryWrapper = new QueryWrapperFilter(mainQuery);
// get the bitset for main query
DocIdSet mainQueryBits = mainQueryWrapper.getDocIdSet(reader);
// get the filter query doc id set
DocIdSet filterQueryBits = chainedFilter.getDocIdSet(reader);
// apply the filters for the collection root and range
OpenBitSetDISI mainQueryBitSet = new OpenBitSetDISI(mainQueryBits.iterator(), maxNumberOfMainQueryHits);
OpenBitSetDISI filterBitSet = new OpenBitSetDISI(filterQueryBits.iterator(), maxNumberOfMainQueryHits);
mainQueryBitSet.and(filterBitSet);
log.debug(" executeSearchWithFacets 5 = mainQuery = " + mainQuery + " filter = " + chainedFilter);
TopDocs hits = null;
hits = searcher.search(mainQuery, chainedFilter, maxNumberOfMainQueryHits);
// determine the set of data we should use to determine facets
HashMap<String, HashMap<String, FacetResult>> possibleFacets = this.generateFacetSearches(hits,
numberOfHitsToProcessForFacets,
numberOfResultsToCollectForFacets,
searcher);
// process the data and determine the facets
FacetSearchHelper helper = processPossibleFacets(possibleFacets,
reader,
mainQueryBitSet,
facetResults,
hits,
numberOfIdsToCollect,
idsToCollectStartPosition,
numberOfFactsToShow,
mainQueryString,
searcher);
helper.setExecutedQuery(executedQuery);
searcher.close();
return helper;
}
/**
* Set up the filters for collections - this is for searching within collections.
*
* @param collection - to search within
* @return - created filter
* @throws ParseException
*/
private List<Filter> getCollectionFilters(InstitutionalCollection collection) throws ParseException
{
List<Filter> filters = new LinkedList<Filter>();
//isolate the collection root
QueryParser subQueryParser = new QueryParser("collection_root_id", analyzer);
subQueryParser.setDefaultOperator(QueryParser.AND_OPERATOR);
Query subQuery = subQueryParser.parse(NumberTools.longToString(collection.getTreeRoot().getId()));
filters.add(new QueryWrapperFilter(subQuery));
//isolate the range of children
subQueryParser = new QueryParser("collection_left_value", analyzer);
subQueryParser.setDefaultOperator(QueryParser.AND_OPERATOR);
subQuery = subQueryParser.parse("[" + NumberTools.longToString(collection.getLeftValue()) + " TO " + NumberTools.longToString(collection.getRightValue()) + "]" );
filters.add(new QueryWrapperFilter(subQuery));
return filters;
}
/**
* Maxmimum number of main query hits to retrieve.
*
* @return
*/
public int getMaxNumberOfMainQueryHits() {
return maxNumberOfMainQueryHits;
}
/**
* Maximum number of main query hits to retrieve
*
* @param maxNumberOfMainQueryHits
*/
public void setMaxNumberOfMainQueryHits(int maxNumberOfMainQueryHits) {
this.maxNumberOfMainQueryHits = maxNumberOfMainQueryHits;
}
}
|
ir_service/src/edu/ur/ir/institution/service/DefaultInstitutionalItemSearchService.java
|
/**
Copyright 2008 University of Rochester
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 edu.ur.ir.institution.service;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;
import org.apache.log4j.Logger;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.LoadFirstFieldSelector;
import org.apache.lucene.document.MapFieldSelector;
import org.apache.lucene.document.NumberTools;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.misc.ChainedFilter;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.DocIdSet;
import org.apache.lucene.search.Filter;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.QueryWrapperFilter;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.util.OpenBitSet;
import org.apache.lucene.util.OpenBitSetDISI;
import edu.ur.ir.FacetSearchHelper;
import edu.ur.ir.SearchHelper;
import edu.ur.ir.institution.InstitutionalCollection;
import edu.ur.ir.institution.InstitutionalItemSearchService;
import edu.ur.ir.search.FacetFilter;
import edu.ur.ir.search.FacetResult;
import edu.ur.ir.search.FacetResultHitComparator;
/**
* Excecute the search and determine facets
*
* @author Nathan Sarr
*
*/
public class DefaultInstitutionalItemSearchService implements InstitutionalItemSearchService{
/** Analyzer to use for parsing the queries */
private Analyzer analyzer;
/** Logger for editing a file database. */
private static final Logger log = Logger.getLogger(DefaultInstitutionalItemSearchService.class);
/** max number of hits to retrieve */
private int maxNumberOfMainQueryHits = 10000;
/** fields to search in the index*/
private static final String[] fields =
{DefaultInstitutionalItemIndexService.ABSTRACT,
DefaultInstitutionalItemIndexService.NAME,
DefaultInstitutionalItemIndexService.DESCRIPTION,
DefaultInstitutionalItemIndexService.LINK_NAMES,
DefaultInstitutionalItemIndexService.FILE_TEXT,
DefaultInstitutionalItemIndexService.CONTRIBUTOR_NAMES,
DefaultInstitutionalItemIndexService.LANGUAGE,
DefaultInstitutionalItemIndexService.IDENTIFIERS,
DefaultInstitutionalItemIndexService.KEY_WORDS,
DefaultInstitutionalItemIndexService.SUB_TITLES,
DefaultInstitutionalItemIndexService.PUBLISHER,
DefaultInstitutionalItemIndexService.CITATION,
DefaultInstitutionalItemIndexService.CONTENT_TYPES,
DefaultInstitutionalItemIndexService.COLLECTION_LEFT_VALUE,
DefaultInstitutionalItemIndexService.COLLECTION_RIGHT_VALUE,
DefaultInstitutionalItemIndexService.COLLECTION_NAME};
/**
* Get the facets and results
* @see edu.ur.ir.institution.InstitutionalItemSearchService#executeSearchWithFacets(java.lang.String, java.lang.String, int, int, int, int)
*/
public FacetSearchHelper executeSearchWithFacets(
String mainQueryString,
String indexFolder,
int numberOfHitsToProcessForFacets,
int numberOfResultsToCollectForFacets,
int numberOfFactsToShow,
int numberOfIdsToCollect,
int idsToCollectStartPosition )
throws CorruptIndexException, IOException, ParseException
{
if( searchDirectoryIsEmpty(indexFolder) || isInvalidQuery(mainQueryString))
{
return new FacetSearchHelper(new HashSet<Long>(), 0, new HashMap<String, Collection<FacetResult>>(), mainQueryString);
}
IndexSearcher searcher = new IndexSearcher(indexFolder);
IndexReader reader = searcher.getIndexReader();
QueryParser parser = new MultiFieldQueryParser(fields, analyzer);
parser.setDefaultOperator(QueryParser.AND_OPERATOR);
HashMap<String, Collection<FacetResult>> facetResults = new HashMap<String, Collection<FacetResult>>();
// execute the main query - we will use this to extract data to determine the facet searches
String executedQuery = SearchHelper.prepareMainSearchString(mainQueryString, false);
Query mainQuery = parser.parse(executedQuery);
if( log.isDebugEnabled() )
{
log.debug("main query = " + executedQuery );
}
TopDocs topDocs = searcher.search(mainQuery, maxNumberOfMainQueryHits);
// determine the set of data we should use to determine facets
HashMap<String, HashMap<String, FacetResult>> possibleFacets = this.generateFacetSearches(
topDocs,
numberOfHitsToProcessForFacets,
numberOfResultsToCollectForFacets,
searcher);
QueryWrapperFilter mainQueryWrapper = new QueryWrapperFilter(mainQuery);
log.debug("executeSearchWithFacets 1 query = " + mainQuery);
DocIdSet mainQueryBits = mainQueryWrapper.getDocIdSet(reader);
OpenBitSetDISI mainQueryBitSet = new OpenBitSetDISI(mainQueryBits.iterator(), maxNumberOfMainQueryHits);
// process the data and determine the facets
FacetSearchHelper helper = processPossibleFacets(possibleFacets,
reader,
mainQueryBitSet,
facetResults,
topDocs,
numberOfIdsToCollect,
idsToCollectStartPosition,
numberOfFactsToShow,
mainQueryString,
searcher);
helper.setExecutedQuery(executedQuery);
searcher.close();
return helper;
}
/**
* Determine the number of hits based on the overall number of results the main search returned.
*
* @param baseBitSet
* @param filterBitSet
* @return
*/
private long getFacetHitCount(OpenBitSet baseBitSet, OpenBitSet filterBitSet)
{
filterBitSet.and(baseBitSet);
return filterBitSet.cardinality();
}
/**
* This determines the possible facets for each of the categories. For example - possible authors
* for the display. This does not care about counts later on counts will be important.
*
* @param topDocs - top doucment hits found
* @param numberOfHitsToProcess
* @return
* @throws CorruptIndexException
* @throws IOException
*/
private HashMap<String, HashMap<String, FacetResult>> generateFacetSearches(TopDocs topDocs,
int numberOfHitsToProcess,
int numberOfResultsToCollect,
IndexSearcher searcher) throws CorruptIndexException, IOException
{
String[] fieldsToLoad = {
DefaultInstitutionalItemIndexService.CONTRIBUTOR_NAMES,
DefaultInstitutionalItemIndexService.LANGUAGE,
DefaultInstitutionalItemIndexService.KEY_WORDS,
DefaultInstitutionalItemIndexService.CONTENT_TYPES,
DefaultInstitutionalItemIndexService.COLLECTION_NAME,
DefaultInstitutionalItemIndexService.CONTRIBUTOR_NAMES
};
MapFieldSelector fieldSelector= new MapFieldSelector(fieldsToLoad);
HashMap<String, HashMap<String, FacetResult>> facets = new HashMap<String, HashMap<String, FacetResult>>();
HashMap<String, FacetResult> authorsMap = new HashMap<String, FacetResult>();
HashMap<String, FacetResult> languagesMap = new HashMap<String, FacetResult>();
HashMap<String, FacetResult> subjectsMap = new HashMap<String, FacetResult>();
HashMap<String, FacetResult> formatsMap = new HashMap<String, FacetResult>();
HashMap<String, FacetResult> collectionMap = new HashMap<String, FacetResult>();
facets.put(AUTHOR_MAP, authorsMap);
facets.put(LANGUAGE_MAP, languagesMap);
facets.put(SUBJECT_MAP, subjectsMap);
facets.put(FORMAT_MAP, formatsMap);
facets.put(COLLECTION_MAP, collectionMap);
int length = topDocs.totalHits;
if (length <= numberOfHitsToProcess)
{
numberOfHitsToProcess = length;
}
for( int index = 0; index < numberOfHitsToProcess; index++)
{
Document doc = searcher.doc(topDocs.scoreDocs[index].doc, fieldSelector);
String names = doc.get(DefaultInstitutionalItemIndexService.CONTRIBUTOR_NAMES);
String language = doc.get(DefaultInstitutionalItemIndexService.LANGUAGE);
if( language != null )
{
language = language.trim();
}
String subjects = doc.get(DefaultInstitutionalItemIndexService.KEY_WORDS);
String formats = doc.get(DefaultInstitutionalItemIndexService.CONTENT_TYPES);
String collection = doc.get(DefaultInstitutionalItemIndexService.COLLECTION_NAME);
if( collection != null)
{
collection = collection.trim();
FacetResult f = collectionMap.get(collection);
if( f == null )
{
f = new FacetResult(1l, DefaultInstitutionalItemIndexService.COLLECTION_NAME, collection);
collectionMap.put(collection, f);
}
}
if( names != null && authorsMap.size() < numberOfResultsToCollect)
{
StringTokenizer tokenizer = new StringTokenizer(names, DefaultInstitutionalItemIndexService.SEPERATOR);
while(tokenizer.hasMoreElements() && authorsMap.size() < numberOfResultsToCollect)
{
String nextName = tokenizer.nextToken().trim();
FacetResult f = authorsMap.get(nextName);
if( f== null )
{
f = new FacetResult(1l, DefaultInstitutionalItemIndexService.CONTRIBUTOR_NAMES, nextName);
authorsMap.put(nextName, f);
}
}
}
if( language != null && languagesMap.size() < numberOfResultsToCollect )
{
FacetResult f = languagesMap.get(language);
if( f == null )
{
f = new FacetResult(1l, DefaultInstitutionalItemIndexService.LANGUAGE, language);
languagesMap.put(language, f);
}
}
if( subjects != null && subjectsMap.size() < numberOfResultsToCollect)
{
StringTokenizer tokenizer = new StringTokenizer(subjects, DefaultInstitutionalItemIndexService.SEPERATOR);
while(tokenizer.hasMoreElements() && languagesMap.size() < numberOfResultsToCollect)
{
String subject = tokenizer.nextToken().trim();
FacetResult f = subjectsMap.get(subject);
if( f == null )
{
f = new FacetResult(1l, DefaultInstitutionalItemIndexService.KEY_WORDS, subject);
subjectsMap.put(subject, f);
}
}
}
if( formats != null && formatsMap.size() < numberOfResultsToCollect)
{
StringTokenizer tokenizer = new StringTokenizer(formats, DefaultInstitutionalItemIndexService.SEPERATOR);
while(tokenizer.hasMoreElements() && formatsMap.size() < numberOfResultsToCollect)
{
String nextFormat = tokenizer.nextToken().trim();
FacetResult f = formatsMap.get(nextFormat);
if( f== null )
{
f = new FacetResult(1l, DefaultInstitutionalItemIndexService.CONTENT_TYPES, nextFormat);
formatsMap.put(nextFormat, f);
}
}
}
doc = null;
}
return facets;
}
/**
* Determines the number of hits for each facet across the main query.
*
* @param facets
* @param reader
* @param mainQueryBits
* @throws ParseException
* @throws IOException
*/
private void processFacetCategory(Collection<FacetResult> facets,
IndexReader reader,
OpenBitSetDISI mainQueryBitSet,
IndexSearcher searcher)
throws ParseException, IOException
{
for(FacetResult f : facets )
{
long count = 0;
String searchString = SearchHelper.prepareFacetSearchString(f.getFacetName(), false);
if( !searchString.trim().equals(""))
{
QueryParser subQueryParser = new QueryParser(f.getField(), analyzer);
subQueryParser.setDefaultOperator(QueryParser.AND_OPERATOR);
Query subQuery = subQueryParser.parse(searchString);
QueryWrapperFilter subQueryWrapper = new QueryWrapperFilter(subQuery);
DocIdSet subQueryBits = subQueryWrapper.getDocIdSet(reader);
OpenBitSetDISI subQuerybitSet = new OpenBitSetDISI(subQueryBits.iterator(), maxNumberOfMainQueryHits);
count = getFacetHitCount(mainQueryBitSet, subQuerybitSet);
}
else
{
log.error("bad search string " + searchString);
}
f.setHits(count);
}
}
public void setAnalyzer(Analyzer analyzer) {
this.analyzer = analyzer;
}
public String[] getFields() {
return fields;
}
/* (non-Javadoc)
* @see edu.ur.ir.repository.InstitutionalItemSearchService#executeSearchWithFacets(java.lang.String, java.util.Set, java.lang.String, int, int, int)
*/
public FacetSearchHelper executeSearchWithFacets(
String mainQueryString,
List<FacetFilter> filters,
String indexFolder,
int numberOfHitsToProcessForFacets,
int numberOfResultsToCollectForFacets,
int numberOfFactsToShow,
int numberOfIdsToCollect,
int idsToCollectStartPosition)
throws CorruptIndexException, IOException, ParseException {
if( searchDirectoryIsEmpty(indexFolder) || isInvalidQuery(mainQueryString))
{
return new FacetSearchHelper(new HashSet<Long>(), 0, new HashMap<String, Collection<FacetResult>>(), mainQueryString);
}
IndexSearcher searcher = new IndexSearcher(indexFolder);
IndexReader reader = searcher.getIndexReader();
QueryParser parser = new MultiFieldQueryParser(fields, analyzer);
parser.setDefaultOperator(QueryParser.AND_OPERATOR);
HashMap<String, Collection<FacetResult>> facetResults = new HashMap<String, Collection<FacetResult>>();
// execute the main query - we will use this to extract data to determine the facet searches
String executedQuery = SearchHelper.prepareMainSearchString(mainQueryString, false);
if( log.isDebugEnabled() )
{
log.debug("parsed query = " + executedQuery.trim());
}
Query mainQuery = parser.parse( executedQuery);
//create a filter for the main query
QueryWrapperFilter mainQueryWrapper = new QueryWrapperFilter(mainQuery);
// get the bitset for main query
DocIdSet mainQueryBits = mainQueryWrapper.getDocIdSet(reader);
OpenBitSetDISI mainQueryBitSet = new OpenBitSetDISI(mainQueryBits.iterator(), maxNumberOfMainQueryHits);
TopDocs hits = null;
if( filters.size() > 0 )
{
// create a filter that will match the main query plus all other filters
List<Filter> luceneFilters = getSubQueryFilters(filters, searcher);
Filter filter = new ChainedFilter(luceneFilters.toArray(new Filter[luceneFilters.size()]), ChainedFilter.AND);
if(log.isDebugEnabled())
{
log.debug("filter = " + filter);
}
// apply the facets and include them in the main query bit set
DocIdSet filterQueryBits = filter.getDocIdSet(reader);
OpenBitSetDISI filterBitSet = new OpenBitSetDISI(filterQueryBits.iterator(), maxNumberOfMainQueryHits);
mainQueryBitSet.and(filterBitSet);
hits = searcher.search(mainQuery, filter, maxNumberOfMainQueryHits);
log.debug(" executeSearchWithFacets 2 = mainQuery = " + executedQuery + " filter = " + filter);
}
else
{
hits = searcher.search(mainQuery, maxNumberOfMainQueryHits);
log.debug(" executeSearchWithFacets 3 = mainQuery = " + mainQuery);
}
// determine the set of data we should use to determine facets
HashMap<String, HashMap<String, FacetResult>> possibleFacets = this.generateFacetSearches(hits, numberOfHitsToProcessForFacets, numberOfResultsToCollectForFacets, searcher);
FacetSearchHelper helper = processPossibleFacets(possibleFacets,
reader,
mainQueryBitSet,
facetResults,
hits,
numberOfIdsToCollect,
idsToCollectStartPosition,
numberOfFactsToShow,
mainQueryString,
searcher);
helper.setExecutedQuery(executedQuery);
helper.setFacetTrail(filters);
searcher.close();
return helper;
}
/* (non-Javadoc)
* @see edu.ur.ir.institution.InstitutionalItemSearchService#executeSearchWithFacets(java.lang.String, java.util.List, java.lang.String, int, int, int, edu.ur.ir.institution.InstitutionalCollection)
*/
public FacetSearchHelper executeSearchWithFacets(
String mainQueryString,
List<FacetFilter> filters,
String indexFolder,
int numberOfHitsToProcessForFacets,
int numberOfResultsToCollectForFacets,
int numberOfFactsToShow,
int numberOfIdsToCollect,
int idsToCollectStartPosition,
InstitutionalCollection collection)
throws CorruptIndexException, IOException, ParseException {
if( searchDirectoryIsEmpty(indexFolder) || isInvalidQuery(mainQueryString))
{
return new FacetSearchHelper(new HashSet<Long>(), 0, new HashMap<String, Collection<FacetResult>>(), mainQueryString);
}
IndexSearcher searcher = new IndexSearcher(indexFolder);
IndexReader reader = searcher.getIndexReader();
QueryParser parser = new MultiFieldQueryParser(fields, analyzer);
parser.setDefaultOperator(QueryParser.AND_OPERATOR);
HashMap<String, Collection<FacetResult>> facetResults = new HashMap<String, Collection<FacetResult>>();
// execute the main query - we will use this to extract data to determine the facet searches
String executedQuery = SearchHelper.prepareMainSearchString(mainQueryString, false);
Query mainQuery = parser.parse(executedQuery);
if( log.isDebugEnabled() )
{
log.debug("parsed query = " + executedQuery);
}
//create a filter for the main query
QueryWrapperFilter mainQueryWrapper = new QueryWrapperFilter(mainQuery);
// get the bitset for main query
DocIdSet mainQueryBits = mainQueryWrapper.getDocIdSet(reader);
TopDocs hits = null;
List<Filter> luceneFilters = new LinkedList<Filter>();
if( filters.size() > 0 )
{
// create a filter that will match the main query plus all other filters
luceneFilters.addAll(getSubQueryFilters(filters, searcher));
}
// add filters for the collection first
luceneFilters.addAll(0, getCollectionFilters(collection));
Filter filter = new ChainedFilter(luceneFilters.toArray(new Filter[luceneFilters.size()]), ChainedFilter.AND);
if(log.isDebugEnabled())
{
log.debug("filter = " + filter);
}
// get the filter query doc id set
DocIdSet filterQueryBits = filter.getDocIdSet(reader);
// apply the facets and include them in the main query bit set
OpenBitSetDISI mainQueryBitSet = new OpenBitSetDISI(mainQueryBits.iterator(), maxNumberOfMainQueryHits);
OpenBitSetDISI filterBitSet = new OpenBitSetDISI(filterQueryBits.iterator(), maxNumberOfMainQueryHits);
mainQueryBitSet.and(filterBitSet);
hits = searcher.search(mainQuery, filter, maxNumberOfMainQueryHits);
log.debug(" executeSearchWithFacets 4 = mainQuery = " + mainQuery + " filter = " + filter);
// determine the set of data we should use to determine facets
HashMap<String, HashMap<String, FacetResult>> possibleFacets = this.generateFacetSearches(hits, numberOfHitsToProcessForFacets, numberOfResultsToCollectForFacets, searcher);
FacetSearchHelper helper = processPossibleFacets(possibleFacets,
reader,
mainQueryBitSet,
facetResults,
hits,
numberOfIdsToCollect,
idsToCollectStartPosition,
numberOfFactsToShow,
mainQueryString,
searcher);
helper.setFacetTrail(filters);
helper.setExecutedQuery(executedQuery);
searcher.close();
return helper;
}
/**
* Execute the sub query facets and return the search results
* @throws ParseException
* @throws IOException
*/
private List<Filter> getSubQueryFilters( List<FacetFilter> filters,
IndexSearcher searcher) throws ParseException, IOException
{
List<Filter> luceneFilters = new LinkedList<Filter>();
for(FacetFilter filter : filters)
{
if(log.isDebugEnabled())
{
log.debug("adding filter for field " + filter.getField() + " and query " + filter.getQuery());
}
QueryParser subQueryParser = new QueryParser(filter.getField(), analyzer);
subQueryParser.setDefaultOperator(QueryParser.AND_OPERATOR);
Query subQuery = subQueryParser.parse(SearchHelper.prepareFacetSearchString(filter.getQuery(), false));
if(log.isDebugEnabled())
{
log.debug("sub query is " + subQuery);
}
luceneFilters.add(new QueryWrapperFilter(subQuery));
}
return luceneFilters;
}
/**
* Process the possible facets and determine the number of hits for each facet accross the main query.
*
* @param possibleFacets - possible facets to show to the user
* @param reader - lucene reader
* @param mainQueryBits - bitset from the main query
* @param facetResults - set of facet results
* @param hits - number of hits
* @param numberOfIdsToCollect - number of ids to collect and show to user
* @param mainQueryString - main query
*
* @return - search helper
* @throws ParseException
* @throws IOException
*/
private FacetSearchHelper processPossibleFacets(HashMap<String, HashMap<String, FacetResult>> possibleFacets,
IndexReader reader,
OpenBitSetDISI mainQueryBits,
HashMap<String,
Collection<FacetResult>> facetResults,
TopDocs hits,
int numberOfIdsToCollect,
int idsToCollectStartPosition,
int numberOfFacetsToShow,
String mainQueryString,
IndexSearcher searcher) throws ParseException, IOException
{
FacetResultHitComparator facetResultHitComparator = new FacetResultHitComparator();
// get the authors and create a facet for each author
// determine the number of hits the author has in the main query
HashMap<String, FacetResult> authorFacetMap = possibleFacets.get(AUTHOR_MAP);
LinkedList<FacetResult> authorFacets = new LinkedList<FacetResult>();
authorFacets.addAll(authorFacetMap.values());
processFacetCategory(authorFacets, reader, mainQueryBits, searcher);
Collections.sort(authorFacets, facetResultHitComparator );
// final holder of facets
LinkedList<FacetResult> finalAuthorFacets;
if( authorFacets.size() < numberOfFacetsToShow )
{
finalAuthorFacets = authorFacets;
}
else
{
finalAuthorFacets = new LinkedList<FacetResult>();
for( int index = 0; index < numberOfFacetsToShow; index++ )
{
finalAuthorFacets.add(authorFacets.get(index));
}
}
facetResults.put(AUTHOR_MAP,finalAuthorFacets);
// get the subjects and create a facet for each subject
// determine the number of hits the subject has in the main query
HashMap<String, FacetResult> subjectFacetMap = possibleFacets.get(SUBJECT_MAP);
LinkedList<FacetResult> subjectFacets = new LinkedList<FacetResult>();
subjectFacets.addAll(subjectFacetMap.values());
processFacetCategory(subjectFacets, reader, mainQueryBits, searcher);
Collections.sort(subjectFacets, facetResultHitComparator);
// final holder of facets
LinkedList<FacetResult> finalSubjectFacets;
if( subjectFacets.size() < numberOfFacetsToShow )
{
finalSubjectFacets = subjectFacets;
}
else
{
finalSubjectFacets = new LinkedList<FacetResult>();
for( int index = 0; index < numberOfFacetsToShow; index++ )
{
finalSubjectFacets.add(subjectFacets.get(index));
}
}
facetResults.put(SUBJECT_MAP, finalSubjectFacets);
// get the language and create a facet for each language
// determine the number of hits the language has in the main query
HashMap<String, FacetResult> languageFacetMap = possibleFacets.get(LANGUAGE_MAP);
LinkedList<FacetResult> languageFacets = new LinkedList<FacetResult>();
languageFacets.addAll(languageFacetMap.values());
processFacetCategory(languageFacets, reader, mainQueryBits, searcher);
Collections.sort(languageFacets, facetResultHitComparator);
// final holder of facets
LinkedList<FacetResult> finalLanguageFacets;
if( languageFacets.size() < numberOfFacetsToShow )
{
finalLanguageFacets = languageFacets;
}
else
{
finalLanguageFacets = new LinkedList<FacetResult>();
for( int index = 0; index < numberOfFacetsToShow; index++ )
{
finalLanguageFacets.add(languageFacets.get(index));
}
}
facetResults.put(LANGUAGE_MAP, finalLanguageFacets);
// get the format and create a facet for each format
// determine the number of hits the format has in the main query
HashMap<String, FacetResult> formatFacetMap = possibleFacets.get(FORMAT_MAP);
LinkedList<FacetResult> formatFacets = new LinkedList<FacetResult>();
formatFacets.addAll(formatFacetMap.values());
processFacetCategory(formatFacets, reader, mainQueryBits, searcher);
Collections.sort(formatFacets, facetResultHitComparator);
// final holder of facets
LinkedList<FacetResult> finalFormatFacets;
if( formatFacets.size() < numberOfFacetsToShow )
{
finalFormatFacets = formatFacets;
}
else
{
finalFormatFacets = new LinkedList<FacetResult>();
for( int index = 0; index < numberOfFacetsToShow; index++ )
{
finalFormatFacets.add(formatFacets.get(index));
}
}
facetResults.put(FORMAT_MAP, finalFormatFacets);
// get the format and create a facet for each format
// determine the number of hits the format has in the main query
HashMap<String, FacetResult> collectionFacetMap = possibleFacets.get(COLLECTION_MAP);
LinkedList<FacetResult> collectionFacets = new LinkedList<FacetResult>();
collectionFacets.addAll(collectionFacetMap.values());
processFacetCategory(collectionFacets, reader, mainQueryBits, searcher);
Collections.sort(collectionFacets, facetResultHitComparator);
// final holder of facets
LinkedList<FacetResult> finalCollectionFacets;
if( collectionFacets.size() < numberOfFacetsToShow )
{
finalCollectionFacets = collectionFacets;
}
else
{
finalCollectionFacets = new LinkedList<FacetResult>();
for( int index = 0; index < numberOfFacetsToShow; index++ )
{
finalCollectionFacets.add(collectionFacets.get(index));
}
}
facetResults.put(COLLECTION_MAP, finalCollectionFacets);
HashSet<Long> ids = new HashSet<Long>();
// end position of id's to collect will be start position plus the number to collect
int endPosition = idsToCollectStartPosition + numberOfIdsToCollect;
// make sure that the end position is set up correctly
if(hits.totalHits < endPosition )
{
endPosition = hits.totalHits;
}
for( int index = idsToCollectStartPosition; index < endPosition; index ++ )
{
Document doc = searcher.doc(hits.scoreDocs[index].doc, new LoadFirstFieldSelector());
ids.add(NumberTools.stringToLong(doc.get(DefaultInstitutionalItemIndexService.ID)));
}
FacetSearchHelper helper = new FacetSearchHelper(ids, hits.totalHits, facetResults, mainQueryString);
return helper;
}
/**
* Determine if the search directory is empty.
*
* @param indexFolder
* @return
*/
private boolean searchDirectoryIsEmpty(String indexFolder )
{
File indexFolderLocation = new File(indexFolder);
if( indexFolderLocation.isDirectory() && indexFolderLocation.exists())
{
// do not search if the folder is empty
String[] files = indexFolderLocation.list();
if( files == null || files.length <= 0 )
{
log.debug("no index files found");
return true;
}
return false;
}
else
{
log.debug("search directory is not a directory or does not exist " + indexFolder);
return true;
}
}
private boolean isInvalidQuery(String mainQuery)
{
log.debug("check to see if problem with main query " + mainQuery);
return (mainQuery == null || mainQuery.trim().equals("") || mainQuery.trim().equals("*"));
}
/* (non-Javadoc)
* @see edu.ur.ir.institution.InstitutionalItemSearchService#executeSearchWithFacets(java.lang.String, java.lang.String, int, int, int, edu.ur.ir.institution.InstitutionalCollection)
*/
public FacetSearchHelper executeSearchWithFacets(
String mainQueryString,
String indexFolder,
int numberOfHitsToProcessForFacets,
int numberOfResultsToCollectForFacets,
int numberOfFactsToShow,
int numberOfIdsToCollect,
int idsToCollectStartPosition,
InstitutionalCollection collection) throws CorruptIndexException,
IOException, ParseException
{
log.debug("execute search with facets for a collection");
if( searchDirectoryIsEmpty(indexFolder) || isInvalidQuery(mainQueryString))
{
log.debug("problem with search!");
return new FacetSearchHelper(new HashSet<Long>(), 0, new HashMap<String, Collection<FacetResult>>(), mainQueryString);
}
IndexSearcher searcher = new IndexSearcher(indexFolder);
IndexReader reader = searcher.getIndexReader();
QueryParser parser = new MultiFieldQueryParser(fields, analyzer);
parser.setDefaultOperator(QueryParser.AND_OPERATOR);
HashMap<String, Collection<FacetResult>> facetResults = new HashMap<String, Collection<FacetResult>>();
// execute the main query - we will use this to extract data to determine the facet searches
String executedQuery = SearchHelper.prepareMainSearchString(mainQueryString, false);
Query mainQuery = parser.parse(executedQuery);
Filter[] aFilters = this.getCollectionFilters(collection).toArray(new Filter[2]);
Filter chainedFilter = new ChainedFilter(aFilters, ChainedFilter.AND);
//create a filter for the main query
QueryWrapperFilter mainQueryWrapper = new QueryWrapperFilter(mainQuery);
// get the bitset for main query
DocIdSet mainQueryBits = mainQueryWrapper.getDocIdSet(reader);
// get the filter query doc id set
DocIdSet filterQueryBits = chainedFilter.getDocIdSet(reader);
// apply the filters for the collection root and range
OpenBitSetDISI mainQueryBitSet = new OpenBitSetDISI(mainQueryBits.iterator(), maxNumberOfMainQueryHits);
OpenBitSetDISI filterBitSet = new OpenBitSetDISI(filterQueryBits.iterator(), maxNumberOfMainQueryHits);
mainQueryBitSet.and(filterBitSet);
log.debug(" executeSearchWithFacets 5 = mainQuery = " + mainQuery + " filter = " + chainedFilter);
TopDocs hits = null;
hits = searcher.search(mainQuery, chainedFilter, maxNumberOfMainQueryHits);
// determine the set of data we should use to determine facets
HashMap<String, HashMap<String, FacetResult>> possibleFacets = this.generateFacetSearches(hits,
numberOfHitsToProcessForFacets,
numberOfResultsToCollectForFacets,
searcher);
// process the data and determine the facets
FacetSearchHelper helper = processPossibleFacets(possibleFacets,
reader,
mainQueryBitSet,
facetResults,
hits,
numberOfIdsToCollect,
idsToCollectStartPosition,
numberOfFactsToShow,
mainQueryString,
searcher);
helper.setExecutedQuery(executedQuery);
searcher.close();
return helper;
}
/**
* Set up the filters for collections - this is for searching within collections.
*
* @param collection - to search within
* @return - created filter
* @throws ParseException
*/
private List<Filter> getCollectionFilters(InstitutionalCollection collection) throws ParseException
{
List<Filter> filters = new LinkedList<Filter>();
//isolate the collection root
QueryParser subQueryParser = new QueryParser("collection_root_id", analyzer);
subQueryParser.setDefaultOperator(QueryParser.AND_OPERATOR);
Query subQuery = subQueryParser.parse(NumberTools.longToString(collection.getTreeRoot().getId()));
filters.add(new QueryWrapperFilter(subQuery));
//isolate the range of children
subQueryParser = new QueryParser("collection_left_value", analyzer);
subQueryParser.setDefaultOperator(QueryParser.AND_OPERATOR);
subQuery = subQueryParser.parse("[" + NumberTools.longToString(collection.getLeftValue()) + " TO " + NumberTools.longToString(collection.getRightValue()) + "]" );
filters.add(new QueryWrapperFilter(subQuery));
return filters;
}
/**
* Maxmimum number of main query hits to retrieve.
*
* @return
*/
public int getMaxNumberOfMainQueryHits() {
return maxNumberOfMainQueryHits;
}
/**
* Maximum number of main query hits to retrieve
*
* @param maxNumberOfMainQueryHits
*/
public void setMaxNumberOfMainQueryHits(int maxNumberOfMainQueryHits) {
this.maxNumberOfMainQueryHits = maxNumberOfMainQueryHits;
}
}
|
fixed to use field selector
|
ir_service/src/edu/ur/ir/institution/service/DefaultInstitutionalItemSearchService.java
|
fixed to use field selector
|
|
Java
|
apache-2.0
|
b51ebe9b50034989f19ae7c2da61c81bcc9672e8
| 0
|
thusithathilina/carbon-transports,chanakaudaya/carbon-transports,bsenduran/carbon-transports,wggihan/carbon-transports,wso2/carbon-transports,shafreenAnfar/carbon-transports
|
package org.wso2.carbon.transport.http.netty.internal;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
import org.wso2.carbon.messaging.CarbonTransportServerInitializer;
import java.util.Map;
/**
* OSGi declarative service for initializer.
* @since 5.0.0
*/
@Component(
name = "org.wso2.carbon.transport.http.netty.internal.CarbonTransportServiceComponent",
immediate = true
)
public class CarbonTransportServiceComponent {
public static final String CHANNEL_ID_KEY = "channel.id";
@Reference(
name = "transport-initializer",
service = CarbonTransportServerInitializer.class,
cardinality = ReferenceCardinality.OPTIONAL,
policy = ReferencePolicy.DYNAMIC,
unbind = "removeTransportInitializer"
)
protected void addTransportInitializer(CarbonTransportServerInitializer serverInitializer, Map<String, ?> ref) {
NettyTransportDataHolder.getInstance().removeNettyChannelInitializer((String) ref.get(CHANNEL_ID_KEY));
NettyTransportDataHolder.getInstance()
.addNettyChannelInitializer((String) ref.get(CHANNEL_ID_KEY), serverInitializer);
}
protected void removeTransportInitializer(CarbonTransportServerInitializer serverInitializer) {
//// TODO: 11/30/15
}
}
|
http/netty/component/src/main/java/org/wso2/carbon/transport/http/netty/internal/CarbonTransportServiceComponent.java
|
package org.wso2.carbon.transport.http.netty.internal;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
import org.wso2.carbon.messaging.CarbonTransportServerInitializer;
import java.util.Map;
/**
* OSGi declarative service for initializer.
* @since 5.0.0
*/
@Component(
name = "org.wso2.carbon.messaging.service.MessagingServiceComponent",
immediate = true
)
public class CarbonTransportServiceComponent {
public static final String CHANNEL_ID_KEY = "channel.id";
@Reference(
name = "transport-initializer",
service = CarbonTransportServerInitializer.class,
cardinality = ReferenceCardinality.OPTIONAL,
policy = ReferencePolicy.DYNAMIC,
unbind = "removeTransportInitializer"
)
protected void addTransportInitializer(CarbonTransportServerInitializer serverInitializer, Map<String, ?> ref) {
NettyTransportDataHolder.getInstance()
.addNettyChannelInitializer((String) ref.get(CHANNEL_ID_KEY), serverInitializer);
}
protected void removeTransportInitializer(CarbonTransportServerInitializer serverInitializer) {
//// TODO: 11/30/15
}
}
|
component name modified
|
http/netty/component/src/main/java/org/wso2/carbon/transport/http/netty/internal/CarbonTransportServiceComponent.java
|
component name modified
|
|
Java
|
apache-2.0
|
7083bcad03481f0284560845d77e0f68479e94ba
| 0
|
stephanenicolas/toothpick,stephanenicolas/toothpick,stephanenicolas/toothpick
|
package toothpick;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.Map;
import javax.inject.Provider;
import toothpick.config.Binding;
import toothpick.config.Module;
import toothpick.registries.factory.FactoryRegistryLocator;
import static java.lang.String.format;
/**
* {@inheritDoc}
* <p>
* A note on concurrency :
* <ul>
* <li> all operations related to the scope tree are synchronized on the {@code ToothPick} class.
* <li> all operations related to a scope's content (binding & providers) are synchronized on the key (class) of the binding/injection.
* <li> all providers provided by the public API (including Lazy) should return a thread safe provider (done)
* but internally, we can live with a non synchronized provider.
* </ul>
* <em>All operations on the scope itself are non thread-safe. They <em>must</em> be used via the {@code ToothPick} class
* or <em>must</em> be synchronized using the {@code ToothPick} class if used concurrently.</em>
* </p>
*/
public class ScopeImpl extends Scope {
private static IdentityHashMap<Class, UnNamedAndNamedProviders> mapClassesToUnBoundProviders = new IdentityHashMap<>();
protected IdentityHashMap<Class, UnNamedAndNamedProviders> mapClassesToAllProviders = new IdentityHashMap<>();
private boolean hasTestModules;
public ScopeImpl(Object name) {
super(name);
//it's always possible to get access to the scope that conitains an injected object.
installBoundProvider(Scope.class, null, new InternalProviderImpl<>(this));
}
@Override
public <T> T getInstance(Class<T> clazz) {
return lookupProvider(clazz, null).get(this);
}
@Override
public <T> T getInstance(Class<T> clazz, String name) {
return lookupProvider(clazz, name).get(this);
}
@Override
public <T> Provider<T> getProvider(Class<T> clazz) {
InternalProviderImpl<? extends T> provider = lookupProvider(clazz, null);
return new ThreadSafeProviderImpl<>(this, provider, false);
}
@Override
public <T> Provider<T> getProvider(Class<T> clazz, String name) {
InternalProviderImpl<? extends T> provider = lookupProvider(clazz, name);
return new ThreadSafeProviderImpl<>(this, provider, false);
}
@Override
public <T> Lazy<T> getLazy(Class<T> clazz) {
InternalProviderImpl<? extends T> provider = lookupProvider(clazz, null);
return new ThreadSafeProviderImpl<>(this, provider, true);
}
@Override
public <T> Lazy<T> getLazy(Class<T> clazz, String name) {
InternalProviderImpl<? extends T> provider = lookupProvider(clazz, name);
return new ThreadSafeProviderImpl<>(this, provider, true);
}
@Override
public void installTestModules(Module... modules) {
//we allow multiple calls to this method
boolean oldHasTestModules = hasTestModules;
hasTestModules = false;
installModules(modules);
boolean doOverrideModulesExist = modules != null;
hasTestModules = oldHasTestModules || doOverrideModulesExist;
}
@Override
public void installModules(Module... modules) {
for (Module module : modules) {
installModule(module);
}
}
@Override
public String toString() {
final String branch = "---";
final char lastNode = '\\';
final char node = '+';
final String indent = " ";
StringBuilder builder = new StringBuilder();
builder.append(name);
builder.append(':');
builder.append(System.identityHashCode(this));
builder.append('\n');
builder.append("Providers: [");
for (Class aClass : mapClassesToAllProviders.keySet()) {
builder.append(aClass.getName());
builder.append(',');
}
builder.deleteCharAt(builder.length() - 1);
builder.append(']');
builder.append('\n');
Iterator<Scope> iterator = childrenScopes.iterator();
while (iterator.hasNext()) {
Scope scope = iterator.next();
boolean isLast = !iterator.hasNext();
builder.append(isLast ? lastNode : node);
builder.append(branch);
String childString = scope.toString();
String[] split = childString.split("\n");
for (int i = 0; i < split.length; i++) {
String childLine = split[i];
if (i != 0) {
builder.append(indent);
}
builder.append(childLine);
builder.append('\n');
}
}
builder.append("UnScoped providers : [");
for (Class aClass : mapClassesToUnBoundProviders.keySet()) {
builder.append(aClass.getName());
builder.append(',');
}
builder.deleteCharAt(builder.length() - 1);
builder.append(']');
builder.append('\n');
return builder.toString();
}
private void installModule(Module module) {
for (Binding binding : module.getBindingSet()) {
if (binding == null) {
throw new IllegalStateException("A module can't have a null binding.");
}
Class clazz = binding.getKey();
synchronized (clazz) {
String bindingName = binding.getName();
if (!hasTestModules || getBoundProvider(clazz, bindingName) == null) {
InternalProviderImpl provider = toProvider(binding);
if (binding.isScoped()) {
installScopedProvider(clazz, bindingName, (ScopedProviderImpl) provider);
} else {
installBoundProvider(clazz, bindingName, provider);
}
}
}
}
}
//do not change the return type to Provider<? extends T>.
//it would be cool and more convenient for bindings, but it would
//make the APIs very unstable as you could not get any instance of the
//implementation class via an scope, it would fail but be syntactically valid.
//only creating an instance of the interface is valid with this syntax.
/*VisibleForTesting*/ <T> InternalProviderImpl<T> toProvider(Binding<T> binding) {
if (binding == null) {
throw new IllegalStateException("null binding are not allowed. Should not happen unless getBindingSet is overridden.");
}
switch (binding.getMode()) {
case SIMPLE:
return createInternalProvider(this, binding.getKey(), false, binding.isScoped());
case CLASS:
return createInternalProvider(this, binding.getImplementationClass(), false, binding.isScoped());
case INSTANCE:
return new InternalProviderImpl<>(binding.getInstance());
case PROVIDER_INSTANCE:
// to ensure providers do not have to deal with concurrency, we wrap them in a thread safe provider
// We do not need to pass the scope here because the provider won't use any scope to create the instance
return new InternalProviderImpl<>(binding.getProviderInstance(), false);
case PROVIDER_CLASS:
return createInternalProvider(this, binding.getProviderClass(), true, binding.isScoped());
//JACOCO:OFF
default:
throw new IllegalStateException(format("mode is not handled: %s. This should not happen.", binding.getMode()));
//JACOCO:ON
}
}
private <T> InternalProviderImpl<T> createInternalProvider(Scope scope, Class<?> factoryKeyClass, boolean isProviderClass, boolean isScoped) {
if (isScoped) {
return new ScopedProviderImpl<>(scope, factoryKeyClass, isProviderClass);
} else {
return new InternalProviderImpl<>(factoryKeyClass, isProviderClass);
}
}
/**
* The core of Toothpick internals : the provider lookup.
* It will look for a scoped provider, bubbling up in the scope hierarchy.
* If one is found, we return it. If not, we look in the un-scoped provider pool,
* if one is found, we return it. If not, we create a provider dynamically, using a factory. Depending
* on the whether or not the discovered factory for this class is scoped (={@link javax.inject.Scope} annotated),
* the provider will be scoped or not. If it is scoped, it will be scoped in the appropriate scope, if not
* it will be added to the pool of un-scoped providers.
* Note that
*
* @param clazz the {@link Class} of {@code T} for which we lookup an {@link InternalProviderImpl}.
* @param bindingName the potential name of the provider when it was bound (which means we always returned a scoped provider if
* name is not null).
* @param <T> the type for which we lookup an {@link InternalProviderImpl}.
* @return a provider associated to the {@code T}. The returned provider is un-scoped (remember that {@link ScopedProviderImpl} is a subclass of
* {@link InternalProviderImpl}). The returned provider will be scoped by the public methods to use the current scope.
*/
private <T> InternalProviderImpl<? extends T> lookupProvider(Class<T> clazz, String bindingName) {
if (clazz == null) {
throw new IllegalArgumentException("TP can't get an instance of a null class.");
}
synchronized (clazz) {
InternalProviderImpl<? extends T> scopedProvider = getBoundProvider(clazz, bindingName);
if (scopedProvider != null) {
return scopedProvider;
}
Iterator<Scope> iterator = parentScopes.iterator();
while (iterator.hasNext()) {
Scope parentScope = iterator.next();
ScopeImpl parentScopeImpl = (ScopeImpl) parentScope;
InternalProviderImpl<? extends T> parentScopedProvider = parentScopeImpl.getBoundProvider(clazz, bindingName);
if (parentScopedProvider != null) {
return parentScopedProvider;
}
}
//check if we have a cached un-scoped provider
InternalProviderImpl unScopedProviderInPool = getUnBoundProvider(clazz, bindingName);
if (unScopedProviderInPool != null) {
return unScopedProviderInPool;
}
//classes discovered at runtime, not bound by any module
//they will be a bit slower as we need to get the factory first
//we need to know whether they are scoped or not, if so we scope them
//if not, they are place in the pool
Factory<T> factory = FactoryRegistryLocator.getFactory(clazz);
Scope targetScope = factory.getTargetScope(this);
ScopeImpl targetScopeImpl = (ScopeImpl) targetScope;
if (factory.hasScopeAnnotation()) {
//the new provider will have to work in the current scope
final ScopedProviderImpl<T> newProvider = new ScopedProviderImpl<>(targetScope, factory, false);
//it is bound to its target scope only if it has a scope annotation.
targetScopeImpl.installScopedProvider(clazz, bindingName, newProvider);
return newProvider;
} else {
//the provider is but in a pool of unbound providers for later reuse
final InternalProviderImpl<T> newProvider = new InternalProviderImpl<>(factory, false);
//the pool is static as it is accessible from all scopes
installUnBoundProvider(clazz, bindingName, newProvider);
return newProvider;
}
}
}
/**
* Obtains the provider of the class {@code clazz} and name {@code bindingName}, if any. The returned provider
* will be bound to the scope. It can be {@code null} if there is no such provider.
* Ancestors are not taken into account.
*
* @param clazz the class for which to obtain the bound provider.
* @param bindingName the name, possibly {@code null}, for which to obtain the bound provider.
* @param <T> the type of {@code clazz}.
* @return the bound provider for class {@code clazz} and {@code bindingName}. Returns {@code null} is there
* is no such bound provider.
*/
private <T> InternalProviderImpl<? extends T> getBoundProvider(Class<T> clazz, String bindingName) {
return getInternalProvider(clazz, bindingName, true);
}
/**
* Obtains the provider of the class {@code clazz} and name {@code bindingName}, if any. The returned provider
* will belong to the pool of unbound providers. It can be {@code null} if there is no such provider.
*
* @param clazz the class for which to obtain the unbound provider.
* @param bindingName the name, possibly {@code null}, for which to obtain the unbound provider.
* @param <T> the type of {@code clazz}.
* @return the unbound provider for class {@code clazz} and {@code bindingName}. Returns {@code null} is there
* is no such unbound provider.
*/
private <T> InternalProviderImpl<? extends T> getUnBoundProvider(Class<T> clazz, String bindingName) {
return getInternalProvider(clazz, bindingName, false);
}
/**
* Obtains the provider of the class {@code clazz} and name {@code bindingName}. The returned provider
* can either be bound to the scope or not depending on {@code isBound}.
* Ancestors are not taken into account.
*
* @param clazz the class for which to obtain the provider.
* @param bindingName the name, possibly {@code null}, for which to obtain the provider.
* @param <T> the type of {@code clazz}.
* @return the provider for class {@code clazz} and {@code bindingName},
* either from the set of providers bound to the scope or from the pool of unbound providers.
* If there is no such provider, returns {@code null}.
*
* Note to maintainers : we don't use this method directly, both {@link #getBoundProvider} and {@link #getUnBoundProvider}
* are a facade of this method and make the calls more clear.
*/
private <T> InternalProviderImpl<? extends T> getInternalProvider(Class<T> clazz, String bindingName, boolean isBound) {
Map<Class, UnNamedAndNamedProviders> map;
if (isBound) {
map = mapClassesToAllProviders;
} else {
map = mapClassesToUnBoundProviders;
}
synchronized (clazz) {
UnNamedAndNamedProviders<T> unNamedAndNamedProviders = map.get(clazz);
if (unNamedAndNamedProviders == null) {
return null;
}
if (bindingName == null) {
return unNamedAndNamedProviders.unNamedProvider;
}
Map<String, InternalProviderImpl<? extends T>> mapNameToProvider = unNamedAndNamedProviders.getMapNameToProvider();
if (mapNameToProvider == null) {
return null;
}
return mapNameToProvider.get(bindingName);
}
}
/**
* Install the provider of the class {@code clazz} and name {@code bindingName}
* in the current scope.
*
* @param clazz the class for which to install the scoped provider of this scope.
* @param bindingName the name, possibly {@code null}, for which to install the scoped provider.
* @param <T> the type of {@code clazz}.
*/
private <T> void installScopedProvider(Class<T> clazz, String bindingName, ScopedProviderImpl<? extends T> scopedProvider) {
installBoundProvider(clazz, bindingName, scopedProvider);
}
/**
* Install the provider of the class {@code clazz} and name {@code bindingName}
* in the current scope.
*
* @param clazz the class for which to install the scoped provider.
* @param bindingName the name, possibly {@code null}, for which to install the scoped provider.
* @param <T> the type of {@code clazz}.
*/
private <T> void installBoundProvider(Class<T> clazz, String bindingName, InternalProviderImpl<? extends T> internalProvider) {
installInternalProvider(clazz, bindingName, internalProvider, true);
}
/**
* Install the provider of the class {@code clazz} and name {@code bindingName}
* in the pool of unbound providers.
*
* @param clazz the class for which to install the provider.
* @param bindingName the name, possibly {@code null}, for which to install the scoped provider.
* @param <T> the type of {@code clazz}.
*/
private <T> void installUnBoundProvider(Class<T> clazz, String bindingName, InternalProviderImpl<? extends T> internalProvider) {
installInternalProvider(clazz, bindingName, internalProvider, false);
}
/**
* Installs a provider either in the scope or the pool of unbound providers.
*
* @param clazz the class for which to install the provider.
* @param bindingName the name, possibly {@code null}, for which to install the scoped provider.
* @param internalProvider the internal provider to install.
* @param isBound whether or not the provider is bound to the scope or belongs to the pool of unbound providers
* @param <T> the type of {@code clazz}.
*
* Note to maintainers : we don't use this method directly, both {@link #installBoundProvider(Class, String, InternalProviderImpl)}
* and {@link #installUnBoundProvider(Class, String, InternalProviderImpl)}
* are a facade of this method and make the calls more clear.
*/
private <T> void installInternalProvider(Class<T> clazz, String bindingName, InternalProviderImpl<? extends T> internalProvider, boolean isBound) {
Map<Class, UnNamedAndNamedProviders> map;
if (isBound) {
map = mapClassesToAllProviders;
} else {
map = mapClassesToUnBoundProviders;
}
synchronized (clazz) {
UnNamedAndNamedProviders<T> unNamedAndNamedProviders = map.get(clazz);
if (unNamedAndNamedProviders == null) {
unNamedAndNamedProviders = new UnNamedAndNamedProviders<>();
map.put(clazz, unNamedAndNamedProviders);
}
if (bindingName == null) {
unNamedAndNamedProviders.setUnNamedProvider(internalProvider);
} else {
Map<String, InternalProviderImpl<? extends T>> mapNameToProvider = unNamedAndNamedProviders.getMapNameToProvider();
if (mapNameToProvider == null) {
mapNameToProvider = new HashMap<>();
unNamedAndNamedProviders.setMapNameToProvider(mapNameToProvider);
}
mapNameToProvider.put(bindingName, internalProvider);
}
}
}
private static class UnNamedAndNamedProviders<T> {
private InternalProviderImpl<? extends T> unNamedProvider;
private Map<String, InternalProviderImpl<? extends T>> mapNameToProvider;
public Map<String, InternalProviderImpl<? extends T>> getMapNameToProvider() {
return mapNameToProvider;
}
public void setMapNameToProvider(Map<String, InternalProviderImpl<? extends T>> mapNameToProvider) {
this.mapNameToProvider = mapNameToProvider;
}
public void setUnNamedProvider(InternalProviderImpl<? extends T> unNamedProvider) {
this.unNamedProvider = unNamedProvider;
}
}
static void reset() {
mapClassesToUnBoundProviders.clear();
}
}
|
toothpick-runtime/src/main/java/toothpick/ScopeImpl.java
|
package toothpick;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.Map;
import javax.inject.Provider;
import toothpick.config.Binding;
import toothpick.config.Module;
import toothpick.registries.factory.FactoryRegistryLocator;
import static java.lang.String.format;
/**
* {@inheritDoc}
* <p>
* A note on concurrency :
* <ul>
* <li> all operations related to the scope tree are synchronized on the {@code ToothPick} class.
* <li> all operations related to a scope's content (binding & providers) are synchronized on the key (class) of the binding/injection.
* <li> all providers provided by the public API (including Lazy) should return a thread safe provider (done)
* but internally, we can live with a non synchronized provider.
* </ul>
* <em>All operations on the scope itself are non thread-safe. They <em>must</em> be used via the {@code ToothPick} class
* or <em>must</em> be synchronized using the {@code ToothPick} class if used concurrently.</em>
* </p>
*/
public class ScopeImpl extends Scope {
private static IdentityHashMap<Class, UnNamedAndNamedProviders> mapClassesToUnScopedProviders = new IdentityHashMap<>();
protected IdentityHashMap<Class, UnNamedAndNamedProviders> mapClassesToAllProviders = new IdentityHashMap<>();
private boolean hasTestModules;
public ScopeImpl(Object name) {
super(name);
//it's always possible to get access to the scope that conitains an injected object.
installInternalProvider(Scope.class, null, new InternalProviderImpl<>(this), true);
}
@Override
public <T> T getInstance(Class<T> clazz) {
return getProviderInternal(clazz, null).get(this);
}
@Override
public <T> T getInstance(Class<T> clazz, String name) {
return getProviderInternal(clazz, name).get(this);
}
@Override
public <T> Provider<T> getProvider(Class<T> clazz) {
InternalProviderImpl<? extends T> provider = getProviderInternal(clazz, null);
return new ThreadSafeProviderImpl<>(this, provider, false);
}
@Override
public <T> Provider<T> getProvider(Class<T> clazz, String name) {
InternalProviderImpl<? extends T> provider = getProviderInternal(clazz, name);
return new ThreadSafeProviderImpl<>(this, provider, false);
}
@Override
public <T> Lazy<T> getLazy(Class<T> clazz) {
InternalProviderImpl<? extends T> provider = getProviderInternal(clazz, null);
return new ThreadSafeProviderImpl<>(this, provider, true);
}
@Override
public <T> Lazy<T> getLazy(Class<T> clazz, String name) {
InternalProviderImpl<? extends T> provider = getProviderInternal(clazz, name);
return new ThreadSafeProviderImpl<>(this, provider, true);
}
@Override
public void installTestModules(Module... modules) {
//we allow multiple calls to this method
boolean oldHasTestModules = hasTestModules;
hasTestModules = false;
installModules(modules);
boolean doOverrideModulesExist = modules != null;
hasTestModules = oldHasTestModules || doOverrideModulesExist;
}
@Override
public void installModules(Module... modules) {
for (Module module : modules) {
installModule(module);
}
}
@Override
public String toString() {
final String branch = "---";
final char lastNode = '\\';
final char node = '+';
final String indent = " ";
StringBuilder builder = new StringBuilder();
builder.append(name);
builder.append(':');
builder.append(System.identityHashCode(this));
builder.append('\n');
builder.append("Providers: [");
for (Class aClass : mapClassesToAllProviders.keySet()) {
builder.append(aClass.getName());
builder.append(',');
}
builder.deleteCharAt(builder.length() - 1);
builder.append(']');
builder.append('\n');
Iterator<Scope> iterator = childrenScopes.iterator();
while (iterator.hasNext()) {
Scope scope = iterator.next();
boolean isLast = !iterator.hasNext();
builder.append(isLast ? lastNode : node);
builder.append(branch);
String childString = scope.toString();
String[] split = childString.split("\n");
for (int i = 0; i < split.length; i++) {
String childLine = split[i];
if (i != 0) {
builder.append(indent);
}
builder.append(childLine);
builder.append('\n');
}
}
builder.append("UnScoped providers : [");
for (Class aClass : mapClassesToUnScopedProviders.keySet()) {
builder.append(aClass.getName());
builder.append(',');
}
builder.deleteCharAt(builder.length() - 1);
builder.append(']');
builder.append('\n');
return builder.toString();
}
private void installModule(Module module) {
for (Binding binding : module.getBindingSet()) {
if (binding == null) {
throw new IllegalStateException("A module can't have a null binding.");
}
Class clazz = binding.getKey();
synchronized (clazz) {
String bindingName = binding.getName();
if (!hasTestModules || getScopedProvider(clazz, bindingName) == null) {
InternalProviderImpl provider = toProvider(binding);
if (binding.isScoped()) {
installScopedProvider(clazz, bindingName, (ScopedProviderImpl) provider);
} else {
installInternalProvider(clazz, bindingName, provider, true);
}
}
}
}
}
//do not change the return type to Provider<? extends T>.
//it would be cool and more convenient for bindings, but it would
//make the APIs very unstable as you could not get any instance of the
//implementation class via an scope, it would fail but be syntactically valid.
//only creating an instance of the interface is valid with this syntax.
/*VisibleForTesting*/ <T> InternalProviderImpl<T> toProvider(Binding<T> binding) {
if (binding == null) {
throw new IllegalStateException("null binding are not allowed. Should not happen unless getBindingSet is overridden.");
}
switch (binding.getMode()) {
case SIMPLE:
return createInternalProvider(this, binding.getKey(), false, binding.isScoped());
case CLASS:
return createInternalProvider(this, binding.getImplementationClass(), false,
binding.isScoped());
case INSTANCE:
return new InternalProviderImpl<>(binding.getInstance());
case PROVIDER_INSTANCE:
// to ensure providers do not have to deal with concurrency, we wrap them in a thread safe provider
// We do not need to pass the scope here because the provider won't use any scope to create the instance
return new InternalProviderImpl<>(binding.getProviderInstance(), false);
case PROVIDER_CLASS:
return createInternalProvider(this, binding.getProviderClass(), true, binding.isScoped());
//JACOCO:OFF
default:
throw new IllegalStateException(format("mode is not handled: %s. This should not happen.", binding.getMode()));
//JACOCO:ON
}
}
private <T> InternalProviderImpl<T> createInternalProvider(Scope scope, Class<?> factoryKeyClass, boolean isProviderClass, boolean isScoped) {
if (isScoped) {
return new ScopedProviderImpl<>(scope, factoryKeyClass, isProviderClass);
} else {
return new InternalProviderImpl<>(factoryKeyClass, isProviderClass);
}
}
/**
* The core of Toothpick internals : the provider lookup.
* It will look for a scoped provider, bubbling up in the scope hierarchy.
* If one is found, we return it. If not, we look in the un-scoped provider pool,
* if one is found, we return it. If not, we create a provider dynamically, using a factory. Depending
* on the whether or not the discovered factory for this class is scoped (={@link javax.inject.Scope} annotated),
* the provider will be scoped or not. If it is scoped, it will be scoped in the appropriate scope, if not
* it will be added to the pool of un-scoped providers.
* Note that
*
* @param clazz the {@link Class} of {@code T} for which we lookup an {@link InternalProviderImpl}.
* @param bindingName the potential name of the provider when it was bound (which means we always returned a scoped provider if
* name is not null).
* @param <T> the type for which we lookup an {@link InternalProviderImpl}.
* @return a provider associated to the {@code T}. The returned provider is un-scoped (remember that {@link ScopedProviderImpl} is a subclass of
* {@link InternalProviderImpl}). The returned provider will be scoped by the public methods to use the current scope.
*/
private <T> InternalProviderImpl<? extends T> getProviderInternal(Class<T> clazz, String bindingName) {
if (clazz == null) {
throw new IllegalArgumentException("TP can't get an instance of a null class.");
}
synchronized (clazz) {
InternalProviderImpl<? extends T> scopedProvider = getScopedProvider(clazz, bindingName);
if (scopedProvider != null) {
return scopedProvider;
}
Iterator<Scope> iterator = parentScopes.iterator();
while (iterator.hasNext()) {
Scope parentScope = iterator.next();
ScopeImpl parentScopeImpl = (ScopeImpl) parentScope;
InternalProviderImpl<? extends T> parentScopedProvider = parentScopeImpl.getScopedProvider(clazz, bindingName);
if (parentScopedProvider != null) {
return parentScopedProvider;
}
}
//check if we have a cached un-scoped provider
InternalProviderImpl unScopedProviderInPool = getUnscopedProvider(clazz, bindingName);
if (unScopedProviderInPool != null) {
return unScopedProviderInPool;
}
//classes discovered at runtime, not bound by any module
//they will be a bit slower as we need to get the factory first
//we need to know whether they are scoped or not, if so we scope them
//if not, they are place in the pool
Factory<T> factory = FactoryRegistryLocator.getFactory(clazz);
Scope targetScope = factory.getTargetScope(this);
ScopeImpl targetScopeImpl = (ScopeImpl) targetScope;
if (factory.hasScopeAnnotation()) {
//the new provider will have to work in the current scope
final ScopedProviderImpl<T> newProvider = new ScopedProviderImpl<>(targetScope, factory, false);
//it is bound to its target scope only if it has a scope annotation.
targetScopeImpl.installScopedProvider(clazz, bindingName, newProvider);
return newProvider;
} else {
//the provider is but in a pool of unbound providers for later reuse
final InternalProviderImpl<T> newProvider = new InternalProviderImpl<>(factory, false);
//the pool is static as it is accessible from all scopes
installInternalProvider(clazz, bindingName, newProvider, false);
return newProvider;
}
}
}
private <T> InternalProviderImpl<? extends T> getScopedProvider(Class<T> clazz, String bindingName) {
return getProvider(clazz, bindingName, true);
}
private <T> InternalProviderImpl<? extends T> getUnscopedProvider(Class<T> clazz, String bindingName) {
return getProvider(clazz, bindingName, false);
}
/**
* Obtains the provider of the class {@code clazz} and name {@code bindingName}
* that is scoped in the current scope, if any.
* Ancestors are not taken into account.
*
* @param clazz the class for which to obtain the scoped provider of this scope, if one is scoped.
* @param bindingName the name, possibly {@code null}, for which to obtain the scoped provider of this scope, if one is scoped.
* @param <T> the type of {@code clazz}.
* @return the scoped provider of this scope for class {@code clazz} and {@code bindingName},
* if one is scoped, {@code null} otherwise.
*/
private <T> InternalProviderImpl<? extends T> getProvider(Class<T> clazz, String bindingName, boolean isScoped) {
Map<Class, UnNamedAndNamedProviders> map;
if (isScoped) {
map = mapClassesToAllProviders;
} else {
map = mapClassesToUnScopedProviders;
}
synchronized (clazz) {
UnNamedAndNamedProviders<T> unNamedAndNamedProviders = map.get(clazz);
if (unNamedAndNamedProviders == null) {
return null;
}
if (bindingName == null) {
return unNamedAndNamedProviders.unNamedProvider;
}
Map<String, InternalProviderImpl<? extends T>> mapNameToProvider = unNamedAndNamedProviders.getMapNameToProvider();
if (mapNameToProvider == null) {
return null;
}
return mapNameToProvider.get(bindingName);
}
}
/**
* Install the provider of the class {@code clazz} and name {@code bindingName}
* in the current scope.
*
* @param clazz the class for which to install the scoped provider of this scope.
* @param bindingName the name, possibly {@code null}, for which to install the scoped provider.
* @param <T> the type of {@code clazz}.
*/
private <T> void installScopedProvider(Class<T> clazz, String bindingName, ScopedProviderImpl<? extends T> scopedProvider) {
installInternalProvider(clazz, bindingName, scopedProvider, true);
}
private <T> void installInternalProvider(Class<T> clazz, String bindingName, InternalProviderImpl<? extends T> unScopedProvider, boolean installInScope) {
Map<Class, UnNamedAndNamedProviders> map;
if (installInScope) {
map = mapClassesToAllProviders;
} else {
map = mapClassesToUnScopedProviders;
}
synchronized (clazz) {
UnNamedAndNamedProviders<T> unNamedAndNamedProviders = map.get(clazz);
if (unNamedAndNamedProviders == null) {
unNamedAndNamedProviders = new UnNamedAndNamedProviders<>();
map.put(clazz, unNamedAndNamedProviders);
}
if (bindingName == null) {
unNamedAndNamedProviders.setUnNamedProvider(unScopedProvider);
} else {
Map<String, InternalProviderImpl<? extends T>> mapNameToProvider = unNamedAndNamedProviders.getMapNameToProvider();
if (mapNameToProvider == null) {
mapNameToProvider = new HashMap<>();
unNamedAndNamedProviders.setMapNameToProvider(mapNameToProvider);
}
mapNameToProvider.put(bindingName, unScopedProvider);
}
}
}
private static class UnNamedAndNamedProviders<T> {
private InternalProviderImpl<? extends T> unNamedProvider;
private Map<String, InternalProviderImpl<? extends T>> mapNameToProvider;
public Map<String, InternalProviderImpl<? extends T>> getMapNameToProvider() {
return mapNameToProvider;
}
public void setMapNameToProvider(Map<String, InternalProviderImpl<? extends T>> mapNameToProvider) {
this.mapNameToProvider = mapNameToProvider;
}
public void setUnNamedProvider(InternalProviderImpl<? extends T> unNamedProvider) {
this.unNamedProvider = unNamedProvider;
}
}
static void reset() {
mapClassesToUnScopedProviders.clear();
}
}
|
clean up and javadoc. Code's sweet
|
toothpick-runtime/src/main/java/toothpick/ScopeImpl.java
|
clean up and javadoc. Code's sweet
|
|
Java
|
apache-2.0
|
7dadf1faebaf3bbc2cba2673e2e965d71bc8502c
| 0
|
ahb0327/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,fitermay/intellij-community,samthor/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,samthor/intellij-community,ibinti/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,samthor/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,holmes/intellij-community,da1z/intellij-community,robovm/robovm-studio,kool79/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,consulo/consulo,ibinti/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,dslomov/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,diorcety/intellij-community,consulo/consulo,semonte/intellij-community,hurricup/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,fitermay/intellij-community,clumsy/intellij-community,robovm/robovm-studio,amith01994/intellij-community,nicolargo/intellij-community,ryano144/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,supersven/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,kool79/intellij-community,amith01994/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,caot/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,kool79/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,hurricup/intellij-community,retomerz/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,clumsy/intellij-community,da1z/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,consulo/consulo,vladmm/intellij-community,ernestp/consulo,hurricup/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,caot/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,asedunov/intellij-community,diorcety/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,caot/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,adedayo/intellij-community,allotria/intellij-community,hurricup/intellij-community,semonte/intellij-community,dslomov/intellij-community,ernestp/consulo,hurricup/intellij-community,supersven/intellij-community,holmes/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,samthor/intellij-community,fitermay/intellij-community,jagguli/intellij-community,xfournet/intellij-community,allotria/intellij-community,semonte/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,izonder/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,signed/intellij-community,holmes/intellij-community,fnouama/intellij-community,asedunov/intellij-community,vladmm/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,caot/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,retomerz/intellij-community,allotria/intellij-community,Lekanich/intellij-community,consulo/consulo,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,jagguli/intellij-community,apixandru/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,apixandru/intellij-community,ernestp/consulo,fitermay/intellij-community,ryano144/intellij-community,kdwink/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,signed/intellij-community,signed/intellij-community,kdwink/intellij-community,apixandru/intellij-community,izonder/intellij-community,da1z/intellij-community,robovm/robovm-studio,petteyg/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,amith01994/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,semonte/intellij-community,clumsy/intellij-community,holmes/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,samthor/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,ibinti/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,allotria/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,hurricup/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,supersven/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,slisson/intellij-community,semonte/intellij-community,fitermay/intellij-community,allotria/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,asedunov/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,supersven/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,signed/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,supersven/intellij-community,blademainer/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,izonder/intellij-community,consulo/consulo,orekyuu/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,slisson/intellij-community,diorcety/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,holmes/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,fnouama/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,da1z/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,caot/intellij-community,TangHao1987/intellij-community,robovm/robovm-studio,FHannes/intellij-community,caot/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,kool79/intellij-community,fnouama/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,FHannes/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,robovm/robovm-studio,allotria/intellij-community,nicolargo/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,hurricup/intellij-community,signed/intellij-community,amith01994/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,holmes/intellij-community,slisson/intellij-community,gnuhub/intellij-community,semonte/intellij-community,semonte/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,dslomov/intellij-community,samthor/intellij-community,adedayo/intellij-community,dslomov/intellij-community,hurricup/intellij-community,vladmm/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,ryano144/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,apixandru/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,supersven/intellij-community,semonte/intellij-community,xfournet/intellij-community,caot/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,slisson/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,ernestp/consulo,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,kdwink/intellij-community,fnouama/intellij-community,izonder/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,consulo/consulo,fengbaicanhe/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,signed/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,da1z/intellij-community,tmpgit/intellij-community,da1z/intellij-community,caot/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,vladmm/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,da1z/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,asedunov/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,ernestp/consulo,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,jagguli/intellij-community,signed/intellij-community,asedunov/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,hurricup/intellij-community,da1z/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,Distrotech/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,samthor/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,signed/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,caot/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,kool79/intellij-community,suncycheng/intellij-community,izonder/intellij-community,robovm/robovm-studio,pwoodworth/intellij-community,semonte/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,amith01994/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,robovm/robovm-studio,akosyakov/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,apixandru/intellij-community,kool79/intellij-community,orekyuu/intellij-community,semonte/intellij-community,signed/intellij-community,dslomov/intellij-community,holmes/intellij-community,SerCeMan/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,slisson/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,slisson/intellij-community,izonder/intellij-community,xfournet/intellij-community,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,adedayo/intellij-community,blademainer/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,diorcety/intellij-community,caot/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,ryano144/intellij-community,signed/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,supersven/intellij-community,kool79/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,samthor/intellij-community,tmpgit/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,izonder/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,akosyakov/intellij-community,holmes/intellij-community,SerCeMan/intellij-community,Distrotech/intellij-community,slisson/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,asedunov/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,ernestp/consulo,ftomassetti/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,xfournet/intellij-community,ibinti/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,amith01994/intellij-community,diorcety/intellij-community,FHannes/intellij-community,holmes/intellij-community,fitermay/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,caot/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd
|
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.wm.impl.content;
import com.intellij.openapi.ui.GraphicsConfig;
import com.intellij.openapi.ui.popup.ListPopup;
import com.intellij.ui.ColorUtil;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.ui.awt.RelativeRectangle;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentManagerEvent;
import com.intellij.util.ui.UIUtil;
import java.awt.*;
import java.awt.image.BufferedImage;
class ComboContentLayout extends ContentLayout {
ContentComboLabel myComboLabel;
private BufferedImage myImage;
ComboContentLayout(ToolWindowContentUi ui) {
super(ui);
}
@Override
public void init() {
reset();
myIdLabel = new BaseLabel(myUi, false);
myComboLabel = new ContentComboLabel(this);
}
@Override
public void reset() {
myIdLabel = null;
myComboLabel = null;
myImage = null;
}
@Override
public void layout() {
Rectangle bounds = myUi.getBounds();
Dimension idSize = isIdVisible() ? myIdLabel.getPreferredSize() : new Dimension(0, 0);
int eachX = 0;
int eachY = 0;
myIdLabel.setBounds(eachX, eachY, idSize.width, bounds.height);
eachX += idSize.width;
Dimension comboSize = myComboLabel.getPreferredSize();
int spaceLeft = bounds.width - eachX - (isToDrawCombo() && isIdVisible() ? 3 : 0);
int width = comboSize.width;
if (width > spaceLeft) {
width = spaceLeft;
}
myComboLabel.setBounds(eachX, eachY, width, bounds.height);
}
@Override
public void paintComponent(Graphics g) {
if (!isToDrawCombo()) return;
Rectangle r = myComboLabel.getBounds();
if (UIUtil.isUnderDarcula()) {
g.setColor(ColorUtil.toAlpha(UIUtil.getLabelForeground(), 20));
g.drawLine(r.width, 0, r.width, r.height);
g.setColor(ColorUtil.toAlpha(UIUtil.getBorderColor(), 50));
g.drawLine(r.width-1, 0, r.width-1, r.height);
return;
}
if (myImage == null || myImage.getHeight() != r.height || myImage.getWidth() != r.width) {
myImage = new BufferedImage(r.width, r.height, BufferedImage.TYPE_INT_ARGB);
final Graphics2D g2d = myImage.createGraphics();
final GraphicsConfig c = new GraphicsConfig(g);
c.setAntialiasing(true);
g2d.setPaint(new GradientPaint(0, 0, new Color(0, 0, 0, 10), 0, r.height, new Color(0, 0, 0, 30)));
g2d.fillRect(0, 0, r.width, r.height);
g2d.setColor(new Color(0, 0, 0, 60));
g2d.drawLine(0, 0, 0, r.height);
g2d.drawLine(r.width - 1, 0, r.width - 1, r.height);
g2d.setColor(new Color(255, 255, 255, 80));
g2d.drawRect(1, 0, r.width - 3, r.height - 1);
g2d.dispose();
}
g.drawImage(myImage, isIdVisible() ? r.x : r.x - 2, r.y, null);
}
@Override
public void paintChildren(Graphics g) {
if (!isToDrawCombo()) return;
final GraphicsConfig c = new GraphicsConfig(g);
c.setAntialiasing(true);
final Graphics2D g2d = (Graphics2D)g;
c.restore();
}
@Override
public void update() {
updateIdLabel(myIdLabel);
myComboLabel.update();
}
@Override
public void rebuild() {
myUi.removeAll();
myUi.add(myIdLabel);
myUi.initMouseListeners(myIdLabel, myUi);
myUi.add(myComboLabel);
myUi.initMouseListeners(myComboLabel, myUi);
}
boolean isToDrawCombo() {
return myUi.myManager.getContentCount() > 1;
}
@Override
public void contentAdded(ContentManagerEvent event) {
}
@Override
public void contentRemoved(ContentManagerEvent event) {
}
@Override
public boolean shouldDrawDecorations() {
return isToDrawCombo();
}
@Override
public void showContentPopup(ListPopup listPopup) {
final int width = myComboLabel.getSize().width;
listPopup.setMinimumSize(new Dimension(width, 0));
listPopup.show(new RelativePoint(myComboLabel, new Point(-2, myComboLabel.getHeight())));
}
@Override
public RelativeRectangle getRectangleFor(Content content) {
return null;
}
@Override
public Component getComponentFor(Content content) {
return null;
}
@Override
public String getCloseActionName() {
return "Close View";
}
@Override
public String getCloseAllButThisActionName() {
return "Close Other Views";
}
@Override
public String getPreviousContentActionName() {
return "Select Previous View";
}
@Override
public String getNextContentActionName() {
return "Select Next View";
}
}
|
platform/platform-impl/src/com/intellij/openapi/wm/impl/content/ComboContentLayout.java
|
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.wm.impl.content;
import com.intellij.openapi.ui.GraphicsConfig;
import com.intellij.openapi.ui.popup.ListPopup;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.ui.awt.RelativeRectangle;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentManagerEvent;
import java.awt.*;
import java.awt.image.BufferedImage;
class ComboContentLayout extends ContentLayout {
ContentComboLabel myComboLabel;
private BufferedImage myImage;
ComboContentLayout(ToolWindowContentUi ui) {
super(ui);
}
@Override
public void init() {
reset();
myIdLabel = new BaseLabel(myUi, false);
myComboLabel = new ContentComboLabel(this);
}
@Override
public void reset() {
myIdLabel = null;
myComboLabel = null;
myImage = null;
}
@Override
public void layout() {
Rectangle bounds = myUi.getBounds();
Dimension idSize = isIdVisible() ? myIdLabel.getPreferredSize() : new Dimension(0, 0);
int eachX = 0;
int eachY = 0;
myIdLabel.setBounds(eachX, eachY, idSize.width, bounds.height);
eachX += idSize.width;
Dimension comboSize = myComboLabel.getPreferredSize();
int spaceLeft = bounds.width - eachX - (isToDrawCombo() && isIdVisible() ? 3 : 0);
int width = comboSize.width;
if (width > spaceLeft) {
width = spaceLeft;
}
myComboLabel.setBounds(eachX, eachY, width, bounds.height);
}
@Override
public void paintComponent(Graphics g) {
if (!isToDrawCombo()) return;
Rectangle r = myComboLabel.getBounds();
if (myImage == null || myImage.getHeight() != r.height || myImage.getWidth() != r.width) {
myImage = new BufferedImage(r.width, r.height, BufferedImage.TYPE_INT_ARGB);
final Graphics2D g2d = myImage.createGraphics();
final GraphicsConfig c = new GraphicsConfig(g);
c.setAntialiasing(true);
g2d.setPaint(new GradientPaint(0, 0, new Color(0, 0, 0, 10), 0, r.height, new Color(0, 0, 0, 30)));
g2d.fillRect(0, 0, r.width, r.height);
g2d.setColor(new Color(0, 0, 0, 60));
g2d.drawLine(0, 0, 0, r.height);
g2d.drawLine(r.width - 1, 0, r.width - 1, r.height);
g2d.setColor(new Color(255, 255, 255, 80));
g2d.drawRect(1, 0, r.width - 3, r.height - 1);
g2d.dispose();
}
g.drawImage(myImage, isIdVisible() ? r.x : r.x - 2, r.y, null);
}
@Override
public void paintChildren(Graphics g) {
if (!isToDrawCombo()) return;
final GraphicsConfig c = new GraphicsConfig(g);
c.setAntialiasing(true);
final Graphics2D g2d = (Graphics2D)g;
c.restore();
}
@Override
public void update() {
updateIdLabel(myIdLabel);
myComboLabel.update();
}
@Override
public void rebuild() {
myUi.removeAll();
myUi.add(myIdLabel);
myUi.initMouseListeners(myIdLabel, myUi);
myUi.add(myComboLabel);
myUi.initMouseListeners(myComboLabel, myUi);
}
boolean isToDrawCombo() {
return myUi.myManager.getContentCount() > 1;
}
@Override
public void contentAdded(ContentManagerEvent event) {
}
@Override
public void contentRemoved(ContentManagerEvent event) {
}
@Override
public boolean shouldDrawDecorations() {
return isToDrawCombo();
}
@Override
public void showContentPopup(ListPopup listPopup) {
final int width = myComboLabel.getSize().width;
listPopup.setMinimumSize(new Dimension(width, 0));
listPopup.show(new RelativePoint(myComboLabel, new Point(-2, myComboLabel.getHeight())));
}
@Override
public RelativeRectangle getRectangleFor(Content content) {
return null;
}
@Override
public Component getComponentFor(Content content) {
return null;
}
@Override
public String getCloseActionName() {
return "Close View";
}
@Override
public String getCloseAllButThisActionName() {
return "Close Other Views";
}
@Override
public String getPreviousContentActionName() {
return "Select Previous View";
}
@Override
public String getNextContentActionName() {
return "Select Next View";
}
}
|
remove white lines and add sexy separator
|
platform/platform-impl/src/com/intellij/openapi/wm/impl/content/ComboContentLayout.java
|
remove white lines and add sexy separator
|
|
Java
|
apache-2.0
|
64b4553284e46ad588756fbec8e0d9024a7aa215
| 0
|
franz1981/activemq-artemis,orpiske/activemq-artemis,kjniemi/activemq-artemis,dejanb/activemq-artemis,pgfox/activemq-artemis,apache/activemq-artemis,dudaerich/activemq-artemis,d0k1/activemq-artemis,TomRoss/activemq-artemis,mnovak1/activemq-artemis,franz1981/activemq-artemis,tabish121/activemq-artemis,dudaerich/activemq-artemis,andytaylor/activemq-artemis,franz1981/activemq-artemis,clebertsuconic/activemq-artemis,andytaylor/activemq-artemis,iweiss/activemq-artemis,rgodfrey/activemq-artemis,jmesnil/activemq-artemis,gtully/activemq-artemis,gaohoward/activemq-artemis,cshannon/activemq-artemis,mnovak1/activemq-artemis,dejanb/activemq-artemis,gtully/activemq-artemis,cshannon/activemq-artemis,dejanb/activemq-artemis,iweiss/activemq-artemis,bennetelli/activemq-artemis,kjniemi/activemq-artemis,d0k1/activemq-artemis,jmesnil/activemq-artemis,clebertsuconic/activemq-artemis,kjniemi/activemq-artemis,mnovak1/activemq-artemis,bennetelli/activemq-artemis,d0k1/activemq-artemis,rgodfrey/activemq-artemis,dudaerich/activemq-artemis,jbertram/activemq-artemis,gaohoward/activemq-artemis,pgfox/activemq-artemis,orpiske/activemq-artemis,bennetelli/activemq-artemis,dudaerich/activemq-artemis,rgodfrey/activemq-artemis,bennetelli/activemq-artemis,pgfox/activemq-artemis,tabish121/activemq-artemis,iweiss/activemq-artemis,graben/activemq-artemis,pgfox/activemq-artemis,d0k1/activemq-artemis,gtully/activemq-artemis,kjniemi/activemq-artemis,gtully/activemq-artemis,bennetelli/activemq-artemis,clebertsuconic/activemq-artemis,dejanb/activemq-artemis,dejanb/activemq-artemis,rgodfrey/activemq-artemis,gaohoward/activemq-artemis,apache/activemq-artemis,jbertram/activemq-artemis,mnovak1/activemq-artemis,tabish121/activemq-artemis,mnovak1/activemq-artemis,jmesnil/activemq-artemis,cshannon/activemq-artemis,graben/activemq-artemis,andytaylor/activemq-artemis,franz1981/activemq-artemis,jbertram/activemq-artemis,kjniemi/activemq-artemis,apache/activemq-artemis,jmesnil/activemq-artemis,jmesnil/activemq-artemis,orpiske/activemq-artemis,graben/activemq-artemis,pgfox/activemq-artemis,gtully/activemq-artemis,andytaylor/activemq-artemis,rgodfrey/activemq-artemis,orpiske/activemq-artemis,d0k1/activemq-artemis,tabish121/activemq-artemis,mnovak1/activemq-artemis,dudaerich/activemq-artemis,iweiss/activemq-artemis,rgodfrey/activemq-artemis,jbertram/activemq-artemis,cshannon/activemq-artemis,gaohoward/activemq-artemis,TomRoss/activemq-artemis,dejanb/activemq-artemis,apache/activemq-artemis,TomRoss/activemq-artemis,pgfox/activemq-artemis,franz1981/activemq-artemis,jmesnil/activemq-artemis,TomRoss/activemq-artemis,cshannon/activemq-artemis,graben/activemq-artemis,clebertsuconic/activemq-artemis
|
/*
* 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.activemq.artemis.protocol.amqp.broker;
import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.activemq.artemis.api.core.ActiveMQBuffer;
import org.apache.activemq.artemis.api.core.ActiveMQPropertyConversionException;
import org.apache.activemq.artemis.api.core.ICoreMessage;
import org.apache.activemq.artemis.api.core.RefCountMessage;
import org.apache.activemq.artemis.api.core.RoutingType;
import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.artemis.core.persistence.Persister;
import org.apache.activemq.artemis.protocol.amqp.converter.AMQPConverter;
import org.apache.activemq.artemis.protocol.amqp.converter.AMQPMessageSupport;
import org.apache.activemq.artemis.protocol.amqp.util.NettyWritable;
import org.apache.activemq.artemis.protocol.amqp.util.TLSEncode;
import org.apache.activemq.artemis.reader.MessageUtil;
import org.apache.activemq.artemis.utils.DataConstants;
import org.apache.qpid.proton.amqp.Symbol;
import org.apache.qpid.proton.amqp.UnsignedByte;
import org.apache.qpid.proton.amqp.UnsignedInteger;
import org.apache.qpid.proton.amqp.UnsignedLong;
import org.apache.qpid.proton.amqp.UnsignedShort;
import org.apache.qpid.proton.amqp.messaging.ApplicationProperties;
import org.apache.qpid.proton.amqp.messaging.DeliveryAnnotations;
import org.apache.qpid.proton.amqp.messaging.Header;
import org.apache.qpid.proton.amqp.messaging.MessageAnnotations;
import org.apache.qpid.proton.amqp.messaging.Properties;
import org.apache.qpid.proton.amqp.messaging.Section;
import org.apache.qpid.proton.codec.DecoderImpl;
import org.apache.qpid.proton.codec.WritableBuffer;
import org.apache.qpid.proton.message.Message;
import org.apache.qpid.proton.message.impl.MessageImpl;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.buffer.Unpooled;
// see https://docs.oasis-open.org/amqp/core/v1.0/os/amqp-core-messaging-v1.0-os.html#section-message-format
public class AMQPMessage extends RefCountMessage {
final long messageFormat;
ByteBuf data;
boolean bufferValid;
boolean durable;
long messageID;
String address;
MessageImpl protonMessage;
private volatile int memoryEstimate = -1;
private long expiration = 0;
// this is to store where to start sending bytes, ignoring header and delivery annotations.
private int sendFrom = 0;
private boolean parsedHeaders = false;
private Header _header;
private DeliveryAnnotations _deliveryAnnotations;
private MessageAnnotations _messageAnnotations;
private Properties _properties;
private int appLocation = -1;
private ApplicationProperties applicationProperties;
private long scheduledTime = -1;
private String connectionID;
public AMQPMessage(long messageFormat, byte[] data) {
this.data = Unpooled.wrappedBuffer(data);
this.messageFormat = messageFormat;
this.bufferValid = true;
parseHeaders();
}
/** for persistence reload */
public AMQPMessage(long messageFormat) {
this.messageFormat = messageFormat;
this.bufferValid = false;
}
public AMQPMessage(long messageFormat, Message message) {
this.messageFormat = messageFormat;
this.protonMessage = (MessageImpl) message;
this.bufferValid = false;
}
public AMQPMessage(Message message) {
this(0, message);
}
public MessageImpl getProtonMessage() {
if (protonMessage == null) {
protonMessage = (MessageImpl) Message.Factory.create();
if (data != null) {
data.readerIndex(0);
protonMessage.decode(data.nioBuffer());
this._header = protonMessage.getHeader();
protonMessage.setHeader(null);
}
}
return protonMessage;
}
private void initalizeObjects() {
if (protonMessage == null) {
if (data == null) {
this.sendFrom = 0;
_header = new Header();
_deliveryAnnotations = new DeliveryAnnotations(new HashMap<>());
_properties = new Properties();
this.applicationProperties = new ApplicationProperties(new HashMap<>());
this.protonMessage = (MessageImpl) Message.Factory.create();
this.protonMessage.setApplicationProperties(applicationProperties);
this.protonMessage.setDeliveryAnnotations(_deliveryAnnotations);
}
}
}
private Map getApplicationPropertiesMap() {
ApplicationProperties appMap = getApplicationProperties();
Map map = null;
if (appMap != null) {
map = appMap.getValue();
}
if (map == null) {
return Collections.emptyMap();
} else {
return map;
}
}
private ApplicationProperties getApplicationProperties() {
parseHeaders();
if (applicationProperties == null && appLocation >= 0) {
ByteBuffer buffer = getBuffer().nioBuffer();
buffer.position(appLocation);
TLSEncode.getDecoder().setByteBuffer(buffer);
Object section = TLSEncode.getDecoder().readObject();
if (section instanceof ApplicationProperties) {
this.applicationProperties = (ApplicationProperties) section;
}
this.appLocation = -1;
TLSEncode.getDecoder().setByteBuffer(null);
}
return applicationProperties;
}
private void parseHeaders() {
if (!parsedHeaders) {
if (data == null) {
initalizeObjects();
} else {
partialDecode(data.nioBuffer());
}
parsedHeaders = true;
}
}
@Override
public org.apache.activemq.artemis.api.core.Message setConnectionID(String connectionID) {
this.connectionID = connectionID;
return this;
}
@Override
public String getConnectionID() {
return connectionID;
}
public MessageAnnotations getMessageAnnotations() {
parseHeaders();
return _messageAnnotations;
}
public Header getHeader() {
parseHeaders();
return _header;
}
public Properties getProperties() {
parseHeaders();
return _properties;
}
private Object getSymbol(String symbol) {
return getSymbol(Symbol.getSymbol(symbol));
}
private Object getSymbol(Symbol symbol) {
MessageAnnotations annotations = getMessageAnnotations();
Map mapAnnotations = annotations != null ? annotations.getValue() : null;
if (mapAnnotations != null) {
return mapAnnotations.get(symbol);
}
return null;
}
private Object removeSymbol(Symbol symbol) {
MessageAnnotations annotations = getMessageAnnotations();
Map mapAnnotations = annotations != null ? annotations.getValue() : null;
if (mapAnnotations != null) {
return mapAnnotations.remove(symbol);
}
return null;
}
private void setSymbol(String symbol, Object value) {
setSymbol(Symbol.getSymbol(symbol), value);
}
private void setSymbol(Symbol symbol, Object value) {
MessageAnnotations annotations = getMessageAnnotations();
if (annotations == null) {
_messageAnnotations = new MessageAnnotations(new HashMap<>());
annotations = _messageAnnotations;
}
Map mapAnnotations = annotations != null ? annotations.getValue() : null;
if (mapAnnotations != null) {
mapAnnotations.put(symbol, value);
}
}
@Override
public RoutingType getRouteType() {
/* TODO-now How to use this properly
switch (((Byte)type).byteValue()) {
case AMQPMessageSupport.QUEUE_TYPE:
case AMQPMessageSupport.TEMP_QUEUE_TYPE:
return RoutingType.ANYCAST;
case AMQPMessageSupport.TOPIC_TYPE:
case AMQPMessageSupport.TEMP_TOPIC_TYPE:
return RoutingType.MULTICAST;
default:
return null;
} */
return null;
}
@Override
public SimpleString getGroupID() {
parseHeaders();
if (_properties != null && _properties.getGroupId() != null) {
return SimpleString.toSimpleString(_properties.getGroupId());
} else {
return null;
}
}
@Override
public Long getScheduledDeliveryTime() {
if (scheduledTime < 0) {
Object objscheduledTime = getSymbol("x-opt-delivery-time");
Object objdelay = getSymbol("x-opt-delivery-delay");
if (objscheduledTime != null && objscheduledTime instanceof Number) {
this.scheduledTime = ((Number) objscheduledTime).longValue();
} else if (objdelay != null && objdelay instanceof Number) {
this.scheduledTime = System.currentTimeMillis() + ((Number) objdelay).longValue();
} else {
this.scheduledTime = 0;
}
}
return scheduledTime;
}
@Override
public AMQPMessage setScheduledDeliveryTime(Long time) {
parseHeaders();
setSymbol(AMQPMessageSupport.JMS_DELIVERY_TIME, time);
return this;
}
@Override
public Persister<org.apache.activemq.artemis.api.core.Message> getPersister() {
return AMQPMessagePersister.getInstance();
}
private synchronized void partialDecode(ByteBuffer buffer) {
DecoderImpl decoder = TLSEncode.getDecoder();
decoder.setByteBuffer(buffer);
buffer.position(0);
_header = null;
_deliveryAnnotations = null;
_messageAnnotations = null;
_properties = null;
applicationProperties = null;
Section section = null;
try {
if (buffer.hasRemaining()) {
section = (Section) decoder.readObject();
}
if (section instanceof Header) {
sendFrom = buffer.position();
_header = (Header) section;
if (_header.getTtl() != null) {
this.expiration = System.currentTimeMillis() + _header.getTtl().intValue();
}
if (buffer.hasRemaining()) {
section = (Section) decoder.readObject();
} else {
section = null;
}
} else {
// meaning there is no header
sendFrom = 0;
}
if (section instanceof DeliveryAnnotations) {
_deliveryAnnotations = (DeliveryAnnotations) section;
sendFrom = buffer.position();
if (buffer.hasRemaining()) {
section = (Section) decoder.readObject();
} else {
section = null;
}
}
if (section instanceof MessageAnnotations) {
_messageAnnotations = (MessageAnnotations) section;
if (buffer.hasRemaining()) {
section = (Section) decoder.readObject();
} else {
section = null;
}
}
if (section instanceof Properties) {
_properties = (Properties) section;
if (_properties.getAbsoluteExpiryTime() != null) {
this.expiration = _properties.getAbsoluteExpiryTime().getTime();
}
// We don't read the next section on purpose, as we will parse ApplicationProperties
// lazily
section = null;
}
if (section instanceof ApplicationProperties) {
applicationProperties = (ApplicationProperties) section;
} else {
if (buffer.hasRemaining()) {
this.appLocation = buffer.position();
} else {
this.appLocation = -1;
}
}
} finally {
decoder.setByteBuffer(null);
}
}
public long getMessageFormat() {
return messageFormat;
}
public int getLength() {
return data.array().length;
}
public byte[] getArray() {
return data.array();
}
@Override
public void messageChanged() {
bufferValid = false;
this.data = null;
}
@Override
public ByteBuf getBuffer() {
if (data == null) {
return null;
} else {
return Unpooled.wrappedBuffer(data);
}
}
@Override
public AMQPMessage setBuffer(ByteBuf buffer) {
this.data = null;
return this;
}
@Override
public org.apache.activemq.artemis.api.core.Message copy() {
checkBuffer();
byte[] origin = data.array();
byte[] newData = new byte[data.array().length - sendFrom];
for (int i = 0; i < newData.length; i++) {
newData[i] = origin[i + sendFrom];
}
AMQPMessage newEncode = new AMQPMessage(this.messageFormat, newData);
newEncode.setDurable(isDurable());
return newEncode;
}
@Override
public org.apache.activemq.artemis.api.core.Message copy(long newID) {
checkBuffer();
return copy().setMessageID(newID);
}
@Override
public long getMessageID() {
return messageID;
}
@Override
public org.apache.activemq.artemis.api.core.Message setMessageID(long id) {
this.messageID = id;
return this;
}
@Override
public long getExpiration() {
return expiration;
}
@Override
public AMQPMessage setExpiration(long expiration) {
Properties properties = getProperties();
if (properties != null) {
if (expiration <= 0) {
properties.setAbsoluteExpiryTime(null);
} else {
properties.setAbsoluteExpiryTime(new Date(expiration));
}
}
this.expiration = expiration;
return this;
}
@Override
public Object getUserID() {
Properties properties = getProperties();
if (properties != null && properties.getMessageId() != null) {
return properties.getMessageId();
} else {
return this;
}
}
@Override
public org.apache.activemq.artemis.api.core.Message setUserID(Object userID) {
return null;
}
@Override
public boolean isDurable() {
if (getHeader() != null && getHeader().getDurable() != null) {
return getHeader().getDurable().booleanValue();
} else {
return durable;
}
}
@Override
public Object getDuplicateProperty() {
return null;
}
@Override
public org.apache.activemq.artemis.api.core.Message setDurable(boolean durable) {
this.durable = durable;
return this;
}
@Override
public String getAddress() {
if (address == null) {
Properties properties = getProtonMessage().getProperties();
if (properties != null) {
return properties.getTo();
} else {
return null;
}
} else {
return address;
}
}
@Override
public AMQPMessage setAddress(String address) {
this.address = address;
return this;
}
@Override
public AMQPMessage setAddress(SimpleString address) {
return setAddress(address.toString());
}
@Override
public SimpleString getAddressSimpleString() {
return SimpleString.toSimpleString(getAddress());
}
@Override
public long getTimestamp() {
return 0;
}
@Override
public org.apache.activemq.artemis.api.core.Message setTimestamp(long timestamp) {
return null;
}
@Override
public byte getPriority() {
return 0;
}
@Override
public org.apache.activemq.artemis.api.core.Message setPriority(byte priority) {
return null;
}
@Override
public void receiveBuffer(ByteBuf buffer) {
}
private synchronized void checkBuffer() {
if (!bufferValid) {
ByteBuf buffer = PooledByteBufAllocator.DEFAULT.heapBuffer(1500);
try {
getProtonMessage().encode(new NettyWritable(buffer));
byte[] bytes = new byte[buffer.writerIndex()];
buffer.readBytes(bytes);
this.data = Unpooled.wrappedBuffer(bytes);
} finally {
buffer.release();
}
}
}
@Override
public int getEncodeSize() {
checkBuffer();
// + 20checkBuffer is an estimate for the Header with the deliveryCount
return data.array().length - sendFrom + 20;
}
@Override
public void sendBuffer(ByteBuf buffer, int deliveryCount) {
checkBuffer();
Header header = getHeader();
if (header == null && deliveryCount > 0) {
header = new Header();
header.setDurable(durable);
}
if (header != null) {
synchronized (header) {
header.setDeliveryCount(UnsignedInteger.valueOf(deliveryCount - 1));
TLSEncode.getEncoder().setByteBuffer(new NettyWritable(buffer));
TLSEncode.getEncoder().writeObject(header);
TLSEncode.getEncoder().setByteBuffer((WritableBuffer) null);
}
}
buffer.writeBytes(data, sendFrom, data.writerIndex() - sendFrom);
}
@Override
public org.apache.activemq.artemis.api.core.Message putBooleanProperty(String key, boolean value) {
getApplicationPropertiesMap().put(key, Boolean.valueOf(value));
return this;
}
@Override
public org.apache.activemq.artemis.api.core.Message putByteProperty(String key, byte value) {
getApplicationPropertiesMap().put(key, Byte.valueOf(value));
return this;
}
@Override
public org.apache.activemq.artemis.api.core.Message putBytesProperty(String key, byte[] value) {
getApplicationPropertiesMap().put(key, value);
return this;
}
@Override
public org.apache.activemq.artemis.api.core.Message putShortProperty(String key, short value) {
getApplicationPropertiesMap().put(key, Short.valueOf(value));
return this;
}
@Override
public org.apache.activemq.artemis.api.core.Message putCharProperty(String key, char value) {
getApplicationPropertiesMap().put(key, Character.valueOf(value));
return this;
}
@Override
public org.apache.activemq.artemis.api.core.Message putIntProperty(String key, int value) {
getApplicationPropertiesMap().put(key, Integer.valueOf(value));
return this;
}
@Override
public org.apache.activemq.artemis.api.core.Message putLongProperty(String key, long value) {
getApplicationPropertiesMap().put(key, Long.valueOf(value));
return this;
}
@Override
public org.apache.activemq.artemis.api.core.Message putFloatProperty(String key, float value) {
getApplicationPropertiesMap().put(key, Float.valueOf(value));
return this;
}
@Override
public org.apache.activemq.artemis.api.core.Message putDoubleProperty(String key, double value) {
getApplicationPropertiesMap().put(key, Double.valueOf(value));
return this;
}
@Override
public org.apache.activemq.artemis.api.core.Message putBooleanProperty(SimpleString key, boolean value) {
getApplicationPropertiesMap().put(key, Boolean.valueOf(value));
return this;
}
@Override
public org.apache.activemq.artemis.api.core.Message putByteProperty(SimpleString key, byte value) {
return putByteProperty(key.toString(), value);
}
@Override
public org.apache.activemq.artemis.api.core.Message putBytesProperty(SimpleString key, byte[] value) {
return putBytesProperty(key.toString(), value);
}
@Override
public org.apache.activemq.artemis.api.core.Message putShortProperty(SimpleString key, short value) {
return putShortProperty(key.toString(), value);
}
@Override
public org.apache.activemq.artemis.api.core.Message putCharProperty(SimpleString key, char value) {
return putCharProperty(key.toString(), value);
}
@Override
public org.apache.activemq.artemis.api.core.Message putIntProperty(SimpleString key, int value) {
return putIntProperty(key.toString(), value);
}
@Override
public org.apache.activemq.artemis.api.core.Message putLongProperty(SimpleString key, long value) {
return putLongProperty(key.toString(), value);
}
@Override
public org.apache.activemq.artemis.api.core.Message putFloatProperty(SimpleString key, float value) {
return putFloatProperty(key.toString(), value);
}
@Override
public org.apache.activemq.artemis.api.core.Message putDoubleProperty(SimpleString key, double value) {
return putDoubleProperty(key.toString(), value);
}
@Override
public org.apache.activemq.artemis.api.core.Message putStringProperty(String key, String value) {
getApplicationPropertiesMap().put(key, value);
return this;
}
@Override
public org.apache.activemq.artemis.api.core.Message putObjectProperty(String key,
Object value) throws ActiveMQPropertyConversionException {
getApplicationPropertiesMap().put(key, value);
return this;
}
@Override
public org.apache.activemq.artemis.api.core.Message putObjectProperty(SimpleString key,
Object value) throws ActiveMQPropertyConversionException {
return putObjectProperty(key.toString(), value);
}
@Override
public Object removeProperty(String key) {
return getApplicationPropertiesMap().remove(key);
}
@Override
public boolean containsProperty(String key) {
return getApplicationPropertiesMap().containsKey(key);
}
@Override
public Boolean getBooleanProperty(String key) throws ActiveMQPropertyConversionException {
return (Boolean) getApplicationPropertiesMap().get(key);
}
@Override
public Byte getByteProperty(String key) throws ActiveMQPropertyConversionException {
return (Byte) getApplicationPropertiesMap().get(key);
}
@Override
public Double getDoubleProperty(String key) throws ActiveMQPropertyConversionException {
return (Double) getApplicationPropertiesMap().get(key);
}
@Override
public Integer getIntProperty(String key) throws ActiveMQPropertyConversionException {
return (Integer) getApplicationPropertiesMap().get(key);
}
@Override
public Long getLongProperty(String key) throws ActiveMQPropertyConversionException {
return (Long) getApplicationPropertiesMap().get(key);
}
@Override
public Object getObjectProperty(String key) {
if (key.equals(MessageUtil.TYPE_HEADER_NAME.toString())) {
return getProperties().getSubject();
} else if (key.equals(MessageUtil.CONNECTION_ID_PROPERTY_NAME.toString())) {
return getConnectionID();
} else {
Object value = getApplicationPropertiesMap().get(key);
if (value instanceof UnsignedInteger ||
value instanceof UnsignedByte ||
value instanceof UnsignedLong ||
value instanceof UnsignedShort) {
return ((Number)value).longValue();
} else {
return value;
}
}
}
@Override
public Short getShortProperty(String key) throws ActiveMQPropertyConversionException {
return (Short) getApplicationPropertiesMap().get(key);
}
@Override
public Float getFloatProperty(String key) throws ActiveMQPropertyConversionException {
return (Float) getApplicationPropertiesMap().get(key);
}
@Override
public String getStringProperty(String key) throws ActiveMQPropertyConversionException {
if (key.equals(MessageUtil.TYPE_HEADER_NAME.toString())) {
return getProperties().getSubject();
} else if (key.equals(MessageUtil.CONNECTION_ID_PROPERTY_NAME.toString())) {
return getConnectionID();
} else {
return (String) getApplicationPropertiesMap().get(key);
}
}
@Override
public Object removeAnnotation(SimpleString key) {
return removeSymbol(Symbol.getSymbol(key.toString()));
}
@Override
public Object getAnnotation(SimpleString key) {
return getSymbol(key.toString());
}
@Override
public AMQPMessage setAnnotation(SimpleString key, Object value) {
setSymbol(key.toString(), value);
return this;
}
@Override
public void reencode() {
if (_deliveryAnnotations != null) getProtonMessage().setDeliveryAnnotations(_deliveryAnnotations);
if (_messageAnnotations != null) getProtonMessage().setMessageAnnotations(_messageAnnotations);
if (applicationProperties != null) getProtonMessage().setApplicationProperties(applicationProperties);
if (_properties != null) getProtonMessage().setProperties(this._properties);
bufferValid = false;
checkBuffer();
}
@Override
public SimpleString getSimpleStringProperty(String key) throws ActiveMQPropertyConversionException {
return SimpleString.toSimpleString((String) getApplicationPropertiesMap().get(key));
}
@Override
public byte[] getBytesProperty(String key) throws ActiveMQPropertyConversionException {
return (byte[]) getApplicationPropertiesMap().get(key);
}
@Override
public Object removeProperty(SimpleString key) {
return removeProperty(key.toString());
}
@Override
public boolean containsProperty(SimpleString key) {
return containsProperty(key.toString());
}
@Override
public Boolean getBooleanProperty(SimpleString key) throws ActiveMQPropertyConversionException {
return getBooleanProperty(key.toString());
}
@Override
public Byte getByteProperty(SimpleString key) throws ActiveMQPropertyConversionException {
return getByteProperty(key.toString());
}
@Override
public Double getDoubleProperty(SimpleString key) throws ActiveMQPropertyConversionException {
return getDoubleProperty(key.toString());
}
@Override
public Integer getIntProperty(SimpleString key) throws ActiveMQPropertyConversionException {
return getIntProperty(key.toString());
}
@Override
public Long getLongProperty(SimpleString key) throws ActiveMQPropertyConversionException {
return getLongProperty(key.toString());
}
@Override
public Object getObjectProperty(SimpleString key) {
return getObjectProperty(key.toString());
}
@Override
public Short getShortProperty(SimpleString key) throws ActiveMQPropertyConversionException {
return getShortProperty(key.toString());
}
@Override
public Float getFloatProperty(SimpleString key) throws ActiveMQPropertyConversionException {
return getFloatProperty(key.toString());
}
@Override
public String getStringProperty(SimpleString key) throws ActiveMQPropertyConversionException {
return getStringProperty(key.toString());
}
@Override
public SimpleString getSimpleStringProperty(SimpleString key) throws ActiveMQPropertyConversionException {
return getSimpleStringProperty(key.toString());
}
@Override
public byte[] getBytesProperty(SimpleString key) throws ActiveMQPropertyConversionException {
return getBytesProperty(key.toString());
}
@Override
public org.apache.activemq.artemis.api.core.Message putStringProperty(SimpleString key, SimpleString value) {
return putStringProperty(key.toString(), value.toString());
}
@Override
public Set<SimpleString> getPropertyNames() {
HashSet<SimpleString> values = new HashSet<>();
for (Object k : getApplicationPropertiesMap().keySet()) {
values.add(SimpleString.toSimpleString(k.toString()));
}
return values;
}
@Override
public int getMemoryEstimate() {
if (memoryEstimate == -1) {
memoryEstimate = memoryOffset + (data != null ? data.capacity() : 0);
}
return memoryEstimate;
}
@Override
public ICoreMessage toCore() {
try {
return AMQPConverter.getInstance().toCore(this);
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
@Override
public SimpleString getReplyTo() {
if (getProperties() != null) {
return SimpleString.toSimpleString(getProperties().getReplyTo());
} else {
return null;
}
}
@Override
public AMQPMessage setReplyTo(SimpleString address) {
if (getProperties() != null) {
getProperties().setReplyTo(address != null ? address.toString() : null);
}
return this;
}
@Override
public int getPersistSize() {
checkBuffer();
return DataConstants.SIZE_INT + internalPersistSize();
}
private int internalPersistSize() {
return data.array().length - sendFrom;
}
@Override
public void persist(ActiveMQBuffer targetRecord) {
checkBuffer();
targetRecord.writeInt(internalPersistSize());
targetRecord.writeBytes(data.array(), sendFrom, data.array().length - sendFrom);
}
@Override
public void reloadPersistence(ActiveMQBuffer record) {
int size = record.readInt();
byte[] recordArray = new byte[size];
record.readBytes(recordArray);
this.sendFrom = 0; // whatever was persisted will be sent
this.data = Unpooled.wrappedBuffer(recordArray);
this.bufferValid = true;
this.durable = true; // it's coming from the journal, so it's durable
parseHeaders();
}
}
|
artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/protocol/amqp/broker/AMQPMessage.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.activemq.artemis.protocol.amqp.broker;
import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.activemq.artemis.api.core.ActiveMQBuffer;
import org.apache.activemq.artemis.api.core.ActiveMQPropertyConversionException;
import org.apache.activemq.artemis.api.core.ICoreMessage;
import org.apache.activemq.artemis.api.core.RefCountMessage;
import org.apache.activemq.artemis.api.core.RoutingType;
import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.artemis.core.persistence.Persister;
import org.apache.activemq.artemis.protocol.amqp.converter.AMQPConverter;
import org.apache.activemq.artemis.protocol.amqp.converter.AMQPMessageSupport;
import org.apache.activemq.artemis.protocol.amqp.util.NettyWritable;
import org.apache.activemq.artemis.protocol.amqp.util.TLSEncode;
import org.apache.activemq.artemis.reader.MessageUtil;
import org.apache.activemq.artemis.utils.DataConstants;
import org.apache.qpid.proton.amqp.Symbol;
import org.apache.qpid.proton.amqp.UnsignedByte;
import org.apache.qpid.proton.amqp.UnsignedInteger;
import org.apache.qpid.proton.amqp.UnsignedLong;
import org.apache.qpid.proton.amqp.UnsignedShort;
import org.apache.qpid.proton.amqp.messaging.ApplicationProperties;
import org.apache.qpid.proton.amqp.messaging.DeliveryAnnotations;
import org.apache.qpid.proton.amqp.messaging.Header;
import org.apache.qpid.proton.amqp.messaging.MessageAnnotations;
import org.apache.qpid.proton.amqp.messaging.Properties;
import org.apache.qpid.proton.amqp.messaging.Section;
import org.apache.qpid.proton.codec.DecoderImpl;
import org.apache.qpid.proton.codec.WritableBuffer;
import org.apache.qpid.proton.message.Message;
import org.apache.qpid.proton.message.impl.MessageImpl;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.buffer.Unpooled;
// see https://docs.oasis-open.org/amqp/core/v1.0/os/amqp-core-messaging-v1.0-os.html#section-message-format
public class AMQPMessage extends RefCountMessage {
final long messageFormat;
ByteBuf data;
boolean bufferValid;
boolean durable;
long messageID;
String address;
MessageImpl protonMessage;
private volatile int memoryEstimate = -1;
private long expiration = 0;
// this is to store where to start sending bytes, ignoring header and delivery annotations.
private int sendFrom = 0;
private boolean parsedHeaders = false;
private Header _header;
private DeliveryAnnotations _deliveryAnnotations;
private MessageAnnotations _messageAnnotations;
private Properties _properties;
private int appLocation = -1;
private ApplicationProperties applicationProperties;
private long scheduledTime = -1;
private String connectionID;
public AMQPMessage(long messageFormat, byte[] data) {
this.data = Unpooled.wrappedBuffer(data);
this.messageFormat = messageFormat;
this.bufferValid = true;
parseHeaders();
}
/** for persistence reload */
public AMQPMessage(long messageFormat) {
this.messageFormat = messageFormat;
this.bufferValid = false;
}
public AMQPMessage(long messageFormat, Message message) {
this.messageFormat = messageFormat;
this.protonMessage = (MessageImpl) message;
}
public AMQPMessage(Message message) {
this(0, message);
}
public MessageImpl getProtonMessage() {
if (protonMessage == null) {
protonMessage = (MessageImpl) Message.Factory.create();
if (data != null) {
data.readerIndex(0);
protonMessage.decode(data.nioBuffer());
this._header = protonMessage.getHeader();
protonMessage.setHeader(null);
}
}
return protonMessage;
}
private void initalizeObjects() {
if (protonMessage == null) {
if (data == null) {
this.sendFrom = 0;
_header = new Header();
_deliveryAnnotations = new DeliveryAnnotations(new HashMap<>());
_properties = new Properties();
this.applicationProperties = new ApplicationProperties(new HashMap<>());
this.protonMessage = (MessageImpl) Message.Factory.create();
this.protonMessage.setApplicationProperties(applicationProperties);
this.protonMessage.setDeliveryAnnotations(_deliveryAnnotations);
}
}
}
private Map getApplicationPropertiesMap() {
ApplicationProperties appMap = getApplicationProperties();
Map map = null;
if (appMap != null) {
map = appMap.getValue();
}
if (map == null) {
return Collections.emptyMap();
} else {
return map;
}
}
private ApplicationProperties getApplicationProperties() {
parseHeaders();
if (applicationProperties == null && appLocation >= 0) {
ByteBuffer buffer = getBuffer().nioBuffer();
buffer.position(appLocation);
TLSEncode.getDecoder().setByteBuffer(buffer);
Object section = TLSEncode.getDecoder().readObject();
if (section instanceof ApplicationProperties) {
this.applicationProperties = (ApplicationProperties) section;
}
this.appLocation = -1;
TLSEncode.getDecoder().setByteBuffer(null);
}
return applicationProperties;
}
private void parseHeaders() {
if (!parsedHeaders) {
if (data == null) {
initalizeObjects();
} else {
partialDecode(data.nioBuffer());
}
parsedHeaders = true;
}
}
@Override
public org.apache.activemq.artemis.api.core.Message setConnectionID(String connectionID) {
this.connectionID = connectionID;
return this;
}
@Override
public String getConnectionID() {
return connectionID;
}
public MessageAnnotations getMessageAnnotations() {
parseHeaders();
return _messageAnnotations;
}
public Header getHeader() {
parseHeaders();
return _header;
}
public Properties getProperties() {
parseHeaders();
return _properties;
}
private Object getSymbol(String symbol) {
return getSymbol(Symbol.getSymbol(symbol));
}
private Object getSymbol(Symbol symbol) {
MessageAnnotations annotations = getMessageAnnotations();
Map mapAnnotations = annotations != null ? annotations.getValue() : null;
if (mapAnnotations != null) {
return mapAnnotations.get(symbol);
}
return null;
}
private Object removeSymbol(Symbol symbol) {
MessageAnnotations annotations = getMessageAnnotations();
Map mapAnnotations = annotations != null ? annotations.getValue() : null;
if (mapAnnotations != null) {
return mapAnnotations.remove(symbol);
}
return null;
}
private void setSymbol(String symbol, Object value) {
setSymbol(Symbol.getSymbol(symbol), value);
}
private void setSymbol(Symbol symbol, Object value) {
MessageAnnotations annotations = getMessageAnnotations();
if (annotations == null) {
_messageAnnotations = new MessageAnnotations(new HashMap<>());
annotations = _messageAnnotations;
}
Map mapAnnotations = annotations != null ? annotations.getValue() : null;
if (mapAnnotations != null) {
mapAnnotations.put(symbol, value);
}
}
@Override
public RoutingType getRouteType() {
/* TODO-now How to use this properly
switch (((Byte)type).byteValue()) {
case AMQPMessageSupport.QUEUE_TYPE:
case AMQPMessageSupport.TEMP_QUEUE_TYPE:
return RoutingType.ANYCAST;
case AMQPMessageSupport.TOPIC_TYPE:
case AMQPMessageSupport.TEMP_TOPIC_TYPE:
return RoutingType.MULTICAST;
default:
return null;
} */
return null;
}
@Override
public SimpleString getGroupID() {
parseHeaders();
if (_properties != null && _properties.getGroupId() != null) {
return SimpleString.toSimpleString(_properties.getGroupId());
} else {
return null;
}
}
@Override
public Long getScheduledDeliveryTime() {
if (scheduledTime < 0) {
Object objscheduledTime = getSymbol("x-opt-delivery-time");
Object objdelay = getSymbol("x-opt-delivery-delay");
if (objscheduledTime != null && objscheduledTime instanceof Number) {
this.scheduledTime = ((Number) objscheduledTime).longValue();
} else if (objdelay != null && objdelay instanceof Number) {
this.scheduledTime = System.currentTimeMillis() + ((Number) objdelay).longValue();
} else {
this.scheduledTime = 0;
}
}
return scheduledTime;
}
@Override
public AMQPMessage setScheduledDeliveryTime(Long time) {
parseHeaders();
setSymbol(AMQPMessageSupport.JMS_DELIVERY_TIME, time);
return this;
}
@Override
public Persister<org.apache.activemq.artemis.api.core.Message> getPersister() {
return AMQPMessagePersister.getInstance();
}
private synchronized void partialDecode(ByteBuffer buffer) {
DecoderImpl decoder = TLSEncode.getDecoder();
decoder.setByteBuffer(buffer);
buffer.position(0);
_header = null;
_deliveryAnnotations = null;
_messageAnnotations = null;
_properties = null;
applicationProperties = null;
Section section = null;
try {
if (buffer.hasRemaining()) {
section = (Section) decoder.readObject();
}
if (section instanceof Header) {
sendFrom = buffer.position();
_header = (Header) section;
if (_header.getTtl() != null) {
this.expiration = System.currentTimeMillis() + _header.getTtl().intValue();
}
if (buffer.hasRemaining()) {
section = (Section) decoder.readObject();
} else {
section = null;
}
} else {
// meaning there is no header
sendFrom = 0;
}
if (section instanceof DeliveryAnnotations) {
_deliveryAnnotations = (DeliveryAnnotations) section;
sendFrom = buffer.position();
if (buffer.hasRemaining()) {
section = (Section) decoder.readObject();
} else {
section = null;
}
}
if (section instanceof MessageAnnotations) {
_messageAnnotations = (MessageAnnotations) section;
if (buffer.hasRemaining()) {
section = (Section) decoder.readObject();
} else {
section = null;
}
}
if (section instanceof Properties) {
_properties = (Properties) section;
if (_properties.getAbsoluteExpiryTime() != null) {
this.expiration = _properties.getAbsoluteExpiryTime().getTime();
}
// We don't read the next section on purpose, as we will parse ApplicationProperties
// lazily
section = null;
}
if (section instanceof ApplicationProperties) {
applicationProperties = (ApplicationProperties) section;
} else {
if (buffer.hasRemaining()) {
this.appLocation = buffer.position();
} else {
this.appLocation = -1;
}
}
} finally {
decoder.setByteBuffer(null);
}
}
public long getMessageFormat() {
return messageFormat;
}
public int getLength() {
return data.array().length;
}
public byte[] getArray() {
return data.array();
}
@Override
public void messageChanged() {
bufferValid = false;
this.data = null;
}
@Override
public ByteBuf getBuffer() {
if (data == null) {
return null;
} else {
return Unpooled.wrappedBuffer(data);
}
}
@Override
public AMQPMessage setBuffer(ByteBuf buffer) {
this.data = null;
return this;
}
@Override
public org.apache.activemq.artemis.api.core.Message copy() {
checkBuffer();
byte[] origin = data.array();
byte[] newData = new byte[data.array().length - sendFrom];
for (int i = 0; i < newData.length; i++) {
newData[i] = origin[i + sendFrom];
}
AMQPMessage newEncode = new AMQPMessage(this.messageFormat, newData);
newEncode.setDurable(isDurable());
return newEncode;
}
@Override
public org.apache.activemq.artemis.api.core.Message copy(long newID) {
checkBuffer();
return copy().setMessageID(newID);
}
@Override
public long getMessageID() {
return messageID;
}
@Override
public org.apache.activemq.artemis.api.core.Message setMessageID(long id) {
this.messageID = id;
return this;
}
@Override
public long getExpiration() {
return expiration;
}
@Override
public AMQPMessage setExpiration(long expiration) {
Properties properties = getProperties();
if (properties != null) {
if (expiration <= 0) {
properties.setAbsoluteExpiryTime(null);
} else {
properties.setAbsoluteExpiryTime(new Date(expiration));
}
}
this.expiration = expiration;
return this;
}
@Override
public Object getUserID() {
Properties properties = getProperties();
if (properties != null && properties.getMessageId() != null) {
return properties.getMessageId();
} else {
return this;
}
}
@Override
public org.apache.activemq.artemis.api.core.Message setUserID(Object userID) {
return null;
}
@Override
public boolean isDurable() {
if (getHeader() != null && getHeader().getDurable() != null) {
return getHeader().getDurable().booleanValue();
} else {
return durable;
}
}
@Override
public Object getDuplicateProperty() {
return null;
}
@Override
public org.apache.activemq.artemis.api.core.Message setDurable(boolean durable) {
this.durable = durable;
return this;
}
@Override
public String getAddress() {
if (address == null) {
Properties properties = getProtonMessage().getProperties();
if (properties != null) {
return properties.getTo();
} else {
return null;
}
} else {
return address;
}
}
@Override
public AMQPMessage setAddress(String address) {
this.address = address;
return this;
}
@Override
public AMQPMessage setAddress(SimpleString address) {
return setAddress(address.toString());
}
@Override
public SimpleString getAddressSimpleString() {
return SimpleString.toSimpleString(getAddress());
}
@Override
public long getTimestamp() {
return 0;
}
@Override
public org.apache.activemq.artemis.api.core.Message setTimestamp(long timestamp) {
return null;
}
@Override
public byte getPriority() {
return 0;
}
@Override
public org.apache.activemq.artemis.api.core.Message setPriority(byte priority) {
return null;
}
@Override
public void receiveBuffer(ByteBuf buffer) {
}
private synchronized void checkBuffer() {
if (!bufferValid) {
ByteBuf buffer = PooledByteBufAllocator.DEFAULT.heapBuffer(1500);
try {
getProtonMessage().encode(new NettyWritable(buffer));
byte[] bytes = new byte[buffer.writerIndex()];
buffer.readBytes(bytes);
this.data = Unpooled.wrappedBuffer(bytes);
} finally {
buffer.release();
}
}
}
@Override
public int getEncodeSize() {
checkBuffer();
// + 20checkBuffer is an estimate for the Header with the deliveryCount
return data.array().length - sendFrom + 20;
}
@Override
public void sendBuffer(ByteBuf buffer, int deliveryCount) {
checkBuffer();
Header header = getHeader();
if (header == null && deliveryCount > 0) {
header = new Header();
header.setDurable(durable);
}
if (header != null) {
synchronized (header) {
header.setDeliveryCount(UnsignedInteger.valueOf(deliveryCount - 1));
TLSEncode.getEncoder().setByteBuffer(new NettyWritable(buffer));
TLSEncode.getEncoder().writeObject(header);
TLSEncode.getEncoder().setByteBuffer((WritableBuffer) null);
}
}
buffer.writeBytes(data, sendFrom, data.writerIndex() - sendFrom);
}
@Override
public org.apache.activemq.artemis.api.core.Message putBooleanProperty(String key, boolean value) {
getApplicationPropertiesMap().put(key, Boolean.valueOf(value));
return this;
}
@Override
public org.apache.activemq.artemis.api.core.Message putByteProperty(String key, byte value) {
getApplicationPropertiesMap().put(key, Byte.valueOf(value));
return this;
}
@Override
public org.apache.activemq.artemis.api.core.Message putBytesProperty(String key, byte[] value) {
getApplicationPropertiesMap().put(key, value);
return this;
}
@Override
public org.apache.activemq.artemis.api.core.Message putShortProperty(String key, short value) {
getApplicationPropertiesMap().put(key, Short.valueOf(value));
return this;
}
@Override
public org.apache.activemq.artemis.api.core.Message putCharProperty(String key, char value) {
getApplicationPropertiesMap().put(key, Character.valueOf(value));
return this;
}
@Override
public org.apache.activemq.artemis.api.core.Message putIntProperty(String key, int value) {
getApplicationPropertiesMap().put(key, Integer.valueOf(value));
return this;
}
@Override
public org.apache.activemq.artemis.api.core.Message putLongProperty(String key, long value) {
getApplicationPropertiesMap().put(key, Long.valueOf(value));
return this;
}
@Override
public org.apache.activemq.artemis.api.core.Message putFloatProperty(String key, float value) {
getApplicationPropertiesMap().put(key, Float.valueOf(value));
return this;
}
@Override
public org.apache.activemq.artemis.api.core.Message putDoubleProperty(String key, double value) {
getApplicationPropertiesMap().put(key, Double.valueOf(value));
return this;
}
@Override
public org.apache.activemq.artemis.api.core.Message putBooleanProperty(SimpleString key, boolean value) {
getApplicationPropertiesMap().put(key, Boolean.valueOf(value));
return this;
}
@Override
public org.apache.activemq.artemis.api.core.Message putByteProperty(SimpleString key, byte value) {
return putByteProperty(key.toString(), value);
}
@Override
public org.apache.activemq.artemis.api.core.Message putBytesProperty(SimpleString key, byte[] value) {
return putBytesProperty(key.toString(), value);
}
@Override
public org.apache.activemq.artemis.api.core.Message putShortProperty(SimpleString key, short value) {
return putShortProperty(key.toString(), value);
}
@Override
public org.apache.activemq.artemis.api.core.Message putCharProperty(SimpleString key, char value) {
return putCharProperty(key.toString(), value);
}
@Override
public org.apache.activemq.artemis.api.core.Message putIntProperty(SimpleString key, int value) {
return putIntProperty(key.toString(), value);
}
@Override
public org.apache.activemq.artemis.api.core.Message putLongProperty(SimpleString key, long value) {
return putLongProperty(key.toString(), value);
}
@Override
public org.apache.activemq.artemis.api.core.Message putFloatProperty(SimpleString key, float value) {
return putFloatProperty(key.toString(), value);
}
@Override
public org.apache.activemq.artemis.api.core.Message putDoubleProperty(SimpleString key, double value) {
return putDoubleProperty(key.toString(), value);
}
@Override
public org.apache.activemq.artemis.api.core.Message putStringProperty(String key, String value) {
getApplicationPropertiesMap().put(key, value);
return this;
}
@Override
public org.apache.activemq.artemis.api.core.Message putObjectProperty(String key,
Object value) throws ActiveMQPropertyConversionException {
getApplicationPropertiesMap().put(key, value);
return this;
}
@Override
public org.apache.activemq.artemis.api.core.Message putObjectProperty(SimpleString key,
Object value) throws ActiveMQPropertyConversionException {
return putObjectProperty(key.toString(), value);
}
@Override
public Object removeProperty(String key) {
return getApplicationPropertiesMap().remove(key);
}
@Override
public boolean containsProperty(String key) {
return getApplicationPropertiesMap().containsKey(key);
}
@Override
public Boolean getBooleanProperty(String key) throws ActiveMQPropertyConversionException {
return (Boolean) getApplicationPropertiesMap().get(key);
}
@Override
public Byte getByteProperty(String key) throws ActiveMQPropertyConversionException {
return (Byte) getApplicationPropertiesMap().get(key);
}
@Override
public Double getDoubleProperty(String key) throws ActiveMQPropertyConversionException {
return (Double) getApplicationPropertiesMap().get(key);
}
@Override
public Integer getIntProperty(String key) throws ActiveMQPropertyConversionException {
return (Integer) getApplicationPropertiesMap().get(key);
}
@Override
public Long getLongProperty(String key) throws ActiveMQPropertyConversionException {
return (Long) getApplicationPropertiesMap().get(key);
}
@Override
public Object getObjectProperty(String key) {
if (key.equals(MessageUtil.TYPE_HEADER_NAME.toString())) {
return getProperties().getSubject();
} else if (key.equals(MessageUtil.CONNECTION_ID_PROPERTY_NAME.toString())) {
return getConnectionID();
} else {
Object value = getApplicationPropertiesMap().get(key);
if (value instanceof UnsignedInteger ||
value instanceof UnsignedByte ||
value instanceof UnsignedLong ||
value instanceof UnsignedShort) {
return ((Number)value).longValue();
} else {
return value;
}
}
}
@Override
public Short getShortProperty(String key) throws ActiveMQPropertyConversionException {
return (Short) getApplicationPropertiesMap().get(key);
}
@Override
public Float getFloatProperty(String key) throws ActiveMQPropertyConversionException {
return (Float) getApplicationPropertiesMap().get(key);
}
@Override
public String getStringProperty(String key) throws ActiveMQPropertyConversionException {
if (key.equals(MessageUtil.TYPE_HEADER_NAME.toString())) {
return getProperties().getSubject();
} else if (key.equals(MessageUtil.CONNECTION_ID_PROPERTY_NAME.toString())) {
return getConnectionID();
} else {
return (String) getApplicationPropertiesMap().get(key);
}
}
@Override
public Object removeAnnotation(SimpleString key) {
return removeSymbol(Symbol.getSymbol(key.toString()));
}
@Override
public Object getAnnotation(SimpleString key) {
return getSymbol(key.toString());
}
@Override
public AMQPMessage setAnnotation(SimpleString key, Object value) {
setSymbol(key.toString(), value);
return this;
}
@Override
public void reencode() {
parseHeaders();
ApplicationProperties properties = getApplicationProperties();
getProtonMessage().setDeliveryAnnotations(_deliveryAnnotations);
getProtonMessage().setMessageAnnotations(_messageAnnotations);
getProtonMessage().setApplicationProperties(properties);
getProtonMessage().setProperties(this._properties);
bufferValid = false;
checkBuffer();
}
@Override
public SimpleString getSimpleStringProperty(String key) throws ActiveMQPropertyConversionException {
return SimpleString.toSimpleString((String) getApplicationPropertiesMap().get(key));
}
@Override
public byte[] getBytesProperty(String key) throws ActiveMQPropertyConversionException {
return (byte[]) getApplicationPropertiesMap().get(key);
}
@Override
public Object removeProperty(SimpleString key) {
return removeProperty(key.toString());
}
@Override
public boolean containsProperty(SimpleString key) {
return containsProperty(key.toString());
}
@Override
public Boolean getBooleanProperty(SimpleString key) throws ActiveMQPropertyConversionException {
return getBooleanProperty(key.toString());
}
@Override
public Byte getByteProperty(SimpleString key) throws ActiveMQPropertyConversionException {
return getByteProperty(key.toString());
}
@Override
public Double getDoubleProperty(SimpleString key) throws ActiveMQPropertyConversionException {
return getDoubleProperty(key.toString());
}
@Override
public Integer getIntProperty(SimpleString key) throws ActiveMQPropertyConversionException {
return getIntProperty(key.toString());
}
@Override
public Long getLongProperty(SimpleString key) throws ActiveMQPropertyConversionException {
return getLongProperty(key.toString());
}
@Override
public Object getObjectProperty(SimpleString key) {
return getObjectProperty(key.toString());
}
@Override
public Short getShortProperty(SimpleString key) throws ActiveMQPropertyConversionException {
return getShortProperty(key.toString());
}
@Override
public Float getFloatProperty(SimpleString key) throws ActiveMQPropertyConversionException {
return getFloatProperty(key.toString());
}
@Override
public String getStringProperty(SimpleString key) throws ActiveMQPropertyConversionException {
return getStringProperty(key.toString());
}
@Override
public SimpleString getSimpleStringProperty(SimpleString key) throws ActiveMQPropertyConversionException {
return getSimpleStringProperty(key.toString());
}
@Override
public byte[] getBytesProperty(SimpleString key) throws ActiveMQPropertyConversionException {
return getBytesProperty(key.toString());
}
@Override
public org.apache.activemq.artemis.api.core.Message putStringProperty(SimpleString key, SimpleString value) {
return putStringProperty(key.toString(), value.toString());
}
@Override
public Set<SimpleString> getPropertyNames() {
HashSet<SimpleString> values = new HashSet<>();
for (Object k : getApplicationPropertiesMap().keySet()) {
values.add(SimpleString.toSimpleString(k.toString()));
}
return values;
}
@Override
public int getMemoryEstimate() {
if (memoryEstimate == -1) {
memoryEstimate = memoryOffset + (data != null ? data.capacity() : 0);
}
return memoryEstimate;
}
@Override
public ICoreMessage toCore() {
try {
return AMQPConverter.getInstance().toCore(this);
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
@Override
public SimpleString getReplyTo() {
if (getProperties() != null) {
return SimpleString.toSimpleString(getProperties().getReplyTo());
} else {
return null;
}
}
@Override
public AMQPMessage setReplyTo(SimpleString address) {
if (getProperties() != null) {
getProperties().setReplyTo(address != null ? address.toString() : null);
}
return this;
}
@Override
public int getPersistSize() {
return DataConstants.SIZE_INT + internalPersistSize();
}
private int internalPersistSize() {
return data.array().length - sendFrom;
}
@Override
public void persist(ActiveMQBuffer targetRecord) {
checkBuffer();
targetRecord.writeInt(internalPersistSize());
targetRecord.writeBytes(data.array(), sendFrom, data.array().length - sendFrom);
}
@Override
public void reloadPersistence(ActiveMQBuffer record) {
int size = record.readInt();
byte[] recordArray = new byte[size];
record.readBytes(recordArray);
this.sendFrom = 0; // whatever was persisted will be sent
this.data = Unpooled.wrappedBuffer(recordArray);
this.bufferValid = true;
this.durable = true; // it's coming from the journal, so it's durable
parseHeaders();
}
}
|
ARTEMIS-1052 Fixing MessageJournalTest::testStoreAMQP
|
artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/protocol/amqp/broker/AMQPMessage.java
|
ARTEMIS-1052 Fixing MessageJournalTest::testStoreAMQP
|
|
Java
|
apache-2.0
|
74586dad1b12166ef20673181086b335dc67c802
| 0
|
aosp-mirror/platform_frameworks_support,aosp-mirror/platform_frameworks_support,androidx/androidx,androidx/androidx,androidx/androidx,AndroidX/androidx,aosp-mirror/platform_frameworks_support,androidx/androidx,AndroidX/androidx,AndroidX/androidx,androidx/androidx,aosp-mirror/platform_frameworks_support,AndroidX/androidx,aosp-mirror/platform_frameworks_support,AndroidX/androidx,AndroidX/androidx,AndroidX/androidx,AndroidX/androidx,AndroidX/androidx,androidx/androidx,androidx/androidx,androidx/androidx,AndroidX/androidx,androidx/androidx,androidx/androidx
|
/*
* Copyright (C) 2012 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 android.support.v4.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* SlidingPaneLayout provides a horizontal, multi-pane layout for use at the top level
* of a UI. A left (or first) pane is treated as a content list or browser, subordinate to a
* primary detail view for displaying content.
*
* <p>Child views may overlap if their combined width exceeds the available width
* in the SlidingPaneLayout. When this occurs the user may slide the topmost view out of the way
* by dragging it, or by navigating in the direction of the overlapped view using a keyboard.
* If the content of the dragged child view is itself horizontally scrollable, the user may
* grab it by the very edge.</p>
*
* <p>Thanks to this sliding behavior, SlidingPaneLayout may be suitable for creating layouts
* that can smoothly adapt across many different screen sizes, expanding out fully on larger
* screens and collapsing on smaller screens.</p>
*
* <p>SlidingPaneLayout is distinct from a navigation drawer as described in the design
* guide and should not be used in the same scenarios. SlidingPaneLayout should be thought
* of only as a way to allow a two-pane layout normally used on larger screens to adapt to smaller
* screens in a natural way. The interaction patterns expressed by SlidingPaneLayout imply
* a physicality and direct information hierarchy between panes that does not necessarily exist
* in a scenario where a navigation drawer should be used instead.</p>
*
* <p>Appropriate uses of SlidingPaneLayout include pairings of panes such as a contact list and
* subordinate interactions with those contacts, or an email thread list with the content pane
* displaying the contents of the selected thread. Inappropriate uses of SlidingPaneLayout include
* switching between disparate functions of your app, such as jumping from a social stream view
* to a view of your personal profile - cases such as this should use the navigation drawer
* pattern instead. ({@link DrawerLayout DrawerLayout} implements this pattern.)</p>
*
* <p>Like {@link android.widget.LinearLayout LinearLayout}, SlidingPaneLayout supports
* the use of the layout parameter <code>layout_weight</code> on child views to determine
* how to divide leftover space after measurement is complete. It is only relevant for width.
* When views do not overlap weight behaves as it does in a LinearLayout.</p>
*
* <p>When views do overlap, weight on a slideable pane indicates that the pane should be
* sized to fill all available space in the closed state. Weight on a pane that becomes covered
* indicates that the pane should be sized to fill all available space except a small minimum strip
* that the user may use to grab the slideable view and pull it back over into a closed state.</p>
*
* <p>Experimental. This class may be removed.</p>
*/
public class SlidingPaneLayout extends ViewGroup {
private static final String TAG = "SlidingPaneLayout";
/**
* Default size of the overhang for a pane in the open state.
* At least this much of a sliding pane will remain visible.
* This indicates that there is more content available and provides
* a "physical" edge to grab to pull it closed.
*/
private static final int DEFAULT_OVERHANG_SIZE = 32; // dp;
/**
* If no fade color is given by default it will fade to 80% gray.
*/
private static final int DEFAULT_FADE_COLOR = 0xcccccccc;
/**
* The fade color used for the sliding panel. 0 = no fading.
*/
private int mSliderFadeColor = DEFAULT_FADE_COLOR;
/**
* The fade color used for the panel covered by the slider. 0 = no fading.
*/
private int mCoveredFadeColor;
/**
* Drawable used to draw the shadow between panes.
*/
private Drawable mShadowDrawable;
/**
* The size of the overhang in pixels.
* This is the minimum section of the sliding panel that will
* be visible in the open state to allow for a closing drag.
*/
private final int mOverhangSize;
/**
* True if a panel can slide with the current measurements
*/
private boolean mCanSlide;
/**
* The child view that can slide, if any.
*/
private View mSlideableView;
/**
* How far the panel is offset from its closed position.
* range [0, 1] where 0 = closed, 1 = open.
*/
private float mSlideOffset;
/**
* How far the non-sliding panel is parallaxed from its usual position when open.
* range [0, 1]
*/
private float mParallaxOffset;
/**
* How far in pixels the slideable panel may move.
*/
private int mSlideRange;
/**
* A panel view is locked into internal scrolling or another condition that
* is preventing a drag.
*/
private boolean mIsUnableToDrag;
/**
* Distance in pixels to parallax the fixed pane by when fully closed
*/
private int mParallaxBy;
private float mInitialMotionX;
private float mInitialMotionY;
private PanelSlideListener mPanelSlideListener;
private final ViewDragHelper mDragHelper;
private final Rect mTmpRect = new Rect();
static final SlidingPanelLayoutImpl IMPL;
static {
final int deviceVersion = Build.VERSION.SDK_INT;
if (deviceVersion >= 17) {
IMPL = new SlidingPanelLayoutImplJBMR1();
} else if (deviceVersion >= 16) {
IMPL = new SlidingPanelLayoutImplJB();
} else {
IMPL = new SlidingPanelLayoutImplBase();
}
}
/**
* Listener for monitoring events about sliding panes.
*/
public interface PanelSlideListener {
/**
* Called when a sliding pane's position changes.
* @param panel The child view that was moved
* @param slideOffset The new offset of this sliding pane within its range, from 0-1
*/
public void onPanelSlide(View panel, float slideOffset);
/**
* Called when a sliding pane becomes slid completely open. The pane may or may not
* be interactive at this point depending on how much of the pane is visible.
* @param panel The child view that was slid to an open position, revealing other panes
*/
public void onPanelOpened(View panel);
/**
* Called when a sliding pane becomes slid completely closed. The pane is now guaranteed
* to be interactive. It may now obscure other views in the layout.
* @param panel The child view that was slid to a closed position
*/
public void onPanelClosed(View panel);
}
/**
* No-op stubs for {@link PanelSlideListener}. If you only want to implement a subset
* of the listener methods you can extend this instead of implement the full interface.
*/
public static class SimplePanelSlideListener implements PanelSlideListener {
@Override
public void onPanelSlide(View panel, float slideOffset) {
}
@Override
public void onPanelOpened(View panel) {
}
@Override
public void onPanelClosed(View panel) {
}
}
public SlidingPaneLayout(Context context) {
this(context, null);
}
public SlidingPaneLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public SlidingPaneLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
final float density = context.getResources().getDisplayMetrics().density;
mOverhangSize = (int) (DEFAULT_OVERHANG_SIZE * density + 0.5f);
final ViewConfiguration viewConfig = ViewConfiguration.get(context);
setWillNotDraw(false);
mDragHelper = ViewDragHelper.create(this, 0.5f, new DragHelperCallback());
mDragHelper.setEdgeTrackingEnabled(ViewDragHelper.EDGE_LEFT);
}
/**
* Set a distance to parallax the lower pane by when the upper pane is in its
* fully closed state. The lower pane will scroll between this position and
* its fully open state.
*
* @param parallaxBy Distance to parallax by in pixels
*/
public void setParallaxDistance(int parallaxBy) {
mParallaxBy = parallaxBy;
requestLayout();
}
/**
* @return The distance the lower pane will parallax by when the upper pane is fully closed.
*
* @see #setParallaxDistance(int)
*/
public int getParallaxDistance() {
return mParallaxBy;
}
/**
* Set the color used to fade the sliding pane out when it is slid most of the way offscreen.
*
* @param color An ARGB-packed color value
*/
public void setSliderFadeColor(int color) {
mSliderFadeColor = color;
}
/**
* @return The ARGB-packed color value used to fade the sliding pane
*/
public int getSliderFadeColor() {
return mSliderFadeColor;
}
/**
* Set the color used to fade the pane covered by the sliding pane out when the pane
* will become fully covered in the closed state.
*
* @param color An ARGB-packed color value
*/
public void setCoveredFadeColor(int color) {
mCoveredFadeColor = color;
}
/**
* @return The ARGB-packed color value used to fade the fixed pane
*/
public int getCoveredFadeColor() {
return mCoveredFadeColor;
}
public void setPanelSlideListener(PanelSlideListener listener) {
mPanelSlideListener = listener;
}
void dispatchOnPanelSlide(View panel) {
if (mPanelSlideListener != null) {
mPanelSlideListener.onPanelSlide(panel, mSlideOffset);
}
}
void dispatchOnPanelOpened(View panel) {
if (mPanelSlideListener != null) {
mPanelSlideListener.onPanelOpened(panel);
}
}
void dispatchOnPanelClosed(View panel) {
if (mPanelSlideListener != null) {
mPanelSlideListener.onPanelClosed(panel);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
final int widthSize = MeasureSpec.getSize(widthMeasureSpec);
final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
final int heightSize = MeasureSpec.getSize(heightMeasureSpec);
if (widthMode != MeasureSpec.EXACTLY) {
throw new IllegalStateException("Width must have an exact value or MATCH_PARENT");
} else if (heightMode == MeasureSpec.UNSPECIFIED) {
throw new IllegalStateException("Height must not be UNSPECIFIED");
}
int layoutHeight = 0;
int maxLayoutHeight = -1;
switch (heightMode) {
case MeasureSpec.EXACTLY:
layoutHeight = maxLayoutHeight = heightSize - getPaddingTop() - getPaddingBottom();
break;
case MeasureSpec.AT_MOST:
maxLayoutHeight = heightSize - getPaddingTop() - getPaddingBottom();
break;
}
float weightSum = 0;
boolean canSlide = false;
int widthRemaining = widthSize - getPaddingLeft() - getPaddingRight();
final int childCount = getChildCount();
if (childCount > 2) {
Log.e(TAG, "onMeasure: More than two child views are not supported.");
}
// We'll find the current one below.
mSlideableView = null;
// First pass. Measure based on child LayoutParams width/height.
// Weight will incur a second pass.
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (child.getVisibility() == GONE) {
lp.dimWhenOffset = false;
continue;
}
if (lp.weight > 0) {
weightSum += lp.weight;
// If we have no width, weight is the only contributor to the final size.
// Measure this view on the weight pass only.
if (lp.width == 0) continue;
}
int childWidthSpec;
final int horizontalMargin = lp.leftMargin + lp.rightMargin;
if (lp.width == LayoutParams.WRAP_CONTENT) {
childWidthSpec = MeasureSpec.makeMeasureSpec(widthSize - horizontalMargin,
MeasureSpec.AT_MOST);
} else if (lp.width == LayoutParams.FILL_PARENT) {
childWidthSpec = MeasureSpec.makeMeasureSpec(widthSize - horizontalMargin,
MeasureSpec.EXACTLY);
} else {
childWidthSpec = MeasureSpec.makeMeasureSpec(lp.width, MeasureSpec.EXACTLY);
}
int childHeightSpec;
if (lp.height == LayoutParams.WRAP_CONTENT) {
childHeightSpec = MeasureSpec.makeMeasureSpec(maxLayoutHeight, MeasureSpec.AT_MOST);
} else if (lp.height == LayoutParams.FILL_PARENT) {
childHeightSpec = MeasureSpec.makeMeasureSpec(maxLayoutHeight, MeasureSpec.EXACTLY);
} else {
childHeightSpec = MeasureSpec.makeMeasureSpec(lp.height, MeasureSpec.EXACTLY);
}
child.measure(childWidthSpec, childHeightSpec);
final int childWidth = child.getMeasuredWidth();
final int childHeight = child.getMeasuredHeight();
if (heightMode == MeasureSpec.AT_MOST && childHeight > layoutHeight) {
layoutHeight = Math.min(childHeight, maxLayoutHeight);
}
widthRemaining -= childWidth;
canSlide |= lp.slideable = widthRemaining < 0;
if (lp.slideable) {
mSlideableView = child;
}
}
// Resolve weight and make sure non-sliding panels are smaller than the full screen.
if (canSlide || weightSum > 0) {
final int fixedPanelWidthLimit = widthSize - mOverhangSize;
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == GONE) {
continue;
}
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final boolean skippedFirstPass = lp.width == 0 && lp.weight > 0;
final int measuredWidth = skippedFirstPass ? 0 : child.getMeasuredWidth();
if (canSlide && child != mSlideableView) {
if (lp.width < 0 && (measuredWidth > fixedPanelWidthLimit || lp.weight > 0)) {
// Fixed panels in a sliding configuration should
// be clamped to the fixed panel limit.
final int childHeightSpec;
if (skippedFirstPass) {
// Do initial height measurement if we skipped measuring this view
// the first time around.
if (lp.height == LayoutParams.WRAP_CONTENT) {
childHeightSpec = MeasureSpec.makeMeasureSpec(maxLayoutHeight,
MeasureSpec.AT_MOST);
} else if (lp.height == LayoutParams.FILL_PARENT) {
childHeightSpec = MeasureSpec.makeMeasureSpec(maxLayoutHeight,
MeasureSpec.EXACTLY);
} else {
childHeightSpec = MeasureSpec.makeMeasureSpec(lp.height,
MeasureSpec.EXACTLY);
}
} else {
childHeightSpec = MeasureSpec.makeMeasureSpec(
child.getMeasuredHeight(), MeasureSpec.EXACTLY);
}
final int childWidthSpec = MeasureSpec.makeMeasureSpec(
fixedPanelWidthLimit, MeasureSpec.EXACTLY);
child.measure(childWidthSpec, childHeightSpec);
}
} else if (lp.weight > 0) {
int childHeightSpec;
if (lp.width == 0) {
// This was skipped the first time; figure out a real height spec.
if (lp.height == LayoutParams.WRAP_CONTENT) {
childHeightSpec = MeasureSpec.makeMeasureSpec(maxLayoutHeight,
MeasureSpec.AT_MOST);
} else if (lp.height == LayoutParams.FILL_PARENT) {
childHeightSpec = MeasureSpec.makeMeasureSpec(maxLayoutHeight,
MeasureSpec.EXACTLY);
} else {
childHeightSpec = MeasureSpec.makeMeasureSpec(lp.height,
MeasureSpec.EXACTLY);
}
} else {
childHeightSpec = MeasureSpec.makeMeasureSpec(
child.getMeasuredHeight(), MeasureSpec.EXACTLY);
}
if (canSlide) {
// Consume available space
final int horizontalMargin = lp.leftMargin + lp.rightMargin;
final int newWidth = widthSize - horizontalMargin;
final int childWidthSpec = MeasureSpec.makeMeasureSpec(
newWidth, MeasureSpec.EXACTLY);
if (measuredWidth != newWidth) {
child.measure(childWidthSpec, childHeightSpec);
}
} else {
// Distribute the extra width proportionally similar to LinearLayout
final int widthToDistribute = Math.max(0, widthRemaining);
final int addedWidth = (int) (lp.weight * widthToDistribute / weightSum);
final int childWidthSpec = MeasureSpec.makeMeasureSpec(
measuredWidth + addedWidth, MeasureSpec.EXACTLY);
child.measure(childWidthSpec, childHeightSpec);
}
}
}
}
setMeasuredDimension(widthSize, layoutHeight);
mCanSlide = canSlide;
if (mDragHelper.getViewDragState() != ViewDragHelper.STATE_IDLE && !canSlide) {
// Cancel scrolling in progress, it's no longer relevant.
mDragHelper.abort();
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final int width = r - l;
final int paddingLeft = getPaddingLeft();
final int paddingRight = getPaddingRight();
final int paddingTop = getPaddingTop();
final int childCount = getChildCount();
int xStart = paddingLeft;
int nextXStart = xStart;
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == GONE) {
continue;
}
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final int childWidth = child.getMeasuredWidth();
int offset = 0;
if (lp.slideable) {
final int margin = lp.leftMargin + lp.rightMargin;
final int range = Math.min(nextXStart,
width - paddingRight - mOverhangSize) - xStart - margin;
mSlideRange = range;
lp.dimWhenOffset = xStart + lp.leftMargin + range + childWidth / 2 >
width - paddingRight;
xStart += (int) (range * mSlideOffset) + lp.leftMargin;
} else if (mCanSlide && mParallaxBy != 0) {
offset = (int) ((1 - mSlideOffset) * mParallaxBy);
xStart = nextXStart;
} else {
xStart = nextXStart;
}
final int childLeft = xStart - offset;
final int childRight = childLeft + childWidth;
final int childTop = paddingTop;
final int childBottom = childTop + child.getMeasuredHeight();
child.layout(childLeft, paddingTop, childRight, childBottom);
nextXStart += child.getWidth();
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
final int action = ev.getAction() & MotionEventCompat.ACTION_MASK;
if (!mCanSlide || (mIsUnableToDrag && action != MotionEvent.ACTION_DOWN)) {
mDragHelper.cancel();
return super.onInterceptTouchEvent(ev);
}
if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
mDragHelper.cancel();
return false;
}
boolean interceptTap = false;
switch (action) {
case MotionEvent.ACTION_DOWN: {
mIsUnableToDrag = false;
final float x = ev.getX();
final float y = ev.getY();
mInitialMotionX = x;
mInitialMotionY = y;
if (mDragHelper.isViewUnder(mSlideableView, (int) x, (int) y) &&
isDimmed(mSlideableView)) {
interceptTap = true;
}
break;
}
case MotionEvent.ACTION_MOVE: {
final float x = ev.getX();
final float y = ev.getY();
final float adx = Math.abs(x - mInitialMotionX);
final float ady = Math.abs(y - mInitialMotionY);
final int slop = mDragHelper.getTouchSlop();
if (adx > slop && ady > adx) {
mDragHelper.cancel();
mIsUnableToDrag = true;
return false;
}
}
}
final boolean interceptForDrag = mDragHelper.shouldInterceptTouchEvent(ev);
return interceptForDrag || interceptTap;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (!mCanSlide) {
return super.onTouchEvent(ev);
}
mDragHelper.processTouchEvent(ev);
final int action = ev.getAction();
boolean wantTouchEvents = true;
switch (action & MotionEventCompat.ACTION_MASK) {
case MotionEvent.ACTION_DOWN: {
final float x = ev.getX();
final float y = ev.getY();
mInitialMotionX = x;
mInitialMotionY = y;
break;
}
case MotionEvent.ACTION_UP: {
if (isDimmed(mSlideableView)) {
final float x = ev.getX();
final float y = ev.getY();
final float dx = x - mInitialMotionX;
final float dy = y - mInitialMotionY;
final int slop = mDragHelper.getTouchSlop();
if (dx * dx + dy * dy < slop * slop &&
mDragHelper.isViewUnder(mSlideableView, (int) x, (int) y)) {
// Taps close a dimmed open pane.
closePane(mSlideableView, 0);
break;
}
}
break;
}
}
return wantTouchEvents;
}
private void closePane(View pane, int initialVelocity) {
if (mCanSlide) {
smoothSlideTo(0.f, initialVelocity);
}
}
private void openPane(View pane, int initialVelocity) {
if (mCanSlide) {
smoothSlideTo(1.f, initialVelocity);
}
}
/**
* Animate the sliding panel to its open state.
*/
public void smoothSlideOpen() {
if (mCanSlide) {
openPane(mSlideableView, 0);
}
}
/**
* Animate the sliding panel to its closed state.
*/
public void smoothSlideClosed() {
if (mCanSlide) {
closePane(mSlideableView, 0);
}
}
/**
* @return true if sliding panels are completely open
*/
public boolean isOpen() {
return !mCanSlide || mSlideOffset == 1;
}
/**
* @return true if content in this layout can be slid open and closed
*/
public boolean canSlide() {
return mCanSlide;
}
private boolean performDrag(int newLeft) {
final LayoutParams lp = (LayoutParams) mSlideableView.getLayoutParams();
final int leftBound = getPaddingLeft() + lp.leftMargin;
final float oldLeft = mSlideableView.getLeft();
final int dxPane = (int) (newLeft - oldLeft);
mSlideableView.offsetLeftAndRight(dxPane);
mSlideOffset = (float) (newLeft - leftBound) / mSlideRange;
if (mParallaxBy != 0) {
parallaxOtherViews(mSlideOffset);
}
if (lp.dimWhenOffset) {
dimChildView(mSlideableView, mSlideOffset, mSliderFadeColor);
}
dispatchOnPanelSlide(mSlideableView);
return true;
}
private void dimChildView(View v, float mag, int fadeColor) {
final LayoutParams lp = (LayoutParams) v.getLayoutParams();
if (mag > 0 && fadeColor != 0) {
final int baseAlpha = (fadeColor & 0xff000000) >>> 24;
int imag = (int) (baseAlpha * mag);
int color = imag << 24 | (fadeColor & 0xffffff);
if (lp.dimPaint == null) {
lp.dimPaint = new Paint();
}
lp.dimPaint.setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.SRC_OVER));
if (ViewCompat.getLayerType(v) != ViewCompat.LAYER_TYPE_HARDWARE) {
ViewCompat.setLayerType(v, ViewCompat.LAYER_TYPE_HARDWARE, lp.dimPaint);
}
invalidateChildRegion(v);
} else if (ViewCompat.getLayerType(v) != ViewCompat.LAYER_TYPE_NONE) {
ViewCompat.setLayerType(v, ViewCompat.LAYER_TYPE_NONE, null);
}
}
@Override
protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
boolean result;
final int save = canvas.save(Canvas.CLIP_SAVE_FLAG);
if (mCanSlide && !lp.slideable && mSlideableView != null) {
// Clip against the slider; no sense drawing what will immediately be covered.
canvas.getClipBounds(mTmpRect);
mTmpRect.right = Math.min(mTmpRect.right, mSlideableView.getLeft());
canvas.clipRect(mTmpRect);
}
if (Build.VERSION.SDK_INT >= 11) { // HC
result = super.drawChild(canvas, child, drawingTime);
} else {
if (lp.dimWhenOffset && mSlideOffset > 0) {
if (!child.isDrawingCacheEnabled()) {
child.setDrawingCacheEnabled(true);
}
final Bitmap cache = child.getDrawingCache();
canvas.drawBitmap(cache, child.getLeft(), child.getTop(), lp.dimPaint);
result = false;
} else {
if (child.isDrawingCacheEnabled()) {
child.setDrawingCacheEnabled(false);
}
result = super.drawChild(canvas, child, drawingTime);
}
}
canvas.restoreToCount(save);
return result;
}
private void invalidateChildRegion(View v) {
IMPL.invalidateChildRegion(this, v);
}
/**
* Smoothly animate mDraggingPane to the target X position within its range.
*
* @param slideOffset position to animate to
* @param velocity initial velocity in case of fling, or 0.
*/
void smoothSlideTo(float slideOffset, int velocity) {
if (!mCanSlide) {
// Nothing to do.
return;
}
final LayoutParams lp = (LayoutParams) mSlideableView.getLayoutParams();
final int leftBound = getPaddingLeft() + lp.leftMargin;
int x = (int) (leftBound + slideOffset * mSlideRange);
if (mDragHelper.smoothSlideViewTo(mSlideableView, x, mSlideableView.getTop())) {
ViewCompat.postInvalidateOnAnimation(this);
}
}
@Override
public void computeScroll() {
if (mDragHelper.continueSettling(true)) {
if (!mCanSlide) {
mDragHelper.abort();
return;
}
ViewCompat.postInvalidateOnAnimation(this);
}
}
/**
* Set a drawable to use as a shadow cast by the right pane onto the left pane
* during opening/closing.
*
* @param d drawable to use as a shadow
*/
public void setShadowDrawable(Drawable d) {
mShadowDrawable = d;
}
/**
* Set a drawable to use as a shadow cast by the right pane onto the left pane
* during opening/closing.
*
* @param resId Resource ID of a drawable to use
*/
public void setShadowResource(int resId) {
setShadowDrawable(getResources().getDrawable(resId));
}
@Override
public void draw(Canvas c) {
super.draw(c);
final View shadowView = getChildCount() > 1 ? getChildAt(1) : null;
if (shadowView == null || mShadowDrawable == null) {
// No need to draw a shadow if we don't have one.
return;
}
final int shadowWidth = mShadowDrawable.getIntrinsicWidth();
final int right = shadowView.getLeft();
final int top = shadowView.getTop();
final int bottom = shadowView.getBottom();
final int left = right - shadowWidth;
mShadowDrawable.setBounds(left, top, right, bottom);
mShadowDrawable.draw(c);
}
private void parallaxOtherViews(float slideOffset) {
final LayoutParams slideLp = (LayoutParams) mSlideableView.getLayoutParams();
final boolean dimViews = slideLp.dimWhenOffset && slideLp.leftMargin <= 0;
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View v = getChildAt(i);
if (v == mSlideableView) continue;
final int oldOffset = (int) ((1 - mParallaxOffset) * mParallaxBy);
mParallaxOffset = slideOffset;
final int newOffset = (int) ((1 - slideOffset) * mParallaxBy);
final int dx = oldOffset - newOffset;
v.offsetLeftAndRight(dx);
if (dimViews) {
dimChildView(v, 1 - mParallaxOffset, mCoveredFadeColor);
}
}
}
/**
* Tests scrollability within child views of v given a delta of dx.
*
* @param v View to test for horizontal scrollability
* @param checkV Whether the view v passed should itself be checked for scrollability (true),
* or just its children (false).
* @param dx Delta scrolled in pixels
* @param x X coordinate of the active touch point
* @param y Y coordinate of the active touch point
* @return true if child views of v can be scrolled by delta of dx.
*/
protected boolean canScroll(View v, boolean checkV, int dx, int x, int y) {
if (v instanceof ViewGroup) {
final ViewGroup group = (ViewGroup) v;
final int scrollX = v.getScrollX();
final int scrollY = v.getScrollY();
final int count = group.getChildCount();
// Count backwards - let topmost views consume scroll distance first.
for (int i = count - 1; i >= 0; i--) {
// TODO: Add versioned support here for transformed views.
// This will not work for transformed views in Honeycomb+
final View child = group.getChildAt(i);
if (x + scrollX >= child.getLeft() && x + scrollX < child.getRight() &&
y + scrollY >= child.getTop() && y + scrollY < child.getBottom() &&
canScroll(child, true, dx, x + scrollX - child.getLeft(),
y + scrollY - child.getTop())) {
return true;
}
}
}
return checkV && ViewCompat.canScrollHorizontally(v, -dx);
}
boolean isDimmed(View child) {
if (child == null) {
return false;
}
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
return mCanSlide && lp.dimWhenOffset && mSlideOffset > 0;
}
@Override
protected ViewGroup.LayoutParams generateDefaultLayoutParams() {
return new LayoutParams();
}
@Override
protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
return p instanceof MarginLayoutParams
? new LayoutParams((MarginLayoutParams) p)
: new LayoutParams(p);
}
@Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
return p instanceof LayoutParams && super.checkLayoutParams(p);
}
@Override
public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
return new LayoutParams(getContext(), attrs);
}
@Override
protected Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
SavedState ss = new SavedState(superState);
ss.isOpen = isOpen();
return ss;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
SavedState ss = (SavedState) state;
super.onRestoreInstanceState(ss.getSuperState());
// TODO: Completely restore state
}
private class DragHelperCallback extends ViewDragHelper.Callback {
@Override
public boolean tryCaptureView(View child, int pointerId) {
if (mIsUnableToDrag) {
return false;
}
return ((LayoutParams) child.getLayoutParams()).slideable;
}
@Override
public void onViewDragStateChanged(int state) {
if (mDragHelper.getViewDragState() == ViewDragHelper.STATE_IDLE) {
if (mSlideOffset == 0) {
dispatchOnPanelClosed(mSlideableView);
} else {
dispatchOnPanelOpened(mSlideableView);
}
}
}
@Override
public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {
performDrag(left);
invalidate();
}
@Override
public void onViewReleased(View releasedChild, float xvel, float yvel) {
final LayoutParams lp = (LayoutParams) releasedChild.getLayoutParams();
int left = getPaddingLeft() + lp.leftMargin;
if (xvel > 0 || (xvel == 0 && mSlideOffset > 0.5f)) {
left += mSlideRange;
}
mDragHelper.settleCapturedViewAt(left, releasedChild.getTop());
invalidate();
}
@Override
public int getViewHorizontalDragRange(View child) {
return mSlideRange;
}
@Override
public int clampViewPositionHorizontal(View child, int left, int dx) {
final LayoutParams lp = (LayoutParams) mSlideableView.getLayoutParams();
final int leftBound = getPaddingLeft() + lp.leftMargin;
final int rightBound = leftBound + mSlideRange;
final int newLeft = Math.min(Math.max(left, leftBound), rightBound);
return newLeft;
}
@Override
public void onEdgeDragStarted(int edgeFlags, int pointerId) {
mDragHelper.captureChildView(mSlideableView, pointerId);
}
}
public static class LayoutParams extends ViewGroup.MarginLayoutParams {
private static final int[] ATTRS = new int[] {
android.R.attr.layout_weight
};
/**
* The weighted proportion of how much of the leftover space
* this child should consume after measurement.
*/
public float weight = 0;
/**
* True if this pane is the slideable pane in the layout.
*/
boolean slideable;
/**
* True if this view should be drawn dimmed
* when it's been offset from its default position.
*/
boolean dimWhenOffset;
Paint dimPaint;
public LayoutParams() {
super(FILL_PARENT, FILL_PARENT);
}
public LayoutParams(int width, int height) {
super(width, height);
}
public LayoutParams(android.view.ViewGroup.LayoutParams source) {
super(source);
}
public LayoutParams(MarginLayoutParams source) {
super(source);
}
public LayoutParams(LayoutParams source) {
super(source);
this.weight = source.weight;
}
public LayoutParams(Context c, AttributeSet attrs) {
super(c, attrs);
final TypedArray a = c.obtainStyledAttributes(attrs, ATTRS);
this.weight = a.getFloat(0, 0);
a.recycle();
}
}
static class SavedState extends BaseSavedState {
boolean isOpen;
SavedState(Parcelable superState) {
super(superState);
}
private SavedState(Parcel in) {
super(in);
isOpen = in.readInt() != 0;
}
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeInt(isOpen ? 1 : 0);
}
public static final Parcelable.Creator<SavedState> CREATOR =
new Parcelable.Creator<SavedState>() {
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
interface SlidingPanelLayoutImpl {
void invalidateChildRegion(SlidingPaneLayout parent, View child);
}
static class SlidingPanelLayoutImplBase implements SlidingPanelLayoutImpl {
public void invalidateChildRegion(SlidingPaneLayout parent, View child) {
ViewCompat.postInvalidateOnAnimation(parent, child.getLeft(), child.getTop(),
child.getRight(), child.getBottom());
}
}
static class SlidingPanelLayoutImplJB extends SlidingPanelLayoutImplBase {
/*
* Private API hacks! Nasty! Bad!
*
* In Jellybean, some optimizations in the hardware UI renderer
* prevent a changed Paint on a View using a hardware layer from having
* the intended effect. This twiddles some internal bits on the view to force
* it to recreate the display list.
*/
private Method mGetDisplayList;
private Field mRecreateDisplayList;
SlidingPanelLayoutImplJB() {
try {
mGetDisplayList = View.class.getDeclaredMethod("getDisplayList", (Class[]) null);
} catch (NoSuchMethodException e) {
Log.e(TAG, "Couldn't fetch getDisplayList method; dimming won't work right.", e);
}
try {
mRecreateDisplayList = View.class.getDeclaredField("mRecreateDisplayList");
mRecreateDisplayList.setAccessible(true);
} catch (NoSuchFieldException e) {
Log.e(TAG, "Couldn't fetch mRecreateDisplayList field; dimming will be slow.", e);
}
}
@Override
public void invalidateChildRegion(SlidingPaneLayout parent, View child) {
if (mGetDisplayList != null && mRecreateDisplayList != null) {
try {
mRecreateDisplayList.setBoolean(child, true);
mGetDisplayList.invoke(child, (Object[]) null);
} catch (Exception e) {
Log.e(TAG, "Error refreshing display list state", e);
}
} else {
// Slow path. REALLY slow path. Let's hope we don't get here.
child.invalidate();
return;
}
super.invalidateChildRegion(parent, child);
}
}
static class SlidingPanelLayoutImplJBMR1 extends SlidingPanelLayoutImplBase {
@Override
public void invalidateChildRegion(SlidingPaneLayout parent, View child) {
ViewCompat.setLayerPaint(child, ((LayoutParams) child.getLayoutParams()).dimPaint);
}
}
}
|
v4/java/android/support/v4/widget/SlidingPaneLayout.java
|
/*
* Copyright (C) 2012 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 android.support.v4.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* SlidingPaneLayout provides a horizontal, multi-pane layout for use at the top level
* of a UI. A left (or first) pane is treated as a content list or browser, subordinate to a
* primary detail view for displaying content.
*
* <p>Child views may overlap if their combined width exceeds the available width
* in the SlidingPaneLayout. When this occurs the user may slide the topmost view out of the way
* by dragging it, or by navigating in the direction of the overlapped view using a keyboard.
* If the content of the dragged child view is itself horizontally scrollable, the user may
* grab it by the very edge.</p>
*
* <p>Thanks to this sliding behavior, SlidingPaneLayout may be suitable for creating layouts
* that can smoothly adapt across many different screen sizes, expanding out fully on larger
* screens and collapsing on smaller screens.</p>
*
* <p>SlidingPaneLayout is distinct from a navigation drawer as described in the design
* guide and should not be used in the same scenarios. SlidingPaneLayout should be thought
* of only as a way to allow a two-pane layout normally used on larger screens to adapt to smaller
* screens in a natural way. The interaction patterns expressed by SlidingPaneLayout imply
* a physicality and direct information hierarchy between panes that does not necessarily exist
* in a scenario where a navigation drawer should be used instead.</p>
*
* <p>Appropriate uses of SlidingPaneLayout include pairings of panes such as a contact list and
* subordinate interactions with those contacts, or an email thread list with the content pane
* displaying the contents of the selected thread. Inappropriate uses of SlidingPaneLayout include
* switching between disparate functions of your app, such as jumping from a social stream view
* to a view of your personal profile - cases such as this should use the navigation drawer
* pattern instead. ({@link DrawerLayout DrawerLayout} implements this pattern.)</p>
*
* <p>Like {@link android.widget.LinearLayout LinearLayout}, SlidingPaneLayout supports
* the use of the layout parameter <code>layout_weight</code> on child views to determine
* how to divide leftover space after measurement is complete. It is only relevant for width.
* When views do not overlap weight behaves as it does in a LinearLayout.</p>
*
* <p>When views do overlap, weight on a slideable pane indicates that the pane should be
* sized to fill all available space in the closed state. Weight on a pane that becomes covered
* indicates that the pane should be sized to fill all available space except a small minimum strip
* that the user may use to grab the slideable view and pull it back over into a closed state.</p>
*
* <p>Experimental. This class may be removed.</p>
*/
public class SlidingPaneLayout extends ViewGroup {
private static final String TAG = "SlidingPaneLayout";
/**
* Default size of the overhang for a pane in the open state.
* At least this much of a sliding pane will remain visible.
* This indicates that there is more content available and provides
* a "physical" edge to grab to pull it closed.
*/
private static final int DEFAULT_OVERHANG_SIZE = 32; // dp;
/**
* If no fade color is given by default it will fade to 80% gray.
*/
private static final int DEFAULT_FADE_COLOR = 0xcccccccc;
/**
* The fade color used for the sliding panel. 0 = no fading.
*/
private int mSliderFadeColor = DEFAULT_FADE_COLOR;
/**
* The fade color used for the panel covered by the slider. 0 = no fading.
*/
private int mCoveredFadeColor;
/**
* Drawable used to draw the shadow between panes.
*/
private Drawable mShadowDrawable;
/**
* The size of the overhang in pixels.
* This is the minimum section of the sliding panel that will
* be visible in the open state to allow for a closing drag.
*/
private final int mOverhangSize;
/**
* True if a panel can slide with the current measurements
*/
private boolean mCanSlide;
/**
* The child view that can slide, if any.
*/
private View mSlideableView;
/**
* How far the panel is offset from its closed position.
* range [0, 1] where 0 = closed, 1 = open.
*/
private float mSlideOffset;
/**
* How far the non-sliding panel is parallaxed from its usual position when open.
* range [0, 1]
*/
private float mParallaxOffset;
/**
* How far in pixels the slideable panel may move.
*/
private int mSlideRange;
/**
* A panel view is locked into internal scrolling or another condition that
* is preventing a drag.
*/
private boolean mIsUnableToDrag;
/**
* Distance in pixels to parallax the fixed pane by when fully closed
*/
private int mParallaxBy;
private float mInitialMotionX;
private float mInitialMotionY;
private PanelSlideListener mPanelSlideListener;
private final ViewDragHelper mDragHelper;
private final Rect mTmpRect = new Rect();
static final SlidingPanelLayoutImpl IMPL;
static {
final int deviceVersion = Build.VERSION.SDK_INT;
if (deviceVersion >= 17) {
IMPL = new SlidingPanelLayoutImplJBMR1();
} else if (deviceVersion >= 16) {
IMPL = new SlidingPanelLayoutImplJB();
} else {
IMPL = new SlidingPanelLayoutImplBase();
}
}
/**
* Listener for monitoring events about sliding panes.
*/
public interface PanelSlideListener {
/**
* Called when a sliding pane's position changes.
* @param panel The child view that was moved
* @param slideOffset The new offset of this sliding pane within its range, from 0-1
*/
public void onPanelSlide(View panel, float slideOffset);
/**
* Called when a sliding pane becomes slid completely open. The pane may or may not
* be interactive at this point depending on how much of the pane is visible.
* @param panel The child view that was slid to an open position, revealing other panes
*/
public void onPanelOpened(View panel);
/**
* Called when a sliding pane becomes slid completely closed. The pane is now guaranteed
* to be interactive. It may now obscure other views in the layout.
* @param panel The child view that was slid to a closed position
*/
public void onPanelClosed(View panel);
}
/**
* No-op stubs for {@link PanelSlideListener}. If you only want to implement a subset
* of the listener methods you can extend this instead of implement the full interface.
*/
public static class SimplePanelSlideListener implements PanelSlideListener {
@Override
public void onPanelSlide(View panel, float slideOffset) {
}
@Override
public void onPanelOpened(View panel) {
}
@Override
public void onPanelClosed(View panel) {
}
}
public SlidingPaneLayout(Context context) {
this(context, null);
}
public SlidingPaneLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public SlidingPaneLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
final float density = context.getResources().getDisplayMetrics().density;
mOverhangSize = (int) (DEFAULT_OVERHANG_SIZE * density + 0.5f);
final ViewConfiguration viewConfig = ViewConfiguration.get(context);
setWillNotDraw(false);
mDragHelper = ViewDragHelper.create(this, 0.5f, new DragHelperCallback());
mDragHelper.setEdgeTrackingEnabled(ViewDragHelper.EDGE_LEFT);
}
/**
* Set a distance to parallax the lower pane by when the upper pane is in its
* fully closed state. The lower pane will scroll between this position and
* its fully open state.
*
* @param parallaxBy Distance to parallax by in pixels
*/
public void setParallaxDistance(int parallaxBy) {
mParallaxBy = parallaxBy;
requestLayout();
}
/**
* @return The distance the lower pane will parallax by when the upper pane is fully closed.
*
* @see #setParallaxDistance(int)
*/
public int getParallaxDistance() {
return mParallaxBy;
}
/**
* Set the color used to fade the sliding pane out when it is slid most of the way offscreen.
*
* @param color An ARGB-packed color value
*/
public void setSliderFadeColor(int color) {
mSliderFadeColor = color;
}
/**
* @return The ARGB-packed color value used to fade the sliding pane
*/
public int getSliderFadeColor() {
return mSliderFadeColor;
}
/**
* Set the color used to fade the pane covered by the sliding pane out when the pane
* will become fully covered in the closed state.
*
* @param color An ARGB-packed color value
*/
public void setCoveredFadeColor(int color) {
mCoveredFadeColor = color;
}
/**
* @return The ARGB-packed color value used to fade the fixed pane
*/
public int getCoveredFadeColor() {
return mCoveredFadeColor;
}
public void setPanelSlideListener(PanelSlideListener listener) {
mPanelSlideListener = listener;
}
void dispatchOnPanelSlide(View panel) {
if (mPanelSlideListener != null) {
mPanelSlideListener.onPanelSlide(panel, mSlideOffset);
}
}
void dispatchOnPanelOpened(View panel) {
if (mPanelSlideListener != null) {
mPanelSlideListener.onPanelOpened(panel);
}
}
void dispatchOnPanelClosed(View panel) {
if (mPanelSlideListener != null) {
mPanelSlideListener.onPanelClosed(panel);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
final int widthSize = MeasureSpec.getSize(widthMeasureSpec);
final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
final int heightSize = MeasureSpec.getSize(heightMeasureSpec);
if (widthMode != MeasureSpec.EXACTLY) {
throw new IllegalStateException("Width must have an exact value or MATCH_PARENT");
} else if (heightMode == MeasureSpec.UNSPECIFIED) {
throw new IllegalStateException("Height must not be UNSPECIFIED");
}
int layoutHeight = 0;
int maxLayoutHeight = -1;
switch (heightMode) {
case MeasureSpec.EXACTLY:
layoutHeight = maxLayoutHeight = heightSize - getPaddingTop() - getPaddingBottom();
break;
case MeasureSpec.AT_MOST:
maxLayoutHeight = heightSize - getPaddingTop() - getPaddingBottom();
break;
}
float weightSum = 0;
boolean canSlide = false;
int widthRemaining = widthSize - getPaddingLeft() - getPaddingRight();
final int childCount = getChildCount();
if (childCount > 2) {
Log.e(TAG, "onMeasure: More than two child views are not supported.");
}
// We'll find the current one below.
mSlideableView = null;
// First pass. Measure based on child LayoutParams width/height.
// Weight will incur a second pass.
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (child.getVisibility() == GONE) {
lp.dimWhenOffset = false;
continue;
}
if (lp.weight > 0) {
weightSum += lp.weight;
// If we have no width, weight is the only contributor to the final size.
// Measure this view on the weight pass only.
if (lp.width == 0) continue;
}
int childWidthSpec;
final int horizontalMargin = lp.leftMargin + lp.rightMargin;
if (lp.width == LayoutParams.WRAP_CONTENT) {
childWidthSpec = MeasureSpec.makeMeasureSpec(widthSize - horizontalMargin,
MeasureSpec.AT_MOST);
} else if (lp.width == LayoutParams.FILL_PARENT) {
childWidthSpec = MeasureSpec.makeMeasureSpec(widthSize - horizontalMargin,
MeasureSpec.EXACTLY);
} else {
childWidthSpec = MeasureSpec.makeMeasureSpec(lp.width, MeasureSpec.EXACTLY);
}
int childHeightSpec;
if (lp.height == LayoutParams.WRAP_CONTENT) {
childHeightSpec = MeasureSpec.makeMeasureSpec(maxLayoutHeight, MeasureSpec.AT_MOST);
} else if (lp.height == LayoutParams.FILL_PARENT) {
childHeightSpec = MeasureSpec.makeMeasureSpec(maxLayoutHeight, MeasureSpec.EXACTLY);
} else {
childHeightSpec = MeasureSpec.makeMeasureSpec(lp.height, MeasureSpec.EXACTLY);
}
child.measure(childWidthSpec, childHeightSpec);
final int childWidth = child.getMeasuredWidth();
final int childHeight = child.getMeasuredHeight();
if (heightMode == MeasureSpec.AT_MOST && childHeight > layoutHeight) {
layoutHeight = Math.min(childHeight, maxLayoutHeight);
}
widthRemaining -= childWidth;
canSlide |= lp.slideable = widthRemaining < 0;
if (lp.slideable) {
mSlideableView = child;
}
}
// Resolve weight and make sure non-sliding panels are smaller than the full screen.
if (canSlide || weightSum > 0) {
final int fixedPanelWidthLimit = widthSize - mOverhangSize;
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == GONE) {
continue;
}
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final boolean skippedFirstPass = lp.width == 0 && lp.weight > 0;
final int measuredWidth = skippedFirstPass ? 0 : child.getMeasuredWidth();
if (canSlide && child != mSlideableView) {
if (lp.width < 0 && (measuredWidth > fixedPanelWidthLimit || lp.weight > 0)) {
// Fixed panels in a sliding configuration should
// be clamped to the fixed panel limit.
final int childHeightSpec;
if (skippedFirstPass) {
// Do initial height measurement if we skipped measuring this view
// the first time around.
if (lp.height == LayoutParams.WRAP_CONTENT) {
childHeightSpec = MeasureSpec.makeMeasureSpec(maxLayoutHeight,
MeasureSpec.AT_MOST);
} else if (lp.height == LayoutParams.FILL_PARENT) {
childHeightSpec = MeasureSpec.makeMeasureSpec(maxLayoutHeight,
MeasureSpec.EXACTLY);
} else {
childHeightSpec = MeasureSpec.makeMeasureSpec(lp.height,
MeasureSpec.EXACTLY);
}
} else {
childHeightSpec = MeasureSpec.makeMeasureSpec(
child.getMeasuredHeight(), MeasureSpec.EXACTLY);
}
final int childWidthSpec = MeasureSpec.makeMeasureSpec(
fixedPanelWidthLimit, MeasureSpec.EXACTLY);
child.measure(childWidthSpec, childHeightSpec);
}
} else if (lp.weight > 0) {
int childHeightSpec;
if (lp.width == 0) {
// This was skipped the first time; figure out a real height spec.
if (lp.height == LayoutParams.WRAP_CONTENT) {
childHeightSpec = MeasureSpec.makeMeasureSpec(maxLayoutHeight,
MeasureSpec.AT_MOST);
} else if (lp.height == LayoutParams.FILL_PARENT) {
childHeightSpec = MeasureSpec.makeMeasureSpec(maxLayoutHeight,
MeasureSpec.EXACTLY);
} else {
childHeightSpec = MeasureSpec.makeMeasureSpec(lp.height,
MeasureSpec.EXACTLY);
}
} else {
childHeightSpec = MeasureSpec.makeMeasureSpec(
child.getMeasuredHeight(), MeasureSpec.EXACTLY);
}
if (canSlide) {
// Consume available space
final int horizontalMargin = lp.leftMargin + lp.rightMargin;
final int newWidth = widthSize - horizontalMargin;
final int childWidthSpec = MeasureSpec.makeMeasureSpec(
newWidth, MeasureSpec.EXACTLY);
if (measuredWidth != newWidth) {
child.measure(childWidthSpec, childHeightSpec);
}
} else {
// Distribute the extra width proportionally similar to LinearLayout
final int widthToDistribute = Math.max(0, widthRemaining);
final int addedWidth = (int) (lp.weight * widthToDistribute / weightSum);
final int childWidthSpec = MeasureSpec.makeMeasureSpec(
measuredWidth + addedWidth, MeasureSpec.EXACTLY);
child.measure(childWidthSpec, childHeightSpec);
}
}
}
}
setMeasuredDimension(widthSize, layoutHeight);
mCanSlide = canSlide;
if (mDragHelper.getViewDragState() != ViewDragHelper.STATE_IDLE && !canSlide) {
// Cancel scrolling in progress, it's no longer relevant.
mDragHelper.abort();
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final int width = r - l;
final int paddingLeft = getPaddingLeft();
final int paddingRight = getPaddingRight();
final int paddingTop = getPaddingTop();
final int childCount = getChildCount();
int xStart = paddingLeft;
int nextXStart = xStart;
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == GONE) {
continue;
}
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final int childWidth = child.getMeasuredWidth();
int offset = 0;
if (lp.slideable) {
final int margin = lp.leftMargin + lp.rightMargin;
final int range = Math.min(nextXStart,
width - paddingRight - mOverhangSize) - xStart - margin;
mSlideRange = range;
lp.dimWhenOffset = xStart + lp.leftMargin + range + childWidth / 2 >
width - paddingRight;
xStart += (int) (range * mSlideOffset) + lp.leftMargin;
} else if (mCanSlide && mParallaxBy != 0) {
offset = (int) ((1 - mSlideOffset) * mParallaxBy);
xStart = nextXStart;
} else {
xStart = nextXStart;
}
final int childLeft = xStart - offset;
final int childRight = childLeft + childWidth;
final int childTop = paddingTop;
final int childBottom = childTop + child.getMeasuredHeight();
child.layout(childLeft, paddingTop, childRight, childBottom);
nextXStart += child.getWidth();
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
final int action = ev.getAction() & MotionEventCompat.ACTION_MASK;
if (!mCanSlide || (mIsUnableToDrag && action != MotionEvent.ACTION_DOWN)) {
mDragHelper.cancel();
return super.onInterceptTouchEvent(ev);
}
if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
mDragHelper.cancel();
return false;
}
final boolean interceptForDrag = mDragHelper.shouldInterceptTouchEvent(ev);
boolean interceptTap = false;
switch (action) {
case MotionEvent.ACTION_DOWN: {
mIsUnableToDrag = false;
final float x = ev.getX();
final float y = ev.getY();
mInitialMotionX = x;
mInitialMotionY = y;
if (mDragHelper.isViewUnder(mSlideableView, (int) x, (int) y) &&
isDimmed(mSlideableView)) {
interceptTap = true;
}
break;
}
}
return interceptForDrag || interceptTap;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (!mCanSlide) {
return super.onTouchEvent(ev);
}
mDragHelper.processTouchEvent(ev);
final int action = ev.getAction();
boolean wantTouchEvents = true;
switch (action & MotionEventCompat.ACTION_MASK) {
case MotionEvent.ACTION_DOWN: {
final float x = ev.getX();
final float y = ev.getY();
mInitialMotionX = x;
mInitialMotionY = y;
break;
}
case MotionEvent.ACTION_UP: {
if (isDimmed(mSlideableView)) {
final float x = ev.getX();
final float y = ev.getY();
final float dx = x - mInitialMotionX;
final float dy = y - mInitialMotionY;
final int slop = mDragHelper.getTouchSlop();
if (dx * dx + dy * dy < slop * slop &&
mDragHelper.isViewUnder(mSlideableView, (int) x, (int) y)) {
// Taps close a dimmed open pane.
closePane(mSlideableView, 0);
break;
}
}
break;
}
}
return wantTouchEvents;
}
private void closePane(View pane, int initialVelocity) {
if (mCanSlide) {
smoothSlideTo(0.f, initialVelocity);
}
}
private void openPane(View pane, int initialVelocity) {
if (mCanSlide) {
smoothSlideTo(1.f, initialVelocity);
}
}
/**
* Animate the sliding panel to its open state.
*/
public void smoothSlideOpen() {
if (mCanSlide) {
openPane(mSlideableView, 0);
}
}
/**
* Animate the sliding panel to its closed state.
*/
public void smoothSlideClosed() {
if (mCanSlide) {
closePane(mSlideableView, 0);
}
}
/**
* @return true if sliding panels are completely open
*/
public boolean isOpen() {
return !mCanSlide || mSlideOffset == 1;
}
/**
* @return true if content in this layout can be slid open and closed
*/
public boolean canSlide() {
return mCanSlide;
}
private boolean performDrag(int newLeft) {
final LayoutParams lp = (LayoutParams) mSlideableView.getLayoutParams();
final int leftBound = getPaddingLeft() + lp.leftMargin;
final float oldLeft = mSlideableView.getLeft();
final int dxPane = (int) (newLeft - oldLeft);
mSlideableView.offsetLeftAndRight(dxPane);
mSlideOffset = (float) (newLeft - leftBound) / mSlideRange;
if (mParallaxBy != 0) {
parallaxOtherViews(mSlideOffset);
}
if (lp.dimWhenOffset) {
dimChildView(mSlideableView, mSlideOffset, mSliderFadeColor);
}
dispatchOnPanelSlide(mSlideableView);
return true;
}
private void dimChildView(View v, float mag, int fadeColor) {
final LayoutParams lp = (LayoutParams) v.getLayoutParams();
if (mag > 0 && fadeColor != 0) {
final int baseAlpha = (fadeColor & 0xff000000) >>> 24;
int imag = (int) (baseAlpha * mag);
int color = imag << 24 | (fadeColor & 0xffffff);
if (lp.dimPaint == null) {
lp.dimPaint = new Paint();
}
lp.dimPaint.setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.SRC_OVER));
if (ViewCompat.getLayerType(v) != ViewCompat.LAYER_TYPE_HARDWARE) {
ViewCompat.setLayerType(v, ViewCompat.LAYER_TYPE_HARDWARE, lp.dimPaint);
}
invalidateChildRegion(v);
} else if (ViewCompat.getLayerType(v) != ViewCompat.LAYER_TYPE_NONE) {
ViewCompat.setLayerType(v, ViewCompat.LAYER_TYPE_NONE, null);
}
}
@Override
protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
boolean result;
final int save = canvas.save(Canvas.CLIP_SAVE_FLAG);
if (mCanSlide && !lp.slideable && mSlideableView != null) {
// Clip against the slider; no sense drawing what will immediately be covered.
canvas.getClipBounds(mTmpRect);
mTmpRect.right = Math.min(mTmpRect.right, mSlideableView.getLeft());
canvas.clipRect(mTmpRect);
}
if (Build.VERSION.SDK_INT >= 11) { // HC
result = super.drawChild(canvas, child, drawingTime);
} else {
if (lp.dimWhenOffset && mSlideOffset > 0) {
if (!child.isDrawingCacheEnabled()) {
child.setDrawingCacheEnabled(true);
}
final Bitmap cache = child.getDrawingCache();
canvas.drawBitmap(cache, child.getLeft(), child.getTop(), lp.dimPaint);
result = false;
} else {
if (child.isDrawingCacheEnabled()) {
child.setDrawingCacheEnabled(false);
}
result = super.drawChild(canvas, child, drawingTime);
}
}
canvas.restoreToCount(save);
return result;
}
private void invalidateChildRegion(View v) {
IMPL.invalidateChildRegion(this, v);
}
/**
* Smoothly animate mDraggingPane to the target X position within its range.
*
* @param slideOffset position to animate to
* @param velocity initial velocity in case of fling, or 0.
*/
void smoothSlideTo(float slideOffset, int velocity) {
if (!mCanSlide) {
// Nothing to do.
return;
}
final LayoutParams lp = (LayoutParams) mSlideableView.getLayoutParams();
final int leftBound = getPaddingLeft() + lp.leftMargin;
int x = (int) (leftBound + slideOffset * mSlideRange);
if (mDragHelper.smoothSlideViewTo(mSlideableView, x, mSlideableView.getTop())) {
ViewCompat.postInvalidateOnAnimation(this);
}
}
@Override
public void computeScroll() {
if (mDragHelper.continueSettling(true)) {
if (!mCanSlide) {
mDragHelper.abort();
return;
}
ViewCompat.postInvalidateOnAnimation(this);
}
}
/**
* Set a drawable to use as a shadow cast by the right pane onto the left pane
* during opening/closing.
*
* @param d drawable to use as a shadow
*/
public void setShadowDrawable(Drawable d) {
mShadowDrawable = d;
}
/**
* Set a drawable to use as a shadow cast by the right pane onto the left pane
* during opening/closing.
*
* @param resId Resource ID of a drawable to use
*/
public void setShadowResource(int resId) {
setShadowDrawable(getResources().getDrawable(resId));
}
@Override
public void draw(Canvas c) {
super.draw(c);
final View shadowView = getChildCount() > 1 ? getChildAt(1) : null;
if (shadowView == null || mShadowDrawable == null) {
// No need to draw a shadow if we don't have one.
return;
}
final int shadowWidth = mShadowDrawable.getIntrinsicWidth();
final int right = shadowView.getLeft();
final int top = shadowView.getTop();
final int bottom = shadowView.getBottom();
final int left = right - shadowWidth;
mShadowDrawable.setBounds(left, top, right, bottom);
mShadowDrawable.draw(c);
}
private void parallaxOtherViews(float slideOffset) {
final LayoutParams slideLp = (LayoutParams) mSlideableView.getLayoutParams();
final boolean dimViews = slideLp.dimWhenOffset && slideLp.leftMargin <= 0;
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View v = getChildAt(i);
if (v == mSlideableView) continue;
final int oldOffset = (int) ((1 - mParallaxOffset) * mParallaxBy);
mParallaxOffset = slideOffset;
final int newOffset = (int) ((1 - slideOffset) * mParallaxBy);
final int dx = oldOffset - newOffset;
v.offsetLeftAndRight(dx);
if (dimViews) {
dimChildView(v, 1 - mParallaxOffset, mCoveredFadeColor);
}
}
}
/**
* Tests scrollability within child views of v given a delta of dx.
*
* @param v View to test for horizontal scrollability
* @param checkV Whether the view v passed should itself be checked for scrollability (true),
* or just its children (false).
* @param dx Delta scrolled in pixels
* @param x X coordinate of the active touch point
* @param y Y coordinate of the active touch point
* @return true if child views of v can be scrolled by delta of dx.
*/
protected boolean canScroll(View v, boolean checkV, int dx, int x, int y) {
if (v instanceof ViewGroup) {
final ViewGroup group = (ViewGroup) v;
final int scrollX = v.getScrollX();
final int scrollY = v.getScrollY();
final int count = group.getChildCount();
// Count backwards - let topmost views consume scroll distance first.
for (int i = count - 1; i >= 0; i--) {
// TODO: Add versioned support here for transformed views.
// This will not work for transformed views in Honeycomb+
final View child = group.getChildAt(i);
if (x + scrollX >= child.getLeft() && x + scrollX < child.getRight() &&
y + scrollY >= child.getTop() && y + scrollY < child.getBottom() &&
canScroll(child, true, dx, x + scrollX - child.getLeft(),
y + scrollY - child.getTop())) {
return true;
}
}
}
return checkV && ViewCompat.canScrollHorizontally(v, -dx);
}
boolean isDimmed(View child) {
if (child == null) {
return false;
}
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
return mCanSlide && lp.dimWhenOffset && mSlideOffset > 0;
}
@Override
protected ViewGroup.LayoutParams generateDefaultLayoutParams() {
return new LayoutParams();
}
@Override
protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
return p instanceof MarginLayoutParams
? new LayoutParams((MarginLayoutParams) p)
: new LayoutParams(p);
}
@Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
return p instanceof LayoutParams && super.checkLayoutParams(p);
}
@Override
public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
return new LayoutParams(getContext(), attrs);
}
@Override
protected Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
SavedState ss = new SavedState(superState);
ss.isOpen = isOpen();
return ss;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
SavedState ss = (SavedState) state;
super.onRestoreInstanceState(ss.getSuperState());
// TODO: Completely restore state
}
private class DragHelperCallback extends ViewDragHelper.Callback {
@Override
public boolean tryCaptureView(View child, int pointerId) {
if (mIsUnableToDrag) {
return false;
}
return ((LayoutParams) child.getLayoutParams()).slideable;
}
@Override
public void onViewDragStateChanged(int state) {
if (mDragHelper.getViewDragState() == ViewDragHelper.STATE_IDLE) {
if (mSlideOffset == 0) {
dispatchOnPanelClosed(mSlideableView);
} else {
dispatchOnPanelOpened(mSlideableView);
}
}
}
@Override
public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {
performDrag(left);
invalidate();
}
@Override
public void onViewReleased(View releasedChild, float xvel, float yvel) {
final LayoutParams lp = (LayoutParams) releasedChild.getLayoutParams();
int left = getPaddingLeft() + lp.leftMargin;
if (xvel > 0 || (xvel == 0 && mSlideOffset > 0.5f)) {
left += mSlideRange;
}
mDragHelper.settleCapturedViewAt(left, releasedChild.getTop());
invalidate();
}
@Override
public int getViewHorizontalDragRange(View child) {
return mSlideRange;
}
@Override
public int clampViewPositionHorizontal(View child, int left, int dx) {
final LayoutParams lp = (LayoutParams) mSlideableView.getLayoutParams();
final int leftBound = getPaddingLeft() + lp.leftMargin;
final int rightBound = leftBound + mSlideRange;
final int newLeft = Math.min(Math.max(left, leftBound), rightBound);
return newLeft;
}
@Override
public void onEdgeDragStarted(int edgeFlags, int pointerId) {
mDragHelper.captureChildView(mSlideableView, pointerId);
}
}
public static class LayoutParams extends ViewGroup.MarginLayoutParams {
private static final int[] ATTRS = new int[] {
android.R.attr.layout_weight
};
/**
* The weighted proportion of how much of the leftover space
* this child should consume after measurement.
*/
public float weight = 0;
/**
* True if this pane is the slideable pane in the layout.
*/
boolean slideable;
/**
* True if this view should be drawn dimmed
* when it's been offset from its default position.
*/
boolean dimWhenOffset;
Paint dimPaint;
public LayoutParams() {
super(FILL_PARENT, FILL_PARENT);
}
public LayoutParams(int width, int height) {
super(width, height);
}
public LayoutParams(android.view.ViewGroup.LayoutParams source) {
super(source);
}
public LayoutParams(MarginLayoutParams source) {
super(source);
}
public LayoutParams(LayoutParams source) {
super(source);
this.weight = source.weight;
}
public LayoutParams(Context c, AttributeSet attrs) {
super(c, attrs);
final TypedArray a = c.obtainStyledAttributes(attrs, ATTRS);
this.weight = a.getFloat(0, 0);
a.recycle();
}
}
static class SavedState extends BaseSavedState {
boolean isOpen;
SavedState(Parcelable superState) {
super(superState);
}
private SavedState(Parcel in) {
super(in);
isOpen = in.readInt() != 0;
}
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeInt(isOpen ? 1 : 0);
}
public static final Parcelable.Creator<SavedState> CREATOR =
new Parcelable.Creator<SavedState>() {
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
interface SlidingPanelLayoutImpl {
void invalidateChildRegion(SlidingPaneLayout parent, View child);
}
static class SlidingPanelLayoutImplBase implements SlidingPanelLayoutImpl {
public void invalidateChildRegion(SlidingPaneLayout parent, View child) {
ViewCompat.postInvalidateOnAnimation(parent, child.getLeft(), child.getTop(),
child.getRight(), child.getBottom());
}
}
static class SlidingPanelLayoutImplJB extends SlidingPanelLayoutImplBase {
/*
* Private API hacks! Nasty! Bad!
*
* In Jellybean, some optimizations in the hardware UI renderer
* prevent a changed Paint on a View using a hardware layer from having
* the intended effect. This twiddles some internal bits on the view to force
* it to recreate the display list.
*/
private Method mGetDisplayList;
private Field mRecreateDisplayList;
SlidingPanelLayoutImplJB() {
try {
mGetDisplayList = View.class.getDeclaredMethod("getDisplayList", (Class[]) null);
} catch (NoSuchMethodException e) {
Log.e(TAG, "Couldn't fetch getDisplayList method; dimming won't work right.", e);
}
try {
mRecreateDisplayList = View.class.getDeclaredField("mRecreateDisplayList");
mRecreateDisplayList.setAccessible(true);
} catch (NoSuchFieldException e) {
Log.e(TAG, "Couldn't fetch mRecreateDisplayList field; dimming will be slow.", e);
}
}
@Override
public void invalidateChildRegion(SlidingPaneLayout parent, View child) {
if (mGetDisplayList != null && mRecreateDisplayList != null) {
try {
mRecreateDisplayList.setBoolean(child, true);
mGetDisplayList.invoke(child, (Object[]) null);
} catch (Exception e) {
Log.e(TAG, "Error refreshing display list state", e);
}
} else {
// Slow path. REALLY slow path. Let's hope we don't get here.
child.invalidate();
return;
}
super.invalidateChildRegion(parent, child);
}
}
static class SlidingPanelLayoutImplJBMR1 extends SlidingPanelLayoutImplBase {
@Override
public void invalidateChildRegion(SlidingPaneLayout parent, View child) {
ViewCompat.setLayerPaint(child, ((LayoutParams) child.getLayoutParams()).dimPaint);
}
}
}
|
am 0c8486c1: am 29836199: Prevent strange falsing on SlidingPaneLayout
* commit '0c8486c19d4f1b2c0ad7650bf5a4cc95edb44462':
Prevent strange falsing on SlidingPaneLayout
|
v4/java/android/support/v4/widget/SlidingPaneLayout.java
|
am 0c8486c1: am 29836199: Prevent strange falsing on SlidingPaneLayout
|
|
Java
|
bsd-2-clause
|
241b23ba87e1cd320b5029e2c015cd7f03764576
| 0
|
smcpeak/earthshape
|
// TestProgressDialog.java
// See copyright.txt for license and terms of use.
package util.swing;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.concurrent.ExecutionException;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
/** Little program to test ProgressDialog. */
public class TestProgressDialog extends JFrame {
/** AWT boilerplate. */
private static final long serialVersionUID = 1770692424967304611L;
/** The thread that last issued a 'log' command. This is used to
* only log thread names when there is interleaving. */
private static Thread lastLoggedThread = null;
/** Text field where user can specify how many milliseconds each
* worker tick should require. */
private JTextField msPerTickTextField;
/** Let user request that worker throw an exception. */
private JCheckBox throwExceptionCB;
public TestProgressDialog()
{
super("Test Progress Dialog");
log("in TestProgressDialog ctor");
// Exit the app when window close button is pressed (AWT boilerplate).
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
log("closing due to window close event");
TestProgressDialog.this.dispose();
}
});
HBox outerHB = new HBox();
outerHB.strut();
{
VBox vb = new VBox();
vb.strut();
vb.add(Box.createHorizontalStrut(400));
{
HBox hb = new HBox();
hb.add(new JLabel("Milliseconds per tick: "));
hb.strut();
hb.add(this.msPerTickTextField = new JTextField("30"));
hb.glue();
vb.add(hb);
}
vb.strut();
{
HBox hb = new HBox();
hb.add(this.throwExceptionCB =
new JCheckBox("Throw an exception inside worker", false));
hb.glue();
vb.add(hb);
}
vb.strut();
{
HBox hb = new HBox();
JButton button = new JButton("Start");
hb.add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
TestProgressDialog.this.startTask();
}
});
hb.glue();
vb.add(hb);
}
vb.strut();
{
HBox hb = new HBox();
JButton button = new JButton("Quit");
hb.add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
log("closing due to Quit button press");
TestProgressDialog.this.dispose();
}
});
hb.glue();
vb.add(hb);
}
vb.strut();
outerHB.add(vb);
}
outerHB.strut();
this.add(outerHB);
this.pack();
this.setLocationByPlatform(true);
}
private static class TestTask extends SwingWorker<Integer, Void> {
private int msPerTick;
private boolean throwException;
public TestTask(int msPerTick_, boolean throwException_)
{
this.msPerTick = msPerTick_;
this.throwException = throwException_;
}
protected Integer doInBackground() throws Exception
{
String oldStatus = null;
log("TestTask: starting");
this.setProgress(0);
for (int i=0; i < 100 && !this.isCancelled(); i++) {
Thread.sleep(this.msPerTick);
if (i == 50 && this.throwException) {
log("TestTask: throwing exception");
throw new RuntimeException("Exception thrown from worker");
}
if (i % 10 == 0) {
log("TestTask: progress is "+i);
if (i != 0) {
String newStatus = "Passed "+i+"%";
this.firePropertyChange("status", oldStatus, newStatus);
oldStatus = newStatus;
}
}
this.setProgress(i);
}
if (this.isCancelled()) {
log("TestTask: canceled externally");
return null;
}
else {
log("TestTask: finished with complete task");
return 5;
}
}
}
private void startTask()
{
int msPerTick;
try {
String s = this.msPerTickTextField.getText();
msPerTick = Integer.valueOf(s);
}
catch (NumberFormatException e) {
ModalDialog.errorBox(this, "Invalid integer: "+e.getMessage());
return;
}
boolean throwException = this.throwExceptionCB.isSelected();
log("startTask: starting new task");
TestTask task = new TestTask(msPerTick, throwException);
ProgressDialog<Integer, Void> pd =
new ProgressDialog<Integer, Void>(this, "Test Progress", task);
boolean res = pd.exec();
if (res) {
log("startTask: task finished normally");
try {
Integer i = task.get();
log("startTask: computation returned: "+i);
}
catch (ExecutionException e) {
log("startTask: computation threw exception: "+e.getMessage());
}
catch (InterruptedException e) {
log("startTask: computation was interrupted: "+e.getMessage());
}
}
else {
log("startTask: task was canceled");
}
}
// TODO: Factor a bunch of this commonality with EarthShape.
/** Print a message to the console with a timestamp. */
public static void log(String msg)
{
Thread t = Thread.currentThread();
if (t != TestProgressDialog.lastLoggedThread) {
System.out.println(""+System.currentTimeMillis()+
" ["+t.getName()+"]"+
": "+msg);
TestProgressDialog.lastLoggedThread = t;
}
else {
System.out.println(""+System.currentTimeMillis()+
": "+msg);
}
}
public static void main(String[] args)
{
log("start of main");
SwingUtilities.invokeLater(new Runnable() {
public void run() {
log("start of main.run");
(new TestProgressDialog()).setVisible(true);
}
});
}
}
|
src/util/swing/TestProgressDialog.java
|
// TestProgressDialog.java
// See copyright.txt for license and terms of use.
package util.swing;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.concurrent.ExecutionException;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
/** Little program to test ProgressDialog. */
public class TestProgressDialog extends JFrame {
/** AWT boilerplate. */
private static final long serialVersionUID = 1770692424967304611L;
/** The thread that last issued a 'log' command. This is used to
* only log thread names when there is interleaving. */
private static Thread lastLoggedThread = null;
/** Text field where user can specify how many milliseconds each
* worker tick should require. */
private JTextField msPerTickTextField;
public TestProgressDialog()
{
super("Test Progress Dialog");
log("in TestProgressDialog ctor");
// Exit the app when window close button is pressed (AWT boilerplate).
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
log("closing due to window close event");
TestProgressDialog.this.dispose();
}
});
HBox outerHB = new HBox();
outerHB.strut();
{
VBox vb = new VBox();
vb.strut();
vb.add(Box.createHorizontalStrut(400));
{
HBox hb = new HBox();
hb.add(new JLabel("Milliseconds per tick: "));
hb.strut();
hb.add(this.msPerTickTextField = new JTextField("30"));
hb.glue();
vb.add(hb);
}
vb.strut();
{
HBox hb = new HBox();
JButton button = new JButton("Start");
hb.add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
TestProgressDialog.this.startTask();
}
});
hb.glue();
vb.add(hb);
}
vb.strut();
{
HBox hb = new HBox();
JButton button = new JButton("Quit");
hb.add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
log("closing due to Quit button press");
TestProgressDialog.this.dispose();
}
});
hb.glue();
vb.add(hb);
}
vb.strut();
outerHB.add(vb);
}
outerHB.strut();
this.add(outerHB);
this.pack();
this.setLocationByPlatform(true);
}
private static class TestTask extends SwingWorker<Integer, Void> {
private int msPerTick;
public TestTask(int msPerTick_)
{
this.msPerTick = msPerTick_;
}
protected Integer doInBackground() throws Exception
{
String oldStatus = null;
log("TestTask: starting");
this.setProgress(0);
for (int i=0; i < 100 && !this.isCancelled(); i++) {
Thread.sleep(this.msPerTick);
if (i % 10 == 0) {
log("TestTask: progress is "+i);
if (i != 0) {
String newStatus = "Passed "+i+"%";
this.firePropertyChange("status", oldStatus, newStatus);
oldStatus = newStatus;
}
}
this.setProgress(i);
}
if (this.isCancelled()) {
log("TestTask: canceled");
return null;
}
else {
log("TestTask: finished");
return 5;
}
}
}
private void startTask()
{
int msPerTick;
try {
String s = this.msPerTickTextField.getText();
msPerTick = Integer.valueOf(s);
}
catch (NumberFormatException e) {
ModalDialog.errorBox(this, "Invalid integer: "+e.getMessage());
return;
}
log("startTask: starting new task");
TestTask task = new TestTask(msPerTick);
ProgressDialog<Integer, Void> pd =
new ProgressDialog<Integer, Void>(this, "Test Progress", task);
boolean res = pd.exec();
if (res) {
log("startTask: task finished normally");
try {
Integer i = task.get();
log("startTask: computation returned: "+i);
}
catch (ExecutionException e) {
log("startTask: computation throw exception: "+e.getMessage());
}
catch (InterruptedException e) {
log("startTask: computation was interrupted: "+e.getMessage());
}
}
else {
log("startTask: task was canceled");
}
}
// TODO: Factor a bunch of this commonality with EarthShape.
/** Print a message to the console with a timestamp. */
public static void log(String msg)
{
Thread t = Thread.currentThread();
if (t != TestProgressDialog.lastLoggedThread) {
System.out.println(""+System.currentTimeMillis()+
" ["+t.getName()+"]"+
": "+msg);
TestProgressDialog.lastLoggedThread = t;
}
else {
System.out.println(""+System.currentTimeMillis()+
": "+msg);
}
}
public static void main(String[] args)
{
log("start of main");
SwingUtilities.invokeLater(new Runnable() {
public void run() {
log("start of main.run");
(new TestProgressDialog()).setVisible(true);
}
});
}
}
|
TestProgressDialog: added test of exceptions, works
|
src/util/swing/TestProgressDialog.java
|
TestProgressDialog: added test of exceptions, works
|
|
Java
|
bsd-3-clause
|
2dbdc0d80003f721d7adf4d92c23bd9f6ddeabd2
| 0
|
dhis2/dhis2-android-sdk,dhis2/dhis2-android-sdk,dhis2/dhis2-android-sdk
|
/*
* Copyright (c) 2016, University of Oslo
*
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.client.sdk.android.api.persistence;
import com.raizlabs.android.dbflow.DatabaseHelperListener;
import com.raizlabs.android.dbflow.annotation.Database;
import com.raizlabs.android.dbflow.config.BaseDatabaseDefinition;
import com.raizlabs.dbflow.android.sqlcipher.SQLCipherOpenHelper;
@Database(
name = DbDhis.NAME, version = DbDhis.VERSION,
sqlHelperClass = DbDhisCipher.class
)
public final class DbDhis {
public static final String NAME = "dhis";
public static final int VERSION = 3;
static class DbDhisCipher extends SQLCipherOpenHelper {
public DbDhisCipher(BaseDatabaseDefinition databaseDefinition,
DatabaseHelperListener listener) {
super(databaseDefinition, listener);
}
// TODO replace with proper cipher secret
@Override
protected String getCipherSecret() {
return "dbflow-rules";
}
}
}
|
core-android/src/main/java/org/hisp/dhis/client/sdk/android/api/persistence/DbDhis.java
|
/*
* Copyright (c) 2016, University of Oslo
*
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.client.sdk.android.api.persistence;
import com.raizlabs.android.dbflow.DatabaseHelperListener;
import com.raizlabs.android.dbflow.annotation.Database;
import com.raizlabs.android.dbflow.config.BaseDatabaseDefinition;
import com.raizlabs.dbflow.android.sqlcipher.SQLCipherOpenHelper;
@Database(
name = DbDhis.NAME, version = DbDhis.VERSION
// sqlHelperClass = DbDhisCipher.class
)
public final class DbDhis {
public static final String NAME = "dhis";
public static final int VERSION = 3;
static class DbDhisCipher extends SQLCipherOpenHelper {
public DbDhisCipher(BaseDatabaseDefinition databaseDefinition,
DatabaseHelperListener listener) {
super(databaseDefinition, listener);
}
// TODO replace with proper cipher secret
@Override
protected String getCipherSecret() {
return "dbflow-rules";
}
}
}
|
Moved DbDhisCipher class declaration to DbDhis class.
|
core-android/src/main/java/org/hisp/dhis/client/sdk/android/api/persistence/DbDhis.java
|
Moved DbDhisCipher class declaration to DbDhis class.
|
|
Java
|
mit
|
bc08fa9f8966e3df2c110b6be30278067c35e6f8
| 0
|
overleaf/writelatex-git-bridge,overleaf/writelatex-git-bridge
|
package uk.ac.ic.wlgitbridge.io.http.ning;
import io.netty.handler.codec.http.HttpHeaders;
import org.asynchttpclient.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.ac.ic.wlgitbridge.util.FunctionT;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
public class NingHttpClient implements NingHttpClientFacade {
private static final Logger log
= LoggerFactory.getLogger(NingHttpClient.class);
private final AsyncHttpClient http;
public NingHttpClient(AsyncHttpClient http) {
this.http = http;
}
@Override
public <E extends Exception> byte[] get(
String url,
FunctionT<HttpHeaders, Boolean, E> handler
) throws ExecutionException {
try {
return http
.prepareGet(url)
.execute(new AsyncCompletionHandler<byte[]>() {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
@Override
public State onHeadersReceived(
HttpHeaders headers
) throws E {
return handler.apply(headers)
? State.CONTINUE : State.ABORT;
}
@Override
public State onBodyPartReceived(
HttpResponseBodyPart content
) throws IOException {
bytes.write(content.getBodyPartBytes());
return State.CONTINUE;
}
@Override
public byte[] onCompleted(
Response response
) throws Exception {
int statusCode = response.getStatusCode();
if (statusCode >= 400) {
throw new Exception("got status " + statusCode +
" fetching " + url);
}
byte[] ret = bytes.toByteArray();
bytes.close();
log.info(
statusCode
+ " "
+ response.getStatusText()
+ " ("
+ ret.length
+ "B) -> "
+ url
);
return ret;
}
}).get();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
|
src/main/java/uk/ac/ic/wlgitbridge/io/http/ning/NingHttpClient.java
|
package uk.ac.ic.wlgitbridge.io.http.ning;
import io.netty.handler.codec.http.HttpHeaders;
import org.asynchttpclient.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.ac.ic.wlgitbridge.util.FunctionT;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
public class NingHttpClient implements NingHttpClientFacade {
private static final Logger log
= LoggerFactory.getLogger(NingHttpClient.class);
private final AsyncHttpClient http;
public NingHttpClient(AsyncHttpClient http) {
this.http = http;
}
@Override
public <E extends Exception> byte[] get(
String url,
FunctionT<HttpHeaders, Boolean, E> handler
) throws ExecutionException {
try {
return http
.prepareGet(url)
.execute(new AsyncCompletionHandler<byte[]>() {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
@Override
public State onHeadersReceived(
HttpHeaders headers
) throws E {
return handler.apply(headers)
? State.CONTINUE : State.ABORT;
}
@Override
public State onBodyPartReceived(
HttpResponseBodyPart content
) throws IOException {
bytes.write(content.getBodyPartBytes());
return State.CONTINUE;
}
@Override
public byte[] onCompleted(
Response response
) throws IOException {
byte[] ret = bytes.toByteArray();
bytes.close();
log.info(
response.getStatusCode()
+ " "
+ response.getStatusText()
+ " ("
+ ret.length
+ "B) -> "
+ url
);
return ret;
}
}).get();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
|
Handle errors from the history service
If the history service returns a non-success status code when we request
a blob, chances are the payload is not the expected blob contents. We
throw an exception in that case, which will abort the git operation.
|
src/main/java/uk/ac/ic/wlgitbridge/io/http/ning/NingHttpClient.java
|
Handle errors from the history service
|
|
Java
|
mit
|
db7518063bd4d60a341e2e4d4faacd3f52c067a1
| 0
|
InfinityPhase/CARIS,InfinityPhase/CARIS
|
package caris.modular.handlers;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import caris.framework.basehandlers.InvokedHandler;
import caris.framework.library.Variables;
import caris.framework.reactions.Reaction;
import caris.framework.reactions.ReactionMessage;
import caris.framework.utilities.Logger;
import caris.framework.utilities.TokenParser;
import sx.blah.discord.api.events.Event;
import sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent;
import sx.blah.discord.handle.impl.obj.Role;
import sx.blah.discord.handle.obj.IRole;
public class AutoRoleHandler extends InvokedHandler {
public AutoRoleHandler() {
super("AutoRole Handler");
invocation = "autorole";
}
@Override
protected boolean isTriggered(Event event) {
if( !(event instanceof MessageReceivedEvent) ) {
return false;
}
MessageReceivedEvent messageReceivedEvent = (MessageReceivedEvent) event;
return isAdmin(messageReceivedEvent) && isAdminInvoked(messageReceivedEvent);
}
@SuppressWarnings("unchecked")
@Override
protected Reaction process(Event event) {
MessageReceivedEvent messageReceivedEvent = (MessageReceivedEvent) event;
String text = messageReceivedEvent.getMessage().getContent();
ArrayList<String> tokens = TokenParser.parse(text);
if( tokens.size() >= 3 ) {
if( tokens.get(2).equals("get") ) {
String autoRoles = "";
List<Role> roles = Variables.guildIndex.get(messageReceivedEvent.getGuild()).autoRoles;
for( Role role : roles ) {
autoRoles += role.getName() + ", ";
}
if( !autoRoles.isEmpty() ) {
autoRoles = autoRoles.substring(0, autoRoles.length()-2);
return new ReactionMessage( "Here are the current default roles for this server: " + autoRoles, messageReceivedEvent.getChannel() );
} else {
return new ReactionMessage( "There aren't any default roles set for this server yet.", messageReceivedEvent.getChannel() );
}
}
if( tokens.size() >= 4 ) {
if( tokens.get(2).equals("add") ) {
String addedRoles = "";
for( int f=3; f<tokens.size(); f++ ) {
String token = tokens.get(f);
List<IRole> roles = messageReceivedEvent.getGuild().getRolesByName(token);
Variables.guildIndex.get(messageReceivedEvent.getGuild()).autoRoles.addAll((Collection<? extends Role>) roles);
for( IRole role : roles ) {
addedRoles += role.getName() + ", ";
}
}
if( !addedRoles.isEmpty() ) {
addedRoles = addedRoles.substring(0, addedRoles.length()-2);
Logger.print("Added roles " + addedRoles + " to AutoRole list in Guild " + messageReceivedEvent.getGuild().getName(), 1 );
return new ReactionMessage( "AutoRoles updated successfully!", messageReceivedEvent.getChannel() );
} else {
return new ReactionMessage( "Sorry, I couldn't find those roles. Did you capitalize them correctly?", messageReceivedEvent.getChannel() );
}
} else if( tokens.get(2).equals("remove") ) {
String removedRoles = "";
for( int f=3; f<tokens.size(); f++ ) {
String token = tokens.get(f);
List<IRole> roles = messageReceivedEvent.getGuild().getRolesByName(token);
if( !roles.isEmpty() ) {
for( IRole role : roles ) {
if( Variables.guildIndex.get(messageReceivedEvent.getGuild()).autoRoles.contains(role) ) {
Variables.guildIndex.get(messageReceivedEvent.getGuild()).autoRoles.remove(role);
removedRoles += role.getName() + ", ";
}
}
}
}
if( !removedRoles.isEmpty() ) {
removedRoles = removedRoles.substring(0, removedRoles.length()-2);
Logger.print("Removed roles " + removedRoles + " to AutoRole list in Guild " + messageReceivedEvent.getGuild().getName(), 1 );
return new ReactionMessage( "AutoRoles updated successfully!", messageReceivedEvent.getChannel() );
} else {
return new ReactionMessage( "Sorry, I couldn't find those roles. Did you capitalize them correctly?", messageReceivedEvent.getChannel() );
}
} else {
return new ReactionMessage( "Syntax Error!", messageReceivedEvent.getChannel() );
}
} else {
return new ReactionMessage( "Syntax Error!", messageReceivedEvent.getChannel() );
}
} else {
return new ReactionMessage( "Syntax Error!", messageReceivedEvent.getChannel());
}
}
}
|
src/caris/modular/handlers/AutoRoleHandler.java
|
package caris.modular.handlers;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import caris.framework.basehandlers.InvokedHandler;
import caris.framework.library.Variables;
import caris.framework.reactions.Reaction;
import caris.framework.reactions.ReactionMessage;
import caris.framework.utilities.Logger;
import caris.framework.utilities.TokenParser;
import sx.blah.discord.api.events.Event;
import sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent;
import sx.blah.discord.handle.impl.obj.Role;
import sx.blah.discord.handle.obj.IRole;
public class AutoRoleHandler extends InvokedHandler {
public AutoRoleHandler() {
super("AutoRole Handler");
invocation = "autorole";
}
@Override
protected boolean isTriggered(Event event) {
if( !(event instanceof MessageReceivedEvent) ) {
return false;
}
MessageReceivedEvent messageReceivedEvent = (MessageReceivedEvent) event;
return isAdmin(messageReceivedEvent) && isAdminInvoked(messageReceivedEvent);
}
@SuppressWarnings("unchecked")
@Override
protected Reaction process(Event event) {
MessageReceivedEvent messageReceivedEvent = (MessageReceivedEvent) event;
String text = messageReceivedEvent.getMessage().getContent();
ArrayList<String> tokens = TokenParser.parse(text);
if( tokens.size() >= 4 ) {
if( tokens.get(2).equals("add") ) {
String addedRoles = "";
for( int f=3; f<tokens.size(); f++ ) {
String token = tokens.get(f);
List<IRole> roles = messageReceivedEvent.getGuild().getRolesByName(token);
Variables.guildIndex.get(messageReceivedEvent.getGuild()).autoRoles.addAll((Collection<? extends Role>) roles);
for( IRole role : roles ) {
addedRoles += role.getName() + ", ";
}
}
addedRoles = addedRoles.substring(0, addedRoles.length()-2);
Logger.print("Added roles " + addedRoles + " to AutoRole list in Guild " + messageReceivedEvent.getGuild().getName(), 1 );
return new ReactionMessage( "AutoRoles updated successfully!", messageReceivedEvent.getChannel() );
} else if( tokens.get(2).equals("remove") ) {
String removedRoles = "";
for( int f=3; f<tokens.size(); f++ ) {
String token = tokens.get(f);
List<IRole> roles = messageReceivedEvent.getGuild().getRolesByName(token);
if( !roles.isEmpty() ) {
for( IRole role : roles ) {
if( Variables.guildIndex.get(messageReceivedEvent.getGuild()).autoRoles.contains(role) ) {
Variables.guildIndex.get(messageReceivedEvent.getGuild()).autoRoles.remove(role);
removedRoles += role.getName() + ", ";
}
}
}
}
removedRoles = removedRoles.substring(0, removedRoles.length()-2);
Logger.print("Removed roles " + removedRoles + " from AutoRole list in Guild " + messageReceivedEvent.getGuild().getName(), 1);
return new ReactionMessage( "AutoRoles updated successfully!", messageReceivedEvent.getChannel() );
} else {
return new ReactionMessage( "Syntax Error!", messageReceivedEvent.getChannel() );
}
} else {
return new ReactionMessage( "Syntax Error!", messageReceivedEvent.getChannel() );
}
}
}
|
Fixed autorole handling
|
src/caris/modular/handlers/AutoRoleHandler.java
|
Fixed autorole handling
|
|
Java
|
mit
|
c7c4054f0836426b28a7823c4806a9533ff28543
| 0
|
i-net-software/jlessc,i-net-software/jlessc
|
/**
* MIT License (MIT)
*
* Copyright (c) 2014 - 2015 Volker Berlin
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* UT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author Volker Berlin
* @license: The MIT license <http://opensource.org/licenses/MIT>
*/
package com.inet.lib.less;
import java.util.List;
/**
* Some utilities methods.
*/
class SelectorUtils {
static String[] merge( String[] mainSelector, String[] base ) {
int count = 0;
// counting the & characters and calculate the resulting selectors
int[] counts = new int[base.length];
for( int j = 0; j < base.length; j++ ) {
String selector = base[j];
int andCount = 0;
int idx = -1;
while( (idx = selector.indexOf( '&', idx + 1 )) >= 0 ) {
andCount++;
}
count += counts[j] = (int)Math.pow( mainSelector.length, Math.max( 1, andCount ) );
}
String[] sel = new String[count];
for( int j = 0, t = 0; j < base.length; j++ ) {
String selector = base[j];
int idx = selector.lastIndexOf( '&' );
if( idx < 0 ) {
for( String mainSel : mainSelector ) {
sel[t++] = mainSel.isEmpty() ? selector : mainSel + ' ' + selector;
}
} else {
int off = t;
count = counts[j];
do {
int a = (t - off);
int idx2 = idx;
selector = base[j];
do {
int x = a % mainSelector.length;
selector = selector.substring( 0, idx2 ) + mainSelector[x] + selector.substring( idx2 + 1 );
a /= mainSelector.length;
} while( (idx2 = selector.lastIndexOf( '&', idx2 - 1 )) >= 0 );
sel[t++] = selector;
} while( (t - off) < count );
}
}
return sel;
}
static void appendToWithPlaceHolder( CssFormatter formatter, String str, int i, LessObject caller ) {
int length = str.length();
boolean isJavaScript = length > 0 && str.charAt( 0 ) == '`';
int appendIdx = 0;
char quote = 0;
for( ; i < length; i++ ) {
char ch = str.charAt( i );
switch( ch ) {
case '\"':
case '\'':
if( quote == 0 ) {
quote = ch;
} else {
quote = 0;
}
break;
case '@':
String name;
int nextIdx;
if( str.length() > i + 1 && str.charAt( i + 1 ) == '{' ) {
nextIdx = str.indexOf( '}', i );
name = '@' + str.substring( i + 2, nextIdx );
nextIdx++;
} else {
if( quote != 0 ) {
break;
}
LOOP: for( nextIdx = i + 1; nextIdx < str.length(); nextIdx++ ) {
ch = str.charAt( nextIdx );
switch( ch ) {
case ' ':
case ')':
case ',':
case '\"':
case '\'':
break LOOP;
}
}
name = str.substring( i, nextIdx );
}
formatter.append( str.substring( appendIdx, i ) );
appendIdx = nextIdx;
Expression exp = formatter.getVariable( name );
if( exp == null ) {
throw caller.createException( "Undefine Variable: " + name + " in " + str );
}
if( isJavaScript ) {
boolean isList = exp.getDataType( formatter ) == Expression.LIST;
if( isList ) {
formatter.append( '[' );
List<Expression> values = exp.listValue( formatter ).getOperands();
for( int j = 0; j < values.size(); j++ ) {
if( j > 0 ) {
formatter.append( ", " );
}
values.get( j ).appendTo( formatter );
}
formatter.append( ']' );
} else {
exp.appendTo( formatter );
}
} else {
formatter.setInlineMode( true );
exp.appendTo( formatter );
formatter.setInlineMode( false );
}
break;
}
}
formatter.append( str.substring( appendIdx ) );
}
static String replacePlaceHolder( CssFormatter formatter, String str, LessObject caller ) {
int pos = str.startsWith( "@{" ) ? 0 : str.indexOf( "@", 1 );
if( pos >= 0 ) {
formatter.addOutput();
SelectorUtils.appendToWithPlaceHolder( formatter, str, pos, caller );
return formatter.releaseOutput();
}
return str;
}
}
|
src/com/inet/lib/less/SelectorUtils.java
|
/**
* MIT License (MIT)
*
* Copyright (c) 2014 - 2015 Volker Berlin
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* UT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author Volker Berlin
* @license: The MIT license <http://opensource.org/licenses/MIT>
*/
package com.inet.lib.less;
import java.util.List;
/**
* Some utilities methods.
*/
class SelectorUtils {
static String[] merge( String[] mainSelector, String[] base ) {
int count = 0;
// counting the & characters and calculate the resulting selectors
int[] counts = new int[base.length];
for( int j = 0; j < base.length; j++ ) {
String selector = base[j];
int andCount = 0;
int idx = -1;
while( (idx = selector.indexOf( '&', idx + 1 )) >= 0 ) {
andCount++;
}
count += counts[j] = (int)Math.pow( mainSelector.length, Math.max( 1, andCount ) );
}
String[] sel = new String[count];
for( int j = 0, t = 0; j < base.length; j++ ) {
String selector = base[j];
int idx = selector.lastIndexOf( '&' );
if( idx < 0 ) {
for( int m = 0; m < mainSelector.length; m++ ) {
sel[t++] = mainSelector[m] + ' ' + selector;
}
} else {
int off = t;
count = counts[j];
do {
int a = (t - off);
int idx2 = idx;
selector = base[j];
do {
int x = a % mainSelector.length;
selector = selector.substring( 0, idx2 ) + mainSelector[x] + selector.substring( idx2 + 1 );
a /= mainSelector.length;
} while( (idx2 = selector.lastIndexOf( '&', idx2 - 1 )) >= 0 );
sel[t++] = selector;
} while( (t - off) < count );
}
}
return sel;
}
static void appendToWithPlaceHolder( CssFormatter formatter, String str, int i, LessObject caller ) {
int length = str.length();
boolean isJavaScript = length > 0 && str.charAt( 0 ) == '`';
int appendIdx = 0;
char quote = 0;
for( ; i < length; i++ ) {
char ch = str.charAt( i );
switch( ch ) {
case '\"':
case '\'':
if( quote == 0 ) {
quote = ch;
} else {
quote = 0;
}
break;
case '@':
String name;
int nextIdx;
if( str.length() > i + 1 && str.charAt( i + 1 ) == '{' ) {
nextIdx = str.indexOf( '}', i );
name = '@' + str.substring( i + 2, nextIdx );
nextIdx++;
} else {
if( quote != 0 ) {
break;
}
LOOP: for( nextIdx = i + 1; nextIdx < str.length(); nextIdx++ ) {
ch = str.charAt( nextIdx );
switch( ch ) {
case ' ':
case ')':
case ',':
case '\"':
case '\'':
break LOOP;
}
}
name = str.substring( i, nextIdx );
}
formatter.append( str.substring( appendIdx, i ) );
appendIdx = nextIdx;
Expression exp = formatter.getVariable( name );
if( exp == null ) {
throw caller.createException( "Undefine Variable: " + name + " in " + str );
}
if( isJavaScript ) {
boolean isList = exp.getDataType( formatter ) == Expression.LIST;
if( isList ) {
formatter.append( '[' );
List<Expression> values = exp.listValue( formatter ).getOperands();
for( int j = 0; j < values.size(); j++ ) {
if( j > 0 ) {
formatter.append( ", " );
}
values.get( j ).appendTo( formatter );
}
formatter.append( ']' );
} else {
exp.appendTo( formatter );
}
} else {
formatter.setInlineMode( true );
exp.appendTo( formatter );
formatter.setInlineMode( false );
}
break;
}
}
formatter.append( str.substring( appendIdx ) );
}
static String replacePlaceHolder( CssFormatter formatter, String str, LessObject caller ) {
int pos = str.startsWith( "@{" ) ? 0 : str.indexOf( "@", 1 );
if( pos >= 0 ) {
formatter.addOutput();
SelectorUtils.appendToWithPlaceHolder( formatter, str, pos, caller );
return formatter.releaseOutput();
}
return str;
}
}
|
Remove space if mainSelector is empty
|
src/com/inet/lib/less/SelectorUtils.java
|
Remove space if mainSelector is empty
|
|
Java
|
mit
|
31f34e78562cbcd5fbc4c6bf39bd9f556063a237
| 0
|
bsara/FirehoseAndroid
|
package com.mysterioustrousers.firehose;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.google.gson.annotations.SerializedName;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
public class Agent extends FHObject {
private static transient Agent s_loggedInAgent = null;
@SerializedName("access_token")
private String _accessToken;
@SerializedName("browser_token")
private String _browserToken;
@SerializedName("email")
private String _email;
@SerializedName("first_name")
private String _firstName;
@SerializedName("last_name")
private String _lastName;
@SerializedName("url_token")
private String _urlToken;
@SerializedName("display_name")
private String _displayName;
@SerializedName("avatar_url")
private String _avatarURL;
@SerializedName("agent_settings")
private AgentSettings _agentSettings;
@SerializedName("companies")
private List<Company> _companies; // TODO: Change from List to Set
@SerializedName("devices")
private List<Device> _devices; // TODO: Change from List to Set
public Agent() {
super();
this.setAccessToken(null);
this.setBrowserToken(null);
this.setEmail(null);
this.setFirstName(null);
this.setLastName(null);
this.setURLToken(null);
this.setDisplayName(null);
this.setAvatarURL(null);
this.setAgentSettings(new AgentSettings());
this.setCompanies(new ArrayList<Company>());
this.setDevices(new ArrayList<Device>());
}
public static GsonRequest<Agent> login(String email, String password, Listener<Agent> listener, ErrorListener errorListener) {
String url = String.format("%s/login", EnvironmentManager.getRemoteInstance().getBaseURL(FHApplication.API));
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("email", email);
jsonObject.put("password", password);
} catch (Exception e) {
errorListener.onErrorResponse(new ParseError(e));
}
return new GsonRequest<Agent>(Request.Method.POST, url, Agent.class, jsonObject, listener, errorListener);
}
public static GsonRequest<Agent> loginWithToken(String accessToken, Listener<Agent> listener, ErrorListener errorListener) {
String url = String.format("%s/login", EnvironmentManager.getRemoteInstance().getBaseURL(FHApplication.API));
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Authorization", String.format("Token token=\"%s\"", accessToken));
return new GsonRequest<Agent>(Request.Method.POST, url, Agent.class, headers, null, listener, errorListener);
}
public String getShortName() {
String lastInitial = (!this.getLastName().isEmpty()) ? String.format(" %s.", this.getLastName().substring(0, 1)) : StringUtils.EMPTY;
return String.format("%s %s", this.getFirstName(), lastInitial);
}
// region Getters & Setters
public static Agent getLoggedInAgent() {
return s_loggedInAgent;
}
public static void setLoggedInAgent(Agent agent) {
s_loggedInAgent = agent;
}
public String getAccessToken() {
return _accessToken;
}
public void setAccessToken(String accessToken) {
_accessToken = accessToken;
}
public String getBrowserToken() {
return _browserToken;
}
public void setBrowserToken(String browserToken) {
_browserToken = browserToken;
}
public String getEmail() {
return _email;
}
public void setEmail(String email) {
_email = email;
}
public String getFirstName() {
return _firstName;
}
public void setFirstName(String firstName) {
_firstName = firstName;
}
public String getLastName() {
return _lastName;
}
public void setLastName(String lastName) {
_lastName = lastName;
}
public String getURLToken() {
return _urlToken;
}
public void setURLToken(String urlToken) {
_urlToken = urlToken;
}
public String getDisplayName() {
return _displayName;
}
public void setDisplayName(String displayName) {
_displayName = displayName;
}
public String getAvatarURL() {
return _avatarURL;
}
public void setAvatarURL(String avatarURL) {
_avatarURL = avatarURL;
}
public AgentSettings getAgentSettings() {
return _agentSettings;
}
public void setAgentSettings(AgentSettings agentSettings) {
_agentSettings = agentSettings;
}
public List<Company> getCompanies() {
return _companies;
}
public void setCompanies(List<Company> companies) {
_companies = companies;
}
public List<Device> getDevices() {
return _devices;
}
public void setDevices(List<Device> devices) {
_devices = devices;
}
// endregion
}
|
src/main/java/com/mysterioustrousers/firehose/Agent.java
|
package com.mysterioustrousers.firehose;
import java.util.ArrayList;
import java.util.List;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.google.gson.annotations.SerializedName;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
public class Agent extends FHObject {
private static transient Agent s_loggedInAgent = null;
@SerializedName("access_token")
private String _accessToken;
@SerializedName("browser_token")
private String _browserToken;
@SerializedName("email")
private String _email;
@SerializedName("first_name")
private String _firstName;
@SerializedName("last_name")
private String _lastName;
@SerializedName("url_token")
private String _urlToken;
@SerializedName("display_name")
private String _displayName;
@SerializedName("avatar_url")
private String _avatarURL;
@SerializedName("agent_settings")
private AgentSettings _agentSettings;
@SerializedName("companies")
private List<Company> _companies; // TODO: Change from List to Set
@SerializedName("devices")
private List<Device> _devices; // TODO: Change from List to Set
public Agent() {
super();
this.setAccessToken(null);
this.setBrowserToken(null);
this.setEmail(null);
this.setFirstName(null);
this.setLastName(null);
this.setURLToken(null);
this.setDisplayName(null);
this.setAvatarURL(null);
this.setAgentSettings(new AgentSettings());
this.setCompanies(new ArrayList<Company>());
this.setDevices(new ArrayList<Device>());
}
public static GsonRequest<Agent> login(String email, String password, Listener<Agent> listener, ErrorListener errorListener) {
String url = String.format("%s/login", EnvironmentManager.getRemoteInstance().getBaseURL(FHApplication.API));
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("email", email);
jsonObject.put("password", password);
} catch (Exception e) {
errorListener.onErrorResponse(new ParseError(e));
}
return new GsonRequest<Agent>(Request.Method.POST, url, Agent.class, jsonObject, listener, errorListener);
}
public String getShortName() {
String lastInitial = (!this.getLastName().isEmpty()) ? String.format(" %s.", this.getLastName().substring(0, 1)) : StringUtils.EMPTY;
return String.format("%s %s", this.getFirstName(), lastInitial);
}
// region Getters & Setters
public static Agent getLoggedInAgent() {
return s_loggedInAgent;
}
public static void setLoggedInAgent(Agent agent) {
s_loggedInAgent = agent;
}
public String getAccessToken() {
return _accessToken;
}
public void setAccessToken(String accessToken) {
_accessToken = accessToken;
}
public String getBrowserToken() {
return _browserToken;
}
public void setBrowserToken(String browserToken) {
_browserToken = browserToken;
}
public String getEmail() {
return _email;
}
public void setEmail(String email) {
_email = email;
}
public String getFirstName() {
return _firstName;
}
public void setFirstName(String firstName) {
_firstName = firstName;
}
public String getLastName() {
return _lastName;
}
public void setLastName(String lastName) {
_lastName = lastName;
}
public String getURLToken() {
return _urlToken;
}
public void setURLToken(String urlToken) {
_urlToken = urlToken;
}
public String getDisplayName() {
return _displayName;
}
public void setDisplayName(String displayName) {
_displayName = displayName;
}
public String getAvatarURL() {
return _avatarURL;
}
public void setAvatarURL(String avatarURL) {
_avatarURL = avatarURL;
}
public AgentSettings getAgentSettings() {
return _agentSettings;
}
public void setAgentSettings(AgentSettings agentSettings) {
_agentSettings = agentSettings;
}
public List<Company> getCompanies() {
return _companies;
}
public void setCompanies(List<Company> companies) {
_companies = companies;
}
public List<Device> getDevices() {
return _devices;
}
public void setDevices(List<Device> devices) {
_devices = devices;
}
// endregion
}
|
add accesstoken login
|
src/main/java/com/mysterioustrousers/firehose/Agent.java
|
add accesstoken login
|
|
Java
|
mit
|
22cb99b38ddd4ca0bb5a6fc5defafa75fa6af1d7
| 0
|
jenkinsci/jmx-plugin,jenkinsci/jmx-plugin
|
package hudson.plugins.jmx;
import hudson.Plugin;
import hudson.model.Hudson;
import java.lang.management.ManagementFactory;
import javax.management.MBeanServer;
/**
* Entry point of the plugin. This is responsible for registering listeners
* with Hudson and create/find the MBeanServer.
*
* @author Renaud Bruyeron
* @version $Id: PluginImpl.java 1671 2007-01-07 05:57:43Z kohsuke $
* @plugin
*/
public class PluginImpl extends Plugin {
JmxJobListener jjl = null;
public void start() throws Exception {
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
jjl = new JmxJobListener(server);
Hudson.getInstance().getJobListeners().add(jjl);
}
/**
* @see hudson.Plugin#stop()
*/
@Override
public void stop() throws Exception {
Hudson.getInstance().getJobListeners().remove(jjl);
jjl.unregister();
jjl = null;
}
}
|
src/main/java/hudson/plugins/jmx/PluginImpl.java
|
package hudson.plugins.jmx;
import hudson.Plugin;
import hudson.model.Hudson;
import java.lang.management.ManagementFactory;
import javax.management.MBeanServer;
/**
* Entry point of the plugin. This is responsible for registering listeners
* with Hudson and create/find the MBeanServer.
*
* @author Renaud Bruyeron
* @version $Id: PluginImpl.java 1407 2006-12-21 08:54:09Z bruyeron $
* @plugin
*/
public class PluginImpl extends Plugin {
JmxJobListener jjl = null;
public void start() throws Exception {
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
jjl = new JmxJobListener(server);
Hudson.getInstance().addListener(jjl);
}
/**
* @see hudson.Plugin#stop()
*/
@Override
public void stop() throws Exception {
Hudson.getInstance().removeListener(jjl);
jjl.unregister();
jjl = null;
}
}
|
avoid using a deprecated feature.
|
src/main/java/hudson/plugins/jmx/PluginImpl.java
|
avoid using a deprecated feature.
|
|
Java
|
mit
|
29529538678dc7b20803b1b2ccab4e6e159d16b4
| 0
|
Pyohwan/JakduK,JakduK/JakduK,JakduK/jakduk-api,silverprize/jakduk-api,JakduK/JakduK,JakduK/JakduK,silverprize/JakduK,silverprize/JakduK,silverprize/jakduk-api,silverprize/JakduK,Pyohwan/JakduK,Pyohwan/JakduK,JakduK/jakduk-api
|
package com.jakduk.controller;
import com.jakduk.common.CommonConst;
import com.jakduk.model.db.Token;
import com.jakduk.repository.TokenRepository;
import com.jakduk.service.CommonService;
import com.jakduk.service.EmailService;
import com.jakduk.service.UserService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
@Controller
@RequestMapping()
public class AccessController {
@Autowired
private CommonService commonService;
@Autowired
private TokenRepository tokenRepository;
@Autowired
private EmailService emailService;
@Autowired
private UserService userService;
@Value("#{tokenTerminationTrigger.span}")
private long tokenSpan;
private Logger logger = Logger.getLogger(this.getClass());
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(HttpServletRequest request,
Model model,
@RequestParam(required = false) String result,
@RequestParam(required = false) String loginRedirect) throws UnsupportedEncodingException {
if (loginRedirect == null) {
loginRedirect = request.getHeader("REFERER");
}
if (loginRedirect != null) {
model.addAttribute("loginRedirect", URLEncoder.encode(loginRedirect, "UTF-8"));
}
model.addAttribute("result", result);
return "access/login";
}
@RequestMapping(value = "/logout/success", method = RequestMethod.GET)
public String logoutSuccess(HttpServletRequest request) {
String redirctUrl = "/";
String refererUrl = request.getHeader("REFERER");
if (refererUrl != null) {
if (commonService.isRedirectUrl(refererUrl)) {
redirctUrl = refererUrl;
}
}
return "redirect:" + redirctUrl;
}
@RequestMapping(value = "/denied")
public String denied() {
return "access/denied";
}
@RequestMapping(value = "/reset_password", method = RequestMethod.GET)
public String resetPassword(
Model model,
@RequestParam(value = "code", required = false) String code) {
if (Objects.nonNull(code)) {
Token token = tokenRepository.findByCode(code);
if ((Objects.isNull(token) || !token.getCode().equals(code))) {
model.addAttribute("title", "user.sign.reset.password");
model.addAttribute("result", CommonConst.RESET_PASSWORD_RESULT.INVALID);
} else {
model.addAttribute("title", "user.placeholder.password");
model.addAttribute("user_email", token.getEmail());
model.addAttribute("result", CommonConst.RESET_PASSWORD_RESULT.CODE_OK);
}
model.addAttribute("action", "confirm_password");
} else {
model.addAttribute("action", "reset_password");
model.addAttribute("title", "user.sign.reset.password");
model.addAttribute("result", CommonConst.RESET_PASSWORD_RESULT.NONE);
}
return "access/resetPassword";
}
@RequestMapping(value = "/reset_password", method = RequestMethod.POST)
public String sendResetPassword(
Model model,
@RequestParam(value = "j_useremail") String email
) throws UnsupportedEncodingException {
emailService.sendResetPassword(email);
model.addAttribute("title", "user.sign.reset.password");
model.addAttribute("result", CommonConst.RESET_PASSWORD_RESULT.SEND_OK);
return "access/resetPassword";
}
@RequestMapping(value = "/confirm_password", method = RequestMethod.POST)
public String updatePassword(
Model model,
@RequestParam(value = "j_password") String password,
@RequestParam(value = "code") String code
) {
long tokenSpanMillis = TimeUnit.MINUTES.toMillis(tokenSpan);
Token token = tokenRepository.findByCode(code);
if (Objects.isNull(token) || token.getCreatedTime().getTime() + tokenSpanMillis <= System.currentTimeMillis()) {
model.addAttribute("title", "user.sign.reset.password");
model.addAttribute("result", CommonConst.RESET_PASSWORD_RESULT.INVALID);
} else {
userService.userPasswordUpdateByEmail(token.getEmail(), password);
model.addAttribute("title", "user.placeholder.password");
model.addAttribute("user_email", token.getEmail());
model.addAttribute("result", CommonConst.RESET_PASSWORD_RESULT.CHANGE_OK);
}
if (Objects.nonNull(token)) {
tokenRepository.delete(token);
}
return "access/resetPassword";
}
}
|
jakduk-web/src/com/jakduk/controller/AccessController.java
|
package com.jakduk.controller;
import com.jakduk.common.CommonConst;
import com.jakduk.model.db.Token;
import com.jakduk.repository.TokenRepository;
import com.jakduk.service.CommonService;
import com.jakduk.service.EmailService;
import com.jakduk.service.UserService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
@Controller
@RequestMapping()
public class AccessController {
@Autowired
private CommonService commonService;
@Autowired
private TokenRepository tokenRepository;
@Autowired
private EmailService emailService;
@Autowired
private UserService userService;
@Value("#{tokenTerminationTrigger.span}")
private long tokenSpan;
private Logger logger = Logger.getLogger(this.getClass());
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(HttpServletRequest request,
Model model,
@RequestParam(required = false) String result,
@RequestParam(required = false) String loginRedirect) throws UnsupportedEncodingException {
if (loginRedirect == null) {
loginRedirect = request.getHeader("REFERER");
}
if (loginRedirect != null) {
model.addAttribute("loginRedirect", URLEncoder.encode(loginRedirect, "UTF-8"));
}
model.addAttribute("result", result);
return "access/login";
}
@RequestMapping(value = "/logout/success", method = RequestMethod.GET)
public String logoutSuccess(HttpServletRequest request) {
String redirctUrl = "/";
String refererUrl = request.getHeader("REFERER");
if (refererUrl != null) {
if (commonService.isRedirectUrl(refererUrl)) {
redirctUrl = refererUrl;
}
}
return "redirect:" + redirctUrl;
}
@RequestMapping(value = "/denied")
public String denied() {
return "access/denied";
}
@RequestMapping(value = "/reset_password", method = RequestMethod.GET)
public String resetPassword(
Model model,
@RequestParam(value = "code", required = false) String code) {
if (Objects.nonNull(code)) {
Token token = tokenRepository.findByCode(code);
if ((Objects.isNull(token) || !token.getCode().equals(code))) {
model.addAttribute("title", "user.sign.reset.password");
model.addAttribute("result", CommonConst.RESET_PASSWORD_RESULT.INVALID);
} else {
model.addAttribute("title", "user.placeholder.password");
model.addAttribute("user_email", token.getEmail());
model.addAttribute("result", CommonConst.RESET_PASSWORD_RESULT.CODE_OK);
}
model.addAttribute("action", "confirm_password");
} else {
model.addAttribute("action", "reset_password");
model.addAttribute("title", "user.sign.reset.password");
model.addAttribute("result", CommonConst.RESET_PASSWORD_RESULT.NONE);
}
return "access/resetPassword";
}
@RequestMapping(value = "/reset_password", method = RequestMethod.POST)
public String sendResetPassword(
Model model,
@RequestParam(value = "j_useremail") String email
) throws UnsupportedEncodingException {
emailService.sendResetPassword(email);
model.addAttribute("title", "user.sign.reset.password");
model.addAttribute("result", CommonConst.RESET_PASSWORD_RESULT.SEND_OK);
return "access/resetPassword";
}
@RequestMapping(value = "/confirm_password", method = RequestMethod.POST)
public String updatePassword(
Model model,
@RequestParam(value = "j_password") String password,
@RequestParam(value = "code") String code
) {
long tokenSpanMillis = TimeUnit.MINUTES.toMillis(tokenSpan);
Token token = tokenRepository.findByCode(code);
if (Objects.isNull(token) || token.getCreatedTime().getTime() + tokenSpanMillis <= System.currentTimeMillis()) {
model.addAttribute("title", "user.sign.reset.password");
model.addAttribute("result", CommonConst.RESET_PASSWORD_RESULT.INVALID);
} else {
userService.userPasswordUpdateByEmail(token.getEmail(), password);
model.addAttribute("title", "user.placeholder.password");
model.addAttribute("user_email", token.getEmail());
model.addAttribute("result", CommonConst.RESET_PASSWORD_RESULT.CHANGE_OK);
}
if (Objects.nonNull(token)) {
tokenRepository.delete(token);
}
return "access/resetPassword";
}
}
|
indentation
|
jakduk-web/src/com/jakduk/controller/AccessController.java
|
indentation
|
|
Java
|
agpl-3.0
|
63dec0444920d71c9be57772ec4e843134564719
| 0
|
rakam-io/rakam,buremba/rakam,buremba/rakam,buremba/rakam,rakam-io/rakam,rakam-io/rakam,buremba/rakam,buremba/rakam
|
package org.rakam.presto.analysis.datasource;
import com.facebook.presto.jdbc.internal.guava.base.Function;
import com.facebook.presto.rakam.externaldata.DataManager;
import org.rakam.analysis.JDBCPoolDataSource;
import org.rakam.presto.analysis.datasource.CustomDataSource.ExternalFileCustomDataSource;
import org.rakam.presto.analysis.datasource.CustomDataSource.SupportedCustomDatabase;
import org.rakam.server.http.HttpService;
import org.rakam.server.http.annotations.Api;
import org.rakam.server.http.annotations.ApiOperation;
import org.rakam.server.http.annotations.ApiParam;
import org.rakam.server.http.annotations.Authorization;
import org.rakam.server.http.annotations.BodyParam;
import org.rakam.server.http.annotations.IgnoreApi;
import org.rakam.server.http.annotations.JsonRequest;
import org.rakam.util.JsonHelper;
import org.rakam.util.RakamException;
import org.rakam.util.SuccessMessage;
import org.skife.jdbi.v2.DBI;
import org.skife.jdbi.v2.Handle;
import org.skife.jdbi.v2.Query;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.inject.Named;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
import static io.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND;
import static org.rakam.presto.analysis.datasource.CustomDataSource.DataSource.createDataSource;
@IgnoreApi
@Path("/custom-data-source")
@Api(value = "/integrate/data-source", nickname = "custom-data-source", description = "Connect to custom databases", tags = {"analyze"})
public class CustomDataSourceHttpService
extends HttpService
{
private final DBI dbi;
@Inject
public CustomDataSourceHttpService(@Named("report.metadata.store.jdbc") JDBCPoolDataSource dataSource)
{
this.dbi = new DBI(dataSource);
}
@PostConstruct
public void setup()
{
try (Handle handle = dbi.open()) {
handle.createStatement("CREATE TABLE IF NOT EXISTS custom_data_source (" +
" project VARCHAR(255) NOT NULL," +
" schema_name VARCHAR(255) NOT NULL," +
" type TEXT NOT NULL," +
" options TEXT," +
" PRIMARY KEY (project, schema_name)" +
" )")
.execute();
handle.createStatement("CREATE TABLE IF NOT EXISTS custom_file_source (" +
" project VARCHAR(255) NOT NULL," +
" table_name VARCHAR(255) NOT NULL," +
" options TEXT," +
" PRIMARY KEY (project, table_name)" +
" )")
.execute();
}
}
@ApiOperation(value = "Delete hook", authorizations = @Authorization(value = "master_key"))
@Path("/delete")
@JsonRequest
public void delete(@Named("project") String project, @ApiParam("identifier") String identifier)
{
try (Handle handle = dbi.open()) {
handle.createQuery("SELECT options FROM custom_data_source WHERE project = :project")
.bind("project", project)
.map((index, r, ctx) -> {
return JsonHelper.read(r.getString(1), ExternalFileCustomDataSource.class);
}).list();
}
}
@ApiOperation(value = "List data-sources", authorizations = @Authorization(value = "master_key"))
@Path("/list")
@GET
public List<CustomDataSource> list(@Named("project") String project)
{
try (Handle handle = dbi.open()) {
return handle.createQuery("SELECT schema_name, type, options FROM custom_data_source WHERE project = :project")
.bind("project", project)
.map((index, r, ctx) -> {
DataManager.DataSourceFactory dataSource = createDataSource(r.getString(2), JsonHelper.read(r.getString(3)));
return new CustomDataSource(r.getString(2), r.getString(1), dataSource);
}).list();
}
}
@ApiOperation(value = "Get data-source", authorizations = @Authorization(value = "master_key"))
@Path("/get")
@JsonRequest
public CustomDataSource get(@Named("project") String project, String schema)
{
try (Handle handle = dbi.open()) {
Query<Map<String, Object>> bind = handle.createQuery("SELECT type, options FROM custom_data_source WHERE project = :project AND schema_name = :schema_name")
.bind("project", project)
.bind("schema_name", schema);
CustomDataSource first = bind.map((index, r, ctx) -> {
DataManager.DataSourceFactory dataSource = createDataSource(r.getString(1), JsonHelper.read(r.getString(2)));
return new CustomDataSource(r.getString(1), r.getString(2), dataSource);
}).first();
if (first == null) {
throw new RakamException(NOT_FOUND);
}
return first;
}
}
@ApiOperation(value = "Add data-source", authorizations = @Authorization(value = "master_key"))
@Path("/add/database")
@JsonRequest
public SuccessMessage add(@Named("project") String project, @BodyParam CustomDataSource hook)
{
try (Handle handle = dbi.open()) {
try {
handle.createStatement("INSERT INTO custom_data_source (project, schema_name, type, options) " +
"VALUES (:project, :schema_name, :table_name, :type, :options)")
.bind("project", project)
.bind("schema_name", hook.schemaName)
.bind("type", hook.type)
.bind("options", JsonHelper.encode(hook.options))
.execute();
return SuccessMessage.success();
}
catch (Exception e) {
throw e;
// throw new RakamException(e.getMessage(), BAD_REQUEST);
}
}
}
@ApiOperation(value = "Add file data-source", authorizations = @Authorization(value = "master_key"))
@Path("/add/file")
@JsonRequest
public SuccessMessage add(@Named("project") String project, @BodyParam CustomFile hook)
{
try (Handle handle = dbi.open()) {
try {
handle.createStatement("INSERT INTO custom_file_source (project, table_name, type, options) " +
"VALUES (:project, :schema_name, :table_name, :type, :options)")
.bind("project", project)
.bind("table_name", hook.tableName)
.bind("options", JsonHelper.encode(hook.options))
.execute();
return SuccessMessage.success();
}
catch (Exception e) {
throw e;
// throw new RakamException(e.getMessage(), BAD_REQUEST);
}
}
}
@ApiOperation(value = "Test data-source", authorizations = @Authorization(value = "master_key"))
@Path("/test")
@JsonRequest
public SuccessMessage test(@Named("project") String project, @BodyParam CustomDataSource hook)
{
Function optionalFunction = SupportedCustomDatabase.getTestFunction(hook.type);
Optional<String> test = (Optional<String>) optionalFunction.apply(hook.options);
if (test.isPresent()) {
throw new RakamException(test.get(), BAD_REQUEST);
}
return SuccessMessage.success();
}
}
|
rakam-presto/src/main/java/org/rakam/presto/analysis/datasource/CustomDataSourceHttpService.java
|
package org.rakam.presto.analysis.datasource;
import com.facebook.presto.rakam.externaldata.DataManager;
import org.rakam.analysis.JDBCPoolDataSource;
import org.rakam.presto.analysis.datasource.CustomDataSource.ExternalFileCustomDataSource;
import org.rakam.presto.analysis.datasource.CustomDataSource.SupportedCustomDatabase;
import org.rakam.server.http.HttpService;
import org.rakam.server.http.annotations.Api;
import org.rakam.server.http.annotations.ApiOperation;
import org.rakam.server.http.annotations.ApiParam;
import org.rakam.server.http.annotations.Authorization;
import org.rakam.server.http.annotations.BodyParam;
import org.rakam.server.http.annotations.IgnoreApi;
import org.rakam.server.http.annotations.JsonRequest;
import org.rakam.util.JsonHelper;
import org.rakam.util.RakamException;
import org.rakam.util.SuccessMessage;
import org.skife.jdbi.v2.DBI;
import org.skife.jdbi.v2.Handle;
import org.skife.jdbi.v2.Query;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.inject.Named;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
import static io.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND;
import static org.rakam.presto.analysis.datasource.CustomDataSource.DataSource.createDataSource;
@IgnoreApi
@Path("/custom-data-source")
@Api(value = "/integrate/data-source", nickname = "custom-data-source", description = "Connect to custom databases", tags = {"analyze"})
public class CustomDataSourceHttpService
extends HttpService
{
private final DBI dbi;
@Inject
public CustomDataSourceHttpService(@Named("report.metadata.store.jdbc") JDBCPoolDataSource dataSource)
{
this.dbi = new DBI(dataSource);
}
@PostConstruct
public void setup()
{
try (Handle handle = dbi.open()) {
handle.createStatement("CREATE TABLE IF NOT EXISTS custom_data_source (" +
" project VARCHAR(255) NOT NULL," +
" schema_name VARCHAR(255) NOT NULL," +
" type TEXT NOT NULL," +
" options TEXT," +
" PRIMARY KEY (project, schema_name)" +
" )")
.execute();
handle.createStatement("CREATE TABLE IF NOT EXISTS custom_file_source (" +
" project VARCHAR(255) NOT NULL," +
" table_name VARCHAR(255) NOT NULL," +
" options TEXT," +
" PRIMARY KEY (project, table_name)" +
" )")
.execute();
}
}
@ApiOperation(value = "Delete hook", authorizations = @Authorization(value = "master_key"))
@Path("/delete")
@JsonRequest
public void delete(@Named("project") String project, @ApiParam("identifier") String identifier)
{
try (Handle handle = dbi.open()) {
handle.createQuery("SELECT options FROM custom_data_source WHERE project = :project")
.bind("project", project)
.map((index, r, ctx) -> {
return JsonHelper.read(r.getString(1), ExternalFileCustomDataSource.class);
}).list();
}
}
@ApiOperation(value = "List data-sources", authorizations = @Authorization(value = "master_key"))
@Path("/list")
@GET
public List<CustomDataSource> list(@Named("project") String project)
{
try (Handle handle = dbi.open()) {
return handle.createQuery("SELECT schema_name, type, options FROM custom_data_source WHERE project = :project")
.bind("project", project)
.map((index, r, ctx) -> {
DataManager.DataSourceFactory dataSource = createDataSource(r.getString(2), JsonHelper.read(r.getString(3)));
return new CustomDataSource(r.getString(2), r.getString(1), dataSource);
}).list();
}
}
@ApiOperation(value = "Get data-source", authorizations = @Authorization(value = "master_key"))
@Path("/get")
@JsonRequest
public CustomDataSource get(@Named("project") String project, String schema)
{
try (Handle handle = dbi.open()) {
Query<Map<String, Object>> bind = handle.createQuery("SELECT type, options FROM custom_data_source WHERE project = :project AND schema_name = :schema_name")
.bind("project", project)
.bind("schema_name", schema);
CustomDataSource first = bind.map((index, r, ctx) -> {
DataManager.DataSourceFactory dataSource = createDataSource(r.getString(1), JsonHelper.read(r.getString(2)));
return new CustomDataSource(r.getString(1), r.getString(2), dataSource);
}).first();
if (first == null) {
throw new RakamException(NOT_FOUND);
}
return first;
}
}
@ApiOperation(value = "Add data-source", authorizations = @Authorization(value = "master_key"))
@Path("/add/database")
@JsonRequest
public SuccessMessage add(@Named("project") String project, @BodyParam CustomDataSource hook)
{
try (Handle handle = dbi.open()) {
try {
handle.createStatement("INSERT INTO custom_data_source (project, schema_name, type, options) " +
"VALUES (:project, :schema_name, :table_name, :type, :options)")
.bind("project", project)
.bind("schema_name", hook.schemaName)
.bind("type", hook.type)
.bind("options", JsonHelper.encode(hook.options))
.execute();
return SuccessMessage.success();
}
catch (Exception e) {
throw e;
// throw new RakamException(e.getMessage(), BAD_REQUEST);
}
}
}
@ApiOperation(value = "Add file data-source", authorizations = @Authorization(value = "master_key"))
@Path("/add/file")
@JsonRequest
public SuccessMessage add(@Named("project") String project, @BodyParam CustomFile hook)
{
try (Handle handle = dbi.open()) {
try {
handle.createStatement("INSERT INTO custom_file_source (project, table_name, type, options) " +
"VALUES (:project, :schema_name, :table_name, :type, :options)")
.bind("project", project)
.bind("table_name", hook.tableName)
.bind("options", JsonHelper.encode(hook.options))
.execute();
return SuccessMessage.success();
}
catch (Exception e) {
throw e;
// throw new RakamException(e.getMessage(), BAD_REQUEST);
}
}
}
@ApiOperation(value = "Test data-source", authorizations = @Authorization(value = "master_key"))
@Path("/test")
@JsonRequest
public SuccessMessage test(@Named("project") String project, @BodyParam CustomDataSource hook)
{
Function optionalFunction = SupportedCustomDatabase.getTestFunction(hook.type);
Optional<String> test = (Optional<String>) optionalFunction.apply(hook.options);
if (test.isPresent()) {
throw new RakamException(test.get(), BAD_REQUEST);
}
return SuccessMessage.success();
}
}
|
add missing import
|
rakam-presto/src/main/java/org/rakam/presto/analysis/datasource/CustomDataSourceHttpService.java
|
add missing import
|
|
Java
|
lgpl-2.1
|
bb379290b94f77999a9ccee97e68b1c9e04ab386
| 0
|
xwiki/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform
|
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*
*/
package com.xpn.xwiki.plugin.ldap;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.novell.ldap.LDAPConnection;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.cache.api.XWikiCache;
import com.xpn.xwiki.cache.api.XWikiCacheNeedsRefreshException;
/**
* LDAP communication tool.
*
* @version $Id: $
* @since 1.3 M2
*/
public class XWikiLDAPUtils
{
/**
* Logging tool.
*/
private static final Log LOG = LogFactory.getLog(XWikiLDAPUtils.class);
/**
* Different LDAP implementations groups classes name.
*/
private static final Set LDAP_GROUP_CLASS = new HashSet();
/**
* Different LDAP implementations groups member property name.
*/
private static final Set LDAP_GROUP_MEMBER = new HashSet();
/**
* LDAP objectClass parameter.
*/
private static final String LDAP_OBJECTCLASS = "objectClass";
/**
* The name of the LDAP groups cache.
*/
private static final String CACHE_NAME_GROUPS = "groups";
/**
* Default unique user field name.
*/
private static final String LDAP_DEFAULT_UID = "cn";
/**
* Contains caches for each LDAP host:port.
*/
private static Map cachePool = new Hashtable();
/**
* The LDAP connection.
*/
private XWikiLDAPConnection connection;
/**
* The LDAP attribute containing the identifier for a user.
*/
private String uidAttributeName = LDAP_DEFAULT_UID;
static {
LDAP_GROUP_CLASS.add("group".toLowerCase());
LDAP_GROUP_CLASS.add("groupOfNames".toLowerCase());
LDAP_GROUP_CLASS.add("groupOfUniqueNames".toLowerCase());
LDAP_GROUP_CLASS.add("dynamicGroup".toLowerCase());
LDAP_GROUP_CLASS.add("dynamicGroupAux".toLowerCase());
LDAP_GROUP_CLASS.add("groupWiseDistributionList".toLowerCase());
LDAP_GROUP_MEMBER.add("member".toLowerCase());
LDAP_GROUP_MEMBER.add("uniqueMember".toLowerCase());
}
/**
* Create an instance of {@link XWikiLDAPUtils}.
*
* @param connection the XWiki LDAP connection tool.
*/
public XWikiLDAPUtils(XWikiLDAPConnection connection)
{
this.connection = connection;
}
/**
* @param uidAttributeName the LDAP attribute containing the identifier for a user.
*/
public void setUidAttributeName(String uidAttributeName)
{
this.uidAttributeName = uidAttributeName;
}
/**
* @return the LDAP attribute containing the identifier for a user.
*/
public String getUidAttributeName()
{
return uidAttributeName;
}
/**
* Get the cache with the provided name for a particular LDAP server.
*
* @param cacheName the name of the cache.
* @param context the XWiki context.
* @return the cache.
* @throws XWikiException error when creating the cache.
*/
public XWikiCache getCache(String cacheName, XWikiContext context) throws XWikiException
{
XWikiCache cache;
String cacheKey =
connection.getConnection().getHost() + ":" + connection.getConnection().getPort();
Map cacheMap;
if (cachePool.containsKey(cacheKey)) {
cacheMap = (Map) cachePool.get(cacheKey);
} else {
cacheMap = new Hashtable();
cachePool.put(cacheKey, cacheMap);
}
if (cacheMap.containsKey(cacheName)) {
cache = (XWikiCache) cacheMap.get(cacheName);
} else {
cache = context.getWiki().getCacheService().newCache("ldap." + cacheName);
cacheMap.put(cacheName, cache);
}
return cache;
}
/**
* @return get {@link XWikiLDAPConnection}.
*/
public XWikiLDAPConnection getConnection()
{
return connection;
}
/**
* Execute LDAP query to get all group's members.
*
* @param groupDN the group to retrieve the members of and scan for subgroups.
* @return the LDAP search result.
*/
private List searchGroupsMembers(String groupDN)
{
String[] attrs = new String[2 + LDAP_GROUP_MEMBER.size()];
int i = 0;
attrs[i++] = LDAP_OBJECTCLASS;
attrs[i++] = getUidAttributeName();
for (Iterator it = LDAP_GROUP_MEMBER.iterator(); it.hasNext();) {
attrs[i++] = (String) it.next();
}
return getConnection().searchLDAP(groupDN, null, attrs, LDAPConnection.SCOPE_BASE);
}
/**
* Extract group's members from provided LDAP search result.
*
* @param searchAttributeList the LDAP search result.
* @param memberMap the result: maps DN to member id.
* @param subgroups return all the subgroups identified.
* @param context the XWiki context.
*/
private void getGroupMembers(List searchAttributeList, Map memberMap, List subgroups,
XWikiContext context)
{
for (Iterator searchAttributeIt = searchAttributeList.iterator(); searchAttributeIt
.hasNext();) {
XWikiLDAPSearchAttribute searchAttribute =
(XWikiLDAPSearchAttribute) searchAttributeIt.next();
String key = searchAttribute.name;
if (LDAP_GROUP_MEMBER.contains(key)) {
// or subgroup
String member = searchAttribute.value;
// we check for subgroups recursive call to scan all subgroups and identify members
// and their uid
getGroupMembers(member, memberMap, subgroups, context);
}
}
}
/**
* Get all members of a given group based on the groupDN. If the group contains subgroups get
* these members as well. Retrieve an identifier for each member.
*
* @param groupDN the group to retrieve the members of and scan for subgroups.
* @param memberMap the result: maps DN to member id.
* @param subgroups all the subgroups identified.
* @param searchAttributeList the groups members found in LDAP search.
* @param context the XWiki context.
* @return whether the groupDN is actually a group.
*/
public boolean getGroupMembers(String groupDN, Map memberMap, List subgroups,
List searchAttributeList, XWikiContext context)
{
boolean isGroup = false;
String id = null;
for (Iterator seachAttributeIt = searchAttributeList.iterator(); seachAttributeIt
.hasNext();) {
XWikiLDAPSearchAttribute searchAttribute =
(XWikiLDAPSearchAttribute) seachAttributeIt.next();
String key = searchAttribute.name;
if (key.equalsIgnoreCase(LDAP_OBJECTCLASS)) {
String objectName = searchAttribute.value;
if (LDAP_GROUP_CLASS.contains(objectName.toLowerCase())) {
isGroup = true;
}
} else if (key.equalsIgnoreCase(getUidAttributeName())) {
id = searchAttribute.value;
}
}
if (!isGroup) {
if (id == null) {
LOG.error("Could not find attribute " + getUidAttributeName() + " for LDAP dn "
+ groupDN);
}
if (!memberMap.containsKey(groupDN)) {
memberMap.put(groupDN, id == null ? "" : id);
}
} else {
// remember this group
if (subgroups != null) {
subgroups.add(groupDN);
}
getGroupMembers(searchAttributeList, memberMap, subgroups, context);
}
return isGroup;
}
/**
* Get all members of a given group based on the groupDN. If the group contains subgroups get
* these members as well. Retrieve an identifier for each member.
*
* @param groupDN the group to retrieve the members of and scan for subgroups.
* @param memberMap the result: maps DN to member id.
* @param subgroups all the subgroups identified.
* @param context the XWiki context.
* @return whether the groupDN is actually a group.
*/
public boolean getGroupMembers(String groupDN, Map memberMap, List subgroups,
XWikiContext context)
{
boolean isGroup = false;
// break out if there is a look of groups
if (subgroups != null && subgroups.contains(groupDN)) {
return true;
}
List searchAttributeList = searchGroupsMembers(groupDN);
if (searchAttributeList != null) {
isGroup =
getGroupMembers(groupDN, memberMap, subgroups, searchAttributeList, context);
}
return isGroup;
}
/**
* Get group members from cache or update it from LDAP if it is not already cached.
*
* @param groupDN the name of the group.
* @param context the XWiki context.
* @return the members of the group.
* @throws XWikiException error when getting the group cache.
*/
public Map getGroupMembers(String groupDN, XWikiContext context) throws XWikiException
{
Map groupMembers = null;
XWikiLDAPConfig config = XWikiLDAPConfig.getInstance();
XWikiCache cache = getCache(CACHE_NAME_GROUPS, context);
synchronized (cache) {
try {
groupMembers =
(Map) cache.getFromCache(groupDN, config.getCacheExpiration(context));
} catch (XWikiCacheNeedsRefreshException e) {
if (LOG.isDebugEnabled()) {
LOG.debug("Cache does not caontains group " + groupDN, e);
}
}
}
if (groupMembers == null) {
groupMembers = new HashMap();
if (LOG.isDebugEnabled()) {
LOG.debug("Retrieving Members of the group: " + groupDN);
}
boolean isGroup = getGroupMembers(groupDN, groupMembers, new ArrayList(), context);
if (isGroup) {
synchronized (cache) {
cache.putInCache(groupDN, groupMembers);
}
}
}
return groupMembers;
}
/**
* Locates the user in the Map: either the user is a value or the key starts with the LDAP
* syntax.
*
* @param userName the name of the user.
* @param groupMembers the members of LDAP group.
* @param context the XWiki context.
* @return the full user name.
*/
protected String findInGroup(String userName, Map groupMembers, XWikiContext context)
{
String result = null;
String ldapuser = getUidAttributeName() + "=" + userName.toLowerCase();
for (Iterator it = groupMembers.keySet().iterator(); it.hasNext();) {
String u = (String) it.next();
// implementing it case-insensitive for now
if (userName.equalsIgnoreCase((String) groupMembers.get(u))
|| u.toLowerCase().startsWith(ldapuser)) {
return u;
}
}
return result;
}
/**
* Check if user is in provided LDAP group.
*
* @param userName the user name.
* @param groupDN the LDAP group DN.
* @param context the XWiki context.
* @return user's DB if the user is in the LDAP group, null otherwise.
* @throws XWikiException error when getting the group cache.
*/
public String isUserInGroup(String userName, String groupDN, XWikiContext context)
throws XWikiException
{
String userDN = null;
if (groupDN.length() > 0) {
Map groupMembers = getGroupMembers(groupDN, context);
// check if user is in the list
userDN = findInGroup(userName, groupMembers, context);
if (LOG.isDebugEnabled()) {
LOG.debug("Found user dn in user group:" + userDN);
}
// if a usergroup is specified THEN the user MUST be in the group to validate in
// LDAP
if (userDN == null) {
if (LOG.isDebugEnabled()) {
LOG.debug("LDAP authentication failed: user not in LDAP user group");
}
// no valid LDAP user from the group
return null;
}
}
return userDN;
}
}
|
xwiki-core/src/main/java/com/xpn/xwiki/plugin/ldap/XWikiLDAPUtils.java
|
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*
*/
package com.xpn.xwiki.plugin.ldap;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.novell.ldap.LDAPConnection;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.cache.api.XWikiCache;
import com.xpn.xwiki.cache.api.XWikiCacheNeedsRefreshException;
/**
* LDAP communication tool.
*
* @version $Id: $
* @since 1.3 M2
*/
public class XWikiLDAPUtils
{
/**
* Logging tool.
*/
private static final Log LOG = LogFactory.getLog(XWikiLDAPUtils.class);
/**
* Different LDAP implementations groups classes name.
*/
private static final Set LDAP_GROUP_CLASS = new HashSet();
/**
* Different LDAP implementations groups member property name.
*/
private static final Set LDAP_GROUP_MEMBER = new HashSet();
/**
* LDAP objectClass parameter.
*/
private static final String LDAP_OBJECTCLASS = "objectClass";
/**
* The name of the LDAP groups cache.
*/
private static final String CACHE_NAME_GROUPS = "groups";
/**
* Default unique user field name.
*/
private static final String LDAP_DEFAULT_UID = "cn";
/**
* Contains caches for each LDAP host:port.
*/
private static Map cachePool = new Hashtable();
/**
* The LDAP connection.
*/
private XWikiLDAPConnection connection;
/**
* The LDAP attribute containing the identifier for a user.
*/
private String uidAttributeName = LDAP_DEFAULT_UID;
static {
LDAP_GROUP_CLASS.add("group".toLowerCase());
LDAP_GROUP_CLASS.add("groupOfNames".toLowerCase());
LDAP_GROUP_CLASS.add("groupOfUniqueNames".toLowerCase());
LDAP_GROUP_CLASS.add("dynamicGroup".toLowerCase());
LDAP_GROUP_CLASS.add("dynamicGroupAux".toLowerCase());
LDAP_GROUP_CLASS.add("groupWiseDistributionList".toLowerCase());
LDAP_GROUP_MEMBER.add("member".toLowerCase());
LDAP_GROUP_MEMBER.add("uniqueMember".toLowerCase());
}
/**
* Create an instance of {@link XWikiLDAPUtils}.
*
* @param connection the XWiki LDAP connection tool.
*/
public XWikiLDAPUtils(XWikiLDAPConnection connection)
{
this.connection = connection;
}
/**
* @param uidAttributeName the LDAP attribute containing the identifier for a user.
*/
public void setUidAttributeName(String uidAttributeName)
{
this.uidAttributeName = uidAttributeName;
}
/**
* @return the LDAP attribute containing the identifier for a user.
*/
public String getUidAttributeName()
{
return uidAttributeName;
}
/**
* Get the cache with the provided name for a particular LDAP server.
*
* @param cacheName the name of the cache.
* @param context the XWiki context.
* @return the cache.
* @throws XWikiException error when creating the cache.
*/
public XWikiCache getCache(String cacheName, XWikiContext context) throws XWikiException
{
XWikiCache cache;
String cacheKey =
connection.getConnection().getHost() + ":" + connection.getConnection().getPort();
Map cacheMap;
if (cachePool.containsKey(cacheKey)) {
cacheMap = (Map) cachePool.get(cacheKey);
} else {
cacheMap = new Hashtable();
cachePool.put(cacheKey, cacheMap);
}
if (cacheMap.containsKey(cacheName)) {
cache = (XWikiCache) cacheMap.get(cacheName);
} else {
cache = context.getWiki().getCacheService().newCache("ldap." + cacheName);
cacheMap.put(cacheName, cache);
}
return cache;
}
/**
* @return get {@link XWikiLDAPConnection}.
*/
public XWikiLDAPConnection getConnection()
{
return connection;
}
/**
* Execute LDAP query to get all group's members.
*
* @param groupDN the group to retrieve the members of and scan for subgroups.
* @return the LDAP search result.
*/
private List searchGroupsMembers(String groupDN)
{
String[] attrs = new String[2 + LDAP_GROUP_MEMBER.size()];
int i = 0;
attrs[i++] = LDAP_OBJECTCLASS;
attrs[i++] = getUidAttributeName();
for (Iterator it = LDAP_GROUP_MEMBER.iterator(); it.hasNext();) {
attrs[i++] = (String) it.next();
}
return getConnection().searchLDAP(groupDN, null, attrs, LDAPConnection.SCOPE_BASE);
}
/**
* Extract group's members from provided LDAP search result.
*
* @param searchAttributeList the LDAP search result.
* @param memberMap the result: maps DN to member id.
* @param subgroups return all the subgroups identified.
* @param context the XWiki context.
*/
private void getGroupMembers(List searchAttributeList, Map memberMap, List subgroups,
XWikiContext context)
{
for (Iterator searchAttributeIt = searchAttributeList.iterator(); searchAttributeIt
.hasNext();) {
XWikiLDAPSearchAttribute searchAttribute =
(XWikiLDAPSearchAttribute) searchAttributeIt.next();
String key = searchAttribute.name;
if (LDAP_GROUP_MEMBER.contains(key)) {
// or subgroup
String member = searchAttribute.value;
// we check for subgroups recursive call to scan all subgroups and identify members
// and their uid
getGroupMembers(member, memberMap, subgroups, context);
}
}
}
/**
* Get all members of a given group based on the groupDN. If the group contains subgroups get
* these members as well. Retrieve an identifier for each member.
*
* @param groupDN the group to retrieve the members of and scan for subgroups.
* @param memberMap the result: maps DN to member id.
* @param subgroups all the subgroups identified.
* @param searchAttributeList the groups members found in LDAP search.
* @param context the XWiki context.
* @return whether the groupDN is actually a group.
*/
public boolean getGroupMembers(String groupDN, Map memberMap, List subgroups,
List searchAttributeList, XWikiContext context)
{
boolean isGroup = false;
String id = null;
for (Iterator seachAttributeIt = searchAttributeList.iterator(); seachAttributeIt
.hasNext();) {
XWikiLDAPSearchAttribute searchAttribute =
(XWikiLDAPSearchAttribute) seachAttributeIt.next();
String key = searchAttribute.name;
if (key.equalsIgnoreCase(LDAP_OBJECTCLASS)) {
String objectName = searchAttribute.value;
if (LDAP_GROUP_CLASS.contains(objectName.toLowerCase())) {
isGroup = true;
}
} else if (key.equalsIgnoreCase(getUidAttributeName())) {
id = searchAttribute.value;
}
}
if (!isGroup) {
if (id == null) {
LOG.error("Could not find attribute " + getUidAttributeName() + " for LDAP dn "
+ groupDN);
}
if (!memberMap.containsKey(groupDN)) {
memberMap.put(groupDN, id == null ? "" : id);
}
} else {
// remember this group
if (subgroups != null) {
subgroups.add(groupDN);
}
getGroupMembers(searchAttributeList, memberMap, subgroups, context);
}
return isGroup;
}
/**
* Get all members of a given group based on the groupDN. If the group contains subgroups get
* these members as well. Retrieve an identifier for each member.
*
* @param groupDN the group to retrieve the members of and scan for subgroups.
* @param memberMap the result: maps DN to member id.
* @param subgroups all the subgroups identified.
* @param context the XWiki context.
* @return whether the groupDN is actually a group.
*/
public boolean getGroupMembers(String groupDN, Map memberMap, List subgroups,
XWikiContext context)
{
boolean isGroup = false;
// break out if there is a look of groups
if (subgroups != null && subgroups.contains(groupDN)) {
return true;
}
List searchAttributeList = searchGroupsMembers(groupDN);
if (searchAttributeList != null) {
isGroup =
getGroupMembers(groupDN, memberMap, subgroups, searchAttributeList, context);
}
return isGroup;
}
/**
* Get group members from cache or update it from LDAP if it is not already in cached.
*
* @param groupDN the name of the group.
* @param context the XWiki context.
* @return the members of the group.
* @throws XWikiException error when getting the group cache.
*/
public Map getGroupMembers(String groupDN, XWikiContext context) throws XWikiException
{
Map groupMembers = null;
XWikiLDAPConfig config = XWikiLDAPConfig.getInstance();
XWikiCache cache = getCache(CACHE_NAME_GROUPS, context);
synchronized (cache) {
try {
groupMembers =
(Map) cache.getFromCache(groupDN, config.getCacheExpiration(context));
} catch (XWikiCacheNeedsRefreshException e) {
if (LOG.isDebugEnabled()) {
LOG.debug("Cache does not caontains group " + groupDN, e);
}
}
}
if (groupMembers == null) {
groupMembers = new HashMap();
if (LOG.isDebugEnabled()) {
LOG.debug("Retrieving Members of the group: " + groupDN);
}
boolean isGroup = getGroupMembers(groupDN, groupMembers, new ArrayList(), context);
if (isGroup) {
synchronized (cache) {
cache.putInCache(groupDN, groupMembers);
}
}
}
return groupMembers;
}
/**
* Locates the user in the Map: either the user is a value or the key starts with the LDAP
* syntax.
*
* @param userName the name of the user.
* @param groupMembers the members of LDAP group.
* @param context the XWiki context.
* @return the full user name.
*/
protected String findInGroup(String userName, Map groupMembers, XWikiContext context)
{
String result = null;
String ldapuser = getUidAttributeName() + "=" + userName.toLowerCase();
for (Iterator it = groupMembers.keySet().iterator(); it.hasNext();) {
String u = (String) it.next();
// implementing it case-insensitive for now
if (userName.equalsIgnoreCase((String) groupMembers.get(u))
|| u.toLowerCase().startsWith(ldapuser)) {
return u;
}
}
return result;
}
/**
* Check if user is in provided LDAP group.
*
* @param userName the user name.
* @param groupDN the LDAP group DN.
* @param context the XWiki context.
* @return user's DB if the user is in the LDAP group, null otherwise.
* @throws XWikiException error when getting the group cache.
*/
public String isUserInGroup(String userName, String groupDN, XWikiContext context)
throws XWikiException
{
String userDN = null;
if (groupDN.length() > 0) {
Map groupMembers = getGroupMembers(groupDN, context);
// check if user is in the list
userDN = findInGroup(userName, groupMembers, context);
if (LOG.isDebugEnabled()) {
LOG.debug("Found user dn in user group:" + userDN);
}
// if a usergroup is specified THEN the user MUST be in the group to validate in
// LDAP
if (userDN == null) {
if (LOG.isDebugEnabled()) {
LOG.debug("LDAP authentication failed: user not in LDAP user group");
}
// no valid LDAP user from the group
return null;
}
}
return userDN;
}
}
|
XWIKI-1079: javadoc fix.
git-svn-id: cfa2b40e478804c47c05d0f328c574ec5aa2b82e@7755 f329d543-caf0-0310-9063-dda96c69346f
|
xwiki-core/src/main/java/com/xpn/xwiki/plugin/ldap/XWikiLDAPUtils.java
|
XWIKI-1079: javadoc fix.
|
|
Java
|
apache-2.0
|
157604fe74f4b454c7e946a188ffe8379531820a
| 0
|
google/tink,google/tink,google/tink,google/tink,google/tink,google/tink,google/tink,google/tink
|
// Copyright 2017 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.crypto.tink;
import static com.google.common.truth.Truth.assertThat;
import com.google.crypto.tink.aead.AeadKeyTemplates;
import com.google.crypto.tink.config.TinkConfig;
import com.google.crypto.tink.mac.MacKeyTemplates;
import com.google.crypto.tink.proto.KeyTemplate;
import com.google.crypto.tink.subtle.Random;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.security.GeneralSecurityException;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for JsonKeysetWriter. */
@RunWith(JUnit4.class)
public class JsonKeysetWriterTest {
@BeforeClass
public static void setUp() throws GeneralSecurityException {
Config.register(TinkConfig.TINK_1_0_0);
}
private void assertKeysetHandle(KeysetHandle handle1, KeysetHandle handle2) throws Exception {
Mac mac1 = handle1.getPrimitive(Mac.class);
Mac mac2 = handle2.getPrimitive(Mac.class);
byte[] message = Random.randBytes(20);
assertThat(handle2.getKeyset()).isEqualTo(handle1.getKeyset());
mac2.verifyMac(mac1.computeMac(message), message);
}
private void testWrite_shouldWork(KeysetHandle handle1) throws Exception {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
CleartextKeysetHandle.write(handle1, JsonKeysetWriter.withOutputStream(outputStream));
KeysetHandle handle2 =
CleartextKeysetHandle.read(
JsonKeysetReader.withInputStream(new ByteArrayInputStream(outputStream.toByteArray())));
assertKeysetHandle(handle1, handle2);
}
@Test
public void testWrite_singleKey_shouldWork() throws Exception {
KeyTemplate template = MacKeyTemplates.HMAC_SHA256_128BITTAG;
KeysetHandle handle1 = KeysetHandle.generateNew(template);
testWrite_shouldWork(handle1);
}
@Test
public void testWrite_multipleKeys_shouldWork() throws Exception {
KeyTemplate template = MacKeyTemplates.HMAC_SHA256_128BITTAG;
KeysetHandle handle1 =
KeysetManager.withEmptyKeyset()
.rotate(template)
.add(template)
.add(template)
.getKeysetHandle();
testWrite_shouldWork(handle1);
}
private void testWriteEncrypted_shouldWork(KeysetHandle handle1) throws Exception {
// Encrypt the keyset with an AeadKey.
KeyTemplate masterKeyTemplate = AeadKeyTemplates.AES128_EAX;
Aead masterKey = Registry.getPrimitive(Registry.newKeyData(masterKeyTemplate));
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
handle1.write(JsonKeysetWriter.withOutputStream(outputStream), masterKey);
KeysetHandle handle2 =
KeysetHandle.read(
JsonKeysetReader.withInputStream(new ByteArrayInputStream(outputStream.toByteArray())),
masterKey);
assertKeysetHandle(handle1, handle2);
}
@Test
public void testWriteEncrypted_singleKey_shouldWork() throws Exception {
// Encrypt the keyset with an AeadKey.
KeysetHandle handle1 = KeysetHandle.generateNew(MacKeyTemplates.HMAC_SHA256_128BITTAG);
testWriteEncrypted_shouldWork(handle1);
}
@Test
public void testWriteEncrypted_multipleKeys_shouldWork() throws Exception {
// Encrypt the keyset with an AeadKey.
KeyTemplate template = MacKeyTemplates.HMAC_SHA256_128BITTAG;
KeysetHandle handle1 =
KeysetManager.withEmptyKeyset()
.rotate(template)
.add(template)
.add(template)
.getKeysetHandle();
testWriteEncrypted_shouldWork(handle1);
}
}
|
java/src/test/java/com/google/crypto/tink/JsonKeysetWriterTest.java
|
// Copyright 2017 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.crypto.tink;
import static com.google.common.truth.Truth.assertThat;
import com.google.crypto.tink.aead.AeadKeyTemplates;
import com.google.crypto.tink.config.TinkConfig;
import com.google.crypto.tink.mac.MacFactory;
import com.google.crypto.tink.mac.MacKeyTemplates;
import com.google.crypto.tink.proto.KeyTemplate;
import com.google.crypto.tink.subtle.Random;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.security.GeneralSecurityException;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for JsonKeysetWriter. */
@RunWith(JUnit4.class)
public class JsonKeysetWriterTest {
@BeforeClass
public static void setUp() throws GeneralSecurityException {
Config.register(TinkConfig.TINK_1_0_0);
}
private void assertKeysetHandle(KeysetHandle handle1, KeysetHandle handle2) throws Exception {
Mac mac1 = MacFactory.getPrimitive(handle1);
Mac mac2 = MacFactory.getPrimitive(handle2);
byte[] message = Random.randBytes(20);
assertThat(handle2.getKeyset()).isEqualTo(handle1.getKeyset());
mac2.verifyMac(mac1.computeMac(message), message);
}
private void testWrite_shouldWork(KeysetHandle handle1) throws Exception {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
CleartextKeysetHandle.write(handle1, JsonKeysetWriter.withOutputStream(outputStream));
KeysetHandle handle2 =
CleartextKeysetHandle.read(
JsonKeysetReader.withInputStream(new ByteArrayInputStream(outputStream.toByteArray())));
assertKeysetHandle(handle1, handle2);
}
@Test
public void testWrite_singleKey_shouldWork() throws Exception {
KeyTemplate template = MacKeyTemplates.HMAC_SHA256_128BITTAG;
KeysetHandle handle1 = KeysetHandle.generateNew(template);
testWrite_shouldWork(handle1);
}
@Test
public void testWrite_multipleKeys_shouldWork() throws Exception {
KeyTemplate template = MacKeyTemplates.HMAC_SHA256_128BITTAG;
KeysetHandle handle1 =
KeysetManager.withEmptyKeyset()
.rotate(template)
.add(template)
.add(template)
.getKeysetHandle();
testWrite_shouldWork(handle1);
}
private void testWriteEncrypted_shouldWork(KeysetHandle handle1) throws Exception {
// Encrypt the keyset with an AeadKey.
KeyTemplate masterKeyTemplate = AeadKeyTemplates.AES128_EAX;
Aead masterKey = Registry.getPrimitive(Registry.newKeyData(masterKeyTemplate));
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
handle1.write(JsonKeysetWriter.withOutputStream(outputStream), masterKey);
KeysetHandle handle2 =
KeysetHandle.read(
JsonKeysetReader.withInputStream(new ByteArrayInputStream(outputStream.toByteArray())),
masterKey);
assertKeysetHandle(handle1, handle2);
}
@Test
public void testWriteEncrypted_singleKey_shouldWork() throws Exception {
// Encrypt the keyset with an AeadKey.
KeysetHandle handle1 = KeysetHandle.generateNew(MacKeyTemplates.HMAC_SHA256_128BITTAG);
testWriteEncrypted_shouldWork(handle1);
}
@Test
public void testWriteEncrypted_multipleKeys_shouldWork() throws Exception {
// Encrypt the keyset with an AeadKey.
KeyTemplate template = MacKeyTemplates.HMAC_SHA256_128BITTAG;
KeysetHandle handle1 =
KeysetManager.withEmptyKeyset()
.rotate(template)
.add(template)
.add(template)
.getKeysetHandle();
testWriteEncrypted_shouldWork(handle1);
}
}
|
Replace an instance of the deprecated MacFactory.getPrimitive with the non-deprecated keysetHandle.getPrimitive(Mac.class);
PiperOrigin-RevId: 250255572
|
java/src/test/java/com/google/crypto/tink/JsonKeysetWriterTest.java
|
Replace an instance of the deprecated MacFactory.getPrimitive with the non-deprecated keysetHandle.getPrimitive(Mac.class);
|
|
Java
|
apache-2.0
|
11478edb5b653b136705f5005d52e9277fb95ba7
| 0
|
unei66/netty,kiril-me/netty,tbrooks8/netty,Apache9/netty,CodingFabian/netty,DavidAlphaFox/netty,huanyi0723/netty,ichaki5748/netty,balaprasanna/netty,mcobrien/netty,zzcclp/netty,olupotd/netty,zhoffice/netty,mcanthony/netty,joansmith/netty,youprofit/netty,Scottmitch/netty,djchen/netty,doom369/netty,gerdriesselmann/netty,bryce-anderson/netty,nmittler/netty,satishsaley/netty,idelpivnitskiy/netty,danbev/netty,fantayeneh/netty,exinguu/netty,AnselQiao/netty,dongjiaqiang/netty,exinguu/netty,Kalvar/netty,Kingson4Wu/netty,bigheary/netty,carl-mastrangelo/netty,kiril-me/netty,Techcable/netty,normanmaurer/netty,imangry/netty-zh,eonezhang/netty,mx657649013/netty,woshilaiceshide/netty,mx657649013/netty,nat2013/netty,normanmaurer/netty,imangry/netty-zh,luyiisme/netty,liuciuse/netty,orika/netty,cnoldtree/netty,zhujingling/netty,sammychen105/netty,zhujingling/netty,slandelle/netty,castomer/netty,timboudreau/netty,danbev/netty,louxiu/netty,gerdriesselmann/netty,gigold/netty,golovnin/netty,sunbeansoft/netty,slandelle/netty,lznhust/netty,Kingson4Wu/netty,f7753/netty,brennangaunce/netty,qingsong-xu/netty,s-gheldd/netty,Alwayswithme/netty,fenik17/netty,Kalvar/netty,huanyi0723/netty,AchinthaReemal/netty,kjniemi/netty,Squarespace/netty,LuminateWireless/netty,ninja-/netty,bob329/netty,xiongzheng/netty,Apache9/netty,NiteshKant/netty,zhoffice/netty,purplefox/netty-4.0.2.8-hacked,lugt/netty,jchambers/netty,carl-mastrangelo/netty,kjniemi/netty,shenguoquan/netty,unei66/netty,exinguu/netty,ngocdaothanh/netty,junjiemars/netty,satishsaley/netty,johnou/netty,yawkat/netty,imangry/netty-zh,jdivy/netty,IBYoung/netty,KatsuraKKKK/netty,ninja-/netty,ichaki5748/netty,fengjiachun/netty,DolphinZhao/netty,kjniemi/netty,rovarga/netty,shism/netty,AnselQiao/netty,ejona86/netty,yawkat/netty,caoyanwei/netty,kvr000/netty,joansmith/netty,mway08/netty,mcobrien/netty,ijuma/netty,wangyikai/netty,hepin1989/netty,idelpivnitskiy/netty,clebertsuconic/netty,Squarespace/netty,DavidAlphaFox/netty,Squarespace/netty,chinayin/netty,xiongzheng/netty,ijuma/netty,KatsuraKKKK/netty,hyangtack/netty,JungMinu/netty,LuminateWireless/netty,xiexingguang/netty,Kingson4Wu/netty,jchambers/netty,ajaysarda/netty,jroper/netty,andsel/netty,MediumOne/netty,codevelop/netty,BrunoColin/netty,x1957/netty,louxiu/netty,s-gheldd/netty,shuangqiuan/netty,smayoorans/netty,mubarak/netty,Mounika-Chirukuri/netty,DolphinZhao/netty,lukw00/netty,ngocdaothanh/netty,NiteshKant/netty,JungMinu/netty,mcobrien/netty,unei66/netty,tbrooks8/netty,doom369/netty,WangJunTYTL/netty,lightsocks/netty,blademainer/netty,jovezhougang/netty,purplefox/netty-4.0.2.8-hacked,ifesdjeen/netty,LuminateWireless/netty,jongyeol/netty,sja/netty,Scottmitch/netty,danny200309/netty,artgon/netty,woshilaiceshide/netty,sameira/netty,nkhuyu/netty,moyiguket/netty,gigold/netty,danny200309/netty,junjiemars/netty,Mounika-Chirukuri/netty,duqiao/netty,normanmaurer/netty,andsel/netty,blucas/netty,junjiemars/netty,tempbottle/netty,slandelle/netty,ioanbsu/netty,youprofit/netty,mcobrien/netty,Scottmitch/netty,lznhust/netty,shuangqiuan/netty,fengshao0907/netty,cnoldtree/netty,normanmaurer/netty,netty/netty,xiongzheng/netty,yrcourage/netty,alkemist/netty,alkemist/netty,ninja-/netty,zer0se7en/netty,IBYoung/netty,lukehutch/netty,sverkera/netty,kvr000/netty,liyang1025/netty,tbrooks8/netty,youprofit/netty,brennangaunce/netty,blademainer/netty,eincs/netty,lukehutch/netty,SinaTadayon/netty,CodingFabian/netty,liuciuse/netty,clebertsuconic/netty,nayato/netty,sunbeansoft/netty,NiteshKant/netty,blucas/netty,bob329/netty,bob329/netty,hyangtack/netty,Squarespace/netty,tempbottle/netty,chanakaudaya/netty,fenik17/netty,netty/netty,jongyeol/netty,fengshao0907/netty,duqiao/netty,hepin1989/netty,shenguoquan/netty,bryce-anderson/netty,lugt/netty,yawkat/netty,mikkokar/netty,hgl888/netty,sunbeansoft/netty,AnselQiao/netty,zxhfirefox/netty,gerdriesselmann/netty,WangJunTYTL/netty,develar/netty,lightsocks/netty,junjiemars/netty,clebertsuconic/netty,serioussam/netty,golovnin/netty,andsel/netty,golovnin/netty,Kalvar/netty,zxhfirefox/netty,Mounika-Chirukuri/netty,unei66/netty,CodingFabian/netty,zxhfirefox/netty,lukw00/netty,drowning/netty,smayoorans/netty,kiril-me/netty,afds/netty,castomer/netty,sameira/netty,mikkokar/netty,hyangtack/netty,cnoldtree/netty,bob329/netty,eonezhang/netty,ajaysarda/netty,mway08/netty,lukw00/netty,louxiu/netty,blademainer/netty,nkhuyu/netty,louiscryan/netty,louxiu/netty,AchinthaReemal/netty,nkhuyu/netty,Kalvar/netty,WangJunTYTL/netty,youprofit/netty,blucas/netty,purplefox/netty-4.0.2.8-hacked,golovnin/netty,skyao/netty,sammychen105/netty,mway08/netty,mubarak/netty,KatsuraKKKK/netty,doom369/netty,doom369/netty,ifesdjeen/netty,s-gheldd/netty,joansmith/netty,afds/netty,danbev/netty,ioanbsu/netty,shenguoquan/netty,ajaysarda/netty,Mounika-Chirukuri/netty,balaprasanna/netty,ichaki5748/netty,xiexingguang/netty,lightsocks/netty,imangry/netty-zh,KatsuraKKKK/netty,chrisprobst/netty,shuangqiuan/netty,fengjiachun/netty,sameira/netty,JungMinu/netty,lukw00/netty,Spikhalskiy/netty,MediumOne/netty,SinaTadayon/netty,dongjiaqiang/netty,clebertsuconic/netty,maliqq/netty,artgon/netty,woshilaiceshide/netty,brennangaunce/netty,louiscryan/netty,mx657649013/netty,jdivy/netty,balaprasanna/netty,cnoldtree/netty,sja/netty,nat2013/netty,altihou/netty,kjniemi/netty,gerdriesselmann/netty,danny200309/netty,sammychen105/netty,balaprasanna/netty,maliqq/netty,phlizik/netty,huanyi0723/netty,woshilaiceshide/netty,andsel/netty,wuyinxian124/netty,x1957/netty,moyiguket/netty,caoyanwei/netty,bigheary/netty,MediumOne/netty,lznhust/netty,zhujingling/netty,djchen/netty,jovezhougang/netty,joansmith/netty,eincs/netty,SinaTadayon/netty,ichaki5748/netty,alkemist/netty,ijuma/netty,ioanbsu/netty,moyiguket/netty,Spikhalskiy/netty,lukehutch/netty,maliqq/netty,KatsuraKKKK/netty,chinayin/netty,Alwayswithme/netty,zxhfirefox/netty,jchambers/netty,wuxiaowei907/netty,chrisprobst/netty,yrcourage/netty,mubarak/netty,xiexingguang/netty,gigold/netty,seetharamireddy540/netty,CodingFabian/netty,mcobrien/netty,pengzj/netty,huuthang1993/netty,lukehutch/netty,smayoorans/netty,silvaran/netty,Alwayswithme/netty,doom369/netty,mosoft521/netty,firebase/netty,wuyinxian124/netty,alkemist/netty,wangyikai/netty,jongyeol/netty,liyang1025/netty,junjiemars/netty,yawkat/netty,lukw00/netty,BrunoColin/netty,mikkokar/netty,Kingson4Wu/netty,djchen/netty,brennangaunce/netty,carlbai/netty,hgl888/netty,sverkera/netty,pengzj/netty,louxiu/netty,orika/netty,jenskordowski/netty,shism/netty,timboudreau/netty,serioussam/netty,nadeeshaan/netty,JungMinu/netty,SinaTadayon/netty,phlizik/netty,louiscryan/netty,huuthang1993/netty,danbev/netty,altihou/netty,eincs/netty,johnou/netty,seetharamireddy540/netty,yrcourage/netty,danny200309/netty,shism/netty,johnou/netty,Spikhalskiy/netty,duqiao/netty,kyle-liu/netty4study,SinaTadayon/netty,jovezhougang/netty,sverkera/netty,windie/netty,kiril-me/netty,niuxinghua/netty,develar/netty,johnou/netty,afds/netty,yipen9/netty,nadeeshaan/netty,sameira/netty,windie/netty,s-gheldd/netty,jongyeol/netty,johnou/netty,jovezhougang/netty,Apache9/netty,CodingFabian/netty,timboudreau/netty,lugt/netty,windie/netty,qingsong-xu/netty,Scottmitch/netty,xiongzheng/netty,hyangtack/netty,DolphinZhao/netty,yipen9/netty,ichaki5748/netty,jovezhougang/netty,Alwayswithme/netty,djchen/netty,xiexingguang/netty,pengzj/netty,zer0se7en/netty,liyang1025/netty,KeyNexus/netty,sunbeansoft/netty,chanakaudaya/netty,bigheary/netty,brennangaunce/netty,liyang1025/netty,qingsong-xu/netty,yrcourage/netty,idelpivnitskiy/netty,shenguoquan/netty,LuminateWireless/netty,chanakaudaya/netty,carlbai/netty,nkhuyu/netty,caoyanwei/netty,silvaran/netty,shelsonjava/netty,jdivy/netty,AchinthaReemal/netty,ejona86/netty,olupotd/netty,nmittler/netty,ajaysarda/netty,f7753/netty,louiscryan/netty,buchgr/netty,firebase/netty,NiteshKant/netty,NiteshKant/netty,mosoft521/netty,KeyNexus/netty,lightsocks/netty,maliqq/netty,wuxiaowei907/netty,eonezhang/netty,fantayeneh/netty,wuyinxian124/netty,zhujingling/netty,artgon/netty,f7753/netty,ajaysarda/netty,serioussam/netty,lightsocks/netty,xingguang2013/netty,afds/netty,cnoldtree/netty,duqiao/netty,eincs/netty,xiongzheng/netty,ejona86/netty,zxhfirefox/netty,jchambers/netty,Spikhalskiy/netty,Techcable/netty,MediumOne/netty,castomer/netty,exinguu/netty,eonezhang/netty,nadeeshaan/netty,nadeeshaan/netty,bryce-anderson/netty,afredlyj/learn-netty,kvr000/netty,netty/netty,balaprasanna/netty,shism/netty,yonglehou/netty-1,fantayeneh/netty,yipen9/netty,rovarga/netty,carl-mastrangelo/netty,Kingson4Wu/netty,Alwayswithme/netty,golovnin/netty,exinguu/netty,liyang1025/netty,menacher/netty,slandelle/netty,zzcclp/netty,chinayin/netty,jenskordowski/netty,CliffYuan/netty,hgl888/netty,netty/netty,zzcclp/netty,serioussam/netty,olupotd/netty,windie/netty,kyle-liu/netty4study,liuciuse/netty,WangJunTYTL/netty,purplefox/netty-4.0.2.8-hacked,liuciuse/netty,orika/netty,mway08/netty,firebase/netty,zhoffice/netty,blademainer/netty,ejona86/netty,carlbai/netty,nayato/netty,liuciuse/netty,kjniemi/netty,shism/netty,DolphinZhao/netty,ijuma/netty,luyiisme/netty,zer0se7en/netty,altihou/netty,s-gheldd/netty,bob329/netty,dongjiaqiang/netty,niuxinghua/netty,dongjiaqiang/netty,seetharamireddy540/netty,mway08/netty,sverkera/netty,fengshao0907/netty,drowning/netty,afds/netty,phlizik/netty,danbev/netty,sverkera/netty,Mounika-Chirukuri/netty,Apache9/netty,fengjiachun/netty,yrcourage/netty,netty/netty,daschl/netty,wangyikai/netty,ngocdaothanh/netty,jongyeol/netty,caoyanwei/netty,carlbai/netty,skyao/netty,BrunoColin/netty,djchen/netty,huanyi0723/netty,daschl/netty,xiexingguang/netty,AchinthaReemal/netty,jenskordowski/netty,fantayeneh/netty,huanyi0723/netty,zzcclp/netty,ninja-/netty,mikkokar/netty,MediumOne/netty,olupotd/netty,huuthang1993/netty,gigold/netty,jdivy/netty,dongjiaqiang/netty,silvaran/netty,xingguang2013/netty,tempbottle/netty,mubarak/netty,codevelop/netty,windie/netty,bryce-anderson/netty,fenik17/netty,mcanthony/netty,silvaran/netty,wuxiaowei907/netty,huuthang1993/netty,mx657649013/netty,AnselQiao/netty,kiril-me/netty,hepin1989/netty,jdivy/netty,ijuma/netty,mosoft521/netty,maliqq/netty,zzcclp/netty,mcanthony/netty,orika/netty,qingsong-xu/netty,artgon/netty,bigheary/netty,chinayin/netty,tempbottle/netty,ioanbsu/netty,wuxiaowei907/netty,wuyinxian124/netty,buchgr/netty,ejona86/netty,zhujingling/netty,rovarga/netty,Scottmitch/netty,qingsong-xu/netty,yonglehou/netty-1,altihou/netty,xingguang2013/netty,f7753/netty,idelpivnitskiy/netty,WangJunTYTL/netty,mikkokar/netty,blucas/netty,codevelop/netty,yonglehou/netty-1,artgon/netty,chrisprobst/netty,afredlyj/learn-netty,danny200309/netty,eonezhang/netty,IBYoung/netty,chanakaudaya/netty,lukehutch/netty,skyao/netty,fantayeneh/netty,niuxinghua/netty,AnselQiao/netty,satishsaley/netty,imangry/netty-zh,skyao/netty,codevelop/netty,tempbottle/netty,kvr000/netty,carl-mastrangelo/netty,blucas/netty,hepin1989/netty,shelsonjava/netty,DolphinZhao/netty,skyao/netty,shelsonjava/netty,normanmaurer/netty,sja/netty,ninja-/netty,zhoffice/netty,chanakaudaya/netty,nat2013/netty,altihou/netty,niuxinghua/netty,mosoft521/netty,tbrooks8/netty,unei66/netty,sja/netty,shenguoquan/netty,smayoorans/netty,luyiisme/netty,mcanthony/netty,carl-mastrangelo/netty,daschl/netty,mx657649013/netty,carlbai/netty,DavidAlphaFox/netty,ioanbsu/netty,lznhust/netty,Apache9/netty,menacher/netty,silvaran/netty,yipen9/netty,yonglehou/netty-1,gerdriesselmann/netty,blademainer/netty,sja/netty,yawkat/netty,nadeeshaan/netty,drowning/netty,idelpivnitskiy/netty,DavidAlphaFox/netty,gigold/netty,zer0se7en/netty,fengjiachun/netty,fengjiachun/netty,xingguang2013/netty,Spikhalskiy/netty,timboudreau/netty,tbrooks8/netty,joansmith/netty,Techcable/netty,woshilaiceshide/netty,wangyikai/netty,luyiisme/netty,mubarak/netty,duqiao/netty,andsel/netty,shuangqiuan/netty,buchgr/netty,ngocdaothanh/netty,hgl888/netty,jchambers/netty,afredlyj/learn-netty,castomer/netty,aperepel/netty,shuangqiuan/netty,BrunoColin/netty,castomer/netty,jenskordowski/netty,pengzj/netty,luyiisme/netty,clebertsuconic/netty,firebase/netty,youprofit/netty,seetharamireddy540/netty,huuthang1993/netty,x1957/netty,Kalvar/netty,louiscryan/netty,zhoffice/netty,mosoft521/netty,chrisprobst/netty,rovarga/netty,nayato/netty,wuxiaowei907/netty,orika/netty,IBYoung/netty,wangyikai/netty,BrunoColin/netty,f7753/netty,jenskordowski/netty,serioussam/netty,moyiguket/netty,nayato/netty,Techcable/netty,eincs/netty,seetharamireddy540/netty,buchgr/netty,kvr000/netty,xingguang2013/netty,shelsonjava/netty,lznhust/netty,nkhuyu/netty,moyiguket/netty,bryce-anderson/netty,ngocdaothanh/netty,bigheary/netty,nmittler/netty,nayato/netty,AchinthaReemal/netty,sunbeansoft/netty,zer0se7en/netty,fenik17/netty,Squarespace/netty,mcanthony/netty,hgl888/netty,phlizik/netty,lugt/netty,niuxinghua/netty,chinayin/netty,IBYoung/netty,satishsaley/netty,timboudreau/netty,CliffYuan/netty,x1957/netty,olupotd/netty,Techcable/netty,alkemist/netty,fenik17/netty,satishsaley/netty,LuminateWireless/netty,chrisprobst/netty,smayoorans/netty,drowning/netty,yonglehou/netty-1,sameira/netty,caoyanwei/netty,x1957/netty,shelsonjava/netty,lugt/netty
|
/*
* JBoss, Home of Professional Open Source
*
* Copyright 2009, Red Hat Middleware LLC, and individual contributors
* by the @author tags. See the COPYRIGHT.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.netty.handler.timeout;
import static org.jboss.netty.channel.Channels.*;
import java.util.concurrent.TimeUnit;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipelineCoverage;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.LifeCycleAwareChannelHandler;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.channel.WriteCompletionEvent;
import org.jboss.netty.util.ExternalResourceReleasable;
/**
* @author The Netty Project (netty-dev@lists.jboss.org)
* @author Trustin Lee (tlee@redhat.com)
* @version $Rev$, $Date$
*/
@ChannelPipelineCoverage("one")
public class IdleStateHandler extends SimpleChannelUpstreamHandler
implements LifeCycleAwareChannelHandler,
ExternalResourceReleasable {
final Timer timer;
final long readerIdleTimeMillis;
volatile Timeout readerIdleTimeout;
private volatile ReaderIdleTimeoutTask readerIdleTimeoutTask;
volatile long lastReadTime;
final long writerIdleTimeMillis;
volatile Timeout writerIdleTimeout;
private volatile WriterIdleTimeoutTask writerIdleTimeoutTask;
volatile long lastWriteTime;
final long allIdleTimeMillis;
volatile Timeout allIdleTimeout;
private volatile AllIdleTimeoutTask allIdleTimeoutTask;
public IdleStateHandler(
Timer timer,
long readerIdleTimeSeconds,
long writerIdleTimeSeconds,
long allIdleTimeSeconds) {
this(timer,
readerIdleTimeSeconds, writerIdleTimeSeconds, allIdleTimeSeconds,
TimeUnit.SECONDS);
}
public IdleStateHandler(
Timer timer,
long readerIdleTime, long writerIdleTime, long allIdleTime,
TimeUnit unit) {
if (timer == null) {
throw new NullPointerException("timer");
}
if (unit == null) {
throw new NullPointerException("unit");
}
this.timer = timer;
readerIdleTimeMillis = unit.toMillis(readerIdleTime);
writerIdleTimeMillis = unit.toMillis(writerIdleTime);
allIdleTimeMillis = unit.toMillis(allIdleTime);
}
public void releaseExternalResources() {
timer.stop();
}
public void beforeAdd(ChannelHandlerContext ctx) throws Exception {
initialize(ctx);
}
public void afterAdd(ChannelHandlerContext ctx) throws Exception {
// NOOP
}
public void beforeRemove(ChannelHandlerContext ctx) throws Exception {
destroy();
}
public void afterRemove(ChannelHandlerContext ctx) throws Exception {
// NOOP
}
@Override
public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e)
throws Exception {
initialize(ctx);
ctx.sendUpstream(e);
}
@Override
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e)
throws Exception {
destroy();
ctx.sendUpstream(e);
}
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
throws Exception {
lastReadTime = System.currentTimeMillis();
ctx.sendUpstream(e);
}
@Override
public void writeComplete(ChannelHandlerContext ctx, WriteCompletionEvent e)
throws Exception {
if (e.getWrittenAmount() > 0) {
lastWriteTime = System.currentTimeMillis();
}
ctx.sendUpstream(e);
}
private void initialize(ChannelHandlerContext ctx) {
lastReadTime = lastWriteTime = System.currentTimeMillis();
readerIdleTimeoutTask = new ReaderIdleTimeoutTask(ctx);
writerIdleTimeoutTask = new WriterIdleTimeoutTask(ctx);
allIdleTimeoutTask = new AllIdleTimeoutTask(ctx);
if (readerIdleTimeMillis > 0) {
readerIdleTimeout = timer.newTimeout(
readerIdleTimeoutTask, readerIdleTimeMillis, TimeUnit.MILLISECONDS);
}
if (writerIdleTimeMillis > 0) {
writerIdleTimeout = timer.newTimeout(
writerIdleTimeoutTask, writerIdleTimeMillis, TimeUnit.MILLISECONDS);
}
if (allIdleTimeMillis > 0) {
allIdleTimeout = timer.newTimeout(
allIdleTimeoutTask, allIdleTimeMillis, TimeUnit.MILLISECONDS);
}
}
private void destroy() {
if (readerIdleTimeout != null) {
readerIdleTimeout.cancel();
}
if (writerIdleTimeout != null) {
writerIdleTimeout.cancel();
}
if (allIdleTimeout != null) {
allIdleTimeout.cancel();
}
readerIdleTimeout = null;
readerIdleTimeoutTask = null;
writerIdleTimeout = null;
writerIdleTimeoutTask = null;
allIdleTimeout = null;
allIdleTimeoutTask = null;
}
protected void channelIdle(
ChannelHandlerContext ctx, IdleState state, long lastActivityTimeMillis) throws Exception {
ctx.sendUpstream(new DefaultIdleStateEvent(ctx.getChannel(), state, lastActivityTimeMillis));
}
private final class ReaderIdleTimeoutTask implements TimerTask {
private final ChannelHandlerContext ctx;
ReaderIdleTimeoutTask(ChannelHandlerContext ctx) {
this.ctx = ctx;
}
public void run(Timeout timeout) throws Exception {
if (timeout.isCancelled() || !ctx.getChannel().isOpen()) {
return;
}
long currentTime = System.currentTimeMillis();
long lastReadTime = IdleStateHandler.this.lastReadTime;
long nextDelay = readerIdleTimeMillis - (currentTime - lastReadTime);
if (nextDelay <= 0) {
// Reader is idle - set a new timeout and notify the callback.
readerIdleTimeout =
timer.newTimeout(this, readerIdleTimeMillis, TimeUnit.MILLISECONDS);
try {
channelIdle(ctx, IdleState.READER_IDLE, lastReadTime);
} catch (Throwable t) {
fireExceptionCaught(ctx, t);
}
} else {
// Read occurred before the timeout - set a new timeout with shorter delay.
readerIdleTimeout =
timer.newTimeout(this, nextDelay, TimeUnit.MILLISECONDS);
}
}
}
private final class WriterIdleTimeoutTask implements TimerTask {
private final ChannelHandlerContext ctx;
WriterIdleTimeoutTask(ChannelHandlerContext ctx) {
this.ctx = ctx;
}
public void run(Timeout timeout) throws Exception {
if (timeout.isCancelled() || !ctx.getChannel().isOpen()) {
return;
}
long currentTime = System.currentTimeMillis();
long lastWriteTime = IdleStateHandler.this.lastWriteTime;
long nextDelay = writerIdleTimeMillis - (currentTime - lastWriteTime);
if (nextDelay <= 0) {
// Writer is idle - set a new timeout and notify the callback.
writerIdleTimeout =
timer.newTimeout(this, writerIdleTimeMillis, TimeUnit.MILLISECONDS);
try {
channelIdle(ctx, IdleState.WRITER_IDLE, lastReadTime);
} catch (Throwable t) {
fireExceptionCaught(ctx, t);
}
} else {
// Write occurred before the timeout - set a new timeout with shorter delay.
writerIdleTimeout =
timer.newTimeout(this, nextDelay, TimeUnit.MILLISECONDS);
}
}
}
private final class AllIdleTimeoutTask implements TimerTask {
private final ChannelHandlerContext ctx;
AllIdleTimeoutTask(ChannelHandlerContext ctx) {
this.ctx = ctx;
}
public void run(Timeout timeout) throws Exception {
if (timeout.isCancelled() || !ctx.getChannel().isOpen()) {
return;
}
long currentTime = System.currentTimeMillis();
long lastIoTime = Math.max(lastReadTime, lastWriteTime);
long nextDelay = allIdleTimeMillis - (currentTime - lastIoTime);
if (nextDelay <= 0) {
// Both reader and writer are idle - set a new timeout and
// notify the callback.
allIdleTimeout =
timer.newTimeout(this, allIdleTimeMillis, TimeUnit.MILLISECONDS);
try {
channelIdle(ctx, IdleState.ALL_IDLE, lastReadTime);
} catch (Throwable t) {
fireExceptionCaught(ctx, t);
}
} else {
// Either read or write occurred before the timeout - set a new
// timeout with shorter delay.
allIdleTimeout =
timer.newTimeout(this, nextDelay, TimeUnit.MILLISECONDS);
}
}
}
}
|
src/main/java/org/jboss/netty/handler/timeout/IdleStateHandler.java
|
/*
* JBoss, Home of Professional Open Source
*
* Copyright 2009, Red Hat Middleware LLC, and individual contributors
* by the @author tags. See the COPYRIGHT.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.netty.handler.timeout;
import static org.jboss.netty.channel.Channels.*;
import java.util.concurrent.TimeUnit;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipelineCoverage;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.LifeCycleAwareChannelHandler;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.channel.WriteCompletionEvent;
import org.jboss.netty.util.ExternalResourceReleasable;
/**
* @author The Netty Project (netty-dev@lists.jboss.org)
* @author Trustin Lee (tlee@redhat.com)
* @version $Rev$, $Date$
*/
@ChannelPipelineCoverage("one")
public class IdleStateHandler extends SimpleChannelUpstreamHandler
implements LifeCycleAwareChannelHandler,
ExternalResourceReleasable {
final Timer timer;
final long readerIdleTimeMillis;
volatile Timeout readerIdleTimeout;
private volatile ReaderIdleTimeoutTask readerIdleTimeoutTask;
volatile long lastReadTime;
final long writerIdleTimeMillis;
volatile Timeout writerIdleTimeout;
private volatile WriterIdleTimeoutTask writerIdleTimeoutTask;
volatile long lastWriteTime;
final long allIdleTimeMillis;
volatile Timeout allIdleTimeout;
private volatile AllIdleTimeoutTask allIdleTimeoutTask;
public IdleStateHandler(
Timer timer,
long readerIdleTimeSeconds,
long writerIdleTimeSeconds,
long allIdleTimeSeconds) {
this(timer,
readerIdleTimeSeconds, writerIdleTimeSeconds, allIdleTimeSeconds,
TimeUnit.SECONDS);
}
public IdleStateHandler(
Timer timer,
long readerIdleTime, long writerIdleTime, long allIdleTime,
TimeUnit unit) {
if (timer == null) {
throw new NullPointerException("timer");
}
if (unit == null) {
throw new NullPointerException("unit");
}
this.timer = timer;
readerIdleTimeMillis = unit.toMillis(readerIdleTime);
writerIdleTimeMillis = unit.toMillis(writerIdleTime);
allIdleTimeMillis = unit.toMillis(allIdleTime);
}
public void releaseExternalResources() {
timer.stop();
}
public void beforeAdd(ChannelHandlerContext ctx) throws Exception {
initialize(ctx);
}
public void afterAdd(ChannelHandlerContext ctx) throws Exception {
// NOOP
}
public void beforeRemove(ChannelHandlerContext ctx) throws Exception {
destroy();
}
public void afterRemove(ChannelHandlerContext ctx) throws Exception {
// NOOP
}
@Override
public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e)
throws Exception {
initialize(ctx);
ctx.sendUpstream(e);
}
@Override
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e)
throws Exception {
destroy();
ctx.sendUpstream(e);
}
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
throws Exception {
lastReadTime = System.currentTimeMillis();
ctx.sendUpstream(e);
}
@Override
public void writeComplete(ChannelHandlerContext ctx, WriteCompletionEvent e)
throws Exception {
if (e.getWrittenAmount() > 0) {
lastWriteTime = System.currentTimeMillis();
}
ctx.sendUpstream(e);
}
private void initialize(ChannelHandlerContext ctx) {
lastReadTime = lastWriteTime = System.currentTimeMillis();
readerIdleTimeoutTask = new ReaderIdleTimeoutTask(ctx);
writerIdleTimeoutTask = new WriterIdleTimeoutTask(ctx);
if (readerIdleTimeMillis > 0) {
readerIdleTimeout = timer.newTimeout(
readerIdleTimeoutTask, readerIdleTimeMillis, TimeUnit.MILLISECONDS);
}
if (writerIdleTimeMillis > 0) {
writerIdleTimeout = timer.newTimeout(
writerIdleTimeoutTask, writerIdleTimeMillis, TimeUnit.MILLISECONDS);
}
if (allIdleTimeMillis > 0) {
allIdleTimeout = timer.newTimeout(
allIdleTimeoutTask, allIdleTimeMillis, TimeUnit.MILLISECONDS);
}
}
private void destroy() {
if (readerIdleTimeout != null) {
readerIdleTimeout.cancel();
}
if (writerIdleTimeout != null) {
writerIdleTimeout.cancel();
}
if (allIdleTimeout != null) {
allIdleTimeout.cancel();
}
readerIdleTimeout = null;
readerIdleTimeoutTask = null;
writerIdleTimeout = null;
writerIdleTimeoutTask = null;
allIdleTimeout = null;
allIdleTimeoutTask = null;
}
protected void channelIdle(
ChannelHandlerContext ctx, IdleState state, long lastActivityTimeMillis) throws Exception {
ctx.sendUpstream(new DefaultIdleStateEvent(ctx.getChannel(), state, lastActivityTimeMillis));
}
private final class ReaderIdleTimeoutTask implements TimerTask {
private final ChannelHandlerContext ctx;
ReaderIdleTimeoutTask(ChannelHandlerContext ctx) {
this.ctx = ctx;
}
public void run(Timeout timeout) throws Exception {
if (timeout.isCancelled() || !ctx.getChannel().isOpen()) {
return;
}
long currentTime = System.currentTimeMillis();
long lastReadTime = IdleStateHandler.this.lastReadTime;
long nextDelay = readerIdleTimeMillis - (currentTime - lastReadTime);
if (nextDelay <= 0) {
// Reader is idle - set a new timeout and notify the callback.
readerIdleTimeout =
timer.newTimeout(this, readerIdleTimeMillis, TimeUnit.MILLISECONDS);
try {
channelIdle(ctx, IdleState.READER_IDLE, lastReadTime);
} catch (Throwable t) {
fireExceptionCaught(ctx, t);
}
} else {
// Read occurred before the timeout - set a new timeout with shorter delay.
readerIdleTimeout =
timer.newTimeout(this, nextDelay, TimeUnit.MILLISECONDS);
}
}
}
private final class WriterIdleTimeoutTask implements TimerTask {
private final ChannelHandlerContext ctx;
WriterIdleTimeoutTask(ChannelHandlerContext ctx) {
this.ctx = ctx;
}
public void run(Timeout timeout) throws Exception {
if (timeout.isCancelled() || !ctx.getChannel().isOpen()) {
return;
}
long currentTime = System.currentTimeMillis();
long lastWriteTime = IdleStateHandler.this.lastWriteTime;
long nextDelay = writerIdleTimeMillis - (currentTime - lastWriteTime);
if (nextDelay <= 0) {
// Writer is idle - set a new timeout and notify the callback.
writerIdleTimeout =
timer.newTimeout(this, writerIdleTimeMillis, TimeUnit.MILLISECONDS);
try {
channelIdle(ctx, IdleState.WRITER_IDLE, lastReadTime);
} catch (Throwable t) {
fireExceptionCaught(ctx, t);
}
} else {
// Write occurred before the timeout - set a new timeout with shorter delay.
writerIdleTimeout =
timer.newTimeout(this, nextDelay, TimeUnit.MILLISECONDS);
}
}
}
private final class AllIdleTimeoutTask implements TimerTask {
private final ChannelHandlerContext ctx;
AllIdleTimeoutTask(ChannelHandlerContext ctx) {
this.ctx = ctx;
}
public void run(Timeout timeout) throws Exception {
if (timeout.isCancelled() || !ctx.getChannel().isOpen()) {
return;
}
long currentTime = System.currentTimeMillis();
long lastIoTime = Math.max(lastReadTime, lastWriteTime);
long nextDelay = allIdleTimeMillis - (currentTime - lastIoTime);
if (nextDelay <= 0) {
// Both reader and writer are idle - set a new timeout and
// notify the callback.
allIdleTimeout =
timer.newTimeout(this, allIdleTimeMillis, TimeUnit.MILLISECONDS);
try {
channelIdle(ctx, IdleState.ALL_IDLE, lastReadTime);
} catch (Throwable t) {
fireExceptionCaught(ctx, t);
}
} else {
// Either read or write occurred before the timeout - set a new
// timeout with shorter delay.
allIdleTimeout =
timer.newTimeout(this, nextDelay, TimeUnit.MILLISECONDS);
}
}
}
}
|
Fixed NPE
|
src/main/java/org/jboss/netty/handler/timeout/IdleStateHandler.java
|
Fixed NPE
|
|
Java
|
apache-2.0
|
bf5fb0a5ca6998812c709634562a1a66ecf7a28c
| 0
|
roboguy/pentaho-kettle,birdtsai/pentaho-kettle,ma459006574/pentaho-kettle,hudak/pentaho-kettle,stepanovdg/pentaho-kettle,matthewtckr/pentaho-kettle,ddiroma/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,ivanpogodin/pentaho-kettle,nanata1115/pentaho-kettle,YuryBY/pentaho-kettle,matrix-stone/pentaho-kettle,airy-ict/pentaho-kettle,stevewillcock/pentaho-kettle,MikhailHubanau/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,stepanovdg/pentaho-kettle,roboguy/pentaho-kettle,sajeetharan/pentaho-kettle,YuryBY/pentaho-kettle,bmorrise/pentaho-kettle,pymjer/pentaho-kettle,codek/pentaho-kettle,pentaho/pentaho-kettle,brosander/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,yshakhau/pentaho-kettle,HiromuHota/pentaho-kettle,rmansoor/pentaho-kettle,kurtwalker/pentaho-kettle,skofra0/pentaho-kettle,CapeSepias/pentaho-kettle,akhayrutdinov/pentaho-kettle,pentaho/pentaho-kettle,ViswesvarSekar/pentaho-kettle,Advent51/pentaho-kettle,SergeyTravin/pentaho-kettle,marcoslarsen/pentaho-kettle,lgrill-pentaho/pentaho-kettle,andrei-viaryshka/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,codek/pentaho-kettle,pymjer/pentaho-kettle,zlcnju/kettle,cjsonger/pentaho-kettle,GauravAshara/pentaho-kettle,lgrill-pentaho/pentaho-kettle,flbrino/pentaho-kettle,ccaspanello/pentaho-kettle,drndos/pentaho-kettle,hudak/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,skofra0/pentaho-kettle,SergeyTravin/pentaho-kettle,tkafalas/pentaho-kettle,denisprotopopov/pentaho-kettle,gretchiemoran/pentaho-kettle,hudak/pentaho-kettle,sajeetharan/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,ccaspanello/pentaho-kettle,codek/pentaho-kettle,graimundo/pentaho-kettle,stevewillcock/pentaho-kettle,cjsonger/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,marcoslarsen/pentaho-kettle,zlcnju/kettle,flbrino/pentaho-kettle,CapeSepias/pentaho-kettle,ddiroma/pentaho-kettle,wseyler/pentaho-kettle,eayoungs/pentaho-kettle,mkambol/pentaho-kettle,pminutillo/pentaho-kettle,pminutillo/pentaho-kettle,emartin-pentaho/pentaho-kettle,nicoben/pentaho-kettle,matrix-stone/pentaho-kettle,tmcsantos/pentaho-kettle,flbrino/pentaho-kettle,zlcnju/kettle,mdamour1976/pentaho-kettle,pedrofvteixeira/pentaho-kettle,matrix-stone/pentaho-kettle,mdamour1976/pentaho-kettle,mbatchelor/pentaho-kettle,denisprotopopov/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,tmcsantos/pentaho-kettle,jbrant/pentaho-kettle,rmansoor/pentaho-kettle,alina-ipatina/pentaho-kettle,e-cuellar/pentaho-kettle,mkambol/pentaho-kettle,CapeSepias/pentaho-kettle,ivanpogodin/pentaho-kettle,lgrill-pentaho/pentaho-kettle,zlcnju/kettle,roboguy/pentaho-kettle,birdtsai/pentaho-kettle,birdtsai/pentaho-kettle,sajeetharan/pentaho-kettle,nantunes/pentaho-kettle,jbrant/pentaho-kettle,akhayrutdinov/pentaho-kettle,SergeyTravin/pentaho-kettle,marcoslarsen/pentaho-kettle,nicoben/pentaho-kettle,mattyb149/pentaho-kettle,tkafalas/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,nantunes/pentaho-kettle,pavel-sakun/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,ViswesvarSekar/pentaho-kettle,DFieldFL/pentaho-kettle,sajeetharan/pentaho-kettle,bmorrise/pentaho-kettle,yshakhau/pentaho-kettle,tkafalas/pentaho-kettle,dkincade/pentaho-kettle,mdamour1976/pentaho-kettle,akhayrutdinov/pentaho-kettle,emartin-pentaho/pentaho-kettle,rfellows/pentaho-kettle,ma459006574/pentaho-kettle,SergeyTravin/pentaho-kettle,graimundo/pentaho-kettle,pavel-sakun/pentaho-kettle,ivanpogodin/pentaho-kettle,tkafalas/pentaho-kettle,kurtwalker/pentaho-kettle,mbatchelor/pentaho-kettle,akhayrutdinov/pentaho-kettle,airy-ict/pentaho-kettle,pymjer/pentaho-kettle,mattyb149/pentaho-kettle,ccaspanello/pentaho-kettle,matrix-stone/pentaho-kettle,mattyb149/pentaho-kettle,drndos/pentaho-kettle,nanata1115/pentaho-kettle,eayoungs/pentaho-kettle,denisprotopopov/pentaho-kettle,e-cuellar/pentaho-kettle,skofra0/pentaho-kettle,cjsonger/pentaho-kettle,stepanovdg/pentaho-kettle,wseyler/pentaho-kettle,pentaho/pentaho-kettle,DFieldFL/pentaho-kettle,rmansoor/pentaho-kettle,airy-ict/pentaho-kettle,eayoungs/pentaho-kettle,codek/pentaho-kettle,nantunes/pentaho-kettle,ivanpogodin/pentaho-kettle,brosander/pentaho-kettle,brosander/pentaho-kettle,alina-ipatina/pentaho-kettle,matthewtckr/pentaho-kettle,mattyb149/pentaho-kettle,MikhailHubanau/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,pedrofvteixeira/pentaho-kettle,eayoungs/pentaho-kettle,dkincade/pentaho-kettle,aminmkhan/pentaho-kettle,Advent51/pentaho-kettle,GauravAshara/pentaho-kettle,e-cuellar/pentaho-kettle,alina-ipatina/pentaho-kettle,matthewtckr/pentaho-kettle,lgrill-pentaho/pentaho-kettle,marcoslarsen/pentaho-kettle,YuryBY/pentaho-kettle,bmorrise/pentaho-kettle,CapeSepias/pentaho-kettle,EcoleKeine/pentaho-kettle,e-cuellar/pentaho-kettle,drndos/pentaho-kettle,EcoleKeine/pentaho-kettle,rfellows/pentaho-kettle,pentaho/pentaho-kettle,GauravAshara/pentaho-kettle,ma459006574/pentaho-kettle,pymjer/pentaho-kettle,yshakhau/pentaho-kettle,ViswesvarSekar/pentaho-kettle,Advent51/pentaho-kettle,mdamour1976/pentaho-kettle,aminmkhan/pentaho-kettle,ma459006574/pentaho-kettle,HiromuHota/pentaho-kettle,roboguy/pentaho-kettle,tmcsantos/pentaho-kettle,nicoben/pentaho-kettle,rfellows/pentaho-kettle,alina-ipatina/pentaho-kettle,wseyler/pentaho-kettle,mbatchelor/pentaho-kettle,stevewillcock/pentaho-kettle,wseyler/pentaho-kettle,ccaspanello/pentaho-kettle,brosander/pentaho-kettle,ddiroma/pentaho-kettle,drndos/pentaho-kettle,stevewillcock/pentaho-kettle,andrei-viaryshka/pentaho-kettle,nicoben/pentaho-kettle,graimundo/pentaho-kettle,pedrofvteixeira/pentaho-kettle,pavel-sakun/pentaho-kettle,airy-ict/pentaho-kettle,hudak/pentaho-kettle,stepanovdg/pentaho-kettle,andrei-viaryshka/pentaho-kettle,tmcsantos/pentaho-kettle,GauravAshara/pentaho-kettle,YuryBY/pentaho-kettle,DFieldFL/pentaho-kettle,MikhailHubanau/pentaho-kettle,bmorrise/pentaho-kettle,HiromuHota/pentaho-kettle,HiromuHota/pentaho-kettle,gretchiemoran/pentaho-kettle,dkincade/pentaho-kettle,emartin-pentaho/pentaho-kettle,emartin-pentaho/pentaho-kettle,kurtwalker/pentaho-kettle,nantunes/pentaho-kettle,pminutillo/pentaho-kettle,gretchiemoran/pentaho-kettle,nanata1115/pentaho-kettle,aminmkhan/pentaho-kettle,gretchiemoran/pentaho-kettle,nanata1115/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,jbrant/pentaho-kettle,dkincade/pentaho-kettle,DFieldFL/pentaho-kettle,kurtwalker/pentaho-kettle,denisprotopopov/pentaho-kettle,matthewtckr/pentaho-kettle,pedrofvteixeira/pentaho-kettle,yshakhau/pentaho-kettle,ViswesvarSekar/pentaho-kettle,graimundo/pentaho-kettle,flbrino/pentaho-kettle,ddiroma/pentaho-kettle,jbrant/pentaho-kettle,rmansoor/pentaho-kettle,skofra0/pentaho-kettle,EcoleKeine/pentaho-kettle,mbatchelor/pentaho-kettle,EcoleKeine/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,mkambol/pentaho-kettle,pavel-sakun/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,Advent51/pentaho-kettle,pminutillo/pentaho-kettle,cjsonger/pentaho-kettle,mkambol/pentaho-kettle,aminmkhan/pentaho-kettle,birdtsai/pentaho-kettle
|
/* Copyright (c) 2007 Pentaho Corporation. All rights reserved.
* This software was developed by Pentaho Corporation and is provided under the terms
* of the GNU Lesser General Public License, Version 2.1. You may not use
* this file except in compliance with the license. If you need a copy of the license,
* please go to http://www.gnu.org/licenses/lgpl-2.1.txt. The Original Code is Pentaho
* Data Integration. The Initial Developer is Pentaho Corporation.
*
* Software distributed under the GNU Lesser Public License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to
* the license for the specific language governing your rights and limitations.*/
package org.pentaho.di.trans.steps.dimensionlookup;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.RowMetaAndData;
import org.pentaho.di.core.database.Database;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.database.MySQLDatabaseMeta;
import org.pentaho.di.core.exception.KettleDatabaseException;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleStepException;
import org.pentaho.di.core.exception.KettleValueException;
import org.pentaho.di.core.hash.ByteArrayHashMap;
import org.pentaho.di.core.row.RowMeta;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMeta;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStep;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;
/**
* Manages a slowly changing dimension (lookup or update)
*
* @author Matt
* @since 14-may-2003
*/
public class DimensionLookup extends BaseStep implements StepInterface
{
private static Class<?> PKG = DimensionLookupMeta.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$
private final static int CREATION_METHOD_AUTOINC = 1;
private final static int CREATION_METHOD_SEQUENCE = 2;
private final static int CREATION_METHOD_TABLEMAX = 3;
private int techKeyCreation;
private DimensionLookupMeta meta;
private DimensionLookupData data;
public DimensionLookup(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans)
{
super(stepMeta, stepDataInterface, copyNr, transMeta, trans);
}
private void setTechKeyCreation(int method)
{
techKeyCreation = method;
}
private int getTechKeyCreation()
{
return techKeyCreation;
}
private void determineTechKeyCreation()
{
String keyCreation = meta.getTechKeyCreation();
if (meta.getDatabaseMeta().supportsAutoinc() &&
DimensionLookupMeta.CREATION_METHOD_AUTOINC.equals(keyCreation) )
{
setTechKeyCreation(CREATION_METHOD_AUTOINC);
}
else if (meta.getDatabaseMeta().supportsSequences() &&
DimensionLookupMeta.CREATION_METHOD_SEQUENCE.equals(keyCreation) )
{
setTechKeyCreation(CREATION_METHOD_SEQUENCE);
}
else
{
setTechKeyCreation(CREATION_METHOD_TABLEMAX);
}
}
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException
{
meta=(DimensionLookupMeta)smi;
data=(DimensionLookupData)sdi;
Object[] r=getRow(); // Get row from input rowset & set row busy!
if (r==null) // no more input to be expected...
{
setOutputDone(); // signal end to receiver(s)
return false;
}
if (first)
{
first=false;
data.schemaTable = meta.getDatabaseMeta().getQuotedSchemaTableCombination(data.realSchemaName, data.realTableName);
data.inputRowMeta = getInputRowMeta().clone();
data.outputRowMeta = getInputRowMeta().clone();
meta.getFields(data.outputRowMeta, getStepname(), null, null, this);
// Get the fields that need conversion to normal storage...
// Modify the storage type of the input data...
//
data.lazyList = new ArrayList<Integer>();
for (int i=0;i<data.inputRowMeta.size();i++) {
ValueMetaInterface valueMeta = data.inputRowMeta.getValueMeta(i);
if (valueMeta.isStorageBinaryString()) {
data.lazyList.add(i);
valueMeta.setStorageType(ValueMetaInterface.STORAGE_TYPE_NORMAL);
}
}
// The start date value column (if applicable)
//
data.startDateFieldIndex = -1;
if (data.startDateChoice==DimensionLookupMeta.START_DATE_ALTERNATIVE_COLUMN_VALUE) {
data.startDateFieldIndex = data.inputRowMeta.indexOfValue(meta.getStartDateFieldName());
if (data.startDateFieldIndex<0) {
throw new KettleStepException(BaseMessages.getString(PKG, "DimensionLookup.Exception.StartDateValueColumnNotFound", meta.getStartDateFieldName()));
}
}
// Lookup values
data.keynrs = new int[meta.getKeyStream().length];
for (int i=0;i<meta.getKeyStream().length;i++)
{
//logDetailed("Lookup values key["+i+"] --> "+key[i]+", row==null?"+(row==null));
data.keynrs[i]=data.inputRowMeta.indexOfValue(meta.getKeyStream()[i]);
if (data.keynrs[i]<0) // couldn't find field!
{
throw new KettleStepException(BaseMessages.getString(PKG, "DimensionLookup.Exception.KeyFieldNotFound",meta.getKeyStream()[i])); //$NON-NLS-1$ //$NON-NLS-2$
}
}
// Return values
data.fieldnrs = new int[meta.getFieldStream().length];
for (int i=0;meta.getFieldStream()!=null && i<meta.getFieldStream().length;i++)
{
if (!DimensionLookupMeta.isUpdateTypeWithoutArgument(meta.isUpdate(), meta.getFieldUpdate()[i])) {
data.fieldnrs[i]=data.outputRowMeta.indexOfValue(meta.getFieldStream()[i]);
if (data.fieldnrs[i] < 0)
{
throw new KettleStepException(BaseMessages.getString(PKG, "DimensionLookup.Exception.KeyFieldNotFound", meta.getFieldStream()[i])); //$NON-NLS-1$ //$NON-NLS-2$
}
} else {
data.fieldnrs[i]=-1;
}
}
if (!meta.isUpdate() && meta.isPreloadingCache()) {
preloadCache();
} else {
// Caching...
//
if (data.cacheKeyRowMeta==null)
{
// KEY : the natural key(s)
//
data.cacheKeyRowMeta = new RowMeta();
for (int i=0;i<data.keynrs.length;i++)
{
ValueMetaInterface key = data.inputRowMeta.getValueMeta(data.keynrs[i]);
data.cacheKeyRowMeta.addValueMeta( key.clone());
}
data.cache = new ByteArrayHashMap(meta.getCacheSize()>0 ? meta.getCacheSize() : 5000, data.cacheKeyRowMeta);
}
}
if (!Const.isEmpty(meta.getDateField()))
{
data.datefieldnr = data.inputRowMeta.indexOfValue(meta.getDateField());
}
else
{
data.datefieldnr=-1;
}
// Initialize the start date value in case we don't have one in the input rows
//
data.valueDateNow = determineDimensionUpdatedDate(r);
determineTechKeyCreation();
data.notFoundTk = new Long( (long)meta.getDatabaseMeta().getNotFoundTK(isAutoIncrement()) );
// if (meta.getKeyRename()!=null && meta.getKeyRename().length()>0) data.notFoundTk.setName(meta.getKeyRename());
if (getCopy()==0) checkDimZero();
setDimLookup(data.outputRowMeta);
}
// convert row to normal storage...
//
for (int lazyFieldIndex : data.lazyList) {
ValueMetaInterface valueMeta = getInputRowMeta().getValueMeta(lazyFieldIndex);
r[lazyFieldIndex] = valueMeta.convertToNormalStorageType(r[lazyFieldIndex]);
}
try
{
Object[] outputRow = lookupValues(data.inputRowMeta, r); // add new values to the row in rowset[0].
putRow(data.outputRowMeta, outputRow); // copy row to output rowset(s);
if (checkFeedback(getLinesRead()))
{
if(log.isBasic()) logBasic(BaseMessages.getString(PKG, "DimensionLookup.Log.LineNumber")+getLinesRead()); //$NON-NLS-1$
}
}
catch(KettleException e)
{
logError(BaseMessages.getString(PKG, "DimensionLookup.Log.StepCanNotContinueForErrors", e.getMessage())); //$NON-NLS-1$ //$NON-NLS-2$
logError(Const.getStackTracker(e)); //$NON-NLS-1$ //$NON-NLS-2$
setErrors(1);
stopAll();
setOutputDone(); // signal end to receiver(s)
return false;
}
return true;
}
private Date determineDimensionUpdatedDate(Object[] row) throws KettleException {
if (data.datefieldnr < 0) {
return getTrans().getCurrentDate(); // start of transformation...
} else {
return data.inputRowMeta.getDate(row, data.datefieldnr); // Date field in the input row
}
}
/**
* Pre-load the cache by reading the whole dimension table from disk...
*
* @throws in case there is a database or cache problem.
*/
private void preloadCache() throws KettleException{
try {
DatabaseMeta databaseMeta = meta.getDatabaseMeta();
// tk, version, from, to, natural keys, retrieval fields...
//
String sql = "SELECT "+databaseMeta.quoteField(meta.getKeyField());
// sql+=", "+databaseMeta.quoteField(meta.getVersionField());
for (int i=0;i<meta.getKeyLookup().length;i++) {
sql+=", "+meta.getKeyLookup()[i]; // the natural key field in the table
}
for (int i=0;i<meta.getFieldLookup().length;i++) {
sql+=", "+meta.getFieldLookup()[i]; // the extra fields to retrieve...
}
sql+=", "+databaseMeta.quoteField(meta.getDateFrom()); // extra info in cache
sql+=", "+databaseMeta.quoteField(meta.getDateTo()); // extra info in cache
sql+=" FROM "+data.schemaTable;
logDetailed("Pre-loading cache by reading from database with: "+Const.CR+sql+Const.CR);
List<Object[]> rows = data.db.getRows(sql, -1);
RowMetaInterface rowMeta = data.db.getReturnRowMeta();
data.preloadKeyIndexes = new int[meta.getKeyLookup().length];
for (int i=0;i<data.preloadKeyIndexes.length;i++) {
data.preloadKeyIndexes[i] = rowMeta.indexOfValue(meta.getKeyLookup()[i]); // the field in the table
}
data.preloadFromDateIndex = rowMeta.indexOfValue(meta.getDateFrom());
data.preloadToDateIndex = rowMeta.indexOfValue(meta.getDateTo());
data.preloadCache = new DimensionCache(rowMeta, data.preloadKeyIndexes, data.preloadFromDateIndex, data.preloadToDateIndex);
data.preloadCache.setRowCache(rows);
logDetailed("Sorting the cache rows...");
data.preloadCache.sortRows();
logDetailed("Sorting of cached rows finished.");
// Also see what indexes to take to populate the lookup row...
// We only ever compare indexes and the lookup date in the cache, the rest is not needed...
//
data.preloadIndexes = new ArrayList<Integer>();
for (int i=0;i<meta.getKeyStream().length;i++) {
int index = data.inputRowMeta.indexOfValue(meta.getKeyStream()[i]);
if (index<0) {
// Just to be safe...
//
throw new KettleStepException(BaseMessages.getString(PKG, "DimensionLookup.Exception.KeyFieldNotFound", meta.getFieldStream()[i])); //$NON-NLS-1$ //$NON-NLS-2$
}
data.preloadIndexes.add(index);
}
// This is all for now...
} catch(Exception e) {
throw new KettleException("Error encountered during cache pre-load", e);
}
}
private synchronized Object[] lookupValues(RowMetaInterface rowMeta, Object[] row) throws KettleException {
Object[] outputRow = new Object[data.outputRowMeta.size()];
RowMetaInterface lookupRowMeta;
Object[] lookupRow;
Object[] returnRow = null;
Long technicalKey;
Long valueVersion;
Date valueDate = null;
Date valueDateFrom = null;
Date valueDateTo = null;
// Determine the lookup date ("now") if we have a field that carries said
// date.
// If not, the system date is taken.
//
valueDate = determineDimensionUpdatedDate(row);
if (!meta.isUpdate() && meta.isPreloadingCache()) {
// Obtain a result row from the pre-load cache...
//
// Create a row to compare with
//
RowMetaInterface preloadRowMeta = data.preloadCache.getRowMeta();
// In this case it's all the same. (simple)
//
data.returnRowMeta = data.preloadCache.getRowMeta();
lookupRowMeta = preloadRowMeta;
lookupRow = new Object[preloadRowMeta.size()];
// Assemble the lookup row, convert data if needed...
//
for (int i = 0; i < data.preloadIndexes.size(); i++) {
int from = data.preloadIndexes.get(i); // Input row index
int to = data.preloadCache.getKeyIndexes()[i]; // Lookup row index
// From data type...
//
ValueMetaInterface fromValueMeta = rowMeta.getValueMeta(from);
// to date type...
//
ValueMetaInterface toValueMeta = data.preloadCache.getRowMeta().getValueMeta(to);
// From value:
//
Object fromData = row[from];
// To value:
//
Object toData = toValueMeta.convertData(fromValueMeta, fromData);
// Set the key in the row...
//
lookupRow[to] = toData;
}
// Also set the lookup date on the "end of date range" (toDate) position
//
lookupRow[data.preloadFromDateIndex] = valueDate;
// Look up the row in the pre-load cache...
//
int index = data.preloadCache.lookupRow(lookupRow);
if (index >= 0) {
returnRow = data.preloadCache.getRow(index);
} else {
returnRow = null; // Nothing found!
}
} else {
lookupRow = new Object[data.lookupRowMeta.size()];
lookupRowMeta = data.lookupRowMeta;
// Construct the lookup row...
//
for (int i = 0; i < meta.getKeyStream().length; i++) {
try {
lookupRow[i] = row[data.keynrs[i]];
} catch (Exception e) // TODO : remove exception??
{
throw new KettleStepException(BaseMessages.getString(PKG, "DimensionLookup.Exception.ErrorDetectedInGettingKey", i + "", data.keynrs[i] + "/" + rowMeta.size(), rowMeta.getString(row))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
}
}
lookupRow[meta.getKeyStream().length] = valueDate; // ? >= date_from
lookupRow[meta.getKeyStream().length + 1] = valueDate; // ? < date_to
if (log.isDebug())
logDebug(BaseMessages.getString(PKG, "DimensionLookup.Log.LookupRow") + data.lookupRowMeta.getString(lookupRow)); //$NON-NLS-1$ //$NON-NLS-2$
// Do the lookup and see if we can find anything in the database.
// But before that, let's see if we can find anything in the cache
//
if (meta.getCacheSize() >= 0) {
returnRow = getFromCache(lookupRow, valueDate);
}
// Nothing found in the cache?
// Perform the lookup in the database...
//
if (returnRow == null) {
data.db.setValues(data.lookupRowMeta, lookupRow, data.prepStatementLookup);
returnRow = data.db.getLookup(data.prepStatementLookup);
data.returnRowMeta = data.db.getReturnRowMeta();
incrementLinesInput();
if (returnRow != null && meta.getCacheSize() >= 0) {
addToCache(lookupRow, returnRow);
}
}
}
// This next block of code handles the dimension key LOOKUP ONLY.
// We handle this case where "update = false" first for performance reasons
//
if (!meta.isUpdate()) {
if (returnRow == null) {
returnRow = new Object[data.returnRowMeta.size()];
returnRow[0] = data.notFoundTk;
if (meta.getCacheSize() >= 0) // need -oo to +oo as well...
{
returnRow[returnRow.length - 2] = data.min_date;
returnRow[returnRow.length - 1] = data.max_date;
}
} else {
// We found the return values in row "add".
// Throw away the version nr...
// add.removeValue(1);
// Rename the key field if needed. Do it directly in the row...
// if (meta.getKeyRename()!=null && meta.getKeyRename().length()>0)
// add.getValue(0).setName(meta.getKeyRename());
}
} else
// This is the "update=true" case where we update the dimension table...
// It is an "Insert - update" algorithm for slowly changing dimensions
//
{
// The dimension entry was not found, we need to add it!
//
if (returnRow == null) {
if (log.isRowLevel()) {
logRowlevel(BaseMessages.getString(PKG, "DimensionLookup.Log.NoDimensionEntryFound") + lookupRowMeta.getString(lookupRow) + ")"); //$NON-NLS-1$ //$NON-NLS-2$
}
// Date range: ]-oo,+oo[
//
valueDateFrom = data.min_date;
valueDateTo = data.max_date;
valueVersion = new Long(1L); // Versions always start at 1.
// get a new value from the sequence generator chosen.
//
technicalKey = null;
switch (getTechKeyCreation()) {
case CREATION_METHOD_TABLEMAX:
// What's the next value for the technical key?
technicalKey = data.db.getNextValue(getTransMeta().getCounters(), data.realSchemaName, data.realTableName, meta.getKeyField());
break;
case CREATION_METHOD_AUTOINC:
technicalKey = null; // Set to null to flag auto-increment usage
break;
case CREATION_METHOD_SEQUENCE:
technicalKey = data.db.getNextSequenceValue(data.realSchemaName, meta.getSequenceName(), meta.getKeyField());
if (technicalKey != null && log.isRowLevel())
logRowlevel(BaseMessages.getString(PKG, "DimensionLookup.Log.FoundNextSequence") + technicalKey.toString()); //$NON-NLS-1$
break;
}
/*
* INSERT INTO table(version, datefrom, dateto, fieldlookup)
* VALUES(valueVersion, valueDateFrom, valueDateTo, row.fieldnrs) ;
*/
technicalKey = dimInsert(data.inputRowMeta, row, technicalKey, true, valueVersion, valueDateFrom, valueDateTo);
incrementLinesOutput();
returnRow = new Object[data.returnRowMeta.size()];
int returnIndex = 0;
returnRow[returnIndex] = technicalKey;
returnIndex++;
// See if we need to store this record in the cache as well...
/*
* TODO: we can't really assume like this that the cache layout of the
* incoming rows (below) is the same as the stored data. Storing this in
* the cache gives us data/metadata collision errors. (class cast
* problems etc) Perhaps we need to convert this data to the target data
* types. Alternatively, we can use a separate cache in the future.
* Reference: PDI-911
*
* if (meta.getCacheSize()>=0) { Object[] values =
* getCacheValues(rowMeta, row, technicalKey, valueVersion,
* valueDateFrom, valueDateTo);
*
* // put it in the cache... if (values!=null) { addToCache(lookupRow,
* values); } }
*/
if (log.isRowLevel())
logRowlevel(BaseMessages.getString(PKG, "DimensionLookup.Log.AddedDimensionEntry") + data.returnRowMeta.getString(returnRow)); //$NON-NLS-1$
} else
//
// The entry was found: do we need to insert, update or both?
//
{
if (log.isRowLevel())
logRowlevel(BaseMessages.getString(PKG, "DimensionLookup.Log.DimensionEntryFound") + data.returnRowMeta.getString(returnRow)); //$NON-NLS-1$
// What's the key? The first value of the return row
technicalKey = data.returnRowMeta.getInteger(returnRow, 0);
valueVersion = data.returnRowMeta.getInteger(returnRow, 1);
// Date range: ]-oo,+oo[
valueDateFrom = meta.getMinDate();
valueDateTo = meta.getMaxDate();
// The other values, we compare with
int cmp;
// If everything is the same: don't do anything
// If one of the fields is different: insert or update
// If all changed fields have update = Y, update
// If one of the changed fields has update = N, insert
boolean insert = false;
boolean identical = true;
boolean punch = false;
for (int i = 0; i < meta.getFieldStream().length; i++) {
if (data.fieldnrs[i] >= 0) {
// Only compare real fields, not last updated row, last version, etc
//
ValueMetaInterface v1 = data.outputRowMeta.getValueMeta(data.fieldnrs[i]);
Object valueData1 = row[data.fieldnrs[i]];
ValueMetaInterface v2 = data.returnRowMeta.getValueMeta(i + 2);
Object valueData2 = returnRow[i + 2];
try {
cmp = v1.compare(valueData1, v2, valueData2);
} catch (ClassCastException e) {
throw e;
}
// Not the same and update = 'N' --> insert
if (cmp != 0)
identical = false;
// Field flagged for insert: insert
if (cmp != 0 && meta.getFieldUpdate()[i] == DimensionLookupMeta.TYPE_UPDATE_DIM_INSERT) {
insert = true;
}
// Field flagged for punchthrough
if (cmp != 0 && meta.getFieldUpdate()[i] == DimensionLookupMeta.TYPE_UPDATE_DIM_PUNCHTHROUGH) {
punch = true;
}
if (log.isRowLevel())
logRowlevel(BaseMessages.getString(PKG, "DimensionLookup.Log.ComparingValues", "" + v1, "" + v2, String.valueOf(cmp), String.valueOf(identical), String.valueOf(insert), String.valueOf(punch))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
}
}
// After comparing the record in the database and the data in the input
// and taking into account the rules of the slowly changing dimension,
// we found out whether or not to perform an insert or an update.
//
if (!insert) // Just an update of row at key = valueKey
{
if (!identical) {
if (log.isRowLevel())
logRowlevel(BaseMessages.getString(PKG, "DimensionLookup.Log.UpdateRowWithValues") + data.inputRowMeta.getString(row)); //$NON-NLS-1$
/*
* UPDATE d_customer SET fieldlookup[] = row.getValue(fieldnrs)
* WHERE returnkey = dimkey
*/
dimUpdate(rowMeta, row, technicalKey, valueDate);
incrementLinesUpdated();
// We need to capture this change in the cache as well...
if (meta.getCacheSize() >= 0) {
Object[] values = getCacheValues(rowMeta, row, technicalKey, valueVersion, valueDateFrom, valueDateTo);
addToCache(lookupRow, values);
}
} else {
if (log.isRowLevel())
logRowlevel(BaseMessages.getString(PKG, "DimensionLookup.Log.SkipLine")); //$NON-NLS-1$
// Don't do anything, everything is file in de dimension.
incrementLinesSkipped();
}
} else {
if (log.isRowLevel())
logRowlevel(BaseMessages.getString(PKG, "DimensionLookup.Log.InsertNewVersion") + technicalKey.toString()); //$NON-NLS-1$
Long valueNewVersion = valueVersion + 1;
// From date (valueDate) is calculated at the start of this method to
// be either the system date or the value in a column
//
valueDateFrom = valueDate;
valueDateTo = data.max_date; //$NON-NLS-1$
// First try to use an AUTOINCREMENT field
if (meta.getDatabaseMeta().supportsAutoinc() && isAutoIncrement()) {
technicalKey = new Long(0L); // value to accept new key...
} else
// Try to get the value by looking at a SEQUENCE (oracle mostly)
if (meta.getDatabaseMeta().supportsSequences() && meta.getSequenceName() != null && meta.getSequenceName().length() > 0) {
technicalKey = data.db.getNextSequenceValue(data.realSchemaName, meta.getSequenceName(), meta.getKeyField());
if (technicalKey != null && log.isRowLevel())
logRowlevel(BaseMessages.getString(PKG, "DimensionLookup.Log.FoundNextSequence2") + technicalKey.toString()); //$NON-NLS-1$
} else
// Use our own sequence here...
{
// What's the next value for the technical key?
technicalKey = data.db.getNextValue(getTransMeta().getCounters(), data.realSchemaName, data.realTableName, meta.getKeyField());
}
// update our technicalKey with the return of the insert
technicalKey = dimInsert(rowMeta, row, technicalKey, false, valueNewVersion, valueDateFrom, valueDateTo);
incrementLinesOutput();
// We need to capture this change in the cache as well...
if (meta.getCacheSize() >= 0) {
Object[] values = getCacheValues(rowMeta, row, technicalKey, valueNewVersion, valueDateFrom, valueDateTo);
addToCache(lookupRow, values);
}
}
if (punch) // On of the fields we have to punch through has changed!
{
/*
* This means we have to update all versions:
*
* UPDATE dim SET punchf1 = val1, punchf2 = val2, ... WHERE
* fieldlookup[] = ? ;
*
* --> update ALL versions in the dimension table.
*/
dimPunchThrough(rowMeta, row);
incrementLinesUpdated();
}
returnRow = new Object[data.returnRowMeta.size()];
returnRow[0] = technicalKey;
if (log.isRowLevel())
logRowlevel(BaseMessages.getString(PKG, "DimensionLookup.Log.TechnicalKey") + technicalKey); //$NON-NLS-1$
}
}
if (log.isRowLevel())
logRowlevel(BaseMessages.getString(PKG, "DimensionLookup.Log.AddValuesToRow") + data.returnRowMeta.getString(returnRow)); //$NON-NLS-1$
// Copy the results to the output row...
//
// First copy the input row values to the output..
//
for (int i = 0; i < rowMeta.size(); i++)
outputRow[i] = row[i];
int outputIndex = rowMeta.size();
int inputIndex = 0;
// Then the technical key...
//
outputRow[outputIndex++] = data.returnRowMeta.getInteger(returnRow, inputIndex++);
// skip the version in the input
inputIndex++;
// Then get the "extra fields"...
// don't return date from-to fields, they can be returned when explicitly
// specified in lookup fields.
while (inputIndex < returnRow.length && outputIndex < outputRow.length) {
outputRow[outputIndex] = returnRow[inputIndex];
outputIndex++;
inputIndex++;
}
// Finaly, check the date range!
/*
* TODO: WTF is this??? [May be it makes sense to keep the return date
* from-to fields within min/max range, but even then the code below is
* wrong]. Value date; if (data.datefieldnr>=0) date =
* row.getValue(data.datefieldnr); else date = new Value("date", new
* Date()); // system date //$NON-NLS-1$
*
* if (data.min_date.compare(date)>0) data.min_date.setValue( date.getDate()
* ); if (data.max_date.compare(date)<0) data.max_date.setValue(
* date.getDate() );
*/
return outputRow;
}
/**
* table: dimension table keys[]: which dim-fields do we use to look up key? retval: name of the key to return
* datefield: do we have a datefield? datefrom, dateto: date-range, if any.
*/
private void setDimLookup(RowMetaInterface rowMeta) throws KettleDatabaseException
{
DatabaseMeta databaseMeta = meta.getDatabaseMeta();
data.lookupRowMeta = new RowMeta();
/* DEFAULT, SYSDATE, START_TRANS, COLUMN_VALUE :
*
* SELECT <tk>, <version>, ... ,
* FROM <table>
* WHERE key1=keys[1]
* AND key2=keys[2] ...
* AND <datefrom> <= <datefield>
* AND <dateto> > <datefield>
* ;
*
* NULL :
*
* SELECT <tk>, <version>, ... ,
* FROM <table>
* WHERE key1=keys[1]
* AND key2=keys[2] ...
* AND ( <datefrom> is null OR <datefrom> <= <datefield> )
* AND <dateto> >= <datefield>
*/
String sql = "SELECT "+databaseMeta.quoteField(meta.getKeyField())+", "+databaseMeta.quoteField(meta.getVersionField());
if (!Const.isEmpty(meta.getFieldLookup()))
{
for (int i=0;i<meta.getFieldLookup().length;i++)
{
if (!Const.isEmpty(meta.getFieldLookup()[i]) && !DimensionLookupMeta.isUpdateTypeWithoutArgument(meta.isUpdate(), meta.getFieldUpdate()[i])) // Don't retrieve the fields without input
{
sql+=", "+databaseMeta.quoteField(meta.getFieldLookup()[i]);
if (!Const.isEmpty( meta.getFieldStream()[i] ) && !meta.getFieldLookup()[i].equals(meta.getFieldStream()[i]))
{
sql+=" AS "+databaseMeta.quoteField(meta.getFieldStream()[i]);
}
}
}
}
if (meta.getCacheSize()>=0)
{
sql+=", "+databaseMeta.quoteField(meta.getDateFrom())+", "+databaseMeta.quoteField(meta.getDateTo());
}
sql+= " FROM "+data.schemaTable+" WHERE ";
for (int i=0;i<meta.getKeyLookup().length;i++)
{
if (i!=0) sql += " AND ";
sql += databaseMeta.quoteField(meta.getKeyLookup()[i])+" = ? ";
data.lookupRowMeta.addValueMeta( rowMeta.getValueMeta(data.keynrs[i]) );
}
String dateFromField = databaseMeta.quoteField(meta.getDateFrom());
String dateToField = databaseMeta.quoteField(meta.getDateTo());
if (meta.isUsingStartDateAlternative() &&
( meta.getStartDateAlternative()==DimensionLookupMeta.START_DATE_ALTERNATIVE_NULL) ||
( meta.getStartDateAlternative()==DimensionLookupMeta.START_DATE_ALTERNATIVE_COLUMN_VALUE)
)
{
// Null as a start date is possible...
//
sql += " AND ( "+dateFromField+" IS NULL OR "+dateFromField+" <= ? )"+Const.CR;
sql += " AND "+dateToField+" >= ?"+Const.CR;
data.lookupRowMeta.addValueMeta( new ValueMeta(meta.getDateFrom(), ValueMetaInterface.TYPE_DATE) );
data.lookupRowMeta.addValueMeta( new ValueMeta(meta.getDateTo(), ValueMetaInterface.TYPE_DATE) );
} else {
// Null as a start date is NOT possible
//
sql += " AND ? >= "+dateFromField+Const.CR;
sql += " AND ? < "+dateToField+Const.CR;
data.lookupRowMeta.addValueMeta( new ValueMeta(meta.getDateFrom(), ValueMetaInterface.TYPE_DATE) );
data.lookupRowMeta.addValueMeta( new ValueMeta(meta.getDateTo(), ValueMetaInterface.TYPE_DATE) );
}
try
{
logDetailed("Dimension Lookup setting preparedStatement to ["+sql+"]");
data.prepStatementLookup=data.db.getConnection().prepareStatement(databaseMeta.stripCR(sql));
if (databaseMeta.supportsSetMaxRows())
{
data.prepStatementLookup.setMaxRows(1); // alywas get only 1 line back!
}
if (databaseMeta.getDatabaseInterface() instanceof MySQLDatabaseMeta)
{
data.prepStatementLookup.setFetchSize(0); // Make sure to DISABLE Streaming Result sets
}
logDetailed("Finished preparing dimension lookup statement.");
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare dimension lookup", ex);
}
}
private boolean isAutoIncrement()
{
return techKeyCreation == CREATION_METHOD_AUTOINC;
}
/**
* This inserts new record into dimension Optionally, if the entry already
* exists, update date range from previous version of the entry.
*/
public Long dimInsert(RowMetaInterface inputRowMeta, Object[] row, Long technicalKey, boolean newEntry, Long versionNr, Date dateFrom, Date dateTo) throws KettleException {
DatabaseMeta databaseMeta = meta.getDatabaseMeta();
if (data.prepStatementInsert == null && data.prepStatementUpdate == null) // first
// time:
// construct
// prepared
// statement
{
RowMetaInterface insertRowMeta = new RowMeta();
/*
* Construct the SQL statement...
*
* INSERT INTO d_customer(keyfield, versionfield, datefrom, dateto, key[],
* fieldlookup[], last_updated, last_inserted, last_version) VALUES
* (val_key ,val_version , val_datfrom, val_datto, keynrs[], fieldnrs[],
* last_updated, last_inserted, last_version) ;
*/
String sql = "INSERT INTO " + data.schemaTable + "( ";
if (!isAutoIncrement()) {
sql += databaseMeta.quoteField(meta.getKeyField()) + ", "; // NO
// AUTOINCREMENT
insertRowMeta.addValueMeta(data.outputRowMeta.getValueMeta(inputRowMeta.size())); // the
// first
// return
// value
// after
// the
// input
} else {
if (databaseMeta.needsPlaceHolder()) {
sql += "0, "; // placeholder on informix!
}
}
sql += databaseMeta.quoteField(meta.getVersionField()) + ", " + databaseMeta.quoteField(meta.getDateFrom()) + ", " + databaseMeta.quoteField(meta.getDateTo());
insertRowMeta.addValueMeta(new ValueMeta(meta.getVersionField(), ValueMetaInterface.TYPE_INTEGER));
insertRowMeta.addValueMeta(new ValueMeta(meta.getDateFrom(), ValueMetaInterface.TYPE_DATE));
insertRowMeta.addValueMeta(new ValueMeta(meta.getDateTo(), ValueMetaInterface.TYPE_DATE));
for (int i = 0; i < meta.getKeyLookup().length; i++) {
sql += ", " + databaseMeta.quoteField(meta.getKeyLookup()[i]);
insertRowMeta.addValueMeta(inputRowMeta.getValueMeta(data.keynrs[i]));
}
for (int i = 0; i < meta.getFieldLookup().length; i++) {
// Ignore last_version, last_updated etc, they are handled below (at the
// back of the row).
//
if (!DimensionLookupMeta.isUpdateTypeWithoutArgument(meta.isUpdate(), meta.getFieldUpdate()[i])) {
sql += ", " + databaseMeta.quoteField(meta.getFieldLookup()[i]);
insertRowMeta.addValueMeta(inputRowMeta.getValueMeta(data.fieldnrs[i]));
}
}
// Finally, the special update fields...
//
for (int i = 0; i < meta.getFieldUpdate().length; i++) {
ValueMetaInterface valueMeta = null;
switch (meta.getFieldUpdate()[i]) {
case DimensionLookupMeta.TYPE_UPDATE_DATE_INSUP:
case DimensionLookupMeta.TYPE_UPDATE_DATE_INSERTED:
valueMeta = new ValueMeta(meta.getFieldLookup()[i], ValueMetaInterface.TYPE_DATE);
break;
case DimensionLookupMeta.TYPE_UPDATE_LAST_VERSION:
valueMeta = new ValueMeta(meta.getFieldLookup()[i], ValueMetaInterface.TYPE_BOOLEAN);
break;
}
if (valueMeta != null) {
sql += ", " + databaseMeta.quoteField(valueMeta.getName());
insertRowMeta.addValueMeta(valueMeta);
}
}
sql += ") VALUES (";
if (!isAutoIncrement()) {
sql += "?, ";
}
sql += "?, ?, ?";
for (int i = 0; i < data.keynrs.length; i++) {
sql += ", ?";
}
for (int i = 0; i < meta.getFieldLookup().length; i++) {
// Ignore last_version, last_updated, etc. These are handled below...
//
if (!DimensionLookupMeta.isUpdateTypeWithoutArgument(meta.isUpdate(), meta.getFieldUpdate()[i])) {
sql += ", ?";
}
}
// The special update fields...
//
for (int i = 0; i < meta.getFieldUpdate().length; i++) {
switch (meta.getFieldUpdate()[i]) {
case DimensionLookupMeta.TYPE_UPDATE_DATE_INSUP:
case DimensionLookupMeta.TYPE_UPDATE_DATE_INSERTED:
case DimensionLookupMeta.TYPE_UPDATE_LAST_VERSION:
sql += ", ?";
break;
}
}
sql += " )";
try {
if (technicalKey == null) {
logDetailed("SQL w/ return keys=[" + sql + "]");
data.prepStatementInsert = data.db.getConnection().prepareStatement(databaseMeta.stripCR(sql), Statement.RETURN_GENERATED_KEYS);
} else {
logDetailed("SQL=[" + sql + "]");
data.prepStatementInsert = data.db.getConnection().prepareStatement(databaseMeta.stripCR(sql));
}
// pstmt=con.prepareStatement(sql, new String[] { "klant_tk" } );
} catch (SQLException ex) {
throw new KettleDatabaseException("Unable to prepare dimension insert :" + Const.CR + sql, ex);
}
/*
* UPDATE d_customer SET dateto = val_datnow, last_updated = <now>
* last_version = false WHERE keylookup[] = keynrs[] AND versionfield =
* val_version - 1 ;
*/
RowMetaInterface updateRowMeta = new RowMeta();
String sql_upd = "UPDATE " + data.schemaTable + Const.CR;
// The end of the date range
//
sql_upd += "SET " + databaseMeta.quoteField(meta.getDateTo()) + " = ?" + Const.CR;
updateRowMeta.addValueMeta(new ValueMeta(meta.getDateTo(), ValueMetaInterface.TYPE_DATE));
// The special update fields...
//
for (int i = 0; i < meta.getFieldUpdate().length; i++) {
ValueMetaInterface valueMeta = null;
switch (meta.getFieldUpdate()[i]) {
case DimensionLookupMeta.TYPE_UPDATE_DATE_INSUP:
case DimensionLookupMeta.TYPE_UPDATE_DATE_UPDATED:
valueMeta = new ValueMeta(meta.getFieldLookup()[i], ValueMetaInterface.TYPE_DATE);
break;
case DimensionLookupMeta.TYPE_UPDATE_LAST_VERSION:
valueMeta = new ValueMeta(meta.getFieldLookup()[i], ValueMetaInterface.TYPE_BOOLEAN);
break;
}
if (valueMeta != null) {
sql_upd += ", " + databaseMeta.quoteField(valueMeta.getName()) + " = ?" + Const.CR;
updateRowMeta.addValueMeta(valueMeta);
}
}
sql_upd += "WHERE ";
for (int i = 0; i < meta.getKeyLookup().length; i++) {
if (i > 0)
sql_upd += "AND ";
sql_upd += databaseMeta.quoteField(meta.getKeyLookup()[i]) + " = ?" + Const.CR;
updateRowMeta.addValueMeta(inputRowMeta.getValueMeta(data.keynrs[i]));
}
sql_upd += "AND " + databaseMeta.quoteField(meta.getVersionField()) + " = ? ";
updateRowMeta.addValueMeta(new ValueMeta(meta.getVersionField(), ValueMetaInterface.TYPE_INTEGER));
try {
logDetailed("Preparing update: " + Const.CR + sql_upd + Const.CR);
data.prepStatementUpdate = data.db.getConnection().prepareStatement(databaseMeta.stripCR(sql_upd));
} catch (SQLException ex) {
throw new KettleDatabaseException("Unable to prepare dimension update :" + Const.CR + sql_upd, ex);
}
data.insertRowMeta = insertRowMeta;
data.updateRowMeta = updateRowMeta;
}
Object[] insertRow = new Object[data.insertRowMeta.size()];
int insertIndex = 0;
if (!isAutoIncrement()) {
insertRow[insertIndex++] = technicalKey;
}
// Caller is responsible for setting proper version number depending
// on if newEntry == true
insertRow[insertIndex++] = versionNr;
switch (data.startDateChoice) {
case DimensionLookupMeta.START_DATE_ALTERNATIVE_NONE:
insertRow[insertIndex++] = dateFrom;
break;
case DimensionLookupMeta.START_DATE_ALTERNATIVE_SYSDATE:
insertRow[insertIndex++] = new Date();
break;
case DimensionLookupMeta.START_DATE_ALTERNATIVE_START_OF_TRANS:
insertRow[insertIndex++] = getTrans().getStartDate();
break;
case DimensionLookupMeta.START_DATE_ALTERNATIVE_NULL:
insertRow[insertIndex++] = null;
break;
case DimensionLookupMeta.START_DATE_ALTERNATIVE_COLUMN_VALUE:
insertRow[insertIndex++] = inputRowMeta.getDate(row, data.startDateFieldIndex);
break;
default:
throw new KettleStepException(BaseMessages.getString(PKG, "DimensionLookup.Exception.IllegalStartDateSelection", Integer.toString(data.startDateChoice)));
}
insertRow[insertIndex++] = dateTo;
for (int i = 0; i < data.keynrs.length; i++) {
insertRow[insertIndex++] = row[data.keynrs[i]];
}
for (int i = 0; i < data.fieldnrs.length; i++) {
if (data.fieldnrs[i] >= 0) {
// Ignore last_version, last_updated, etc. These are handled below...
//
insertRow[insertIndex++] = row[data.fieldnrs[i]];
}
}
// The special update fields...
//
for (int i = 0; i < meta.getFieldUpdate().length; i++) {
switch (meta.getFieldUpdate()[i]) {
case DimensionLookupMeta.TYPE_UPDATE_DATE_INSUP:
case DimensionLookupMeta.TYPE_UPDATE_DATE_INSERTED:
insertRow[insertIndex++] = new Date();
break;
case DimensionLookupMeta.TYPE_UPDATE_LAST_VERSION:
insertRow[insertIndex++] = Boolean.TRUE;
break; // Always the last version on insert.
}
}
if (log.isDebug())
logDebug("rins, size=" + data.insertRowMeta.size() + ", values=" + data.insertRowMeta.getString(insertRow));
// INSERT NEW VALUE!
data.db.setValues(data.insertRowMeta, insertRow, data.prepStatementInsert);
data.db.insertRow(data.prepStatementInsert);
if (log.isDebug())
logDebug("Row inserted!");
if (isAutoIncrement()) {
try {
RowMetaAndData keys = data.db.getGeneratedKeys(data.prepStatementInsert);
if (keys.getRowMeta().size() > 0) {
technicalKey = keys.getRowMeta().getInteger(keys.getData(), 0);
} else {
throw new KettleDatabaseException("Unable to retrieve value of auto-generated technical key : no value found!");
}
} catch (Exception e) {
throw new KettleDatabaseException("Unable to retrieve value of auto-generated technical key : unexpected error: ", e);
}
}
if (!newEntry) // we have to update the previous version in the dimension!
{
/*
* UPDATE d_customer SET dateto = val_datfrom , last_updated = <now> ,
* last_version = false WHERE keylookup[] = keynrs[] AND versionfield =
* val_version - 1 ;
*/
Object[] updateRow = new Object[data.updateRowMeta.size()];
int updateIndex = 0;
switch(data.startDateChoice) {
case DimensionLookupMeta.START_DATE_ALTERNATIVE_NONE : updateRow[updateIndex++] = dateFrom; break;
case DimensionLookupMeta.START_DATE_ALTERNATIVE_SYSDATE : updateRow[updateIndex++] = new Date(); break;
case DimensionLookupMeta.START_DATE_ALTERNATIVE_START_OF_TRANS : updateRow[updateIndex++] = getTrans().getCurrentDate(); break;
case DimensionLookupMeta.START_DATE_ALTERNATIVE_NULL : updateRow[updateIndex++] = null; break;
case DimensionLookupMeta.START_DATE_ALTERNATIVE_COLUMN_VALUE : updateRow[updateIndex++] = inputRowMeta.getDate(row, data.startDateFieldIndex); break;
default:
throw new KettleStepException(BaseMessages.getString("DimensionLookup.Exception.IllegalStartDateSelection", Integer.toString(data.startDateChoice)));
}
// The special update fields...
//
for (int i = 0; i < meta.getFieldUpdate().length; i++) {
switch (meta.getFieldUpdate()[i]) {
case DimensionLookupMeta.TYPE_UPDATE_DATE_INSUP:
updateRow[updateIndex++] = new Date();
break;
case DimensionLookupMeta.TYPE_UPDATE_LAST_VERSION:
updateRow[updateIndex++] = Boolean.FALSE;
break; // Never the last version on this update
}
}
for (int i = 0; i < data.keynrs.length; i++) {
updateRow[updateIndex++] = row[data.keynrs[i]];
}
updateRow[updateIndex++] = versionNr - 1;
if (log.isRowLevel())
logRowlevel("UPDATE using rupd=" + data.updateRowMeta.getString(updateRow));
// UPDATE VALUES
// set values for update
//
data.db.setValues(data.updateRowMeta, updateRow, data.prepStatementUpdate);
if (log.isDebug()) {
logDebug("Values set for update (" + data.updateRowMeta.size() + ")");
}
data.db.insertRow(data.prepStatementUpdate); // do the actual update
if (log.isDebug()) {
logDebug("Row updated!");
}
}
return technicalKey;
}
public void dimUpdate(RowMetaInterface rowMeta, Object[] row, Long dimkey, Date valueDate) throws KettleDatabaseException {
if (data.prepStatementDimensionUpdate == null) // first time: construct
// prepared statement
{
data.dimensionUpdateRowMeta = new RowMeta();
// Construct the SQL statement...
/*
* UPDATE d_customer SET fieldlookup[] = row.getValue(fieldnrs) ,
* last_updated = <now> WHERE returnkey = dimkey ;
*/
String sql = "UPDATE " + data.schemaTable + Const.CR + "SET ";
boolean comma = false;
for (int i = 0; i < meta.getFieldLookup().length; i++) {
if (!DimensionLookupMeta.isUpdateTypeWithoutArgument(meta.isUpdate(), meta.getFieldUpdate()[i])) {
if (comma)
sql += ", ";
else
sql += " ";
comma = true;
sql += meta.getDatabaseMeta().quoteField(meta.getFieldLookup()[i]) + " = ?" + Const.CR;
data.dimensionUpdateRowMeta.addValueMeta(rowMeta.getValueMeta(data.fieldnrs[i]));
}
}
// The special update fields...
//
for (int i = 0; i < meta.getFieldUpdate().length; i++) {
ValueMetaInterface valueMeta = null;
switch (meta.getFieldUpdate()[i]) {
case DimensionLookupMeta.TYPE_UPDATE_DATE_INSUP:
case DimensionLookupMeta.TYPE_UPDATE_DATE_UPDATED:
valueMeta = new ValueMeta(meta.getFieldLookup()[i], ValueMetaInterface.TYPE_DATE);
break;
}
if (valueMeta != null) {
if (comma)
sql += ", ";
else
sql += " ";
comma = true;
sql += meta.getDatabaseMeta().quoteField(valueMeta.getName()) + " = ?" + Const.CR;
data.dimensionUpdateRowMeta.addValueMeta(valueMeta);
}
}
sql += "WHERE " + meta.getDatabaseMeta().quoteField(meta.getKeyField()) + " = ?";
data.dimensionUpdateRowMeta.addValueMeta(new ValueMeta(meta.getKeyField(), ValueMetaInterface.TYPE_INTEGER)); // The
// tk
try {
if (log.isDebug())
logDebug("Preparing statement: [" + sql + "]");
data.prepStatementDimensionUpdate = data.db.getConnection().prepareStatement(meta.getDatabaseMeta().stripCR(sql));
} catch (SQLException ex) {
throw new KettleDatabaseException("Couldn't prepare statement :" + Const.CR + sql, ex);
}
}
// Assemble information
// New
Object[] dimensionUpdateRow = new Object[data.dimensionUpdateRowMeta.size()];
int updateIndex = 0;
for (int i = 0; i < data.fieldnrs.length; i++) {
// Ignore last_version, last_updated, etc. These are handled below...
//
if (data.fieldnrs[i] >= 0) {
dimensionUpdateRow[updateIndex++] = row[data.fieldnrs[i]];
}
}
for (int i = 0; i < meta.getFieldUpdate().length; i++) {
switch (meta.getFieldUpdate()[i]) {
case DimensionLookupMeta.TYPE_UPDATE_DATE_INSUP:
case DimensionLookupMeta.TYPE_UPDATE_DATE_UPDATED:
dimensionUpdateRow[updateIndex++] = valueDate;
break;
}
}
dimensionUpdateRow[updateIndex++] = dimkey;
data.db.setValues(data.dimensionUpdateRowMeta, dimensionUpdateRow, data.prepStatementDimensionUpdate);
data.db.insertRow(data.prepStatementDimensionUpdate);
}
// This updates all versions of a dimension entry.
//
public void dimPunchThrough(RowMetaInterface rowMeta, Object[] row) throws KettleDatabaseException
{
if (data.prepStatementPunchThrough==null) // first time: construct prepared statement
{
data.punchThroughRowMeta = new RowMeta();
/*
* UPDATE table
* SET punchv1 = fieldx, ...
* , last_updated = <now>
* WHERE keylookup[] = keynrs[]
* ;
*/
String sql_upd="UPDATE "+data.schemaTable+Const.CR;
sql_upd+="SET ";
boolean first=true;
for (int i=0;i<meta.getFieldLookup().length;i++)
{
if (meta.getFieldUpdate()[i]==DimensionLookupMeta.TYPE_UPDATE_DIM_PUNCHTHROUGH)
{
if (!first) sql_upd+=", "; else sql_upd+=" ";
first=false;
sql_upd+=meta.getFieldLookup()[i]+" = ?"+Const.CR;
data.punchThroughRowMeta.addValueMeta( rowMeta.getValueMeta(data.fieldnrs[i]) );
}
}
// The special update fields...
//
for (int i=0;i<meta.getFieldUpdate().length;i++) {
ValueMetaInterface valueMeta = null;
switch(meta.getFieldUpdate()[i]) {
case DimensionLookupMeta.TYPE_UPDATE_DATE_INSUP :
case DimensionLookupMeta.TYPE_UPDATE_DATE_UPDATED : valueMeta = new ValueMeta(meta.getFieldLookup()[i], ValueMetaInterface.TYPE_DATE); break;
}
if (valueMeta!=null) {
sql_upd+=", "+meta.getDatabaseMeta().quoteField(valueMeta.getName()) +" = ?"+Const.CR;
data.punchThroughRowMeta.addValueMeta(valueMeta);
}
}
sql_upd+="WHERE ";
for (int i=0;i<meta.getKeyLookup().length;i++)
{
if (i>0) sql_upd+="AND ";
sql_upd+=meta.getKeyLookup()[i]+" = ?"+Const.CR;
data.punchThroughRowMeta.addValueMeta( rowMeta.getValueMeta(data.keynrs[i]) );
}
try
{
data.prepStatementPunchThrough=data.db.getConnection().prepareStatement(meta.getDatabaseMeta().stripCR(sql_upd));
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare dimension punchThrough update statement : "+Const.CR+sql_upd, ex);
}
}
Object[] punchThroughRow = new Object[data.punchThroughRowMeta.size()];
int punchIndex=0;
for (int i=0;i<meta.getFieldLookup().length;i++)
{
if (meta.getFieldUpdate()[i]==DimensionLookupMeta.TYPE_UPDATE_DIM_PUNCHTHROUGH)
{
punchThroughRow[punchIndex++] = row[ data.fieldnrs[i] ];
}
}
for (int i=0;i<meta.getFieldUpdate().length;i++) {
switch(meta.getFieldUpdate()[i]) {
case DimensionLookupMeta.TYPE_UPDATE_DATE_INSUP :
case DimensionLookupMeta.TYPE_UPDATE_DATE_UPDATED : punchThroughRow[punchIndex++] = new Date(); break;
}
}
for (int i=0;i<data.keynrs.length;i++)
{
punchThroughRow[punchIndex++] = row[ data.keynrs[i] ];
}
// UPDATE VALUES
data.db.setValues(data.punchThroughRowMeta, punchThroughRow, data.prepStatementPunchThrough); // set values for update
data.db.insertRow(data.prepStatementPunchThrough); // do the actual punch through update
}
/**
* Keys:
* - natural key fields
* Values:
* - Technical key
* - lookup fields / extra fields (allows us to compare or retrieve)
* - Date_from
* - Date_to
*
* @param row The input row
* @param technicalKey the technical key value
* @param valueDateFrom the start of valid date range
* @param valueDateTo the end of the valid date range
* @return the values to store in the cache as a row.
*/
private Object[] getCacheValues(RowMetaInterface rowMeta, Object[] row, Long technicalKey, Long valueVersion, Date valueDateFrom, Date valueDateTo)
{
if (data.cacheValueRowMeta==null) return null; // nothing is in the cache.
Object[] cacheValues = new Object[data.cacheValueRowMeta.size()];
int cacheIndex = 0;
cacheValues[cacheIndex++] = technicalKey;
cacheValues[cacheIndex++] = valueVersion;
for (int i=0;i<data.fieldnrs.length;i++)
{
// Ignore last_version, last_updated, etc. These are handled below...
//
if (data.fieldnrs[i]>=0) {
cacheValues[cacheIndex++] = row[ data.fieldnrs[i] ];
}
}
cacheValues[cacheIndex++] = valueDateFrom;
cacheValues[cacheIndex++] = valueDateTo;
return cacheValues;
}
/**
* Adds a row to the cache
* In case we are doing updates, we need to store the complete rows from the database.
* These are the values we need to store
*
* Key:
* - natural key fields
* Value:
* - Technical key
* - lookup fields / extra fields (allows us to compare or retrieve)
* - Date_from
* - Date_to
*
* @param keyValues
* @param returnValues
* @throws KettleValueException
*/
private void addToCache(Object[] keyValues, Object[] returnValues) throws KettleValueException
{
if (data.cacheValueRowMeta==null)
{
data.cacheValueRowMeta = assembleCacheValueRowMeta();
}
// store it in the cache if needed.
byte[] keyPart = RowMeta.extractData(data.cacheKeyRowMeta, keyValues);
byte[] valuePart = RowMeta.extractData(data.cacheValueRowMeta, returnValues);
data.cache.put(keyPart, valuePart);
// check if the size is not too big...
// Allow for a buffer overrun of 20% and then remove those 20% in one go.
// Just to keep performance in track.
//
int tenPercent = meta.getCacheSize()/10;
if (meta.getCacheSize()>0 && data.cache.size()>meta.getCacheSize()+tenPercent)
{
// Which cache entries do we delete here?
// We delete those with the lowest technical key...
// Those would arguably be the "oldest" dimension entries.
// Oh well... Nothing is going to be perfect here...
//
// Getting the lowest 20% requires some kind of sorting algorithm and I'm not sure we want to do that.
// Sorting is slow and even in the best case situation we need to do 2 passes over the cache entries...
//
// Perhaps we should get 20% random values and delete everything below the lowest but one TK.
//
List<byte[]> keys = data.cache.getKeys();
int sizeBefore = keys.size();
List<Long> samples = new ArrayList<Long>();
// Take 10 sample technical keys....
int stepsize=keys.size()/5;
if (stepsize<1) stepsize=1; //make shure we have no endless loop
for (int i=0;i<keys.size();i+=stepsize)
{
byte[] key = (byte[]) keys.get(i);
byte[] value = data.cache.get(key);
if (value!=null)
{
Object[] values = RowMeta.getRow(data.cacheValueRowMeta, value);
Long tk = data.cacheValueRowMeta.getInteger(values, 0);
samples.add(tk);
}
}
// Sort these 5 elements...
Collections.sort(samples);
// What is the smallest?
// Take the second, not the fist in the list, otherwise we would be removing a single entry = not good.
if (samples.size()>1) {
data.smallestCacheKey = samples.get(1);
} else if (!samples.isEmpty()) { // except when there is only one sample
data.smallestCacheKey = samples.get(0);
} else {
// If no samples found nothing to remove, we're done
return;
}
// Remove anything in the cache <= smallest.
// This makes it almost single pass...
// This algorithm is not 100% correct, but I guess it beats sorting the whole cache all the time.
//
for (int i=0;i<keys.size();i++)
{
byte[] key = (byte[]) keys.get(i);
byte[] value = data.cache.get(key);
if (value!=null)
{
Object[] values = RowMeta.getRow(data.cacheValueRowMeta, value);
long tk = data.cacheValueRowMeta.getInteger(values, 0).longValue();
if (tk<=data.smallestCacheKey)
{
data.cache.remove(key); // this one has to go.
}
}
}
int sizeAfter = data.cache.size();
logDetailed("Reduced the lookup cache from "+sizeBefore+" to "+sizeAfter+" rows.");
}
if (log.isRowLevel()) logRowlevel("Cache store: key="+keyValues+" values="+returnValues);
}
/**
* @return the cache value row metadata.
* The items that are cached is basically the return row metadata:<br>
* - Technical key (Integer)
* - Version (Integer)
* -
*/
private RowMetaInterface assembleCacheValueRowMeta() {
RowMetaInterface cacheRowMeta = data.returnRowMeta.clone();
// The technical key and version are always an Integer...
//
/*
cacheRowMeta.getValueMeta(0).setType(ValueMetaInterface.TYPE_INTEGER);
cacheRowMeta.getValueMeta(1).setType(ValueMetaInterface.TYPE_INTEGER);
*/
return cacheRowMeta;
}
private Object[] getFromCache(Object[] keyValues, Date dateValue) throws KettleValueException
{
if (data.cacheValueRowMeta==null)
{
// nothing in the cache yet, no lookup was ever performed
if (data.returnRowMeta==null) return null;
data.cacheValueRowMeta = assembleCacheValueRowMeta();
}
byte[] key = RowMeta.extractData(data.cacheKeyRowMeta, keyValues);
byte[] value = data.cache.get(key);
if (value!=null)
{
Object[] row = RowMeta.getRow(data.cacheValueRowMeta, value);
// See if the dateValue is between the from and to date ranges...
// The last 2 values are from and to
long time = dateValue.getTime();
long from = ((Date)row[row.length-2]).getTime();
long to = ((Date)row[row.length-1]).getTime();
if (time>=from && time<to) // sanity check to see if we have the right version
{
if (log.isRowLevel()) logRowlevel("Cache hit: key="+data.cacheKeyRowMeta.getString(keyValues)+" values="+data.cacheValueRowMeta.getString(row));
return row;
}
}
return null;
}
public void checkDimZero() throws KettleException
{
// Don't insert anything when running in lookup mode.
//
if (!meta.isUpdate()) return;
DatabaseMeta databaseMeta = meta.getDatabaseMeta();
if (meta.isAutoIncrement()) {
// See if there are rows in the table
// If so, we can't insert the unknown row anymore...
//
String sql = "SELECT count(*) FROM "+data.schemaTable;
RowMetaAndData r = data.db.getOneRow(sql);
Long count = r.getRowMeta().getInteger(r.getData(), 0);
if (count.longValue() != 0)
{
return; // Can't insert below the rows already in there...
}
}
int start_tk = databaseMeta.getNotFoundTK(isAutoIncrement());
String sql = "SELECT count(*) FROM "+data.schemaTable+" WHERE "+databaseMeta.quoteField(meta.getKeyField())+" = "+start_tk;
RowMetaAndData r = data.db.getOneRow(sql);
Long count = r.getRowMeta().getInteger(r.getData(), 0);
if (count.longValue() == 0)
{
String isql = null;
try
{
if (!databaseMeta.supportsAutoinc() || !isAutoIncrement())
{
isql = "insert into "+data.schemaTable+"("+databaseMeta.quoteField(meta.getKeyField())+", "+databaseMeta.quoteField(meta.getVersionField())+") values (0, 1)";
}
else
{
isql = databaseMeta.getSQLInsertAutoIncUnknownDimensionRow(data.schemaTable, databaseMeta.quoteField(meta.getKeyField()), databaseMeta.quoteField(meta.getVersionField()));
}
data.db.execStatement(databaseMeta.stripCR(isql));
}
catch(KettleException e)
{
throw new KettleDatabaseException("Error inserting 'unknown' row in dimension ["+data.schemaTable+"] : "+isql, e);
}
}
}
public boolean init(StepMetaInterface smi, StepDataInterface sdi)
{
meta=(DimensionLookupMeta)smi;
data=(DimensionLookupData)sdi;
if (super.init(smi, sdi))
{
data.min_date = meta.getMinDate(); //$NON-NLS-1$
data.max_date = meta.getMaxDate(); //$NON-NLS-1$
data.realSchemaName=environmentSubstitute(meta.getSchemaName());
data.realTableName=environmentSubstitute(meta.getTableName());
data.startDateChoice = DimensionLookupMeta.START_DATE_ALTERNATIVE_NONE;
if (meta.isUsingStartDateAlternative()) data.startDateChoice = meta.getStartDateAlternative();
data.db=new Database(this, meta.getDatabaseMeta());
data.db.shareVariablesWith(this);
try
{
if (getTransMeta().isUsingUniqueConnections())
{
synchronized (getTrans()) { data.db.connect(getTrans().getThreadName(), getPartitionID()); }
}
else
{
data.db.connect(getPartitionID());
}
if (log.isDetailed()) logDetailed(BaseMessages.getString(PKG, "DimensionLookup.Log.ConnectedToDB")); //$NON-NLS-1$
data.db.setCommit(meta.getCommitSize());
return true;
}
catch(KettleException ke)
{
logError(BaseMessages.getString(PKG, "DimensionLookup.Log.ErrorOccurredInProcessing")+ke.getMessage()); //$NON-NLS-1$
}
}
return false;
}
public void dispose(StepMetaInterface smi, StepDataInterface sdi)
{
meta = (DimensionLookupMeta)smi;
data = (DimensionLookupData)sdi;
try
{
if (!data.db.isAutoCommit())
{
if (getErrors()==0)
{
data.db.commit();
}
else
{
data.db.rollback();
}
}
}
catch(KettleDatabaseException e)
{
logError(BaseMessages.getString(PKG, "DimensionLookup.Log.ErrorOccurredInProcessing")+e.getMessage()); //$NON-NLS-1$
}
finally
{
if (data.db!=null) {
data.db.disconnect();
}
}
super.dispose(smi, sdi);
}
}
|
src/org/pentaho/di/trans/steps/dimensionlookup/DimensionLookup.java
|
/* Copyright (c) 2007 Pentaho Corporation. All rights reserved.
* This software was developed by Pentaho Corporation and is provided under the terms
* of the GNU Lesser General Public License, Version 2.1. You may not use
* this file except in compliance with the license. If you need a copy of the license,
* please go to http://www.gnu.org/licenses/lgpl-2.1.txt. The Original Code is Pentaho
* Data Integration. The Initial Developer is Pentaho Corporation.
*
* Software distributed under the GNU Lesser Public License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to
* the license for the specific language governing your rights and limitations.*/
package org.pentaho.di.trans.steps.dimensionlookup;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.RowMetaAndData;
import org.pentaho.di.core.database.Database;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.database.MySQLDatabaseMeta;
import org.pentaho.di.core.exception.KettleDatabaseException;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleStepException;
import org.pentaho.di.core.exception.KettleValueException;
import org.pentaho.di.core.hash.ByteArrayHashMap;
import org.pentaho.di.core.row.RowMeta;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMeta;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStep;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;
/**
* Manages a slowly changing dimension (lookup or update)
*
* @author Matt
* @since 14-may-2003
*/
public class DimensionLookup extends BaseStep implements StepInterface
{
private static Class<?> PKG = DimensionLookupMeta.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$
private final static int CREATION_METHOD_AUTOINC = 1;
private final static int CREATION_METHOD_SEQUENCE = 2;
private final static int CREATION_METHOD_TABLEMAX = 3;
private int techKeyCreation;
private DimensionLookupMeta meta;
private DimensionLookupData data;
public DimensionLookup(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans)
{
super(stepMeta, stepDataInterface, copyNr, transMeta, trans);
}
private void setTechKeyCreation(int method)
{
techKeyCreation = method;
}
private int getTechKeyCreation()
{
return techKeyCreation;
}
private void determineTechKeyCreation()
{
String keyCreation = meta.getTechKeyCreation();
if (meta.getDatabaseMeta().supportsAutoinc() &&
DimensionLookupMeta.CREATION_METHOD_AUTOINC.equals(keyCreation) )
{
setTechKeyCreation(CREATION_METHOD_AUTOINC);
}
else if (meta.getDatabaseMeta().supportsSequences() &&
DimensionLookupMeta.CREATION_METHOD_SEQUENCE.equals(keyCreation) )
{
setTechKeyCreation(CREATION_METHOD_SEQUENCE);
}
else
{
setTechKeyCreation(CREATION_METHOD_TABLEMAX);
}
}
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException
{
meta=(DimensionLookupMeta)smi;
data=(DimensionLookupData)sdi;
Object[] r=getRow(); // Get row from input rowset & set row busy!
if (r==null) // no more input to be expected...
{
setOutputDone(); // signal end to receiver(s)
return false;
}
if (first)
{
first=false;
data.schemaTable = meta.getDatabaseMeta().getQuotedSchemaTableCombination(data.realSchemaName, data.realTableName);
data.inputRowMeta = getInputRowMeta().clone();
data.outputRowMeta = getInputRowMeta().clone();
meta.getFields(data.outputRowMeta, getStepname(), null, null, this);
// Get the fields that need conversion to normal storage...
// Modify the storage type of the input data...
//
data.lazyList = new ArrayList<Integer>();
for (int i=0;i<data.inputRowMeta.size();i++) {
ValueMetaInterface valueMeta = data.inputRowMeta.getValueMeta(i);
if (valueMeta.isStorageBinaryString()) {
data.lazyList.add(i);
valueMeta.setStorageType(ValueMetaInterface.STORAGE_TYPE_NORMAL);
}
}
// The start date value column (if applicable)
//
data.startDateFieldIndex = -1;
if (data.startDateChoice==DimensionLookupMeta.START_DATE_ALTERNATIVE_COLUMN_VALUE) {
data.startDateFieldIndex = data.inputRowMeta.indexOfValue(meta.getStartDateFieldName());
if (data.startDateFieldIndex<0) {
throw new KettleStepException(BaseMessages.getString(PKG, "DimensionLookup.Exception.StartDateValueColumnNotFound", meta.getStartDateFieldName()));
}
}
// Lookup values
data.keynrs = new int[meta.getKeyStream().length];
for (int i=0;i<meta.getKeyStream().length;i++)
{
//logDetailed("Lookup values key["+i+"] --> "+key[i]+", row==null?"+(row==null));
data.keynrs[i]=data.inputRowMeta.indexOfValue(meta.getKeyStream()[i]);
if (data.keynrs[i]<0) // couldn't find field!
{
throw new KettleStepException(BaseMessages.getString(PKG, "DimensionLookup.Exception.KeyFieldNotFound",meta.getKeyStream()[i])); //$NON-NLS-1$ //$NON-NLS-2$
}
}
// Return values
data.fieldnrs = new int[meta.getFieldStream().length];
for (int i=0;meta.getFieldStream()!=null && i<meta.getFieldStream().length;i++)
{
if (!DimensionLookupMeta.isUpdateTypeWithoutArgument(meta.isUpdate(), meta.getFieldUpdate()[i])) {
data.fieldnrs[i]=data.outputRowMeta.indexOfValue(meta.getFieldStream()[i]);
if (data.fieldnrs[i] < 0)
{
throw new KettleStepException(BaseMessages.getString(PKG, "DimensionLookup.Exception.KeyFieldNotFound", meta.getFieldStream()[i])); //$NON-NLS-1$ //$NON-NLS-2$
}
} else {
data.fieldnrs[i]=-1;
}
}
if (!meta.isUpdate() && meta.isPreloadingCache()) {
preloadCache();
} else {
// Caching...
//
if (data.cacheKeyRowMeta==null)
{
// KEY : the natural key(s)
//
data.cacheKeyRowMeta = new RowMeta();
for (int i=0;i<data.keynrs.length;i++)
{
ValueMetaInterface key = data.inputRowMeta.getValueMeta(data.keynrs[i]);
data.cacheKeyRowMeta.addValueMeta( key.clone());
}
data.cache = new ByteArrayHashMap(meta.getCacheSize()>0 ? meta.getCacheSize() : 5000, data.cacheKeyRowMeta);
}
}
if (!Const.isEmpty(meta.getDateField()))
{
data.datefieldnr = data.inputRowMeta.indexOfValue(meta.getDateField());
}
else
{
data.datefieldnr=-1;
}
// Initialize the start date value in case we don't have one in the input rows
//
data.valueDateNow = determineDimensionUpdatedDate(r);
determineTechKeyCreation();
data.notFoundTk = new Long( (long)meta.getDatabaseMeta().getNotFoundTK(isAutoIncrement()) );
// if (meta.getKeyRename()!=null && meta.getKeyRename().length()>0) data.notFoundTk.setName(meta.getKeyRename());
if (getCopy()==0) checkDimZero();
setDimLookup(data.outputRowMeta);
}
// convert row to normal storage...
//
for (int lazyFieldIndex : data.lazyList) {
ValueMetaInterface valueMeta = getInputRowMeta().getValueMeta(lazyFieldIndex);
r[lazyFieldIndex] = valueMeta.convertToNormalStorageType(r[lazyFieldIndex]);
}
try
{
Object[] outputRow = lookupValues(data.inputRowMeta, r); // add new values to the row in rowset[0].
putRow(data.outputRowMeta, outputRow); // copy row to output rowset(s);
if (checkFeedback(getLinesRead()))
{
if(log.isBasic()) logBasic(BaseMessages.getString(PKG, "DimensionLookup.Log.LineNumber")+getLinesRead()); //$NON-NLS-1$
}
}
catch(KettleException e)
{
logError(BaseMessages.getString(PKG, "DimensionLookup.Log.StepCanNotContinueForErrors", e.getMessage())); //$NON-NLS-1$ //$NON-NLS-2$
logError(Const.getStackTracker(e)); //$NON-NLS-1$ //$NON-NLS-2$
setErrors(1);
stopAll();
setOutputDone(); // signal end to receiver(s)
return false;
}
return true;
}
private Date determineDimensionUpdatedDate(Object[] row) throws KettleException {
if (data.datefieldnr < 0) {
return getTrans().getCurrentDate(); // start of transformation...
} else {
return data.inputRowMeta.getDate(row, data.datefieldnr); // Date field in the input row
}
}
/**
* Pre-load the cache by reading the whole dimension table from disk...
*
* @throws in case there is a database or cache problem.
*/
private void preloadCache() throws KettleException{
try {
DatabaseMeta databaseMeta = meta.getDatabaseMeta();
// tk, version, from, to, natural keys, retrieval fields...
//
String sql = "SELECT "+databaseMeta.quoteField(meta.getKeyField());
// sql+=", "+databaseMeta.quoteField(meta.getVersionField());
for (int i=0;i<meta.getKeyLookup().length;i++) {
sql+=", "+meta.getKeyLookup()[i]; // the natural key field in the table
}
for (int i=0;i<meta.getFieldLookup().length;i++) {
sql+=", "+meta.getFieldLookup()[i]; // the extra fields to retrieve...
}
sql+=", "+databaseMeta.quoteField(meta.getDateFrom()); // extra info in cache
sql+=", "+databaseMeta.quoteField(meta.getDateTo()); // extra info in cache
sql+=" FROM "+data.schemaTable;
logDetailed("Pre-loading cache by reading from database with: "+Const.CR+sql+Const.CR);
List<Object[]> rows = data.db.getRows(sql, -1);
RowMetaInterface rowMeta = data.db.getReturnRowMeta();
data.preloadKeyIndexes = new int[meta.getKeyLookup().length];
for (int i=0;i<data.preloadKeyIndexes.length;i++) {
data.preloadKeyIndexes[i] = rowMeta.indexOfValue(meta.getKeyLookup()[i]); // the field in the table
}
data.preloadFromDateIndex = rowMeta.indexOfValue(meta.getDateFrom());
data.preloadToDateIndex = rowMeta.indexOfValue(meta.getDateTo());
data.preloadCache = new DimensionCache(rowMeta, data.preloadKeyIndexes, data.preloadFromDateIndex, data.preloadToDateIndex);
data.preloadCache.setRowCache(rows);
logDetailed("Sorting the cache rows...");
data.preloadCache.sortRows();
logDetailed("Sorting of cached rows finished.");
// Also see what indexes to take to populate the lookup row...
// We only ever compare indexes and the lookup date in the cache, the rest is not needed...
//
data.preloadIndexes = new ArrayList<Integer>();
for (int i=0;i<meta.getKeyStream().length;i++) {
int index = data.inputRowMeta.indexOfValue(meta.getKeyStream()[i]);
if (index<0) {
// Just to be safe...
//
throw new KettleStepException(BaseMessages.getString(PKG, "DimensionLookup.Exception.KeyFieldNotFound", meta.getFieldStream()[i])); //$NON-NLS-1$ //$NON-NLS-2$
}
data.preloadIndexes.add(index);
}
// This is all for now...
} catch(Exception e) {
throw new KettleException("Error encountered during cache pre-load", e);
}
}
private synchronized Object[] lookupValues(RowMetaInterface rowMeta, Object[] row) throws KettleException {
Object[] outputRow = new Object[data.outputRowMeta.size()];
RowMetaInterface lookupRowMeta;
Object[] lookupRow;
Object[] returnRow = null;
Long technicalKey;
Long valueVersion;
Date valueDate = null;
Date valueDateFrom = null;
Date valueDateTo = null;
// Determine the lookup date ("now") if we have a field that carries said
// date.
// If not, the system date is taken.
//
valueDate = determineDimensionUpdatedDate(row);
if (!meta.isUpdate() && meta.isPreloadingCache()) {
// Obtain a result row from the pre-load cache...
//
// Create a row to compare with
//
RowMetaInterface preloadRowMeta = data.preloadCache.getRowMeta();
// In this case it's all the same. (simple)
//
data.returnRowMeta = data.preloadCache.getRowMeta();
lookupRowMeta = preloadRowMeta;
lookupRow = new Object[preloadRowMeta.size()];
// Assemble the lookup row, convert data if needed...
//
for (int i = 0; i < data.preloadIndexes.size(); i++) {
int from = data.preloadIndexes.get(i); // Input row index
int to = data.preloadCache.getKeyIndexes()[i]; // Lookup row index
// From data type...
//
ValueMetaInterface fromValueMeta = rowMeta.getValueMeta(from);
// to date type...
//
ValueMetaInterface toValueMeta = data.preloadCache.getRowMeta().getValueMeta(to);
// From value:
//
Object fromData = row[from];
// To value:
//
Object toData = toValueMeta.convertData(fromValueMeta, fromData);
// Set the key in the row...
//
lookupRow[to] = toData;
}
// Also set the lookup date on the "end of date range" (toDate) position
//
lookupRow[data.preloadFromDateIndex] = valueDate;
// Look up the row in the pre-load cache...
//
int index = data.preloadCache.lookupRow(lookupRow);
if (index >= 0) {
returnRow = data.preloadCache.getRow(index);
} else {
returnRow = null; // Nothing found!
}
} else {
lookupRow = new Object[data.lookupRowMeta.size()];
lookupRowMeta = data.lookupRowMeta;
// Construct the lookup row...
//
for (int i = 0; i < meta.getKeyStream().length; i++) {
try {
lookupRow[i] = row[data.keynrs[i]];
} catch (Exception e) // TODO : remove exception??
{
throw new KettleStepException(BaseMessages.getString(PKG, "DimensionLookup.Exception.ErrorDetectedInGettingKey", i + "", data.keynrs[i] + "/" + rowMeta.size(), rowMeta.getString(row))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
}
}
lookupRow[meta.getKeyStream().length] = valueDate; // ? >= date_from
lookupRow[meta.getKeyStream().length + 1] = valueDate; // ? < date_to
if (log.isDebug())
logDebug(BaseMessages.getString(PKG, "DimensionLookup.Log.LookupRow") + data.lookupRowMeta.getString(lookupRow)); //$NON-NLS-1$ //$NON-NLS-2$
// Do the lookup and see if we can find anything in the database.
// But before that, let's see if we can find anything in the cache
//
if (meta.getCacheSize() >= 0) {
returnRow = getFromCache(lookupRow, valueDate);
}
// Nothing found in the cache?
// Perform the lookup in the database...
//
if (returnRow == null) {
data.db.setValues(data.lookupRowMeta, lookupRow, data.prepStatementLookup);
returnRow = data.db.getLookup(data.prepStatementLookup);
data.returnRowMeta = data.db.getReturnRowMeta();
incrementLinesInput();
if (returnRow != null && meta.getCacheSize() >= 0) {
addToCache(lookupRow, returnRow);
}
}
}
// This next block of code handles the dimension key LOOKUP ONLY.
// We handle this case where "update = false" first for performance reasons
//
if (!meta.isUpdate()) {
if (returnRow == null) {
returnRow = new Object[data.returnRowMeta.size()];
returnRow[0] = data.notFoundTk;
if (meta.getCacheSize() >= 0) // need -oo to +oo as well...
{
returnRow[returnRow.length - 2] = data.min_date;
returnRow[returnRow.length - 1] = data.max_date;
}
} else {
// We found the return values in row "add".
// Throw away the version nr...
// add.removeValue(1);
// Rename the key field if needed. Do it directly in the row...
// if (meta.getKeyRename()!=null && meta.getKeyRename().length()>0)
// add.getValue(0).setName(meta.getKeyRename());
}
} else
// This is the "update=true" case where we update the dimension table...
// It is an "Insert - update" algorithm for slowly changing dimensions
//
{
// The dimension entry was not found, we need to add it!
//
if (returnRow == null) {
if (log.isRowLevel()) {
logRowlevel(BaseMessages.getString(PKG, "DimensionLookup.Log.NoDimensionEntryFound") + lookupRowMeta.getString(lookupRow) + ")"); //$NON-NLS-1$ //$NON-NLS-2$
}
// Date range: ]-oo,+oo[
//
valueDateFrom = data.min_date;
valueDateTo = data.max_date;
valueVersion = new Long(1L); // Versions always start at 1.
// get a new value from the sequence generator chosen.
//
technicalKey = null;
switch (getTechKeyCreation()) {
case CREATION_METHOD_TABLEMAX:
// What's the next value for the technical key?
technicalKey = data.db.getNextValue(getTransMeta().getCounters(), data.realSchemaName, data.realTableName, meta.getKeyField());
break;
case CREATION_METHOD_AUTOINC:
technicalKey = null; // Set to null to flag auto-increment usage
break;
case CREATION_METHOD_SEQUENCE:
technicalKey = data.db.getNextSequenceValue(data.realSchemaName, meta.getSequenceName(), meta.getKeyField());
if (technicalKey != null && log.isRowLevel())
logRowlevel(BaseMessages.getString(PKG, "DimensionLookup.Log.FoundNextSequence") + technicalKey.toString()); //$NON-NLS-1$
break;
}
/*
* INSERT INTO table(version, datefrom, dateto, fieldlookup)
* VALUES(valueVersion, valueDateFrom, valueDateTo, row.fieldnrs) ;
*/
technicalKey = dimInsert(data.inputRowMeta, row, technicalKey, true, valueVersion, valueDateFrom, valueDateTo);
incrementLinesOutput();
returnRow = new Object[data.returnRowMeta.size()];
int returnIndex = 0;
returnRow[returnIndex] = technicalKey;
returnIndex++;
// See if we need to store this record in the cache as well...
/*
* TODO: we can't really assume like this that the cache layout of the
* incoming rows (below) is the same as the stored data. Storing this in
* the cache gives us data/metadata collision errors. (class cast
* problems etc) Perhaps we need to convert this data to the target data
* types. Alternatively, we can use a separate cache in the future.
* Reference: PDI-911
*
* if (meta.getCacheSize()>=0) { Object[] values =
* getCacheValues(rowMeta, row, technicalKey, valueVersion,
* valueDateFrom, valueDateTo);
*
* // put it in the cache... if (values!=null) { addToCache(lookupRow,
* values); } }
*/
if (log.isRowLevel())
logRowlevel(BaseMessages.getString(PKG, "DimensionLookup.Log.AddedDimensionEntry") + data.returnRowMeta.getString(returnRow)); //$NON-NLS-1$
} else
//
// The entry was found: do we need to insert, update or both?
//
{
if (log.isRowLevel())
logRowlevel(BaseMessages.getString(PKG, "DimensionLookup.Log.DimensionEntryFound") + data.returnRowMeta.getString(returnRow)); //$NON-NLS-1$
// What's the key? The first value of the return row
technicalKey = data.returnRowMeta.getInteger(returnRow, 0);
valueVersion = data.returnRowMeta.getInteger(returnRow, 1);
// Date range: ]-oo,+oo[
valueDateFrom = meta.getMinDate();
valueDateTo = meta.getMaxDate();
// The other values, we compare with
int cmp;
// If everything is the same: don't do anything
// If one of the fields is different: insert or update
// If all changed fields have update = Y, update
// If one of the changed fields has update = N, insert
boolean insert = false;
boolean identical = true;
boolean punch = false;
for (int i = 0; i < meta.getFieldStream().length; i++) {
if (data.fieldnrs[i] >= 0) {
// Only compare real fields, not last updated row, last version, etc
//
ValueMetaInterface v1 = data.outputRowMeta.getValueMeta(data.fieldnrs[i]);
Object valueData1 = row[data.fieldnrs[i]];
ValueMetaInterface v2 = data.returnRowMeta.getValueMeta(i + 2);
Object valueData2 = returnRow[i + 2];
try {
cmp = v1.compare(valueData1, v2, valueData2);
} catch (ClassCastException e) {
throw e;
}
// Not the same and update = 'N' --> insert
if (cmp != 0)
identical = false;
// Field flagged for insert: insert
if (cmp != 0 && meta.getFieldUpdate()[i] == DimensionLookupMeta.TYPE_UPDATE_DIM_INSERT) {
insert = true;
}
// Field flagged for punchthrough
if (cmp != 0 && meta.getFieldUpdate()[i] == DimensionLookupMeta.TYPE_UPDATE_DIM_PUNCHTHROUGH) {
punch = true;
}
if (log.isRowLevel())
logRowlevel(BaseMessages.getString(PKG, "DimensionLookup.Log.ComparingValues", "" + v1, "" + v2, String.valueOf(cmp), String.valueOf(identical), String.valueOf(insert), String.valueOf(punch))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
}
}
// After comparing the record in the database and the data in the input
// and taking into account the rules of the slowly changing dimension,
// we found out whether or not to perform an insert or an update.
//
if (!insert) // Just an update of row at key = valueKey
{
if (!identical) {
if (log.isRowLevel())
logRowlevel(BaseMessages.getString(PKG, "DimensionLookup.Log.UpdateRowWithValues") + data.inputRowMeta.getString(row)); //$NON-NLS-1$
/*
* UPDATE d_customer SET fieldlookup[] = row.getValue(fieldnrs)
* WHERE returnkey = dimkey
*/
dimUpdate(rowMeta, row, technicalKey, valueDate);
incrementLinesUpdated();
// We need to capture this change in the cache as well...
if (meta.getCacheSize() >= 0) {
Object[] values = getCacheValues(rowMeta, row, technicalKey, valueVersion, valueDateFrom, valueDateTo);
addToCache(lookupRow, values);
}
} else {
if (log.isRowLevel())
logRowlevel(BaseMessages.getString(PKG, "DimensionLookup.Log.SkipLine")); //$NON-NLS-1$
// Don't do anything, everything is file in de dimension.
incrementLinesSkipped();
}
} else {
if (log.isRowLevel())
logRowlevel(BaseMessages.getString(PKG, "DimensionLookup.Log.InsertNewVersion") + technicalKey.toString()); //$NON-NLS-1$
Long valueNewVersion = valueVersion + 1;
// From date (valueDate) is calculated at the start of this method to
// be either the system date or the value in a column
//
valueDateFrom = valueDate;
valueDateTo = data.max_date; //$NON-NLS-1$
// First try to use an AUTOINCREMENT field
if (meta.getDatabaseMeta().supportsAutoinc() && isAutoIncrement()) {
technicalKey = new Long(0L); // value to accept new key...
} else
// Try to get the value by looking at a SEQUENCE (oracle mostly)
if (meta.getDatabaseMeta().supportsSequences() && meta.getSequenceName() != null && meta.getSequenceName().length() > 0) {
technicalKey = data.db.getNextSequenceValue(data.realSchemaName, meta.getSequenceName(), meta.getKeyField());
if (technicalKey != null && log.isRowLevel())
logRowlevel(BaseMessages.getString(PKG, "DimensionLookup.Log.FoundNextSequence2") + technicalKey.toString()); //$NON-NLS-1$
} else
// Use our own sequence here...
{
// What's the next value for the technical key?
technicalKey = data.db.getNextValue(getTransMeta().getCounters(), data.realSchemaName, data.realTableName, meta.getKeyField());
}
// update our technicalKey with the return of the insert
technicalKey = dimInsert(rowMeta, row, technicalKey, false, valueNewVersion, valueDateFrom, valueDateTo);
incrementLinesOutput();
// We need to capture this change in the cache as well...
if (meta.getCacheSize() >= 0) {
Object[] values = getCacheValues(rowMeta, row, technicalKey, valueNewVersion, valueDateFrom, valueDateTo);
addToCache(lookupRow, values);
}
}
if (punch) // On of the fields we have to punch through has changed!
{
/*
* This means we have to update all versions:
*
* UPDATE dim SET punchf1 = val1, punchf2 = val2, ... WHERE
* fieldlookup[] = ? ;
*
* --> update ALL versions in the dimension table.
*/
dimPunchThrough(rowMeta, row);
incrementLinesUpdated();
}
returnRow = new Object[data.returnRowMeta.size()];
returnRow[0] = technicalKey;
if (log.isRowLevel())
logRowlevel(BaseMessages.getString(PKG, "DimensionLookup.Log.TechnicalKey") + technicalKey); //$NON-NLS-1$
}
}
if (log.isRowLevel())
logRowlevel(BaseMessages.getString(PKG, "DimensionLookup.Log.AddValuesToRow") + data.returnRowMeta.getString(returnRow)); //$NON-NLS-1$
// Copy the results to the output row...
//
// First copy the input row values to the output..
//
for (int i = 0; i < rowMeta.size(); i++)
outputRow[i] = row[i];
int outputIndex = rowMeta.size();
int inputIndex = 0;
// Then the technical key...
//
outputRow[outputIndex++] = data.returnRowMeta.getInteger(returnRow, inputIndex++);
// skip the version in the input
inputIndex++;
// Then get the "extra fields"...
// don't return date from-to fields, they can be returned when explicitly
// specified in lookup fields.
while (inputIndex < returnRow.length && outputIndex < outputRow.length) {
outputRow[outputIndex] = returnRow[inputIndex];
outputIndex++;
inputIndex++;
}
// Finaly, check the date range!
/*
* TODO: WTF is this??? [May be it makes sense to keep the return date
* from-to fields within min/max range, but even then the code below is
* wrong]. Value date; if (data.datefieldnr>=0) date =
* row.getValue(data.datefieldnr); else date = new Value("date", new
* Date()); // system date //$NON-NLS-1$
*
* if (data.min_date.compare(date)>0) data.min_date.setValue( date.getDate()
* ); if (data.max_date.compare(date)<0) data.max_date.setValue(
* date.getDate() );
*/
return outputRow;
}
/**
* table: dimension table keys[]: which dim-fields do we use to look up key? retval: name of the key to return
* datefield: do we have a datefield? datefrom, dateto: date-range, if any.
*/
private void setDimLookup(RowMetaInterface rowMeta) throws KettleDatabaseException
{
DatabaseMeta databaseMeta = meta.getDatabaseMeta();
data.lookupRowMeta = new RowMeta();
/* DEFAULT, SYSDATE, START_TRANS, COLUMN_VALUE :
*
* SELECT <tk>, <version>, ... ,
* FROM <table>
* WHERE key1=keys[1]
* AND key2=keys[2] ...
* AND <datefrom> <= <datefield>
* AND <dateto> > <datefield>
* ;
*
* NULL :
*
* SELECT <tk>, <version>, ... ,
* FROM <table>
* WHERE key1=keys[1]
* AND key2=keys[2] ...
* AND ( <datefrom> is null OR <datefrom> <= <datefield> )
* AND <dateto> >= <datefield>
*/
String sql = "SELECT "+databaseMeta.quoteField(meta.getKeyField())+", "+databaseMeta.quoteField(meta.getVersionField());
if (!Const.isEmpty(meta.getFieldLookup()))
{
for (int i=0;i<meta.getFieldLookup().length;i++)
{
if (!Const.isEmpty(meta.getFieldLookup()[i]) && !DimensionLookupMeta.isUpdateTypeWithoutArgument(meta.isUpdate(), meta.getFieldUpdate()[i])) // Don't retrieve the fields without input
{
sql+=", "+databaseMeta.quoteField(meta.getFieldLookup()[i]);
if (!Const.isEmpty( meta.getFieldStream()[i] ) && !meta.getFieldLookup()[i].equals(meta.getFieldStream()[i]))
{
sql+=" AS "+databaseMeta.quoteField(meta.getFieldStream()[i]);
}
}
}
}
if (meta.getCacheSize()>=0)
{
sql+=", "+databaseMeta.quoteField(meta.getDateFrom())+", "+databaseMeta.quoteField(meta.getDateTo());
}
sql+= " FROM "+data.schemaTable+" WHERE ";
for (int i=0;i<meta.getKeyLookup().length;i++)
{
if (i!=0) sql += " AND ";
sql += databaseMeta.quoteField(meta.getKeyLookup()[i])+" = ? ";
data.lookupRowMeta.addValueMeta( rowMeta.getValueMeta(data.keynrs[i]) );
}
String dateFromField = databaseMeta.quoteField(meta.getDateFrom());
String dateToField = databaseMeta.quoteField(meta.getDateTo());
if (meta.isUsingStartDateAlternative() &&
( meta.getStartDateAlternative()==DimensionLookupMeta.START_DATE_ALTERNATIVE_NULL) ||
( meta.getStartDateAlternative()==DimensionLookupMeta.START_DATE_ALTERNATIVE_COLUMN_VALUE)
)
{
// Null as a start date is possible...
//
sql += " AND ( "+dateFromField+" IS NULL OR "+dateFromField+" <= ? )"+Const.CR;
sql += " AND "+dateToField+" >= ?"+Const.CR;
data.lookupRowMeta.addValueMeta( new ValueMeta(meta.getDateFrom(), ValueMetaInterface.TYPE_DATE) );
data.lookupRowMeta.addValueMeta( new ValueMeta(meta.getDateTo(), ValueMetaInterface.TYPE_DATE) );
} else {
// Null as a start date is NOT possible
//
sql += " AND ? >= "+dateFromField+Const.CR;
sql += " AND ? < "+dateToField+Const.CR;
data.lookupRowMeta.addValueMeta( new ValueMeta(meta.getDateFrom(), ValueMetaInterface.TYPE_DATE) );
data.lookupRowMeta.addValueMeta( new ValueMeta(meta.getDateTo(), ValueMetaInterface.TYPE_DATE) );
}
try
{
logDetailed("Dimension Lookup setting preparedStatement to ["+sql+"]");
data.prepStatementLookup=data.db.getConnection().prepareStatement(databaseMeta.stripCR(sql));
if (databaseMeta.supportsSetMaxRows())
{
data.prepStatementLookup.setMaxRows(1); // alywas get only 1 line back!
}
if (databaseMeta.getDatabaseInterface() instanceof MySQLDatabaseMeta)
{
data.prepStatementLookup.setFetchSize(0); // Make sure to DISABLE Streaming Result sets
}
logDetailed("Finished preparing dimension lookup statement.");
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare dimension lookup", ex);
}
}
private boolean isAutoIncrement()
{
return techKeyCreation == CREATION_METHOD_AUTOINC;
}
/**
* This inserts new record into dimension Optionally, if the entry already
* exists, update date range from previous version of the entry.
*/
public Long dimInsert(RowMetaInterface inputRowMeta, Object[] row, Long technicalKey, boolean newEntry, Long versionNr, Date dateFrom, Date dateTo) throws KettleException {
DatabaseMeta databaseMeta = meta.getDatabaseMeta();
if (data.prepStatementInsert == null && data.prepStatementUpdate == null) // first
// time:
// construct
// prepared
// statement
{
RowMetaInterface insertRowMeta = new RowMeta();
/*
* Construct the SQL statement...
*
* INSERT INTO d_customer(keyfield, versionfield, datefrom, dateto, key[],
* fieldlookup[], last_updated, last_inserted, last_version) VALUES
* (val_key ,val_version , val_datfrom, val_datto, keynrs[], fieldnrs[],
* last_updated, last_inserted, last_version) ;
*/
String sql = "INSERT INTO " + data.schemaTable + "( ";
if (!isAutoIncrement()) {
sql += databaseMeta.quoteField(meta.getKeyField()) + ", "; // NO
// AUTOINCREMENT
insertRowMeta.addValueMeta(data.outputRowMeta.getValueMeta(inputRowMeta.size())); // the
// first
// return
// value
// after
// the
// input
} else {
if (databaseMeta.needsPlaceHolder()) {
sql += "0, "; // placeholder on informix!
}
}
sql += databaseMeta.quoteField(meta.getVersionField()) + ", " + databaseMeta.quoteField(meta.getDateFrom()) + ", " + databaseMeta.quoteField(meta.getDateTo());
insertRowMeta.addValueMeta(new ValueMeta(meta.getVersionField(), ValueMetaInterface.TYPE_INTEGER));
insertRowMeta.addValueMeta(new ValueMeta(meta.getDateFrom(), ValueMetaInterface.TYPE_DATE));
insertRowMeta.addValueMeta(new ValueMeta(meta.getDateTo(), ValueMetaInterface.TYPE_DATE));
for (int i = 0; i < meta.getKeyLookup().length; i++) {
sql += ", " + databaseMeta.quoteField(meta.getKeyLookup()[i]);
insertRowMeta.addValueMeta(inputRowMeta.getValueMeta(data.keynrs[i]));
}
for (int i = 0; i < meta.getFieldLookup().length; i++) {
// Ignore last_version, last_updated etc, they are handled below (at the
// back of the row).
//
if (!DimensionLookupMeta.isUpdateTypeWithoutArgument(meta.isUpdate(), meta.getFieldUpdate()[i])) {
sql += ", " + databaseMeta.quoteField(meta.getFieldLookup()[i]);
insertRowMeta.addValueMeta(inputRowMeta.getValueMeta(data.fieldnrs[i]));
}
}
// Finally, the special update fields...
//
for (int i = 0; i < meta.getFieldUpdate().length; i++) {
ValueMetaInterface valueMeta = null;
switch (meta.getFieldUpdate()[i]) {
case DimensionLookupMeta.TYPE_UPDATE_DATE_INSUP:
case DimensionLookupMeta.TYPE_UPDATE_DATE_INSERTED:
valueMeta = new ValueMeta(meta.getFieldLookup()[i], ValueMetaInterface.TYPE_DATE);
break;
case DimensionLookupMeta.TYPE_UPDATE_LAST_VERSION:
valueMeta = new ValueMeta(meta.getFieldLookup()[i], ValueMetaInterface.TYPE_BOOLEAN);
break;
}
if (valueMeta != null) {
sql += ", " + databaseMeta.quoteField(valueMeta.getName());
insertRowMeta.addValueMeta(valueMeta);
}
}
sql += ") VALUES (";
if (!isAutoIncrement()) {
sql += "?, ";
}
sql += "?, ?, ?";
for (int i = 0; i < data.keynrs.length; i++) {
sql += ", ?";
}
for (int i = 0; i < meta.getFieldLookup().length; i++) {
// Ignore last_version, last_updated, etc. These are handled below...
//
if (!DimensionLookupMeta.isUpdateTypeWithoutArgument(meta.isUpdate(), meta.getFieldUpdate()[i])) {
sql += ", ?";
}
}
// The special update fields...
//
for (int i = 0; i < meta.getFieldUpdate().length; i++) {
switch (meta.getFieldUpdate()[i]) {
case DimensionLookupMeta.TYPE_UPDATE_DATE_INSUP:
case DimensionLookupMeta.TYPE_UPDATE_DATE_INSERTED:
case DimensionLookupMeta.TYPE_UPDATE_LAST_VERSION:
sql += ", ?";
break;
}
}
sql += " )";
try {
if (technicalKey == null) {
logDetailed("SQL w/ return keys=[" + sql + "]");
data.prepStatementInsert = data.db.getConnection().prepareStatement(databaseMeta.stripCR(sql), Statement.RETURN_GENERATED_KEYS);
} else {
logDetailed("SQL=[" + sql + "]");
data.prepStatementInsert = data.db.getConnection().prepareStatement(databaseMeta.stripCR(sql));
}
// pstmt=con.prepareStatement(sql, new String[] { "klant_tk" } );
} catch (SQLException ex) {
throw new KettleDatabaseException("Unable to prepare dimension insert :" + Const.CR + sql, ex);
}
/*
* UPDATE d_customer SET dateto = val_datnow, last_updated = <now>
* last_version = false WHERE keylookup[] = keynrs[] AND versionfield =
* val_version - 1 ;
*/
RowMetaInterface updateRowMeta = new RowMeta();
String sql_upd = "UPDATE " + data.schemaTable + Const.CR;
// The end of the date range
//
sql_upd += "SET " + databaseMeta.quoteField(meta.getDateTo()) + " = ?" + Const.CR;
updateRowMeta.addValueMeta(new ValueMeta(meta.getDateTo(), ValueMetaInterface.TYPE_DATE));
// The special update fields...
//
for (int i = 0; i < meta.getFieldUpdate().length; i++) {
ValueMetaInterface valueMeta = null;
switch (meta.getFieldUpdate()[i]) {
case DimensionLookupMeta.TYPE_UPDATE_DATE_INSUP:
case DimensionLookupMeta.TYPE_UPDATE_DATE_UPDATED:
valueMeta = new ValueMeta(meta.getFieldLookup()[i], ValueMetaInterface.TYPE_DATE);
break;
case DimensionLookupMeta.TYPE_UPDATE_LAST_VERSION:
valueMeta = new ValueMeta(meta.getFieldLookup()[i], ValueMetaInterface.TYPE_BOOLEAN);
break;
}
if (valueMeta != null) {
sql_upd += ", " + databaseMeta.quoteField(valueMeta.getName()) + " = ?" + Const.CR;
updateRowMeta.addValueMeta(valueMeta);
}
}
sql_upd += "WHERE ";
for (int i = 0; i < meta.getKeyLookup().length; i++) {
if (i > 0)
sql_upd += "AND ";
sql_upd += databaseMeta.quoteField(meta.getKeyLookup()[i]) + " = ?" + Const.CR;
updateRowMeta.addValueMeta(inputRowMeta.getValueMeta(data.keynrs[i]));
}
sql_upd += "AND " + databaseMeta.quoteField(meta.getVersionField()) + " = ? ";
updateRowMeta.addValueMeta(new ValueMeta(meta.getVersionField(), ValueMetaInterface.TYPE_INTEGER));
try {
logDetailed("Preparing update: " + Const.CR + sql_upd + Const.CR);
data.prepStatementUpdate = data.db.getConnection().prepareStatement(databaseMeta.stripCR(sql_upd));
} catch (SQLException ex) {
throw new KettleDatabaseException("Unable to prepare dimension update :" + Const.CR + sql_upd, ex);
}
data.insertRowMeta = insertRowMeta;
data.updateRowMeta = updateRowMeta;
}
Object[] insertRow = new Object[data.insertRowMeta.size()];
int insertIndex = 0;
if (!isAutoIncrement()) {
insertRow[insertIndex++] = technicalKey;
}
// Caller is responsible for setting proper version number depending
// on if newEntry == true
insertRow[insertIndex++] = versionNr;
switch (data.startDateChoice) {
case DimensionLookupMeta.START_DATE_ALTERNATIVE_NONE:
insertRow[insertIndex++] = dateFrom;
break;
case DimensionLookupMeta.START_DATE_ALTERNATIVE_SYSDATE:
insertRow[insertIndex++] = new Date();
break;
case DimensionLookupMeta.START_DATE_ALTERNATIVE_START_OF_TRANS:
insertRow[insertIndex++] = getTrans().getStartDate();
break;
case DimensionLookupMeta.START_DATE_ALTERNATIVE_NULL:
insertRow[insertIndex++] = null;
break;
case DimensionLookupMeta.START_DATE_ALTERNATIVE_COLUMN_VALUE:
insertRow[insertIndex++] = inputRowMeta.getDate(row, data.startDateFieldIndex);
break;
default:
throw new KettleStepException(BaseMessages.getString(PKG, "DimensionLookup.Exception.IllegalStartDateSelection", Integer.toString(data.startDateChoice)));
}
insertRow[insertIndex++] = dateTo;
for (int i = 0; i < data.keynrs.length; i++) {
insertRow[insertIndex++] = row[data.keynrs[i]];
}
for (int i = 0; i < data.fieldnrs.length; i++) {
if (data.fieldnrs[i] >= 0) {
// Ignore last_version, last_updated, etc. These are handled below...
//
insertRow[insertIndex++] = row[data.fieldnrs[i]];
}
}
// The special update fields...
//
for (int i = 0; i < meta.getFieldUpdate().length; i++) {
switch (meta.getFieldUpdate()[i]) {
case DimensionLookupMeta.TYPE_UPDATE_DATE_INSUP:
case DimensionLookupMeta.TYPE_UPDATE_DATE_INSERTED:
insertRow[insertIndex++] = new Date();
break;
case DimensionLookupMeta.TYPE_UPDATE_LAST_VERSION:
insertRow[insertIndex++] = Boolean.TRUE;
break; // Always the last version on insert.
}
}
if (log.isDebug())
logDebug("rins, size=" + data.insertRowMeta.size() + ", values=" + data.insertRowMeta.getString(insertRow));
// INSERT NEW VALUE!
data.db.setValues(data.insertRowMeta, insertRow, data.prepStatementInsert);
data.db.insertRow(data.prepStatementInsert);
if (log.isDebug())
logDebug("Row inserted!");
if (isAutoIncrement()) {
try {
RowMetaAndData keys = data.db.getGeneratedKeys(data.prepStatementInsert);
if (keys.getRowMeta().size() > 0) {
technicalKey = keys.getRowMeta().getInteger(keys.getData(), 0);
} else {
throw new KettleDatabaseException("Unable to retrieve value of auto-generated technical key : no value found!");
}
} catch (Exception e) {
throw new KettleDatabaseException("Unable to retrieve value of auto-generated technical key : unexpected error: ", e);
}
}
if (!newEntry) // we have to update the previous version in the dimension!
{
/*
* UPDATE d_customer SET dateto = val_datfrom , last_updated = <now> ,
* last_version = false WHERE keylookup[] = keynrs[] AND versionfield =
* val_version - 1 ;
*/
Object[] updateRow = new Object[data.updateRowMeta.size()];
int updateIndex = 0;
switch(data.startDateChoice) {
case DimensionLookupMeta.START_DATE_ALTERNATIVE_NONE : updateRow[updateIndex++] = dateFrom; break;
case DimensionLookupMeta.START_DATE_ALTERNATIVE_SYSDATE : updateRow[updateIndex++] = new Date(); break;
case DimensionLookupMeta.START_DATE_ALTERNATIVE_START_OF_TRANS : updateRow[updateIndex++] = getTrans().getCurrentDate(); break;
case DimensionLookupMeta.START_DATE_ALTERNATIVE_NULL : updateRow[updateIndex++] = null; break;
case DimensionLookupMeta.START_DATE_ALTERNATIVE_COLUMN_VALUE : updateRow[updateIndex++] = inputRowMeta.getDate(row, data.startDateFieldIndex); break;
default:
throw new KettleStepException(BaseMessages.getString("DimensionLookup.Exception.IllegalStartDateSelection", Integer.toString(data.startDateChoice)));
}
// The special update fields...
//
for (int i = 0; i < meta.getFieldUpdate().length; i++) {
switch (meta.getFieldUpdate()[i]) {
case DimensionLookupMeta.TYPE_UPDATE_DATE_INSUP:
updateRow[updateIndex++] = new Date();
break;
case DimensionLookupMeta.TYPE_UPDATE_LAST_VERSION:
updateRow[updateIndex++] = Boolean.FALSE;
break; // Never the last version on this update
}
}
for (int i = 0; i < data.keynrs.length; i++) {
updateRow[updateIndex++] = row[data.keynrs[i]];
}
updateRow[updateIndex++] = versionNr - 1;
if (log.isRowLevel())
logRowlevel("UPDATE using rupd=" + data.updateRowMeta.getString(updateRow));
// UPDATE VALUES
// set values for update
//
data.db.setValues(data.updateRowMeta, updateRow, data.prepStatementUpdate);
if (log.isDebug()) {
logDebug("Values set for update (" + data.updateRowMeta.size() + ")");
}
data.db.insertRow(data.prepStatementUpdate); // do the actual update
if (log.isDebug()) {
logDebug("Row updated!");
}
}
return technicalKey;
}
public void dimUpdate(RowMetaInterface rowMeta, Object[] row, Long dimkey, Date valueDate) throws KettleDatabaseException {
if (data.prepStatementDimensionUpdate == null) // first time: construct
// prepared statement
{
data.dimensionUpdateRowMeta = new RowMeta();
// Construct the SQL statement...
/*
* UPDATE d_customer SET fieldlookup[] = row.getValue(fieldnrs) ,
* last_updated = <now> WHERE returnkey = dimkey ;
*/
String sql = "UPDATE " + data.schemaTable + Const.CR + "SET ";
boolean comma = false;
for (int i = 0; i < meta.getFieldLookup().length; i++) {
if (!DimensionLookupMeta.isUpdateTypeWithoutArgument(meta.isUpdate(), meta.getFieldUpdate()[i])) {
if (comma)
sql += ", ";
else
sql += " ";
comma = true;
sql += meta.getDatabaseMeta().quoteField(meta.getFieldLookup()[i]) + " = ?" + Const.CR;
data.dimensionUpdateRowMeta.addValueMeta(rowMeta.getValueMeta(data.fieldnrs[i]));
}
}
// The special update fields...
//
for (int i = 0; i < meta.getFieldUpdate().length; i++) {
ValueMetaInterface valueMeta = null;
switch (meta.getFieldUpdate()[i]) {
case DimensionLookupMeta.TYPE_UPDATE_DATE_INSUP:
case DimensionLookupMeta.TYPE_UPDATE_DATE_UPDATED:
valueMeta = new ValueMeta(meta.getFieldLookup()[i], ValueMetaInterface.TYPE_DATE);
break;
}
if (valueMeta != null) {
if (comma)
sql += ", ";
else
sql += " ";
comma = true;
sql += meta.getDatabaseMeta().quoteField(valueMeta.getName()) + " = ?" + Const.CR;
data.dimensionUpdateRowMeta.addValueMeta(valueMeta);
}
}
sql += "WHERE " + meta.getDatabaseMeta().quoteField(meta.getKeyField()) + " = ?";
data.dimensionUpdateRowMeta.addValueMeta(new ValueMeta(meta.getKeyField(), ValueMetaInterface.TYPE_INTEGER)); // The
// tk
try {
if (log.isDebug())
logDebug("Preparing statement: [" + sql + "]");
data.prepStatementDimensionUpdate = data.db.getConnection().prepareStatement(meta.getDatabaseMeta().stripCR(sql));
} catch (SQLException ex) {
throw new KettleDatabaseException("Couldn't prepare statement :" + Const.CR + sql, ex);
}
}
// Assemble information
// New
Object[] dimensionUpdateRow = new Object[data.dimensionUpdateRowMeta.size()];
int updateIndex = 0;
for (int i = 0; i < data.fieldnrs.length; i++) {
// Ignore last_version, last_updated, etc. These are handled below...
//
if (data.fieldnrs[i] >= 0) {
dimensionUpdateRow[updateIndex++] = row[data.fieldnrs[i]];
}
}
for (int i = 0; i < meta.getFieldUpdate().length; i++) {
switch (meta.getFieldUpdate()[i]) {
case DimensionLookupMeta.TYPE_UPDATE_DATE_INSUP:
case DimensionLookupMeta.TYPE_UPDATE_DATE_UPDATED:
dimensionUpdateRow[updateIndex++] = valueDate;
break;
}
}
dimensionUpdateRow[updateIndex++] = dimkey;
data.db.setValues(data.dimensionUpdateRowMeta, dimensionUpdateRow, data.prepStatementDimensionUpdate);
data.db.insertRow(data.prepStatementDimensionUpdate);
}
// This updates all versions of a dimension entry.
//
public void dimPunchThrough(RowMetaInterface rowMeta, Object[] row) throws KettleDatabaseException
{
if (data.prepStatementPunchThrough==null) // first time: construct prepared statement
{
data.punchThroughRowMeta = new RowMeta();
/*
* UPDATE table
* SET punchv1 = fieldx, ...
* , last_updated = <now>
* WHERE keylookup[] = keynrs[]
* ;
*/
String sql_upd="UPDATE "+data.schemaTable+Const.CR;
sql_upd+="SET ";
boolean first=true;
for (int i=0;i<meta.getFieldLookup().length;i++)
{
if (meta.getFieldUpdate()[i]==DimensionLookupMeta.TYPE_UPDATE_DIM_PUNCHTHROUGH)
{
if (!first) sql_upd+=", "; else sql_upd+=" ";
first=false;
sql_upd+=meta.getFieldLookup()[i]+" = ?"+Const.CR;
data.punchThroughRowMeta.addValueMeta( rowMeta.getValueMeta(data.fieldnrs[i]) );
}
}
// The special update fields...
//
for (int i=0;i<meta.getFieldUpdate().length;i++) {
ValueMetaInterface valueMeta = null;
switch(meta.getFieldUpdate()[i]) {
case DimensionLookupMeta.TYPE_UPDATE_DATE_INSUP :
case DimensionLookupMeta.TYPE_UPDATE_DATE_UPDATED : valueMeta = new ValueMeta(meta.getFieldLookup()[i], ValueMetaInterface.TYPE_DATE); break;
}
if (valueMeta!=null) {
sql_upd+=", "+meta.getDatabaseMeta().quoteField(valueMeta.getName()) +" = ?"+Const.CR;
data.punchThroughRowMeta.addValueMeta(valueMeta);
}
}
sql_upd+="WHERE ";
for (int i=0;i<meta.getKeyLookup().length;i++)
{
if (i>0) sql_upd+="AND ";
sql_upd+=meta.getKeyLookup()[i]+" = ?"+Const.CR;
data.punchThroughRowMeta.addValueMeta( rowMeta.getValueMeta(data.keynrs[i]) );
}
try
{
data.prepStatementPunchThrough=data.db.getConnection().prepareStatement(meta.getDatabaseMeta().stripCR(sql_upd));
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare dimension punchThrough update statement : "+Const.CR+sql_upd, ex);
}
}
Object[] punchThroughRow = new Object[data.punchThroughRowMeta.size()];
int punchIndex=0;
for (int i=0;i<meta.getFieldLookup().length;i++)
{
if (meta.getFieldUpdate()[i]==DimensionLookupMeta.TYPE_UPDATE_DIM_PUNCHTHROUGH)
{
punchThroughRow[punchIndex++] = row[ data.fieldnrs[i] ];
}
}
for (int i=0;i<meta.getFieldUpdate().length;i++) {
switch(meta.getFieldUpdate()[i]) {
case DimensionLookupMeta.TYPE_UPDATE_DATE_INSUP :
case DimensionLookupMeta.TYPE_UPDATE_DATE_UPDATED : punchThroughRow[punchIndex++] = new Date(); break;
}
}
for (int i=0;i<data.keynrs.length;i++)
{
punchThroughRow[punchIndex++] = row[ data.keynrs[i] ];
}
// UPDATE VALUES
data.db.setValues(data.punchThroughRowMeta, punchThroughRow, data.prepStatementPunchThrough); // set values for update
data.db.insertRow(data.prepStatementPunchThrough); // do the actual punch through update
}
/**
* Keys:
* - natural key fields
* Values:
* - Technical key
* - lookup fields / extra fields (allows us to compare or retrieve)
* - Date_from
* - Date_to
*
* @param row The input row
* @param technicalKey the technical key value
* @param valueDateFrom the start of valid date range
* @param valueDateTo the end of the valid date range
* @return the values to store in the cache as a row.
*/
private Object[] getCacheValues(RowMetaInterface rowMeta, Object[] row, Long technicalKey, Long valueVersion, Date valueDateFrom, Date valueDateTo)
{
if (data.cacheValueRowMeta==null) return null; // nothing is in the cache.
Object[] cacheValues = new Object[data.cacheValueRowMeta.size()];
int cacheIndex = 0;
cacheValues[cacheIndex++] = technicalKey;
cacheValues[cacheIndex++] = valueVersion;
for (int i=0;i<data.fieldnrs.length;i++)
{
// Ignore last_version, last_updated, etc. These are handled below...
//
if (data.fieldnrs[i]>=0) {
cacheValues[cacheIndex++] = row[ data.fieldnrs[i] ];
}
}
cacheValues[cacheIndex++] = valueDateFrom;
cacheValues[cacheIndex++] = valueDateTo;
return cacheValues;
}
/**
* Adds a row to the cache
* In case we are doing updates, we need to store the complete rows from the database.
* These are the values we need to store
*
* Key:
* - natural key fields
* Value:
* - Technical key
* - lookup fields / extra fields (allows us to compare or retrieve)
* - Date_from
* - Date_to
*
* @param keyValues
* @param returnValues
* @throws KettleValueException
*/
private void addToCache(Object[] keyValues, Object[] returnValues) throws KettleValueException
{
if (data.cacheValueRowMeta==null)
{
data.cacheValueRowMeta = assembleCacheValueRowMeta();
}
// store it in the cache if needed.
byte[] keyPart = RowMeta.extractData(data.cacheKeyRowMeta, keyValues);
byte[] valuePart = RowMeta.extractData(data.cacheValueRowMeta, returnValues);
data.cache.put(keyPart, valuePart);
// check if the size is not too big...
// Allow for a buffer overrun of 20% and then remove those 20% in one go.
// Just to keep performance in track.
//
int tenPercent = meta.getCacheSize()/10;
if (meta.getCacheSize()>0 && data.cache.size()>meta.getCacheSize()+tenPercent)
{
// Which cache entries do we delete here?
// We delete those with the lowest technical key...
// Those would arguably be the "oldest" dimension entries.
// Oh well... Nothing is going to be perfect here...
//
// Getting the lowest 20% requires some kind of sorting algorithm and I'm not sure we want to do that.
// Sorting is slow and even in the best case situation we need to do 2 passes over the cache entries...
//
// Perhaps we should get 20% random values and delete everything below the lowest but one TK.
//
List<byte[]> keys = data.cache.getKeys();
int sizeBefore = keys.size();
List<Long> samples = new ArrayList<Long>();
// Take 10 sample technical keys....
int stepsize=keys.size()/5;
if (stepsize<1) stepsize=1; //make shure we have no endless loop
for (int i=0;i<keys.size();i+=stepsize)
{
byte[] key = (byte[]) keys.get(i);
byte[] value = data.cache.get(key);
if (value!=null)
{
Object[] values = RowMeta.getRow(data.cacheValueRowMeta, value);
Long tk = data.cacheValueRowMeta.getInteger(values, 0);
samples.add(tk);
}
}
// Sort these 5 elements...
Collections.sort(samples);
// What is the smallest?
// Take the second, not the fist in the list, otherwise we would be removing a single entry = not good.
if (samples.size()>1) {
data.smallestCacheKey = samples.get(1);
} else { // except when there is only one sample
data.smallestCacheKey = samples.get(0);
}
// Remove anything in the cache <= smallest.
// This makes it almost single pass...
// This algorithm is not 100% correct, but I guess it beats sorting the whole cache all the time.
//
for (int i=0;i<keys.size();i++)
{
byte[] key = (byte[]) keys.get(i);
byte[] value = data.cache.get(key);
if (value!=null)
{
Object[] values = RowMeta.getRow(data.cacheValueRowMeta, value);
long tk = data.cacheValueRowMeta.getInteger(values, 0).longValue();
if (tk<=data.smallestCacheKey)
{
data.cache.remove(key); // this one has to go.
}
}
}
int sizeAfter = data.cache.size();
logDetailed("Reduced the lookup cache from "+sizeBefore+" to "+sizeAfter+" rows.");
}
if (log.isRowLevel()) logRowlevel("Cache store: key="+keyValues+" values="+returnValues);
}
/**
* @return the cache value row metadata.
* The items that are cached is basically the return row metadata:<br>
* - Technical key (Integer)
* - Version (Integer)
* -
*/
private RowMetaInterface assembleCacheValueRowMeta() {
RowMetaInterface cacheRowMeta = data.returnRowMeta.clone();
// The technical key and version are always an Integer...
//
/*
cacheRowMeta.getValueMeta(0).setType(ValueMetaInterface.TYPE_INTEGER);
cacheRowMeta.getValueMeta(1).setType(ValueMetaInterface.TYPE_INTEGER);
*/
return cacheRowMeta;
}
private Object[] getFromCache(Object[] keyValues, Date dateValue) throws KettleValueException
{
if (data.cacheValueRowMeta==null)
{
// nothing in the cache yet, no lookup was ever performed
if (data.returnRowMeta==null) return null;
data.cacheValueRowMeta = assembleCacheValueRowMeta();
}
byte[] key = RowMeta.extractData(data.cacheKeyRowMeta, keyValues);
byte[] value = data.cache.get(key);
if (value!=null)
{
Object[] row = RowMeta.getRow(data.cacheValueRowMeta, value);
// See if the dateValue is between the from and to date ranges...
// The last 2 values are from and to
long time = dateValue.getTime();
long from = ((Date)row[row.length-2]).getTime();
long to = ((Date)row[row.length-1]).getTime();
if (time>=from && time<to) // sanity check to see if we have the right version
{
if (log.isRowLevel()) logRowlevel("Cache hit: key="+data.cacheKeyRowMeta.getString(keyValues)+" values="+data.cacheValueRowMeta.getString(row));
return row;
}
}
return null;
}
public void checkDimZero() throws KettleException
{
// Don't insert anything when running in lookup mode.
//
if (!meta.isUpdate()) return;
DatabaseMeta databaseMeta = meta.getDatabaseMeta();
if (meta.isAutoIncrement()) {
// See if there are rows in the table
// If so, we can't insert the unknown row anymore...
//
String sql = "SELECT count(*) FROM "+data.schemaTable;
RowMetaAndData r = data.db.getOneRow(sql);
Long count = r.getRowMeta().getInteger(r.getData(), 0);
if (count.longValue() != 0)
{
return; // Can't insert below the rows already in there...
}
}
int start_tk = databaseMeta.getNotFoundTK(isAutoIncrement());
String sql = "SELECT count(*) FROM "+data.schemaTable+" WHERE "+databaseMeta.quoteField(meta.getKeyField())+" = "+start_tk;
RowMetaAndData r = data.db.getOneRow(sql);
Long count = r.getRowMeta().getInteger(r.getData(), 0);
if (count.longValue() == 0)
{
String isql = null;
try
{
if (!databaseMeta.supportsAutoinc() || !isAutoIncrement())
{
isql = "insert into "+data.schemaTable+"("+databaseMeta.quoteField(meta.getKeyField())+", "+databaseMeta.quoteField(meta.getVersionField())+") values (0, 1)";
}
else
{
isql = databaseMeta.getSQLInsertAutoIncUnknownDimensionRow(data.schemaTable, databaseMeta.quoteField(meta.getKeyField()), databaseMeta.quoteField(meta.getVersionField()));
}
data.db.execStatement(databaseMeta.stripCR(isql));
}
catch(KettleException e)
{
throw new KettleDatabaseException("Error inserting 'unknown' row in dimension ["+data.schemaTable+"] : "+isql, e);
}
}
}
public boolean init(StepMetaInterface smi, StepDataInterface sdi)
{
meta=(DimensionLookupMeta)smi;
data=(DimensionLookupData)sdi;
if (super.init(smi, sdi))
{
data.min_date = meta.getMinDate(); //$NON-NLS-1$
data.max_date = meta.getMaxDate(); //$NON-NLS-1$
data.realSchemaName=environmentSubstitute(meta.getSchemaName());
data.realTableName=environmentSubstitute(meta.getTableName());
data.startDateChoice = DimensionLookupMeta.START_DATE_ALTERNATIVE_NONE;
if (meta.isUsingStartDateAlternative()) data.startDateChoice = meta.getStartDateAlternative();
data.db=new Database(this, meta.getDatabaseMeta());
data.db.shareVariablesWith(this);
try
{
if (getTransMeta().isUsingUniqueConnections())
{
synchronized (getTrans()) { data.db.connect(getTrans().getThreadName(), getPartitionID()); }
}
else
{
data.db.connect(getPartitionID());
}
if (log.isDetailed()) logDetailed(BaseMessages.getString(PKG, "DimensionLookup.Log.ConnectedToDB")); //$NON-NLS-1$
data.db.setCommit(meta.getCommitSize());
return true;
}
catch(KettleException ke)
{
logError(BaseMessages.getString(PKG, "DimensionLookup.Log.ErrorOccurredInProcessing")+ke.getMessage()); //$NON-NLS-1$
}
}
return false;
}
public void dispose(StepMetaInterface smi, StepDataInterface sdi)
{
meta = (DimensionLookupMeta)smi;
data = (DimensionLookupData)sdi;
try
{
if (!data.db.isAutoCommit())
{
if (getErrors()==0)
{
data.db.commit();
}
else
{
data.db.rollback();
}
}
}
catch(KettleDatabaseException e)
{
logError(BaseMessages.getString(PKG, "DimensionLookup.Log.ErrorOccurredInProcessing")+e.getMessage()); //$NON-NLS-1$
}
finally
{
if (data.db!=null) {
data.db.disconnect();
}
}
super.dispose(smi, sdi);
}
}
|
PDI-3593 Dimension lookup/update: java.lang.IndexOutOfBoundsException on specific row numbers when cache is enabled, fixed applying patch provided by Jordan Ganoff
git-svn-id: 51b39fcfd0d3a6ea7caa15377cad4af13b9d2664@14249 5fb7f6ec-07c1-534a-b4ca-9155e429e800
|
src/org/pentaho/di/trans/steps/dimensionlookup/DimensionLookup.java
|
PDI-3593 Dimension lookup/update: java.lang.IndexOutOfBoundsException on specific row numbers when cache is enabled, fixed applying patch provided by Jordan Ganoff
|
|
Java
|
apache-2.0
|
3dcc117672245c4181a0af697463cea5bff9215e
| 0
|
ItamarBenjamin/codeine,ItamarBenjamin/codeine,codeine-cd/codeine,ItamarBenjamin/codeine,ItamarBenjamin/codeine,codeine-cd/codeine,codeine-cd/codeine,codeine-cd/codeine
|
package codeine.servlets.api_servlets;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import codeine.model.Constants;
import codeine.model.Constants.UrlParameters;
import codeine.model.Result;
import codeine.servlet.AbstractApiServlet;
import codeine.utils.os_process.ProcessExecuter.ProcessExecuterBuilder;
import com.google.common.collect.Lists;
public class UpgradeApiServlet extends AbstractApiServlet {
private static final Logger log = Logger.getLogger(UpgradeApiServlet.class);
private static final long serialVersionUID = 1L;
@Override
protected void myGet(HttpServletRequest request, HttpServletResponse response) {
String version = request.getParameter(UrlParameters.VERSION_NAME);
if (version.contains(" ") || version.contains(";")) {
throw new IllegalArgumentException("bad version " + version);
}
List<String> cmd = Lists.newArrayList(Constants.getInstallDir() + "/bin/upgrade.pl","--version",version);
log.info("going to upgrade: " + cmd);
Result r = new ProcessExecuterBuilder(cmd).build().execute();
PrintWriter writer = getWriter(response);
writer.write(r.output);
}
@Override
protected boolean checkPermissions(HttpServletRequest request) {
return isAdministrator(request);
}
}
|
src/web_server/codeine/servlets/api_servlets/UpgradeApiServlet.java
|
package codeine.servlets.api_servlets;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import codeine.model.Constants;
import codeine.model.Constants.UrlParameters;
import codeine.model.Result;
import codeine.servlet.AbstractApiServlet;
import codeine.utils.os_process.ProcessExecuter;
public class UpgradeApiServlet extends AbstractApiServlet {
private static final Logger log = Logger.getLogger(UpgradeApiServlet.class);
private static final long serialVersionUID = 1L;
@Override
protected void myGet(HttpServletRequest request, HttpServletResponse response) {
String version = request.getParameter(UrlParameters.VERSION_NAME);
String cmd = Constants.getInstallDir() + "/bin/upgrade.pl --version " + version;
log.info("going to upgrade: " + cmd);
Result r = ProcessExecuter.execute(cmd);
PrintWriter writer = getWriter(response);
writer.write(r.output);
}
@Override
protected boolean checkPermissions(HttpServletRequest request) {
return isAdministrator(request);
}
}
|
fixed security valunarability
|
src/web_server/codeine/servlets/api_servlets/UpgradeApiServlet.java
|
fixed security valunarability
|
|
Java
|
apache-2.0
|
71344cdb27e799e6da0f68c66baa534effb81b47
| 0
|
smarek/Simple-Dilbert
|
package com.mareksebera.simpledilbert;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import org.joda.time.DateMidnight;
import org.joda.time.DateTimeConstants;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;
public class DilbertPreferences {
private SharedPreferences preferences;
private SharedPreferences.Editor editor;
private static final String PREF_CURRENT_DATE = "dilbert_current_date";
private static final String PREF_CURRENT_URL = "dilbert_current_url";
private static final String PREF_HIGH_QUALITY_ENABLED = "dilbert_use_high_quality";
private static final String TAG = "DilbertPreferences";
public static final DateTimeZone TIME_ZONE = DateTimeZone
.forID("America/Chicago");
public static final DateTimeFormatter DATE_FORMATTER = DateTimeFormat
.forPattern("yyyy-MM-dd");
@SuppressLint("CommitPrefEdits")
public DilbertPreferences(Context context) {
preferences = PreferenceManager.getDefaultSharedPreferences(context);
editor = preferences.edit();
}
public DateMidnight getCurrentDate() {
String savedDate = preferences.getString(PREF_CURRENT_DATE, null);
if (savedDate == null) {
return DateMidnight.now();
} else {
return DateMidnight.parse(savedDate, DATE_FORMATTER);
}
}
public boolean saveCurrentDate(DateMidnight currentDate) {
editor.putString(PREF_CURRENT_DATE,
currentDate.toString(DilbertPreferences.DATE_FORMATTER));
return editor.commit();
}
public String getLastUrl() {
return preferences.getString(PREF_CURRENT_URL, null);
}
public boolean isHighQualityOn() {
return preferences.getBoolean(PREF_HIGH_QUALITY_ENABLED, true);
}
public boolean saveCurrentUrl(String date, String s) {
editor.putString(PREF_CURRENT_URL, s);
editor.putString(date, s);
return editor.commit();
}
public boolean toggleHighQuality() {
return editor.putBoolean(PREF_HIGH_QUALITY_ENABLED, !isHighQualityOn())
.commit();
}
public String getCachedUrl(DateMidnight dateKey) {
return getCachedUrl(dateKey.toString(DATE_FORMATTER));
}
public String getCachedUrl(String dateKey) {
return preferences.getString(dateKey, null);
}
public boolean removeCache(DateMidnight currentDate) {
return editor.remove(
currentDate.toString(DilbertPreferences.DATE_FORMATTER))
.commit();
}
public boolean isFavorited(DateMidnight currentDay) {
return preferences.getBoolean(toFavoritedKey(currentDay), false);
}
public boolean toggleIsFavorited(DateMidnight currentDay) {
boolean newState = !isFavorited(currentDay);
editor.putBoolean(toFavoritedKey(currentDay), newState).commit();
return newState;
}
private String toFavoritedKey(DateMidnight currentDay) {
return "favorite_"
+ currentDay.toString(DilbertPreferences.DATE_FORMATTER);
}
public List<FavoritedItem> getFavoritedItems() {
List<FavoritedItem> favorites = new ArrayList<FavoritedItem>();
Map<String, ?> allPreferences = preferences.getAll();
for (String key : allPreferences.keySet()) {
if (key.startsWith("favorite_")
&& (Boolean) allPreferences.get(key)) {
String date = key.replace("favorite_", "");
favorites.add(new FavoritedItem(DateMidnight.parse(date,
DATE_FORMATTER), (String) allPreferences.get(date)));
}
}
return favorites;
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void downloadImageViaManager(final Activity activity,
final String downloadUrl, DateMidnight stripDate) {
try {
DownloadManager dm = (DownloadManager) activity
.getSystemService(Context.DOWNLOAD_SERVICE);
String url = toHighQuality(downloadUrl);
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(url));
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS,
DATE_FORMATTER.print(stripDate) + ".gif");
request.setVisibleInDownloadsUi(true);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
dm.enqueue(request);
} catch (Exception e) {
Log.e(TAG, "Should not happen", e);
Toast.makeText(activity, R.string.download_manager_unsupported,
Toast.LENGTH_LONG).show();
} catch (Error e) {
Log.e(TAG, "Should not happen", e);
Toast.makeText(activity, R.string.download_manager_unsupported,
Toast.LENGTH_LONG).show();
}
}
public String toHighQuality(String url) {
return url.replace(".gif", ".zoom.gif").replace("zoom.zoom", "zoom");
}
public String toLowQuality(DateMidnight date, String url) {
if (date.getDayOfWeek() == DateTimeConstants.SUNDAY) {
return url.replace(".zoom.gif", ".sunday.gif").replace("zoom.zoom",
"zoom");
}
return url.replace(".zoom.gif", ".gif").replace("zoom.zoom", "zoom");
}
public boolean saveDateForWidgetId(int appWidgetId, DateMidnight date) {
date = validateDate(date);
return editor.putString("widget_" + appWidgetId,
date.toString(DATE_FORMATTER)).commit();
}
public DateMidnight getDateForWidgetId(int appWidgetId) {
String savedDate = preferences.getString("widget_" + appWidgetId, null);
if (savedDate == null)
return DateMidnight.now();
else
return DateMidnight.parse(savedDate, DATE_FORMATTER);
}
public static DateMidnight getRandomDateMidnight() {
Random random = new Random();
DateMidnight now = DateMidnight.now();
int year = 1989 + random.nextInt(now.getYear() - 1989);
int month = 1 + random.nextInt(12);
int day = random.nextInt(31);
return DateMidnight.parse(
String.format(new Locale("en"), "%d-%d-1", year, month))
.plusDays(day);
}
/**
* First strip was published on 16.4.1989
*
* @see <a href="http://en.wikipedia.org/wiki/Dilbert">Wikipedia</a>
* */
public static DateMidnight getFirstStripDate() {
return DateMidnight.parse("1989-04-16",
DilbertPreferences.DATE_FORMATTER);
}
public boolean deleteDateForWidgetId(int widgetId) {
return editor.remove("widget_" + widgetId).commit();
}
public static DateMidnight validateDate(DateMidnight selDate) {
if (selDate.isAfterNow()) {
selDate = DateMidnight.now(DilbertPreferences.TIME_ZONE);
}
if (selDate.isBefore(DilbertPreferences.getFirstStripDate())) {
selDate = DilbertPreferences.getFirstStripDate();
}
return selDate;
}
}
|
src/com/mareksebera/simpledilbert/DilbertPreferences.java
|
package com.mareksebera.simpledilbert;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import org.joda.time.DateMidnight;
import org.joda.time.DateTimeConstants;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;
public class DilbertPreferences {
private SharedPreferences preferences;
private SharedPreferences.Editor editor;
private static final String PREF_CURRENT_DATE = "dilbert_current_date";
private static final String PREF_CURRENT_URL = "dilbert_current_url";
private static final String PREF_HIGH_QUALITY_ENABLED = "dilbert_use_high_quality";
private static final String TAG = "DilbertPreferences";
public static final DateTimeZone TIME_ZONE = DateTimeZone
.forOffsetHours(-3);
public static final DateTimeFormatter DATE_FORMATTER = DateTimeFormat
.forPattern("yyyy-MM-dd");
@SuppressLint("CommitPrefEdits")
public DilbertPreferences(Context context) {
preferences = PreferenceManager.getDefaultSharedPreferences(context);
editor = preferences.edit();
}
public DateMidnight getCurrentDate() {
String savedDate = preferences.getString(PREF_CURRENT_DATE, null);
if (savedDate == null) {
return DateMidnight.now();
} else {
return DateMidnight.parse(savedDate, DATE_FORMATTER);
}
}
public boolean saveCurrentDate(DateMidnight currentDate) {
editor.putString(PREF_CURRENT_DATE,
currentDate.toString(DilbertPreferences.DATE_FORMATTER));
return editor.commit();
}
public String getLastUrl() {
return preferences.getString(PREF_CURRENT_URL, null);
}
public boolean isHighQualityOn() {
return preferences.getBoolean(PREF_HIGH_QUALITY_ENABLED, true);
}
public boolean saveCurrentUrl(String date, String s) {
editor.putString(PREF_CURRENT_URL, s);
editor.putString(date, s);
return editor.commit();
}
public boolean toggleHighQuality() {
return editor.putBoolean(PREF_HIGH_QUALITY_ENABLED, !isHighQualityOn())
.commit();
}
public String getCachedUrl(DateMidnight dateKey) {
return getCachedUrl(dateKey.toString(DATE_FORMATTER));
}
public String getCachedUrl(String dateKey) {
return preferences.getString(dateKey, null);
}
public boolean removeCache(DateMidnight currentDate) {
return editor.remove(
currentDate.toString(DilbertPreferences.DATE_FORMATTER))
.commit();
}
public boolean isFavorited(DateMidnight currentDay) {
return preferences.getBoolean(toFavoritedKey(currentDay), false);
}
public boolean toggleIsFavorited(DateMidnight currentDay) {
boolean newState = !isFavorited(currentDay);
editor.putBoolean(toFavoritedKey(currentDay), newState).commit();
return newState;
}
private String toFavoritedKey(DateMidnight currentDay) {
return "favorite_"
+ currentDay.toString(DilbertPreferences.DATE_FORMATTER);
}
public List<FavoritedItem> getFavoritedItems() {
List<FavoritedItem> favorites = new ArrayList<FavoritedItem>();
Map<String, ?> allPreferences = preferences.getAll();
for (String key : allPreferences.keySet()) {
if (key.startsWith("favorite_")
&& (Boolean) allPreferences.get(key)) {
String date = key.replace("favorite_", "");
favorites.add(new FavoritedItem(DateMidnight.parse(date,
DATE_FORMATTER), (String) allPreferences.get(date)));
}
}
return favorites;
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void downloadImageViaManager(final Activity activity,
final String downloadUrl, DateMidnight stripDate) {
try {
DownloadManager dm = (DownloadManager) activity
.getSystemService(Context.DOWNLOAD_SERVICE);
String url = toHighQuality(downloadUrl);
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(url));
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS,
DATE_FORMATTER.print(stripDate) + ".gif");
request.setVisibleInDownloadsUi(true);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
dm.enqueue(request);
} catch (Exception e) {
Log.e(TAG, "Should not happen", e);
Toast.makeText(activity, R.string.download_manager_unsupported,
Toast.LENGTH_LONG).show();
} catch (Error e) {
Log.e(TAG, "Should not happen", e);
Toast.makeText(activity, R.string.download_manager_unsupported,
Toast.LENGTH_LONG).show();
}
}
public String toHighQuality(String url) {
return url.replace(".gif", ".zoom.gif").replace("zoom.zoom", "zoom");
}
public String toLowQuality(DateMidnight date, String url) {
if (date.getDayOfWeek() == DateTimeConstants.SUNDAY) {
return url.replace(".zoom.gif", ".sunday.gif").replace("zoom.zoom",
"zoom");
}
return url.replace(".zoom.gif", ".gif").replace("zoom.zoom", "zoom");
}
public boolean saveDateForWidgetId(int appWidgetId, DateMidnight date) {
date = validateDate(date);
return editor.putString("widget_" + appWidgetId,
date.toString(DATE_FORMATTER)).commit();
}
public DateMidnight getDateForWidgetId(int appWidgetId) {
String savedDate = preferences.getString("widget_" + appWidgetId, null);
if (savedDate == null)
return DateMidnight.now();
else
return DateMidnight.parse(savedDate, DATE_FORMATTER);
}
public static DateMidnight getRandomDateMidnight() {
Random random = new Random();
DateMidnight now = DateMidnight.now();
int year = 1989 + random.nextInt(now.getYear() - 1989);
int month = 1 + random.nextInt(12);
int day = random.nextInt(31);
return DateMidnight.parse(
String.format(new Locale("en"), "%d-%d-1", year, month))
.plusDays(day);
}
/**
* First strip was published on 16.4.1989
*
* @see <a href="http://en.wikipedia.org/wiki/Dilbert">Wikipedia</a>
* */
public static DateMidnight getFirstStripDate() {
return DateMidnight.parse("1989-04-16",
DilbertPreferences.DATE_FORMATTER);
}
public boolean deleteDateForWidgetId(int widgetId) {
return editor.remove("widget_" + widgetId).commit();
}
public static DateMidnight validateDate(DateMidnight selDate) {
if (selDate.isAfterNow()) {
selDate = DateMidnight.now(DilbertPreferences.TIME_ZONE);
}
if (selDate.isBefore(DilbertPreferences.getFirstStripDate())) {
selDate = DilbertPreferences.getFirstStripDate();
}
return selDate;
}
}
|
Changed timezone to CDT/CST as of dilbert RSS details
|
src/com/mareksebera/simpledilbert/DilbertPreferences.java
|
Changed timezone to CDT/CST as of dilbert RSS details
|
|
Java
|
apache-2.0
|
45a6f5c7f2d622bedd4d429172a82887c5516ebd
| 0
|
jnidzwetzki/scalephant,jnidzwetzki/scalephant,jnidzwetzki/bboxdb,jnidzwetzki/bboxdb,jnidzwetzki/bboxdb
|
/*******************************************************************************
*
* Copyright (C) 2015-2017 the BBoxDB 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 org.bboxdb.converter.osm.store;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import org.bboxdb.converter.osm.util.SerializableNode;
import org.bboxdb.storage.StorageManagerException;
import org.bboxdb.storage.StorageRegistry;
import org.bboxdb.storage.entity.BoundingBox;
import org.bboxdb.storage.entity.SSTableName;
import org.bboxdb.storage.entity.Tuple;
import org.bboxdb.storage.sstable.SSTableManager;
import org.openstreetmap.osmosis.core.domain.v0_6.Node;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class OSMSSTableNodeStore implements OSMNodeStore {
/**
* The number of instances
*/
protected int instances;
/**
* The sstable manager
*/
private SSTableManager storageManager;
/**
* The Logger
*/
private final static Logger logger = LoggerFactory.getLogger(OSMSSTableNodeStore.class);
public OSMSSTableNodeStore(final List<String> baseDir, final long inputLength) {
try {
final SSTableName tableName = new SSTableName("2_group1_test");
StorageRegistry.getInstance().deleteTable(tableName);
storageManager = StorageRegistry.getInstance().getSSTableManager(tableName);
} catch (StorageManagerException e) {
logger.error("Got an exception while getting sstable manager: ", e);
}
}
/**
* Close all resources
*/
public void close() {
storageManager.shutdown();
}
/**
* Store a new node
* @param node
* @throws SQLException
* @throws IOException
* @throws StorageManagerException
*/
public void storeNode(final Node node) throws StorageManagerException {
final SerializableNode serializableNode = new SerializableNode(node);
final byte[] nodeBytes = serializableNode.toByteArray();
final Tuple tuple = new Tuple(Long.toString(node.getId()), BoundingBox.EMPTY_BOX, nodeBytes);
storageManager.put(tuple);
}
/**
* Get the database for nodes
* @param node
* @return
*/
protected int getDatabaseForNode(final long nodeid) {
return (int) (nodeid % instances);
}
/**
* Get the id for the node
* @param nodeId
* @return
* @throws SQLException
* @throws StorageManagerException
*/
public SerializableNode getNodeForId(final long nodeId) throws StorageManagerException {
final Tuple tuple = storageManager.get(Long.toString(nodeId));
final byte[] nodeBytes = tuple.getDataBytes();
return SerializableNode.fromByteArray(nodeBytes);
}
@Override
public int getInstances() {
return instances;
}
}
|
src/main/java/org/bboxdb/converter/osm/store/OSMSSTableNodeStore.java
|
/*******************************************************************************
*
* Copyright (C) 2015-2017 the BBoxDB 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 org.bboxdb.converter.osm.store;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import org.bboxdb.BBoxDBConfigurationManager;
import org.bboxdb.converter.osm.util.SerializableNode;
import org.bboxdb.storage.StorageManagerException;
import org.bboxdb.storage.StorageRegistry;
import org.bboxdb.storage.entity.BoundingBox;
import org.bboxdb.storage.entity.SSTableName;
import org.bboxdb.storage.entity.Tuple;
import org.bboxdb.storage.sstable.SSTableManager;
import org.openstreetmap.osmosis.core.domain.v0_6.Node;
public class OSMSSTableNodeStore implements OSMNodeStore {
/**
* The number of instances
*/
protected int instances;
/**
* The sstable manager
*/
private SSTableManager storageManager;
public OSMSSTableNodeStore(final List<String> baseDir, final long inputLength) {
try {
BBoxDBConfigurationManager.getConfiguration().setStorageCheckpointInterval(0);
storageManager = StorageRegistry.getInstance().getSSTableManager(new SSTableName("2_group1_test"));
} catch (StorageManagerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Close all resources
*/
public void close() {
storageManager.shutdown();
}
/**
* Store a new node
* @param node
* @throws SQLException
* @throws IOException
* @throws StorageManagerException
*/
public void storeNode(final Node node) throws StorageManagerException {
final SerializableNode serializableNode = new SerializableNode(node);
final byte[] nodeBytes = serializableNode.toByteArray();
final Tuple tuple = new Tuple(Long.toString(node.getId()), BoundingBox.EMPTY_BOX, nodeBytes);
storageManager.put(tuple);
}
/**
* Get the database for nodes
* @param node
* @return
*/
protected int getDatabaseForNode(final long nodeid) {
return (int) (nodeid % instances);
}
/**
* Get the id for the node
* @param nodeId
* @return
* @throws SQLException
* @throws StorageManagerException
*/
public SerializableNode getNodeForId(final long nodeId) throws StorageManagerException {
final Tuple tuple = storageManager.get(Long.toString(nodeId));
final byte[] nodeBytes = tuple.getDataBytes();
final SerializableNode node = SerializableNode.fromByteArray(nodeBytes);
return node;
}
@Override
public int getInstances() {
return instances;
}
}
|
Delete old persistent data
|
src/main/java/org/bboxdb/converter/osm/store/OSMSSTableNodeStore.java
|
Delete old persistent data
|
|
Java
|
apache-2.0
|
79d4bbf058e3558a706f251ff6404495c194ecfb
| 0
|
Ensembl/ensj-healthcheck,thomasmaurel/ensj-healthcheck,thomasmaurel/ensj-healthcheck,thomasmaurel/ensj-healthcheck,thomasmaurel/ensj-healthcheck,Ensembl/ensj-healthcheck,Ensembl/ensj-healthcheck,Ensembl/ensj-healthcheck
|
/**
* File: ProcessExec.java
* Created by: dstaines
* Created on: Oct 25, 2006
* CVS: $Id$
*/
package org.ensembl.healthcheck.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.commons.io.IOUtils;
/**
* Class to consume a stream from an executing process to avoid lockups. Code
* derived but extensively modified from <a
* href="http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html">JavaWorld
* article</a>
*
* @author dstaines
*
*/
class StreamGobbler extends Thread {
InputStream is;
boolean discard = false;
Appendable out;
StreamGobbler(InputStream is, Appendable out, boolean discard) {
this.is = is;
this.out = out;
this.discard = discard;
}
public void run() {
try {
if (discard) {
while (is.read() != -1) {
}
} else {
streamToBuffer(is, out);
}
} catch (IOException ioe) {
throw new RuntimeException(ioe);
} finally {
InputOutputUtils.closeQuietly(is);
}
}
public static void streamToBuffer(InputStream is, Appendable out)
throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = null;
while ((line = reader.readLine()) != null) {
out.append(line);
out.append('\n');
}
reader.close();
}
}
/**
* Class to execute a process safely, avoiding hangups by consuming the output
*
* @author dstaines
*
*/
public class ProcessExec {
private static final String SHELL_FLAGS = "-c";
private static final String SHELL = "/bin/sh";
/**
* Time to wait in milliseconds for stream gobblers to finish
*/
private static final int TIMEOUT = 10000;
/**
* Execute the command, capturing the output and error streams to
* Appendables
*
* @param command
* @param out
* @param err
* @return
* @throws Exception
*/
public static int exec(String command, Appendable out, Appendable err)
throws IOException {
return exec(command, out, err, false);
}
public static int exec(String command, Appendable out, Appendable err, String[] environment)
throws IOException {
return exec(command, out, err, false, environment);
}
/**
* Execute the command, capturing the output and error streams to
* Appendables
*
* @param commandarray
* @param out
* @param err
* @return
* @throws Exception
*/
public static int exec(String[] commandarray, Appendable out, Appendable err)
throws IOException {
return exec(commandarray, out, err, false);
}
/**
* Execute the command, discarding output and error
*
* @param command
* @return
* @throws Exception
*/
public static int exec(String command) throws IOException {
return exec(command, null, null, true);
}
/**
* Execute the command, discarding output and error
*
* @param commandarray
* @return
* @throws Exception
*/
public static int exec(String[] commandarray) throws IOException {
return exec(commandarray, null, null, true);
}
/**
* Execute the command, capturing output/error into the supplied streams if
* required
*
* @param command
* @param out
* @param err
* @return
* @throws Exception
*/
private static int exec(String command, Appendable out, Appendable err,
boolean discard) throws IOException {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(command);
return waitForProcess(out, err, discard, proc);
}
private static int exec(
String command,
Appendable out,
Appendable err,
boolean discard,
String[] environment
) throws IOException {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(
command,
environment
);
return waitForProcess(out, err, discard, proc);
}
public static int exec(
String[] command,
Appendable out,
Appendable err,
boolean discard,
String[] environment
) throws IOException {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(
command,
environment
);
// Process proc = rt.exec(
// command,
// environment
// );
return waitForProcess(out, err, discard, proc);
}
/**
* Execute the command, capturing output/error into the supplied streams if
* required
*
* @param commandarray
* @param out
* @param err
* @return
* @throws Exception
*/
private static int exec(String[] commandarray, Appendable out, Appendable err,
boolean discard) throws IOException {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(commandarray);
return waitForProcess(out, err, discard, proc);
}
/**
* Execute the specified shell command, capturing output and error
*
* @param command
* @return
* @throws Exception
*/
public static int execShell(
String command,
Appendable out,
Appendable err
) throws IOException {
return execShell(command, out, err, false);
}
/**
* Execute the specified shell command, discarding output and error
*
* @param command
* @return
* @throws Exception
*/
public static int execShell(String command) throws IOException {
return execShell(command, (Appendable) null, (Appendable) null, true);
}
private static Process createShellProcessObject(String command) throws IOException {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(new String[] { SHELL, SHELL_FLAGS, command });
return proc;
}
private static int execShell(
String command,
Appendable out,
Appendable err,
boolean discard
) throws IOException {
return waitForProcess(out, err, discard, createShellProcessObject(command));
}
private static int execShell(
String command,
Thread outputGobbler,
Thread errorGobbler,
boolean discard
) throws IOException {
return waitForProcess(outputGobbler, errorGobbler, discard, createShellProcessObject(command));
}
private static int waitForProcess(
Thread outputGobbler,
Thread errorGobbler,
boolean discard,
Process proc
) {
// kick them off
errorGobbler.start();
outputGobbler.start();
// return exit status
try {
// get the exit status of the command once finished
//
int exit = proc.waitFor();
// now wait for the output and error to be read with a suitable
// timeout
//
outputGobbler.join(TIMEOUT);
errorGobbler.join(TIMEOUT);
return exit;
} catch (InterruptedException e) {
// While the Process is running, the Thread is in the state
// called "WAITING". If an interrupt has been requested and caught
// within the thread, reinterrupting is requested.
//
// See
// http://download.oracle.com/javase/1,5.0/docs/guide/misc/threadPrimitiveDeprecation.html
// chapter
// Section "How do I stop a thread that waits for long periods (e.g., for input)?"
// for more details on this.
//
Thread.currentThread().interrupt();
return -1;
} finally {
// to make sure the all streams are closed to avoid open file handles
//
IOUtils.closeQuietly(proc.getErrorStream());
IOUtils.closeQuietly(proc.getInputStream());
IOUtils.closeQuietly(proc.getOutputStream());
// Otherwise we will be waiting for the process to terminate on
// its own instead of interrupting as the user has requested.
//
proc.destroy();
}
}
private static int waitForProcess(
Appendable out,
Appendable err,
boolean discard,
Process proc
) {
// any error message?
StreamGobbler errorGobbler = new StreamGobbler(
proc.getErrorStream(),
err,
discard
);
// any output?
StreamGobbler outputGobbler = new StreamGobbler(
proc.getInputStream(),
out,
discard
);
return waitForProcess(
outputGobbler,
errorGobbler,
discard,
proc
);
}
/**
* Execute the command and discard the output and error. If the process is
* timeconsuming, please use
* {@link #exec(String, Appendable, Appendable)} to avoid hangups
*
* @param command
* @return
* @throws IOException
*/
public static int execDirect(String command) throws IOException {
return execDirect(command, null, null, true);
}
/**
* Execute the command and capture the output and error. If the process is
* timeconsuming, please use
* {@link #exec(String, Appendable, Appendable)} to avoid hangups
*
* @param command
* @param out
* @param err
* @return
* @throws IOException
*/
public static int execDirect(String command, Appendable out,
Appendable err) throws IOException {
return execDirect(command, out, err, true);
}
/**
* @param command
* @param out
* @param err
* @param discard
* @return
* @throws IOException
*/
private static int execDirect(String command, Appendable out,
Appendable err, boolean discard) throws IOException {
// return exit status
try {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(command);
// get the exit status of the command once finished
int exit = proc.waitFor();
if (!discard) {
StreamGobbler.streamToBuffer(proc.getInputStream(), out);
StreamGobbler.streamToBuffer(proc.getErrorStream(), out);
}
return exit;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return -1;
}
}
}
|
src/org/ensembl/healthcheck/util/ProcessExec.java
|
/**
* File: ProcessExec.java
* Created by: dstaines
* Created on: Oct 25, 2006
* CVS: $Id$
*/
package org.ensembl.healthcheck.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.commons.io.IOUtils;
/**
* Class to consume a stream from an executing process to avoid lockups. Code
* derived but extensively modified from <a
* href="http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html">JavaWorld
* article</a>
*
* @author dstaines
*
*/
class StreamGobbler extends Thread {
InputStream is;
boolean discard = false;
Appendable out;
StreamGobbler(InputStream is, Appendable out, boolean discard) {
this.is = is;
this.out = out;
this.discard = discard;
}
public void run() {
try {
if (discard) {
while (is.read() != -1) {
}
} else {
streamToBuffer(is, out);
}
} catch (IOException ioe) {
throw new RuntimeException(ioe);
} finally {
InputOutputUtils.closeQuietly(is);
}
}
public static void streamToBuffer(InputStream is, Appendable out)
throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = null;
while ((line = reader.readLine()) != null) {
out.append(line);
out.append('\n');
}
reader.close();
}
}
/**
* Class to execute a process safely, avoiding hangups by consuming the output
*
* @author dstaines
*
*/
public class ProcessExec {
private static final String SHELL_FLAGS = "-c";
private static final String SHELL = "/bin/sh";
/**
* Time to wait in milliseconds for stream gobblers to finish
*/
private static final int TIMEOUT = 10000;
/**
* Execute the command, capturing the output and error streams to
* Appendables
*
* @param command
* @param out
* @param err
* @return
* @throws Exception
*/
public static int exec(String command, Appendable out, Appendable err)
throws IOException {
return exec(command, out, err, false);
}
public static int exec(String command, Appendable out, Appendable err, String[] environment)
throws IOException {
return exec(command, out, err, false, environment);
}
/**
* Execute the command, capturing the output and error streams to
* Appendables
*
* @param commandarray
* @param out
* @param err
* @return
* @throws Exception
*/
public static int exec(String[] commandarray, Appendable out, Appendable err)
throws IOException {
return exec(commandarray, out, err, false);
}
/**
* Execute the command, discarding output and error
*
* @param command
* @return
* @throws Exception
*/
public static int exec(String command) throws IOException {
return exec(command, null, null, true);
}
/**
* Execute the command, discarding output and error
*
* @param commandarray
* @return
* @throws Exception
*/
public static int exec(String[] commandarray) throws IOException {
return exec(commandarray, null, null, true);
}
/**
* Execute the command, capturing output/error into the supplied streams if
* required
*
* @param command
* @param out
* @param err
* @return
* @throws Exception
*/
private static int exec(String command, Appendable out, Appendable err,
boolean discard) throws IOException {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(command);
return waitForProcess(out, err, discard, proc);
}
private static int exec(
String command,
Appendable out,
Appendable err,
boolean discard,
String[] environment
) throws IOException {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(
command,
environment
);
return waitForProcess(out, err, discard, proc);
}
/**
* Execute the command, capturing output/error into the supplied streams if
* required
*
* @param commandarray
* @param out
* @param err
* @return
* @throws Exception
*/
private static int exec(String[] commandarray, Appendable out, Appendable err,
boolean discard) throws IOException {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(commandarray);
return waitForProcess(out, err, discard, proc);
}
/**
* Execute the specified shell command, capturing output and error
*
* @param command
* @return
* @throws Exception
*/
public static int execShell(
String command,
Appendable out,
Appendable err
) throws IOException {
return execShell(command, out, err, false);
}
/**
* Execute the specified shell command, discarding output and error
*
* @param command
* @return
* @throws Exception
*/
public static int execShell(String command) throws IOException {
return execShell(command, (Appendable) null, (Appendable) null, true);
}
private static Process createShellProcessObject(String command) throws IOException {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(new String[] { SHELL, SHELL_FLAGS, command });
return proc;
}
private static int execShell(
String command,
Appendable out,
Appendable err,
boolean discard
) throws IOException {
return waitForProcess(out, err, discard, createShellProcessObject(command));
}
private static int execShell(
String command,
Thread outputGobbler,
Thread errorGobbler,
boolean discard
) throws IOException {
return waitForProcess(outputGobbler, errorGobbler, discard, createShellProcessObject(command));
}
private static int waitForProcess(
Thread outputGobbler,
Thread errorGobbler,
boolean discard,
Process proc
) {
// kick them off
errorGobbler.start();
outputGobbler.start();
// return exit status
try {
// get the exit status of the command once finished
//
int exit = proc.waitFor();
// now wait for the output and error to be read with a suitable
// timeout
//
outputGobbler.join(TIMEOUT);
errorGobbler.join(TIMEOUT);
return exit;
} catch (InterruptedException e) {
// While the Process is running, the Thread is in the state
// called "WAITING". If an interrupt has been requested and caught
// within the thread, reinterrupting is requested.
//
// See
// http://download.oracle.com/javase/1,5.0/docs/guide/misc/threadPrimitiveDeprecation.html
// chapter
// Section "How do I stop a thread that waits for long periods (e.g., for input)?"
// for more details on this.
//
Thread.currentThread().interrupt();
return -1;
} finally {
// to make sure the all streams are closed to avoid open file handles
//
IOUtils.closeQuietly(proc.getErrorStream());
IOUtils.closeQuietly(proc.getInputStream());
IOUtils.closeQuietly(proc.getOutputStream());
// Otherwise we will be waiting for the process to terminate on
// its own instead of interrupting as the user has requested.
//
proc.destroy();
}
}
private static int waitForProcess(
Appendable out,
Appendable err,
boolean discard,
Process proc
) {
// any error message?
StreamGobbler errorGobbler = new StreamGobbler(
proc.getErrorStream(),
err,
discard
);
// any output?
StreamGobbler outputGobbler = new StreamGobbler(
proc.getInputStream(),
out,
discard
);
return waitForProcess(
outputGobbler,
errorGobbler,
discard,
proc
);
}
/**
* Execute the command and discard the output and error. If the process is
* timeconsuming, please use
* {@link #exec(String, Appendable, Appendable)} to avoid hangups
*
* @param command
* @return
* @throws IOException
*/
public static int execDirect(String command) throws IOException {
return execDirect(command, null, null, true);
}
/**
* Execute the command and capture the output and error. If the process is
* timeconsuming, please use
* {@link #exec(String, Appendable, Appendable)} to avoid hangups
*
* @param command
* @param out
* @param err
* @return
* @throws IOException
*/
public static int execDirect(String command, Appendable out,
Appendable err) throws IOException {
return execDirect(command, out, err, true);
}
/**
* @param command
* @param out
* @param err
* @param discard
* @return
* @throws IOException
*/
private static int execDirect(String command, Appendable out,
Appendable err, boolean discard) throws IOException {
// return exit status
try {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(command);
// get the exit status of the command once finished
int exit = proc.waitFor();
if (!discard) {
StreamGobbler.streamToBuffer(proc.getInputStream(), out);
StreamGobbler.streamToBuffer(proc.getErrorStream(), out);
}
return exit;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return -1;
}
}
}
|
*** empty log message ***
|
src/org/ensembl/healthcheck/util/ProcessExec.java
|
*** empty log message ***
|
|
Java
|
apache-2.0
|
07c3d221d2d36693610cfc21d90df830d1129c9c
| 0
|
CMPUT301F15T01/YesWeCandroid,CMPUT301F15T01/YesWeCandroid
|
// Copyright 2015 Andrea McIntosh, Dylan Ashley, Anju Eappen, Jenna Hatchard, Kirsten Svidal, Raghav Vamaraju
//
// 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 ca.ualberta.trinkettrader.User;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.Observer;
import ca.ualberta.trinkettrader.ElasticStorable;
import ca.ualberta.trinkettrader.Friends.FriendsList;
import ca.ualberta.trinkettrader.Friends.TrackedFriends.TrackedFriendsList;
import ca.ualberta.trinkettrader.Inventory.Inventory;
import ca.ualberta.trinkettrader.NotificationManager;
import ca.ualberta.trinkettrader.Trades.TradeManager;
import ca.ualberta.trinkettrader.User.Profile.UserProfile;
/**
* Abstract class representing a user of the app. This user may be either the
* LoggedInUser or a Friend. This class mainly acts as a container for all of
* the various classes that make up a user.
*/
public class User extends ElasticStorable implements ca.ualberta.trinkettrader.Observable {
protected FriendsList friendsList;
protected Inventory inventory;
protected NotificationManager notificationManager;
protected TrackedFriendsList trackedFriendsList;
protected TradeManager tradeManager;
protected UserProfile profile;
protected Boolean needToSave;
private ArrayList<Observer> observers;
/**
* Public constructor for user: initializes all attribute classes as empty classes with no
* active data.
*
* This constructor is called when the application has no information about the user (i.e. a new
* User) or when not all information about the user is available yet.
*/
public User() {
this.friendsList = new FriendsList();
this.inventory = new Inventory();
this.notificationManager = new NotificationManager();
this.trackedFriendsList = new TrackedFriendsList();
this.tradeManager = new TradeManager();
this.profile = new UserProfile();
this.needToSave = Boolean.TRUE;
}
/**
* A public constructor for User in the case where the user's details are known for all its
* attribute classes.
*/
public User(FriendsList friendsList, Inventory inventory, NotificationManager notificationManager, UserProfile profile, TrackedFriendsList trackedFriends, TradeManager tradeManager) {
this.friendsList = friendsList;
this.inventory = inventory;
this.notificationManager = notificationManager;
this.profile = profile;
this.trackedFriendsList = trackedFriends;
this.tradeManager = tradeManager;
this.needToSave = Boolean.TRUE;
}
public User(String email) {
}
protected String getJson() {
Gson gson = new Gson(); // Or use new GsonBuilder().create();
return gson.toJson(this); // serializes target to Json
}
protected void queueUpdate() {
}
/**
* Adds the specified observer to the list of observers. If it is already
* registered, it is not added a second time.
*
* @param observer the Observer to add.
*/
@Override
public void addObserver(Observer observer) {
observers.add(observer);
}
/**
* Removes the specified observer from the list of observers. Passing null
* won't do anything.
*
* @param observer the observer to remove.
*/
@Override
public synchronized void deleteObserver(Observer observer) {
observers.remove(observer);
}
/**
* If {@code hasChanged()} returns {@code true}, calls the {@code update()}
* method for every observer in the list of observers using null as the
* argument. Afterwards, calls {@code clearChanged()}.
* <p/>
* Equivalent to calling {@code notifyObservers(null)}.
*/
@Override
public void notifyObservers() {
for (Observer observer : observers) {
observer.notify();
}
}
/**
* Returns whether User's data needs to be locally cached. This variable is set when a change is
* made to the User's data.
*
* @return Boolean
*/
public Boolean getNeedToSave() {
//TODO: need to implement needToSave for friendslist as well...
return this.needToSave | this.profile.getNeedToSave() | this.inventory.getNeedToSave();
}
/**
* Sets whether User data needs to be locally cached. This Boolean should on be set only when
* changes to the User's data is made.
*
* @param needToSave
*/
protected void setNeedToSave(Boolean needToSave) {
this.needToSave = needToSave;
}
/**
* Returns User's friends
*
* @return FriendList
*/
public FriendsList getFriendsList() {
return friendsList;
}
/**
* Sets user's list of friends
*
* @param friendsList
*/
public void setFriendsList(FriendsList friendsList) {
this.friendsList = friendsList;
this.needToSave = Boolean.TRUE;
}
/**
* Returns user's inventory
*
* @return Inventory
*/
public Inventory getInventory() {
return inventory;
}
/**
* Sets user's inventory
*
* @param inventory
*/
public void setInventory(Inventory inventory) {
this.inventory = inventory;
this.needToSave = Boolean.TRUE;
}
/**
* Returns user's notification manager
*
* @return NotificationManager
*/
public NotificationManager getNotificationManager() {
return notificationManager;
}
/**
* Sets user's notification manager
*
* @param notificationManager
*/
public void setNotificationManager(NotificationManager notificationManager) {
this.notificationManager = notificationManager;
}
/**
* Returns user's UserProfle
*
* @return UserProfile
*/
public UserProfile getProfile() {
return profile;
}
/**
* Sets user's UserProfile
*
* @param profile
*/
public void setProfile(UserProfile profile) {
this.profile = profile;
this.needToSave = Boolean.TRUE;
}
/**
* Returns user's list of tracked friends
*
* @return TrackedFriendsList
*/
public TrackedFriendsList getTrackedFriendsList() {
return trackedFriendsList;
}
/**
* Sets user's list of tracked friends
*
* @param trackedFriendsList
*/
public void setTrackedFriends(TrackedFriendsList trackedFriendsList) {
this.trackedFriendsList = trackedFriendsList;
}
/**
* Returns user's trade manager
*
* @return TradeManager
*/
public TradeManager getTradeManager() {
return tradeManager;
}
/**
* Sets user's trade manager
*
* @param tradeManager
*/
public void setTradeManager(TradeManager tradeManager) {
this.tradeManager = tradeManager;
}
}
|
app/src/main/java/ca/ualberta/trinkettrader/User/User.java
|
// Copyright 2015 Andrea McIntosh, Dylan Ashley, Anju Eappen, Jenna Hatchard, Kirsten Svidal, Raghav Vamaraju
//
// 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 ca.ualberta.trinkettrader.User;
import java.util.ArrayList;
import java.util.Observer;
import ca.ualberta.trinkettrader.ElasticStorable;
import ca.ualberta.trinkettrader.Friends.FriendsList;
import ca.ualberta.trinkettrader.Friends.TrackedFriends.TrackedFriendsList;
import ca.ualberta.trinkettrader.Inventory.Inventory;
import ca.ualberta.trinkettrader.NotificationManager;
import ca.ualberta.trinkettrader.Trades.TradeManager;
import ca.ualberta.trinkettrader.User.Profile.UserProfile;
/**
* Abstract class representing a user of the app. This user may be either the
* LoggedInUser or a Friend. This class mainly acts as a container for all of
* the various classes that make up a user.
*/
public class User extends ElasticStorable implements ca.ualberta.trinkettrader.Observable {
protected FriendsList friendsList;
protected Inventory inventory;
protected NotificationManager notificationManager;
protected TrackedFriendsList trackedFriendsList;
protected TradeManager tradeManager;
protected UserProfile profile;
protected Boolean needToSave;
private ArrayList<Observer> observers;
/**
* Public constructor for user: initializes all attribute classes as empty classes with no
* active data.
*
* This constructor is called when the application has no information about the user (i.e. a new
* User) or when not all information about the user is available yet.
*/
public User() {
this.friendsList = new FriendsList();
this.inventory = new Inventory();
this.notificationManager = new NotificationManager();
this.trackedFriendsList = new TrackedFriendsList();
this.tradeManager = new TradeManager();
this.profile = new UserProfile();
this.needToSave = Boolean.TRUE;
}
/**
* A public constructor for User in the case where the user's details are known for all its
* attribute classes.
*/
public User(FriendsList friendsList, Inventory inventory, NotificationManager notificationManager, UserProfile profile, TrackedFriendsList trackedFriends, TradeManager tradeManager) {
this.friendsList = friendsList;
this.inventory = inventory;
this.notificationManager = notificationManager;
this.profile = profile;
this.trackedFriendsList = trackedFriends;
this.tradeManager = tradeManager;
this.needToSave = Boolean.TRUE;
}
public User(String email) {
}
protected String getJson() {
return new String();
}
protected void queueUpdate() {
}
/**
* Adds the specified observer to the list of observers. If it is already
* registered, it is not added a second time.
*
* @param observer the Observer to add.
*/
@Override
public void addObserver(Observer observer) {
observers.add(observer);
}
/**
* Removes the specified observer from the list of observers. Passing null
* won't do anything.
*
* @param observer the observer to remove.
*/
@Override
public synchronized void deleteObserver(Observer observer) {
observers.remove(observer);
}
/**
* If {@code hasChanged()} returns {@code true}, calls the {@code update()}
* method for every observer in the list of observers using null as the
* argument. Afterwards, calls {@code clearChanged()}.
* <p/>
* Equivalent to calling {@code notifyObservers(null)}.
*/
@Override
public void notifyObservers() {
for (Observer observer : observers) {
observer.notify();
}
}
/**
* Returns whether User's data needs to be locally cached. This variable is set when a change is
* made to the User's data.
*
* @return Boolean
*/
public Boolean getNeedToSave() {
//TODO: need to implement needToSave for friendslist as well...
return this.needToSave | this.profile.getNeedToSave() | this.inventory.getNeedToSave();
}
/**
* Sets whether User data needs to be locally cached. This Boolean should on be set only when
* changes to the User's data is made.
*
* @param needToSave
*/
protected void setNeedToSave(Boolean needToSave) {
this.needToSave = needToSave;
}
/**
* Returns User's friends
*
* @return FriendList
*/
public FriendsList getFriendsList() {
return friendsList;
}
/**
* Sets user's list of friends
*
* @param friendsList
*/
public void setFriendsList(FriendsList friendsList) {
this.friendsList = friendsList;
this.needToSave = Boolean.TRUE;
}
/**
* Returns user's inventory
*
* @return Inventory
*/
public Inventory getInventory() {
return inventory;
}
/**
* Sets user's inventory
*
* @param inventory
*/
public void setInventory(Inventory inventory) {
this.inventory = inventory;
this.needToSave = Boolean.TRUE;
}
/**
* Returns user's notification manager
*
* @return NotificationManager
*/
public NotificationManager getNotificationManager() {
return notificationManager;
}
/**
* Sets user's notification manager
*
* @param notificationManager
*/
public void setNotificationManager(NotificationManager notificationManager) {
this.notificationManager = notificationManager;
}
/**
* Returns user's UserProfle
*
* @return UserProfile
*/
public UserProfile getProfile() {
return profile;
}
/**
* Sets user's UserProfile
*
* @param profile
*/
public void setProfile(UserProfile profile) {
this.profile = profile;
this.needToSave = Boolean.TRUE;
}
/**
* Returns user's list of tracked friends
*
* @return TrackedFriendsList
*/
public TrackedFriendsList getTrackedFriendsList() {
return trackedFriendsList;
}
/**
* Sets user's list of tracked friends
*
* @param trackedFriendsList
*/
public void setTrackedFriends(TrackedFriendsList trackedFriendsList) {
this.trackedFriendsList = trackedFriendsList;
}
/**
* Returns user's trade manager
*
* @return TradeManager
*/
public TradeManager getTradeManager() {
return tradeManager;
}
/**
* Sets user's trade manager
*
* @param tradeManager
*/
public void setTradeManager(TradeManager tradeManager) {
this.tradeManager = tradeManager;
}
}
|
User toJson
|
app/src/main/java/ca/ualberta/trinkettrader/User/User.java
|
User toJson
|
|
Java
|
apache-2.0
|
22310ffbab0eaf3257240b3c9213af1eeb5de01f
| 0
|
gerrit-review/gerrit,qtproject/qtqa-gerrit,qtproject/qtqa-gerrit,joshuawilson/merrit,MerritCR/merrit,qtproject/qtqa-gerrit,joshuawilson/merrit,joshuawilson/merrit,GerritCodeReview/gerrit,MerritCR/merrit,WANdisco/gerrit,WANdisco/gerrit,WANdisco/gerrit,MerritCR/merrit,gerrit-review/gerrit,MerritCR/merrit,GerritCodeReview/gerrit,qtproject/qtqa-gerrit,GerritCodeReview/gerrit,gerrit-review/gerrit,GerritCodeReview/gerrit,gerrit-review/gerrit,qtproject/qtqa-gerrit,joshuawilson/merrit,gerrit-review/gerrit,MerritCR/merrit,joshuawilson/merrit,qtproject/qtqa-gerrit,joshuawilson/merrit,MerritCR/merrit,WANdisco/gerrit,qtproject/qtqa-gerrit,WANdisco/gerrit,gerrit-review/gerrit,joshuawilson/merrit,MerritCR/merrit,GerritCodeReview/gerrit,MerritCR/merrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,WANdisco/gerrit,gerrit-review/gerrit,GerritCodeReview/gerrit,WANdisco/gerrit,joshuawilson/merrit
|
// Copyright (C) 2009 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.google.gerrit.pgm;
import static com.google.gerrit.server.schema.DataSourceProvider.Context.MULTI_USER;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.MoreObjects;
import com.google.gerrit.common.ChangeHookRunner;
import com.google.gerrit.gpg.GpgModule;
import com.google.gerrit.httpd.AllRequestFilter;
import com.google.gerrit.httpd.GerritOptions;
import com.google.gerrit.httpd.GetUserFilter;
import com.google.gerrit.httpd.GitOverHttpModule;
import com.google.gerrit.httpd.H2CacheBasedWebSession;
import com.google.gerrit.httpd.HttpCanonicalWebUrlProvider;
import com.google.gerrit.httpd.RequestContextFilter;
import com.google.gerrit.httpd.WebModule;
import com.google.gerrit.httpd.WebSshGlueModule;
import com.google.gerrit.httpd.auth.oauth.OAuthModule;
import com.google.gerrit.httpd.auth.openid.OpenIdModule;
import com.google.gerrit.httpd.plugins.HttpPluginModule;
import com.google.gerrit.lifecycle.LifecycleManager;
import com.google.gerrit.lucene.LuceneIndexModule;
import com.google.gerrit.pgm.http.jetty.JettyEnv;
import com.google.gerrit.pgm.http.jetty.JettyModule;
import com.google.gerrit.pgm.http.jetty.ProjectQoSFilter;
import com.google.gerrit.pgm.util.ErrorLogFile;
import com.google.gerrit.pgm.util.LogFileCompressor;
import com.google.gerrit.pgm.util.RuntimeShutdown;
import com.google.gerrit.pgm.util.SiteProgram;
import com.google.gerrit.reviewdb.client.AuthType;
import com.google.gerrit.server.account.InternalAccountDirectory;
import com.google.gerrit.server.cache.h2.DefaultCacheFactory;
import com.google.gerrit.server.change.ChangeCleanupRunner;
import com.google.gerrit.server.config.AuthConfig;
import com.google.gerrit.server.config.AuthConfigModule;
import com.google.gerrit.server.config.CanonicalWebUrlModule;
import com.google.gerrit.server.config.CanonicalWebUrlProvider;
import com.google.gerrit.server.config.DownloadConfig;
import com.google.gerrit.server.config.GerritGlobalModule;
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.gerrit.server.config.RestCacheAdminModule;
import com.google.gerrit.server.git.ChangeCacheImplModule;
import com.google.gerrit.server.git.GarbageCollectionModule;
import com.google.gerrit.server.git.ReceiveCommitsExecutorModule;
import com.google.gerrit.server.git.WorkQueue;
import com.google.gerrit.server.index.DummyIndexModule;
import com.google.gerrit.server.index.IndexModule;
import com.google.gerrit.server.index.IndexModule.IndexType;
import com.google.gerrit.server.mail.SignedTokenEmailTokenVerifier;
import com.google.gerrit.server.mail.SmtpEmailSender;
import com.google.gerrit.server.mime.MimeUtil2Module;
import com.google.gerrit.server.patch.DiffExecutorModule;
import com.google.gerrit.server.plugins.PluginGuiceEnvironment;
import com.google.gerrit.server.plugins.PluginRestApiModule;
import com.google.gerrit.server.schema.DataSourceProvider;
import com.google.gerrit.server.schema.SchemaVersionCheck;
import com.google.gerrit.server.securestore.DefaultSecureStore;
import com.google.gerrit.server.securestore.SecureStore;
import com.google.gerrit.server.securestore.SecureStoreClassName;
import com.google.gerrit.server.securestore.SecureStoreProvider;
import com.google.gerrit.server.ssh.NoSshKeyCache;
import com.google.gerrit.server.ssh.NoSshModule;
import com.google.gerrit.server.ssh.SshAddressesModule;
import com.google.gerrit.sshd.SshHostKeyModule;
import com.google.gerrit.sshd.SshKeyCacheImpl;
import com.google.gerrit.sshd.SshModule;
import com.google.gerrit.sshd.commands.DefaultCommandModule;
import com.google.gerrit.sshd.commands.IndexCommandsModule;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Module;
import com.google.inject.Provider;
import com.google.inject.Stage;
import org.eclipse.jgit.lib.Config;
import org.kohsuke.args4j.Option;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.lang.Thread.UncaughtExceptionHandler;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
/** Run SSH daemon portions of Gerrit. */
public class Daemon extends SiteProgram {
private static final Logger log = LoggerFactory.getLogger(Daemon.class);
@Option(name = "--enable-httpd", usage = "Enable the internal HTTP daemon")
private Boolean httpd;
@Option(name = "--disable-httpd", usage = "Disable the internal HTTP daemon")
void setDisableHttpd(@SuppressWarnings("unused") boolean arg) {
httpd = false;
}
@Option(name = "--enable-sshd", usage = "Enable the internal SSH daemon")
private boolean sshd = true;
@Option(name = "--disable-sshd", usage = "Disable the internal SSH daemon")
void setDisableSshd(@SuppressWarnings("unused") boolean arg) {
sshd = false;
}
@Option(name = "--slave", usage = "Support fetch only")
private boolean slave;
@Option(name = "--console-log", usage = "Log to console (not $site_path/logs)")
private boolean consoleLog;
@Option(name = "-s", usage = "Start interactive shell")
private boolean inspector;
@Option(name = "--run-id", usage = "Cookie to store in $site_path/logs/gerrit.run")
private String runId;
@Option(name = "--headless", usage = "Don't start the UI frontend")
private boolean headless;
@Option(name = "--init", aliases = {"-i"},
usage = "Init site before starting the daemon")
private boolean doInit;
private final LifecycleManager manager = new LifecycleManager();
private Injector dbInjector;
private Injector cfgInjector;
private Config config;
private Injector sysInjector;
private Injector sshInjector;
private Injector webInjector;
private Injector httpdInjector;
private Path runFile;
private boolean test;
private AbstractModule luceneModule;
private Module emailModule;
private Runnable serverStarted;
private IndexType indexType;
public Daemon() {
}
@VisibleForTesting
public Daemon(Runnable serverStarted) {
this.serverStarted = serverStarted;
}
public void setEnableHttpd(boolean enable) {
httpd = enable;
}
@Override
public int run() throws Exception {
if (doInit) {
try {
new Init(getSitePath()).run();
} catch (Exception e) {
throw die("Init failed", e);
}
}
mustHaveValidSite();
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
log.error("Thread " + t.getName() + " threw exception", e);
}
});
if (runId != null) {
runFile = getSitePath().resolve("logs").resolve("gerrit.run");
}
if (httpd == null) {
httpd = !slave;
}
if (!httpd && !sshd) {
throw die("No services enabled, nothing to do");
}
try {
start();
RuntimeShutdown.add(new Runnable() {
@Override
public void run() {
log.info("caught shutdown, cleaning up");
if (runId != null) {
try {
Files.delete(runFile);
} catch (IOException err) {
log.warn("failed to delete " + runFile, err);
}
}
manager.stop();
}
});
log.info("Gerrit Code Review " + myVersion() + " ready");
if (runId != null) {
try {
Files.write(runFile, (runId + "\n").getBytes(UTF_8));
runFile.toFile().setReadable(true, false);
} catch (IOException err) {
log.warn("Cannot write --run-id to " + runFile, err);
}
}
if (serverStarted != null) {
serverStarted.run();
}
if (inspector) {
JythonShell shell = new JythonShell();
shell.set("m", manager);
shell.set("ds", dbInjector.getInstance(DataSourceProvider.class));
shell.set("schk", dbInjector.getInstance(SchemaVersionCheck.class));
shell.set("d", this);
shell.run();
} else {
RuntimeShutdown.waitFor();
}
return 0;
} catch (Throwable err) {
log.error("Unable to start daemon", err);
return 1;
}
}
@VisibleForTesting
public LifecycleManager getLifecycleManager() {
return manager;
}
@VisibleForTesting
public void setDatabaseForTesting(List<Module> modules) {
dbInjector = Guice.createInjector(Stage.PRODUCTION, modules);
test = true;
headless = true;
}
@VisibleForTesting
public void setEmailModuleForTesting(Module module) {
emailModule = module;
}
@VisibleForTesting
public void setLuceneModule(LuceneIndexModule m) {
luceneModule = m;
test = true;
}
@VisibleForTesting
public void start() throws IOException {
if (dbInjector == null) {
dbInjector = createDbInjector(MULTI_USER);
}
cfgInjector = createCfgInjector();
config = cfgInjector.getInstance(
Key.get(Config.class, GerritServerConfig.class));
if (!slave) {
initIndexType();
}
sysInjector = createSysInjector();
sysInjector.getInstance(PluginGuiceEnvironment.class)
.setDbCfgInjector(dbInjector, cfgInjector);
manager.add(dbInjector, cfgInjector, sysInjector);
if (!consoleLog) {
manager.add(ErrorLogFile.start(getSitePath(), config));
}
sshd &= !sshdOff();
if (sshd) {
initSshd();
}
if (MoreObjects.firstNonNull(httpd, true)) {
initHttpd();
}
manager.start();
}
@VisibleForTesting
public void stop() {
manager.stop();
}
private boolean sshdOff() {
return new SshAddressesModule().getListenAddresses(config).isEmpty();
}
private String myVersion() {
return com.google.gerrit.common.Version.getVersion();
}
private Injector createCfgInjector() {
final List<Module> modules = new ArrayList<>();
modules.add(new AuthConfigModule());
return dbInjector.createChildInjector(modules);
}
private Injector createSysInjector() {
final List<Module> modules = new ArrayList<>();
modules.add(SchemaVersionCheck.module());
modules.add(new LogFileCompressor.Module());
modules.add(new WorkQueue.Module());
modules.add(new ChangeHookRunner.Module());
modules.add(new ReceiveCommitsExecutorModule());
modules.add(new DiffExecutorModule());
modules.add(new MimeUtil2Module());
modules.add(cfgInjector.getInstance(GerritGlobalModule.class));
modules.add(new ChangeCacheImplModule(slave));
modules.add(new InternalAccountDirectory.Module());
modules.add(new DefaultCacheFactory.Module());
if (emailModule != null) {
modules.add(emailModule);
} else {
modules.add(new SmtpEmailSender.Module());
}
modules.add(new SignedTokenEmailTokenVerifier.Module());
modules.add(new PluginRestApiModule());
modules.add(new RestCacheAdminModule());
modules.add(new GpgModule(config));
modules.add(createIndexModule());
if (MoreObjects.firstNonNull(httpd, true)) {
modules.add(new CanonicalWebUrlModule() {
@Override
protected Class<? extends Provider<String>> provider() {
return HttpCanonicalWebUrlProvider.class;
}
});
} else {
modules.add(new CanonicalWebUrlModule() {
@Override
protected Class<? extends Provider<String>> provider() {
return CanonicalWebUrlProvider.class;
}
});
}
if (sshd) {
modules.add(SshKeyCacheImpl.module());
} else {
modules.add(NoSshKeyCache.module());
}
modules.add(new AbstractModule() {
@Override
protected void configure() {
bind(GerritOptions.class).toInstance(new GerritOptions(headless, slave));
if (test) {
bind(String.class).annotatedWith(SecureStoreClassName.class)
.toInstance(DefaultSecureStore.class.getName());
bind(SecureStore.class).toProvider(SecureStoreProvider.class);
}
}
});
modules.add(new GarbageCollectionModule());
modules.add(new ChangeCleanupRunner.Module());
return cfgInjector.createChildInjector(modules);
}
private AbstractModule createIndexModule() {
if (slave) {
return new DummyIndexModule();
}
switch (indexType) {
case LUCENE:
return luceneModule != null ? luceneModule : new LuceneIndexModule();
default:
throw new IllegalStateException("unsupported index.type = " + indexType);
}
}
private void initIndexType() {
indexType = IndexModule.getIndexType(cfgInjector);
switch (indexType) {
case LUCENE:
break;
default:
throw new IllegalStateException("unsupported index.type = " + indexType);
}
}
private void initSshd() {
sshInjector = createSshInjector();
sysInjector.getInstance(PluginGuiceEnvironment.class)
.setSshInjector(sshInjector);
manager.add(sshInjector);
}
private Injector createSshInjector() {
final List<Module> modules = new ArrayList<>();
modules.add(sysInjector.getInstance(SshModule.class));
if (!test) {
modules.add(new SshHostKeyModule());
}
modules.add(new DefaultCommandModule(slave,
sysInjector.getInstance(DownloadConfig.class)));
if (!slave && indexType == IndexType.LUCENE) {
modules.add(new IndexCommandsModule());
}
return sysInjector.createChildInjector(modules);
}
private void initHttpd() {
webInjector = createWebInjector();
sysInjector.getInstance(PluginGuiceEnvironment.class)
.setHttpInjector(webInjector);
sysInjector.getInstance(HttpCanonicalWebUrlProvider.class)
.setHttpServletRequest(
webInjector.getProvider(HttpServletRequest.class));
httpdInjector = createHttpdInjector();
manager.add(webInjector, httpdInjector);
}
private Injector createWebInjector() {
final List<Module> modules = new ArrayList<>();
if (sshd) {
modules.add(new ProjectQoSFilter.Module());
}
modules.add(RequestContextFilter.module());
modules.add(AllRequestFilter.module());
modules.add(H2CacheBasedWebSession.module());
modules.add(sysInjector.getInstance(GitOverHttpModule.class));
modules.add(sysInjector.getInstance(WebModule.class));
modules.add(new HttpPluginModule());
if (sshd) {
modules.add(sshInjector.getInstance(WebSshGlueModule.class));
} else {
modules.add(new NoSshModule());
}
AuthConfig authConfig = cfgInjector.getInstance(AuthConfig.class);
if (authConfig.getAuthType() == AuthType.OPENID ||
authConfig.getAuthType() == AuthType.OPENID_SSO) {
modules.add(new OpenIdModule());
} else if (authConfig.getAuthType() == AuthType.OAUTH) {
modules.add(new OAuthModule());
}
modules.add(sysInjector.getInstance(GetUserFilter.Module.class));
return sysInjector.createChildInjector(modules);
}
private Injector createHttpdInjector() {
final List<Module> modules = new ArrayList<>();
modules.add(new JettyModule(new JettyEnv(webInjector)));
return webInjector.createChildInjector(modules);
}
}
|
gerrit-pgm/src/main/java/com/google/gerrit/pgm/Daemon.java
|
// Copyright (C) 2009 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.google.gerrit.pgm;
import static com.google.gerrit.server.schema.DataSourceProvider.Context.MULTI_USER;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.MoreObjects;
import com.google.gerrit.common.ChangeHookRunner;
import com.google.gerrit.gpg.GpgModule;
import com.google.gerrit.httpd.AllRequestFilter;
import com.google.gerrit.httpd.GerritOptions;
import com.google.gerrit.httpd.GetUserFilter;
import com.google.gerrit.httpd.GitOverHttpModule;
import com.google.gerrit.httpd.H2CacheBasedWebSession;
import com.google.gerrit.httpd.HttpCanonicalWebUrlProvider;
import com.google.gerrit.httpd.RequestContextFilter;
import com.google.gerrit.httpd.WebModule;
import com.google.gerrit.httpd.WebSshGlueModule;
import com.google.gerrit.httpd.auth.oauth.OAuthModule;
import com.google.gerrit.httpd.auth.openid.OpenIdModule;
import com.google.gerrit.httpd.plugins.HttpPluginModule;
import com.google.gerrit.lifecycle.LifecycleManager;
import com.google.gerrit.lucene.LuceneIndexModule;
import com.google.gerrit.pgm.http.jetty.JettyEnv;
import com.google.gerrit.pgm.http.jetty.JettyModule;
import com.google.gerrit.pgm.http.jetty.ProjectQoSFilter;
import com.google.gerrit.pgm.util.ErrorLogFile;
import com.google.gerrit.pgm.util.LogFileCompressor;
import com.google.gerrit.pgm.util.RuntimeShutdown;
import com.google.gerrit.pgm.util.SiteProgram;
import com.google.gerrit.reviewdb.client.AuthType;
import com.google.gerrit.server.account.InternalAccountDirectory;
import com.google.gerrit.server.cache.h2.DefaultCacheFactory;
import com.google.gerrit.server.change.ChangeCleanupRunner;
import com.google.gerrit.server.config.AuthConfig;
import com.google.gerrit.server.config.AuthConfigModule;
import com.google.gerrit.server.config.CanonicalWebUrlModule;
import com.google.gerrit.server.config.CanonicalWebUrlProvider;
import com.google.gerrit.server.config.DownloadConfig;
import com.google.gerrit.server.config.GerritGlobalModule;
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.gerrit.server.config.RestCacheAdminModule;
import com.google.gerrit.server.git.ChangeCacheImplModule;
import com.google.gerrit.server.git.GarbageCollectionModule;
import com.google.gerrit.server.git.ReceiveCommitsExecutorModule;
import com.google.gerrit.server.git.WorkQueue;
import com.google.gerrit.server.index.DummyIndexModule;
import com.google.gerrit.server.index.IndexModule;
import com.google.gerrit.server.index.IndexModule.IndexType;
import com.google.gerrit.server.mail.SignedTokenEmailTokenVerifier;
import com.google.gerrit.server.mail.SmtpEmailSender;
import com.google.gerrit.server.mime.MimeUtil2Module;
import com.google.gerrit.server.patch.DiffExecutorModule;
import com.google.gerrit.server.plugins.PluginGuiceEnvironment;
import com.google.gerrit.server.plugins.PluginRestApiModule;
import com.google.gerrit.server.schema.DataSourceProvider;
import com.google.gerrit.server.schema.SchemaVersionCheck;
import com.google.gerrit.server.securestore.DefaultSecureStore;
import com.google.gerrit.server.securestore.SecureStore;
import com.google.gerrit.server.securestore.SecureStoreClassName;
import com.google.gerrit.server.securestore.SecureStoreProvider;
import com.google.gerrit.server.ssh.NoSshKeyCache;
import com.google.gerrit.server.ssh.NoSshModule;
import com.google.gerrit.server.ssh.SshAddressesModule;
import com.google.gerrit.sshd.SshHostKeyModule;
import com.google.gerrit.sshd.SshKeyCacheImpl;
import com.google.gerrit.sshd.SshModule;
import com.google.gerrit.sshd.commands.DefaultCommandModule;
import com.google.gerrit.sshd.commands.IndexCommandsModule;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Module;
import com.google.inject.Provider;
import com.google.inject.Stage;
import org.eclipse.jgit.lib.Config;
import org.kohsuke.args4j.Option;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.lang.Thread.UncaughtExceptionHandler;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
/** Run SSH daemon portions of Gerrit. */
public class Daemon extends SiteProgram {
private static final Logger log = LoggerFactory.getLogger(Daemon.class);
@Option(name = "--enable-httpd", usage = "Enable the internal HTTP daemon")
private Boolean httpd;
@Option(name = "--disable-httpd", usage = "Disable the internal HTTP daemon")
void setDisableHttpd(@SuppressWarnings("unused") boolean arg) {
httpd = false;
}
@Option(name = "--enable-sshd", usage = "Enable the internal SSH daemon")
private boolean sshd = true;
@Option(name = "--disable-sshd", usage = "Disable the internal SSH daemon")
void setDisableSshd(@SuppressWarnings("unused") boolean arg) {
sshd = false;
}
@Option(name = "--slave", usage = "Support fetch only")
private boolean slave;
@Option(name = "--console-log", usage = "Log to console (not $site_path/logs)")
private boolean consoleLog;
@Option(name = "-s", usage = "Start interactive shell")
private boolean inspector;
@Option(name = "--run-id", usage = "Cookie to store in $site_path/logs/gerrit.run")
private String runId;
@Option(name = "--headless", usage = "Don't start the UI frontend")
private boolean headless;
@Option(name = "--init", aliases = {"-i"},
usage = "Init site before starting the daemon")
private boolean doInit;
private final LifecycleManager manager = new LifecycleManager();
private Injector dbInjector;
private Injector cfgInjector;
private Config config;
private Injector sysInjector;
private Injector sshInjector;
private Injector webInjector;
private Injector httpdInjector;
private Path runFile;
private boolean test;
private AbstractModule luceneModule;
private Module emailModule;
private Runnable serverStarted;
private IndexType indexType;
public Daemon() {
}
@VisibleForTesting
public Daemon(Runnable serverStarted) {
this.serverStarted = serverStarted;
}
public void setEnableHttpd(boolean enable) {
httpd = enable;
}
@Override
public int run() throws Exception {
if (doInit) {
try {
new Init(getSitePath()).run();
} catch (Exception e) {
throw die("Init failed", e);
}
}
mustHaveValidSite();
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
log.error("Thread " + t.getName() + " threw exception", e);
}
});
if (runId != null) {
runFile = getSitePath().resolve("logs").resolve("gerrit.run");
}
if (httpd == null) {
httpd = !slave;
}
if (!httpd && !sshd) {
throw die("No services enabled, nothing to do");
}
try {
start();
RuntimeShutdown.add(new Runnable() {
@Override
public void run() {
log.info("caught shutdown, cleaning up");
if (runId != null) {
try {
Files.delete(runFile);
} catch (IOException err) {
log.warn("failed to delete " + runFile, err);
}
}
manager.stop();
}
});
log.info("Gerrit Code Review " + myVersion() + " ready");
if (runId != null) {
try {
Files.write(runFile, (runId + "\n").getBytes(UTF_8));
runFile.toFile().setReadable(true, false);
} catch (IOException err) {
log.warn("Cannot write --run-id to " + runFile, err);
}
}
if (serverStarted != null) {
serverStarted.run();
}
if (inspector) {
JythonShell shell = new JythonShell();
shell.set("m", manager);
shell.set("ds", dbInjector.getInstance(DataSourceProvider.class));
shell.set("schk", dbInjector.getInstance(SchemaVersionCheck.class));
shell.set("d", this);
shell.run();
} else {
RuntimeShutdown.waitFor();
}
return 0;
} catch (Throwable err) {
log.error("Unable to start daemon", err);
return 1;
}
}
@VisibleForTesting
public LifecycleManager getLifecycleManager() {
return manager;
}
@VisibleForTesting
public void setDatabaseForTesting(List<Module> modules) {
dbInjector = Guice.createInjector(Stage.PRODUCTION, modules);
test = true;
headless = true;
}
@VisibleForTesting
public void setEmailModuleForTesting(Module module) {
emailModule = module;
}
@VisibleForTesting
public void setLuceneModule(LuceneIndexModule m) {
luceneModule = m;
test = true;
}
@VisibleForTesting
public void start() throws IOException {
if (dbInjector == null) {
dbInjector = createDbInjector(MULTI_USER);
}
cfgInjector = createCfgInjector();
config = cfgInjector.getInstance(
Key.get(Config.class, GerritServerConfig.class));
initIndexType();
sysInjector = createSysInjector();
sysInjector.getInstance(PluginGuiceEnvironment.class)
.setDbCfgInjector(dbInjector, cfgInjector);
manager.add(dbInjector, cfgInjector, sysInjector);
if (!consoleLog) {
manager.add(ErrorLogFile.start(getSitePath(), config));
}
sshd &= !sshdOff();
if (sshd) {
initSshd();
}
if (MoreObjects.firstNonNull(httpd, true)) {
initHttpd();
}
manager.start();
}
@VisibleForTesting
public void stop() {
manager.stop();
}
private boolean sshdOff() {
return new SshAddressesModule().getListenAddresses(config).isEmpty();
}
private String myVersion() {
return com.google.gerrit.common.Version.getVersion();
}
private Injector createCfgInjector() {
final List<Module> modules = new ArrayList<>();
modules.add(new AuthConfigModule());
return dbInjector.createChildInjector(modules);
}
private Injector createSysInjector() {
final List<Module> modules = new ArrayList<>();
modules.add(SchemaVersionCheck.module());
modules.add(new LogFileCompressor.Module());
modules.add(new WorkQueue.Module());
modules.add(new ChangeHookRunner.Module());
modules.add(new ReceiveCommitsExecutorModule());
modules.add(new DiffExecutorModule());
modules.add(new MimeUtil2Module());
modules.add(cfgInjector.getInstance(GerritGlobalModule.class));
modules.add(new ChangeCacheImplModule(slave));
modules.add(new InternalAccountDirectory.Module());
modules.add(new DefaultCacheFactory.Module());
if (emailModule != null) {
modules.add(emailModule);
} else {
modules.add(new SmtpEmailSender.Module());
}
modules.add(new SignedTokenEmailTokenVerifier.Module());
modules.add(new PluginRestApiModule());
modules.add(new RestCacheAdminModule());
modules.add(new GpgModule(config));
modules.add(createIndexModule());
if (MoreObjects.firstNonNull(httpd, true)) {
modules.add(new CanonicalWebUrlModule() {
@Override
protected Class<? extends Provider<String>> provider() {
return HttpCanonicalWebUrlProvider.class;
}
});
} else {
modules.add(new CanonicalWebUrlModule() {
@Override
protected Class<? extends Provider<String>> provider() {
return CanonicalWebUrlProvider.class;
}
});
}
if (sshd) {
modules.add(SshKeyCacheImpl.module());
} else {
modules.add(NoSshKeyCache.module());
}
modules.add(new AbstractModule() {
@Override
protected void configure() {
bind(GerritOptions.class).toInstance(new GerritOptions(headless, slave));
if (test) {
bind(String.class).annotatedWith(SecureStoreClassName.class)
.toInstance(DefaultSecureStore.class.getName());
bind(SecureStore.class).toProvider(SecureStoreProvider.class);
}
}
});
modules.add(new GarbageCollectionModule());
modules.add(new ChangeCleanupRunner.Module());
return cfgInjector.createChildInjector(modules);
}
private AbstractModule createIndexModule() {
if (slave) {
return new DummyIndexModule();
}
switch (indexType) {
case LUCENE:
return luceneModule != null ? luceneModule : new LuceneIndexModule();
default:
throw new IllegalStateException("unsupported index.type = " + indexType);
}
}
private void initIndexType() {
indexType = IndexModule.getIndexType(cfgInjector);
switch (indexType) {
case LUCENE:
break;
default:
throw new IllegalStateException("unsupported index.type = " + indexType);
}
}
private void initSshd() {
sshInjector = createSshInjector();
sysInjector.getInstance(PluginGuiceEnvironment.class)
.setSshInjector(sshInjector);
manager.add(sshInjector);
}
private Injector createSshInjector() {
final List<Module> modules = new ArrayList<>();
modules.add(sysInjector.getInstance(SshModule.class));
if (!test) {
modules.add(new SshHostKeyModule());
}
modules.add(new DefaultCommandModule(slave,
sysInjector.getInstance(DownloadConfig.class)));
if (indexType == IndexType.LUCENE) {
modules.add(new IndexCommandsModule());
}
return sysInjector.createChildInjector(modules);
}
private void initHttpd() {
webInjector = createWebInjector();
sysInjector.getInstance(PluginGuiceEnvironment.class)
.setHttpInjector(webInjector);
sysInjector.getInstance(HttpCanonicalWebUrlProvider.class)
.setHttpServletRequest(
webInjector.getProvider(HttpServletRequest.class));
httpdInjector = createHttpdInjector();
manager.add(webInjector, httpdInjector);
}
private Injector createWebInjector() {
final List<Module> modules = new ArrayList<>();
if (sshd) {
modules.add(new ProjectQoSFilter.Module());
}
modules.add(RequestContextFilter.module());
modules.add(AllRequestFilter.module());
modules.add(H2CacheBasedWebSession.module());
modules.add(sysInjector.getInstance(GitOverHttpModule.class));
modules.add(sysInjector.getInstance(WebModule.class));
modules.add(new HttpPluginModule());
if (sshd) {
modules.add(sshInjector.getInstance(WebSshGlueModule.class));
} else {
modules.add(new NoSshModule());
}
AuthConfig authConfig = cfgInjector.getInstance(AuthConfig.class);
if (authConfig.getAuthType() == AuthType.OPENID ||
authConfig.getAuthType() == AuthType.OPENID_SSO) {
modules.add(new OpenIdModule());
} else if (authConfig.getAuthType() == AuthType.OAUTH) {
modules.add(new OAuthModule());
}
modules.add(sysInjector.getInstance(GetUserFilter.Module.class));
return sysInjector.createChildInjector(modules);
}
private Injector createHttpdInjector() {
final List<Module> modules = new ArrayList<>();
modules.add(new JettyModule(new JettyEnv(webInjector)));
return webInjector.createChildInjector(modules);
}
}
|
Daemon: Don't add index commands when running as slave
Bug: Issue 3694
Change-Id: I3c50269452d9599b74044014090a30e134b3b6ec
|
gerrit-pgm/src/main/java/com/google/gerrit/pgm/Daemon.java
|
Daemon: Don't add index commands when running as slave
|
|
Java
|
apache-2.0
|
a16bcf8e514ea1a505e826fc0e0d05f26acdcbd1
| 0
|
i2p/i2p.itoopie,i2p/i2p.itoopie,i2p/i2p.itoopie,i2p/i2p.itoopie
|
package net.i2p;
import java.io.File;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import net.i2p.client.naming.NamingService;
import net.i2p.client.naming.PetNameDB;
import net.i2p.crypto.AESEngine;
import net.i2p.crypto.CryptixAESEngine;
import net.i2p.crypto.DSAEngine;
import net.i2p.crypto.DummyDSAEngine;
import net.i2p.crypto.DummyElGamalEngine;
import net.i2p.crypto.DummyPooledRandomSource;
import net.i2p.crypto.ElGamalAESEngine;
import net.i2p.crypto.ElGamalEngine;
import net.i2p.crypto.HMAC256Generator;
import net.i2p.crypto.HMACGenerator;
import net.i2p.crypto.KeyGenerator;
import net.i2p.crypto.SHA256Generator;
import net.i2p.crypto.SessionKeyManager;
import net.i2p.crypto.TransientSessionKeyManager;
import net.i2p.data.DataHelper;
import net.i2p.data.RoutingKeyGenerator;
import net.i2p.stat.StatManager;
import net.i2p.util.Clock;
import net.i2p.util.ConcurrentHashSet;
import net.i2p.util.FileUtil;
import net.i2p.util.FortunaRandomSource;
import net.i2p.util.KeyRing;
import net.i2p.util.LogManager;
import net.i2p.util.PooledRandomSource;
import net.i2p.util.RandomSource;
/**
* <p>Provide a base scope for accessing singletons that I2P exposes. Rather than
* using the traditional singleton, where any component can access the component
* in question directly, all of those I2P related singletons are exposed through
* a particular I2PAppContext. This helps not only with understanding their use
* and the components I2P exposes, but it also allows multiple isolated
* environments to operate concurrently within the same JVM - particularly useful
* for stubbing out implementations of the rooted components and simulating the
* software's interaction between multiple instances.</p>
*
* As a simplification, there is also a global context - if some component needs
* access to one of the singletons but doesn't have its own context from which
* to root itself, it binds to the I2PAppContext's globalAppContext(), which is
* the first context that was created within the JVM, or a new one if no context
* existed already. This functionality is often used within the I2P core for
* logging - e.g. <pre>
* private static final Log _log = new Log(someClass.class);
* </pre>
* It is for this reason that applications that care about working with multiple
* contexts should build their own context as soon as possible (within the main(..))
* so that any referenced components will latch on to that context instead of
* instantiating a new one. However, there are situations in which both can be
* relevent.
*
*/
public class I2PAppContext {
/** the context that components without explicit root are bound */
protected static I2PAppContext _globalAppContext;
private Properties _overrideProps;
private StatManager _statManager;
private SessionKeyManager _sessionKeyManager;
private NamingService _namingService;
private PetNameDB _petnameDb;
private ElGamalEngine _elGamalEngine;
private ElGamalAESEngine _elGamalAESEngine;
private AESEngine _AESEngine;
private LogManager _logManager;
private HMACGenerator _hmac;
private HMAC256Generator _hmac256;
private SHA256Generator _sha;
protected Clock _clock; // overridden in RouterContext
private DSAEngine _dsa;
private RoutingKeyGenerator _routingKeyGenerator;
private RandomSource _random;
private KeyGenerator _keyGenerator;
protected KeyRing _keyRing; // overridden in RouterContext
private volatile boolean _statManagerInitialized;
private volatile boolean _sessionKeyManagerInitialized;
private volatile boolean _namingServiceInitialized;
private volatile boolean _petnameDbInitialized;
private volatile boolean _elGamalEngineInitialized;
private volatile boolean _elGamalAESEngineInitialized;
private volatile boolean _AESEngineInitialized;
private volatile boolean _logManagerInitialized;
private volatile boolean _hmacInitialized;
private volatile boolean _hmac256Initialized;
private volatile boolean _shaInitialized;
protected volatile boolean _clockInitialized; // used in RouterContext
private volatile boolean _dsaInitialized;
private volatile boolean _routingKeyGeneratorInitialized;
private volatile boolean _randomInitialized;
private volatile boolean _keyGeneratorInitialized;
protected volatile boolean _keyRingInitialized; // used in RouterContext
private Set<Runnable> _shutdownTasks;
private File _baseDir;
private File _configDir;
private File _routerDir;
private File _pidDir;
private File _logDir;
private File _appDir;
private File _tmpDir;
/**
* Pull the default context, creating a new one if necessary, else using
* the first one created.
*
*/
public static I2PAppContext getGlobalContext() {
synchronized (I2PAppContext.class) {
if (_globalAppContext == null) {
_globalAppContext = new I2PAppContext(false, null);
}
}
return _globalAppContext;
}
/**
* Lets root a brand new context
*
*/
public I2PAppContext() {
this(true, null);
}
/**
* Lets root a brand new context
*
*/
public I2PAppContext(Properties envProps) {
this(true, envProps);
}
/**
* @param doInit should this context be used as the global one (if necessary)?
*/
private I2PAppContext(boolean doInit, Properties envProps) {
if (doInit) {
synchronized (I2PAppContext.class) {
if (_globalAppContext == null)
_globalAppContext = this;
}
}
_overrideProps = envProps;
_statManager = null;
_sessionKeyManager = null;
_namingService = null;
_petnameDb = null;
_elGamalEngine = null;
_elGamalAESEngine = null;
_logManager = null;
_keyRing = null;
_statManagerInitialized = false;
_sessionKeyManagerInitialized = false;
_namingServiceInitialized = false;
_elGamalEngineInitialized = false;
_elGamalAESEngineInitialized = false;
_logManagerInitialized = false;
_keyRingInitialized = false;
_shutdownTasks = new ConcurrentHashSet(0);
initializeDirs();
}
/**
* Directories. These are all set at instantiation and will not be changed by
* subsequent property changes.
* All properties, if set, should be absolute paths.
*
* Name Property Method Files
* ----- -------- ----- -----
* Base i2p.dir.base getBaseDir() lib/, webapps/, docs/, geoip/, licenses/, ...
* Temp i2p.dir.temp getTempDir() Temporary files
* Config i2p.dir.config getConfigDir() *.config, hosts.txt, addressbook/, ...
* PID i2p.dir.pid getPIDDir() wrapper *.pid files, router.ping
*
* (the following all default to the same as Config)
*
* Router i2p.dir.router getRouterDir() netDb/, peerProfiles/, router.*, keyBackup/, ...
* Log i2p.dir.log getLogDir() wrapper.log*, logs/
* App i2p.dir.app getAppDir() eepsite/, ...
*
* Note that we can't control where the wrapper puts its files.
*
* The app dir is where all data files should be. Apps should always read and write files here,
* using a constructor such as:
*
* String path = mypath;
* File f = new File(path);
* if (!f.isAbsolute())
* f = new File(_context.geAppDir(), path);
*
* and never attempt to access files in the CWD using
*
* File f = new File("foo");
*
* An app should assume the CWD is not writable.
*
* Here in I2PAppContext, all the dirs default to CWD.
* However these will be different in RouterContext, as Router.java will set
* the properties in the RouterContext constructor.
*
* Apps should never need to access the base dir, which is the location of the base I2P install.
* However this is provided for the router's use, and for backward compatibility should an app
* need to look there as well.
*
* All dirs except the base are created if they don't exist, but the creation will fail silently.
*/
private void initializeDirs() {
String s = getProperty("i2p.dir.base", System.getProperty("user.dir"));
_baseDir = new File(s);
// config defaults to base
s = getProperty("i2p.dir.config");
if (s != null) {
_configDir = new File(s);
if (!_configDir.exists())
_configDir.mkdir();
} else {
_configDir = _baseDir;
}
_configDir = new File(s);
// router defaults to config
s = getProperty("i2p.dir.router");
if (s != null) {
_routerDir = new File(s);
if (!_routerDir.exists())
_routerDir.mkdir();
} else {
_routerDir = _configDir;
}
// pid defaults to system temp directory
s = getProperty("i2p.dir.pid", System.getProperty("java.io.tmpdir"));
_pidDir = new File(s);
if (!_pidDir.exists())
_pidDir.mkdir();
// these all default to router
s = getProperty("i2p.dir.log");
if (s != null) {
_logDir = new File(s);
if (!_logDir.exists())
_logDir.mkdir();
} else {
_logDir = _routerDir;
}
s = getProperty("i2p.dir.app");
if (s != null) {
_appDir = new File(s);
if (!_appDir.exists())
_appDir.mkdir();
} else {
_appDir = _routerDir;
}
// comment these out later, don't want user names in the wrapper logs
System.err.println("Base directory: " + _baseDir.getAbsolutePath());
System.err.println("Config directory: " + _configDir.getAbsolutePath());
System.err.println("Router directory: " + _routerDir.getAbsolutePath());
System.err.println("App directory: " + _appDir.getAbsolutePath());
System.err.println("Log directory: " + _logDir.getAbsolutePath());
System.err.println("PID directory: " + _pidDir.getAbsolutePath());
System.err.println("Temp directory: " + getTempDir().getAbsolutePath());
}
public File getBaseDir() { return _baseDir; }
public File getConfigDir() { return _configDir; }
public File getRouterDir() { return _routerDir; }
public File getPIDDir() { return _pidDir; }
public File getLogDir() { return _logDir; }
public File getAppDir() { return _appDir; }
public File getTempDir() {
// fixme don't synchronize every time
synchronized (this) {
if (_tmpDir == null) {
String d = getProperty("i2p.dir.temp", System.getProperty("java.io.tmpdir"));
// our random() probably isn't warmed up yet
String f = "i2p-" + (new java.util.Random()).nextInt() + ".tmp";
_tmpDir = new File(d, f);
if (_tmpDir.exists()) {
// good or bad ?
} else if (_tmpDir.mkdir()) {
_tmpDir.deleteOnExit();
} else {
System.err.println("Could not create temp dir " + _tmpDir.getAbsolutePath());
_tmpDir = new File(_routerDir, "tmp");
_tmpDir.mkdir();
}
}
}
return _tmpDir;
}
/** don't rely on deleteOnExit() */
public void deleteTempDir() {
synchronized (this) {
if (_tmpDir != null) {
FileUtil.rmdir(_tmpDir, false);
_tmpDir = null;
}
}
}
/**
* Access the configuration attributes of this context, using properties
* provided during the context construction, or falling back on
* System.getProperty if no properties were provided during construction
* (or the specified prop wasn't included).
*
*/
public String getProperty(String propName) {
if (_overrideProps != null) {
if (_overrideProps.containsKey(propName))
return _overrideProps.getProperty(propName);
}
return System.getProperty(propName);
}
/**
* Access the configuration attributes of this context, using properties
* provided during the context construction, or falling back on
* System.getProperty if no properties were provided during construction
* (or the specified prop wasn't included).
*
*/
public String getProperty(String propName, String defaultValue) {
if (_overrideProps != null) {
if (_overrideProps.containsKey(propName))
return _overrideProps.getProperty(propName, defaultValue);
}
return System.getProperty(propName, defaultValue);
}
/**
* Return an int with an int default
*/
public int getProperty(String propName, int defaultVal) {
String val = null;
if (_overrideProps != null) {
val = _overrideProps.getProperty(propName);
if (val == null)
val = System.getProperty(propName);
}
int ival = defaultVal;
if (val != null) {
try {
ival = Integer.parseInt(val);
} catch (NumberFormatException nfe) {}
}
return ival;
}
/**
* Access the configuration attributes of this context, listing the properties
* provided during the context construction, as well as the ones included in
* System.getProperties.
*
* @return set of Strings containing the names of defined system properties
*/
public Set getPropertyNames() {
Set names = new HashSet(System.getProperties().keySet());
if (_overrideProps != null)
names.addAll(_overrideProps.keySet());
return names;
}
/**
* The statistics component with which we can track various events
* over time.
*/
public StatManager statManager() {
if (!_statManagerInitialized)
initializeStatManager();
return _statManager;
}
private void initializeStatManager() {
synchronized (this) {
if (_statManager == null)
_statManager = new StatManager(this);
_statManagerInitialized = true;
}
}
/**
* The session key manager which coordinates the sessionKey / sessionTag
* data. This component allows transparent operation of the
* ElGamal/AES+SessionTag algorithm, and contains all of the session tags
* for one particular application. If you want to seperate multiple apps
* to have their own sessionTags and sessionKeys, they should use different
* I2PAppContexts, and hence, different sessionKeyManagers.
*
*/
public SessionKeyManager sessionKeyManager() {
if (!_sessionKeyManagerInitialized)
initializeSessionKeyManager();
return _sessionKeyManager;
}
private void initializeSessionKeyManager() {
synchronized (this) {
if (_sessionKeyManager == null)
//_sessionKeyManager = new PersistentSessionKeyManager(this);
_sessionKeyManager = new TransientSessionKeyManager(this);
_sessionKeyManagerInitialized = true;
}
}
/**
* Pull up the naming service used in this context. The naming service itself
* works by querying the context's properties, so those props should be
* specified to customize the naming service exposed.
*/
public NamingService namingService() {
if (!_namingServiceInitialized)
initializeNamingService();
return _namingService;
}
private void initializeNamingService() {
synchronized (this) {
if (_namingService == null) {
_namingService = NamingService.createInstance(this);
}
_namingServiceInitialized = true;
}
}
public PetNameDB petnameDb() {
if (!_petnameDbInitialized)
initializePetnameDb();
return _petnameDb;
}
private void initializePetnameDb() {
synchronized (this) {
if (_petnameDb == null) {
_petnameDb = new PetNameDB();
}
_petnameDbInitialized = true;
}
}
/**
* This is the ElGamal engine used within this context. While it doesn't
* really have anything substantial that is context specific (the algorithm
* just does the algorithm), it does transparently use the context for logging
* its performance and activity. In addition, the engine can be swapped with
* the context's properties (though only someone really crazy should mess with
* it ;)
*/
public ElGamalEngine elGamalEngine() {
if (!_elGamalEngineInitialized)
initializeElGamalEngine();
return _elGamalEngine;
}
private void initializeElGamalEngine() {
synchronized (this) {
if (_elGamalEngine == null) {
if ("off".equals(getProperty("i2p.encryption", "on")))
_elGamalEngine = new DummyElGamalEngine(this);
else
_elGamalEngine = new ElGamalEngine(this);
}
_elGamalEngineInitialized = true;
}
}
/**
* Access the ElGamal/AES+SessionTag engine for this context. The algorithm
* makes use of the context's sessionKeyManager to coordinate transparent
* access to the sessionKeys and sessionTags, as well as the context's elGamal
* engine (which in turn keeps stats, etc).
*
*/
public ElGamalAESEngine elGamalAESEngine() {
if (!_elGamalAESEngineInitialized)
initializeElGamalAESEngine();
return _elGamalAESEngine;
}
private void initializeElGamalAESEngine() {
synchronized (this) {
if (_elGamalAESEngine == null)
_elGamalAESEngine = new ElGamalAESEngine(this);
_elGamalAESEngineInitialized = true;
}
}
/**
* Ok, I'll admit it. there is no good reason for having a context specific
* AES engine. We dont really keep stats on it, since its just too fast to
* matter. Though for the crazy people out there, we do expose a way to
* disable it.
*/
public AESEngine aes() {
if (!_AESEngineInitialized)
initializeAESEngine();
return _AESEngine;
}
private void initializeAESEngine() {
synchronized (this) {
if (_AESEngine == null) {
if ("off".equals(getProperty("i2p.encryption", "on")))
_AESEngine = new AESEngine(this);
else
_AESEngine = new CryptixAESEngine(this);
}
_AESEngineInitialized = true;
}
}
/**
* Query the log manager for this context, which may in turn have its own
* set of configuration settings (loaded from the context's properties).
* Each context's logManager keeps its own isolated set of Log instances with
* their own log levels, output locations, and rotation configuration.
*/
public LogManager logManager() {
if (!_logManagerInitialized)
initializeLogManager();
return _logManager;
}
private void initializeLogManager() {
synchronized (this) {
if (_logManager == null)
_logManager = new LogManager(this);
_logManagerInitialized = true;
}
}
/**
* There is absolutely no good reason to make this context specific,
* other than for consistency, and perhaps later we'll want to
* include some stats.
*/
public HMACGenerator hmac() {
if (!_hmacInitialized)
initializeHMAC();
return _hmac;
}
private void initializeHMAC() {
synchronized (this) {
if (_hmac == null) {
_hmac= new HMACGenerator(this);
}
_hmacInitialized = true;
}
}
public HMAC256Generator hmac256() {
if (!_hmac256Initialized)
initializeHMAC256();
return _hmac256;
}
private void initializeHMAC256() {
synchronized (this) {
if (_hmac256 == null) {
_hmac256 = new HMAC256Generator(this);
}
_hmac256Initialized = true;
}
}
/**
* Our SHA256 instance (see the hmac discussion for why its context specific)
*
*/
public SHA256Generator sha() {
if (!_shaInitialized)
initializeSHA();
return _sha;
}
private void initializeSHA() {
synchronized (this) {
if (_sha == null)
_sha= new SHA256Generator(this);
_shaInitialized = true;
}
}
/**
* Our DSA engine (see HMAC and SHA above)
*
*/
public DSAEngine dsa() {
if (!_dsaInitialized)
initializeDSA();
return _dsa;
}
private void initializeDSA() {
synchronized (this) {
if (_dsa == null) {
if ("off".equals(getProperty("i2p.encryption", "on")))
_dsa = new DummyDSAEngine(this);
else
_dsa = new DSAEngine(this);
}
_dsaInitialized = true;
}
}
/**
* Component to generate ElGamal, DSA, and Session keys. For why it is in
* the appContext, see the DSA, HMAC, and SHA comments above.
*/
public KeyGenerator keyGenerator() {
if (!_keyGeneratorInitialized)
initializeKeyGenerator();
return _keyGenerator;
}
private void initializeKeyGenerator() {
synchronized (this) {
if (_keyGenerator == null)
_keyGenerator = new KeyGenerator(this);
_keyGeneratorInitialized = true;
}
}
/**
* The context's synchronized clock, which is kept context specific only to
* enable simulators to play with clock skew among different instances.
*
*/
public Clock clock() { // overridden in RouterContext
if (!_clockInitialized)
initializeClock();
return _clock;
}
protected void initializeClock() { // overridden in RouterContext
synchronized (this) {
if (_clock == null)
_clock = new Clock(this);
_clockInitialized = true;
}
}
/**
* Determine how much do we want to mess with the keys to turn them
* into something we can route. This is context specific because we
* may want to test out how things react when peers don't agree on
* how to skew.
*
*/
public RoutingKeyGenerator routingKeyGenerator() {
if (!_routingKeyGeneratorInitialized)
initializeRoutingKeyGenerator();
return _routingKeyGenerator;
}
private void initializeRoutingKeyGenerator() {
synchronized (this) {
if (_routingKeyGenerator == null)
_routingKeyGenerator = new RoutingKeyGenerator(this);
_routingKeyGeneratorInitialized = true;
}
}
/**
* Basic hash map
*/
public KeyRing keyRing() {
if (!_keyRingInitialized)
initializeKeyRing();
return _keyRing;
}
protected void initializeKeyRing() {
synchronized (this) {
if (_keyRing == null)
_keyRing = new KeyRing();
_keyRingInitialized = true;
}
}
/**
* [insert snarky comment here]
*
*/
public RandomSource random() {
if (!_randomInitialized)
initializeRandom();
return _random;
}
private void initializeRandom() {
synchronized (this) {
if (_random == null) {
if (true)
_random = new FortunaRandomSource(this);
else if ("true".equals(getProperty("i2p.weakPRNG", "false")))
_random = new DummyPooledRandomSource(this);
else
_random = new PooledRandomSource(this);
}
_randomInitialized = true;
}
}
public void addShutdownTask(Runnable task) {
_shutdownTasks.add(task);
}
public Set<Runnable> getShutdownTasks() {
return new HashSet(_shutdownTasks);
}
}
|
core/java/src/net/i2p/I2PAppContext.java
|
package net.i2p;
import java.io.File;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import net.i2p.client.naming.NamingService;
import net.i2p.client.naming.PetNameDB;
import net.i2p.crypto.AESEngine;
import net.i2p.crypto.CryptixAESEngine;
import net.i2p.crypto.DSAEngine;
import net.i2p.crypto.DummyDSAEngine;
import net.i2p.crypto.DummyElGamalEngine;
import net.i2p.crypto.DummyPooledRandomSource;
import net.i2p.crypto.ElGamalAESEngine;
import net.i2p.crypto.ElGamalEngine;
import net.i2p.crypto.HMAC256Generator;
import net.i2p.crypto.HMACGenerator;
import net.i2p.crypto.KeyGenerator;
import net.i2p.crypto.SHA256Generator;
import net.i2p.crypto.SessionKeyManager;
import net.i2p.crypto.TransientSessionKeyManager;
import net.i2p.data.DataHelper;
import net.i2p.data.RoutingKeyGenerator;
import net.i2p.stat.StatManager;
import net.i2p.util.Clock;
import net.i2p.util.ConcurrentHashSet;
import net.i2p.util.FileUtil;
import net.i2p.util.FortunaRandomSource;
import net.i2p.util.KeyRing;
import net.i2p.util.LogManager;
import net.i2p.util.PooledRandomSource;
import net.i2p.util.RandomSource;
/**
* <p>Provide a base scope for accessing singletons that I2P exposes. Rather than
* using the traditional singleton, where any component can access the component
* in question directly, all of those I2P related singletons are exposed through
* a particular I2PAppContext. This helps not only with understanding their use
* and the components I2P exposes, but it also allows multiple isolated
* environments to operate concurrently within the same JVM - particularly useful
* for stubbing out implementations of the rooted components and simulating the
* software's interaction between multiple instances.</p>
*
* As a simplification, there is also a global context - if some component needs
* access to one of the singletons but doesn't have its own context from which
* to root itself, it binds to the I2PAppContext's globalAppContext(), which is
* the first context that was created within the JVM, or a new one if no context
* existed already. This functionality is often used within the I2P core for
* logging - e.g. <pre>
* private static final Log _log = new Log(someClass.class);
* </pre>
* It is for this reason that applications that care about working with multiple
* contexts should build their own context as soon as possible (within the main(..))
* so that any referenced components will latch on to that context instead of
* instantiating a new one. However, there are situations in which both can be
* relevent.
*
*/
public class I2PAppContext {
/** the context that components without explicit root are bound */
protected static I2PAppContext _globalAppContext;
private Properties _overrideProps;
private StatManager _statManager;
private SessionKeyManager _sessionKeyManager;
private NamingService _namingService;
private PetNameDB _petnameDb;
private ElGamalEngine _elGamalEngine;
private ElGamalAESEngine _elGamalAESEngine;
private AESEngine _AESEngine;
private LogManager _logManager;
private HMACGenerator _hmac;
private HMAC256Generator _hmac256;
private SHA256Generator _sha;
protected Clock _clock; // overridden in RouterContext
private DSAEngine _dsa;
private RoutingKeyGenerator _routingKeyGenerator;
private RandomSource _random;
private KeyGenerator _keyGenerator;
protected KeyRing _keyRing; // overridden in RouterContext
private volatile boolean _statManagerInitialized;
private volatile boolean _sessionKeyManagerInitialized;
private volatile boolean _namingServiceInitialized;
private volatile boolean _petnameDbInitialized;
private volatile boolean _elGamalEngineInitialized;
private volatile boolean _elGamalAESEngineInitialized;
private volatile boolean _AESEngineInitialized;
private volatile boolean _logManagerInitialized;
private volatile boolean _hmacInitialized;
private volatile boolean _hmac256Initialized;
private volatile boolean _shaInitialized;
protected volatile boolean _clockInitialized; // used in RouterContext
private volatile boolean _dsaInitialized;
private volatile boolean _routingKeyGeneratorInitialized;
private volatile boolean _randomInitialized;
private volatile boolean _keyGeneratorInitialized;
protected volatile boolean _keyRingInitialized; // used in RouterContext
private Set<Runnable> _shutdownTasks;
private File _baseDir;
private File _configDir;
private File _routerDir;
private File _pidDir;
private File _logDir;
private File _appDir;
private File _tmpDir;
/**
* Pull the default context, creating a new one if necessary, else using
* the first one created.
*
*/
public static I2PAppContext getGlobalContext() {
synchronized (I2PAppContext.class) {
if (_globalAppContext == null) {
_globalAppContext = new I2PAppContext(false, null);
}
}
return _globalAppContext;
}
/**
* Lets root a brand new context
*
*/
public I2PAppContext() {
this(true, null);
}
/**
* Lets root a brand new context
*
*/
public I2PAppContext(Properties envProps) {
this(true, envProps);
}
/**
* @param doInit should this context be used as the global one (if necessary)?
*/
private I2PAppContext(boolean doInit, Properties envProps) {
if (doInit) {
synchronized (I2PAppContext.class) {
if (_globalAppContext == null)
_globalAppContext = this;
}
}
_overrideProps = envProps;
_statManager = null;
_sessionKeyManager = null;
_namingService = null;
_petnameDb = null;
_elGamalEngine = null;
_elGamalAESEngine = null;
_logManager = null;
_keyRing = null;
_statManagerInitialized = false;
_sessionKeyManagerInitialized = false;
_namingServiceInitialized = false;
_elGamalEngineInitialized = false;
_elGamalAESEngineInitialized = false;
_logManagerInitialized = false;
_keyRingInitialized = false;
_shutdownTasks = new ConcurrentHashSet(0);
initializeDirs();
}
/**
* Directories. These are all set at instantiation and will not be changed by
* subsequent property changes.
* All properties, if set, should be absolute paths.
*
* Name Property Method Files
* ----- -------- ----- -----
* Base i2p.dir.base getBaseDir() lib/, webapps/, docs/, geoip/, licenses/, ...
* Temp i2p.dir.temp getTempDir() Temporary files
* Config i2p.dir.config getConfigDir() *.config, hosts.txt, addressbook/, ...
*
* (the following all default to the same as Config)
*
* Router i2p.dir.router getRouterDir() netDb/, peerProfiles/, router.*, keyBackup/, ...
* Log i2p.dir.log getLogDir() wrapper.log*, logs/
* PID i2p.dir.pid getPIDDir() wrapper *.pid files, router.ping
* App i2p.dir.app getAppDir() eepsite/, ...
*
* Note that we can't control where the wrapper puts its files.
*
* The app dir is where all data files should be. Apps should always read and write files here,
* using a constructor such as:
*
* String path = mypath;
* File f = new File(path);
* if (!f.isAbsolute())
* f = new File(_context.geAppDir(), path);
*
* and never attempt to access files in the CWD using
*
* File f = new File("foo");
*
* An app should assume the CWD is not writable.
*
* Here in I2PAppContext, all the dirs default to CWD.
* However these will be different in RouterContext, as Router.java will set
* the properties in the RouterContext constructor.
*
* Apps should never need to access the base dir, which is the location of the base I2P install.
* However this is provided for the router's use, and for backward compatibility should an app
* need to look there as well.
*
* All dirs except the base are created if they don't exist, but the creation will fail silently.
*/
private void initializeDirs() {
String s = getProperty("i2p.dir.base", System.getProperty("user.dir"));
_baseDir = new File(s);
// config defaults to base
s = getProperty("i2p.dir.config");
if (s != null) {
_configDir = new File(s);
if (!_configDir.exists())
_configDir.mkdir();
} else {
_configDir = _baseDir;
}
_configDir = new File(s);
// router defaults to config
s = getProperty("i2p.dir.router");
if (s != null) {
_routerDir = new File(s);
if (!_routerDir.exists())
_routerDir.mkdir();
} else {
_routerDir = _configDir;
}
// these all default to router
s = getProperty("i2p.dir.pid");
if (s != null) {
_pidDir = new File(s);
if (!_pidDir.exists())
_pidDir.mkdir();
} else {
_pidDir = _routerDir;
}
s = getProperty("i2p.dir.log");
if (s != null) {
_logDir = new File(s);
if (!_logDir.exists())
_logDir.mkdir();
} else {
_logDir = _routerDir;
}
s = getProperty("i2p.dir.app");
if (s != null) {
_appDir = new File(s);
if (!_appDir.exists())
_appDir.mkdir();
} else {
_appDir = _routerDir;
}
// comment these out later, don't want user names in the wrapper logs
System.err.println("Base directory: " + _baseDir.getAbsolutePath());
System.err.println("Config directory: " + _configDir.getAbsolutePath());
System.err.println("Router directory: " + _routerDir.getAbsolutePath());
System.err.println("App directory: " + _appDir.getAbsolutePath());
System.err.println("Log directory: " + _logDir.getAbsolutePath());
System.err.println("PID directory: " + _pidDir.getAbsolutePath());
System.err.println("Temp directory: " + getTempDir().getAbsolutePath());
}
public File getBaseDir() { return _baseDir; }
public File getConfigDir() { return _configDir; }
public File getRouterDir() { return _routerDir; }
public File getPIDDir() { return _pidDir; }
public File getLogDir() { return _logDir; }
public File getAppDir() { return _appDir; }
public File getTempDir() {
// fixme don't synchronize every time
synchronized (this) {
if (_tmpDir == null) {
String d = getProperty("i2p.dir.temp", System.getProperty("java.io.tmpdir"));
// our random() probably isn't warmed up yet
String f = "i2p-" + (new java.util.Random()).nextInt() + ".tmp";
_tmpDir = new File(d, f);
if (_tmpDir.exists()) {
// good or bad ?
} else if (_tmpDir.mkdir()) {
_tmpDir.deleteOnExit();
} else {
System.err.println("Could not create temp dir " + _tmpDir.getAbsolutePath());
_tmpDir = new File(_routerDir, "tmp");
_tmpDir.mkdir();
}
}
}
return _tmpDir;
}
/** don't rely on deleteOnExit() */
public void deleteTempDir() {
synchronized (this) {
if (_tmpDir != null) {
FileUtil.rmdir(_tmpDir, false);
_tmpDir = null;
}
}
}
/**
* Access the configuration attributes of this context, using properties
* provided during the context construction, or falling back on
* System.getProperty if no properties were provided during construction
* (or the specified prop wasn't included).
*
*/
public String getProperty(String propName) {
if (_overrideProps != null) {
if (_overrideProps.containsKey(propName))
return _overrideProps.getProperty(propName);
}
return System.getProperty(propName);
}
/**
* Access the configuration attributes of this context, using properties
* provided during the context construction, or falling back on
* System.getProperty if no properties were provided during construction
* (or the specified prop wasn't included).
*
*/
public String getProperty(String propName, String defaultValue) {
if (_overrideProps != null) {
if (_overrideProps.containsKey(propName))
return _overrideProps.getProperty(propName, defaultValue);
}
return System.getProperty(propName, defaultValue);
}
/**
* Return an int with an int default
*/
public int getProperty(String propName, int defaultVal) {
String val = null;
if (_overrideProps != null) {
val = _overrideProps.getProperty(propName);
if (val == null)
val = System.getProperty(propName);
}
int ival = defaultVal;
if (val != null) {
try {
ival = Integer.parseInt(val);
} catch (NumberFormatException nfe) {}
}
return ival;
}
/**
* Access the configuration attributes of this context, listing the properties
* provided during the context construction, as well as the ones included in
* System.getProperties.
*
* @return set of Strings containing the names of defined system properties
*/
public Set getPropertyNames() {
Set names = new HashSet(System.getProperties().keySet());
if (_overrideProps != null)
names.addAll(_overrideProps.keySet());
return names;
}
/**
* The statistics component with which we can track various events
* over time.
*/
public StatManager statManager() {
if (!_statManagerInitialized)
initializeStatManager();
return _statManager;
}
private void initializeStatManager() {
synchronized (this) {
if (_statManager == null)
_statManager = new StatManager(this);
_statManagerInitialized = true;
}
}
/**
* The session key manager which coordinates the sessionKey / sessionTag
* data. This component allows transparent operation of the
* ElGamal/AES+SessionTag algorithm, and contains all of the session tags
* for one particular application. If you want to seperate multiple apps
* to have their own sessionTags and sessionKeys, they should use different
* I2PAppContexts, and hence, different sessionKeyManagers.
*
*/
public SessionKeyManager sessionKeyManager() {
if (!_sessionKeyManagerInitialized)
initializeSessionKeyManager();
return _sessionKeyManager;
}
private void initializeSessionKeyManager() {
synchronized (this) {
if (_sessionKeyManager == null)
//_sessionKeyManager = new PersistentSessionKeyManager(this);
_sessionKeyManager = new TransientSessionKeyManager(this);
_sessionKeyManagerInitialized = true;
}
}
/**
* Pull up the naming service used in this context. The naming service itself
* works by querying the context's properties, so those props should be
* specified to customize the naming service exposed.
*/
public NamingService namingService() {
if (!_namingServiceInitialized)
initializeNamingService();
return _namingService;
}
private void initializeNamingService() {
synchronized (this) {
if (_namingService == null) {
_namingService = NamingService.createInstance(this);
}
_namingServiceInitialized = true;
}
}
public PetNameDB petnameDb() {
if (!_petnameDbInitialized)
initializePetnameDb();
return _petnameDb;
}
private void initializePetnameDb() {
synchronized (this) {
if (_petnameDb == null) {
_petnameDb = new PetNameDB();
}
_petnameDbInitialized = true;
}
}
/**
* This is the ElGamal engine used within this context. While it doesn't
* really have anything substantial that is context specific (the algorithm
* just does the algorithm), it does transparently use the context for logging
* its performance and activity. In addition, the engine can be swapped with
* the context's properties (though only someone really crazy should mess with
* it ;)
*/
public ElGamalEngine elGamalEngine() {
if (!_elGamalEngineInitialized)
initializeElGamalEngine();
return _elGamalEngine;
}
private void initializeElGamalEngine() {
synchronized (this) {
if (_elGamalEngine == null) {
if ("off".equals(getProperty("i2p.encryption", "on")))
_elGamalEngine = new DummyElGamalEngine(this);
else
_elGamalEngine = new ElGamalEngine(this);
}
_elGamalEngineInitialized = true;
}
}
/**
* Access the ElGamal/AES+SessionTag engine for this context. The algorithm
* makes use of the context's sessionKeyManager to coordinate transparent
* access to the sessionKeys and sessionTags, as well as the context's elGamal
* engine (which in turn keeps stats, etc).
*
*/
public ElGamalAESEngine elGamalAESEngine() {
if (!_elGamalAESEngineInitialized)
initializeElGamalAESEngine();
return _elGamalAESEngine;
}
private void initializeElGamalAESEngine() {
synchronized (this) {
if (_elGamalAESEngine == null)
_elGamalAESEngine = new ElGamalAESEngine(this);
_elGamalAESEngineInitialized = true;
}
}
/**
* Ok, I'll admit it. there is no good reason for having a context specific
* AES engine. We dont really keep stats on it, since its just too fast to
* matter. Though for the crazy people out there, we do expose a way to
* disable it.
*/
public AESEngine aes() {
if (!_AESEngineInitialized)
initializeAESEngine();
return _AESEngine;
}
private void initializeAESEngine() {
synchronized (this) {
if (_AESEngine == null) {
if ("off".equals(getProperty("i2p.encryption", "on")))
_AESEngine = new AESEngine(this);
else
_AESEngine = new CryptixAESEngine(this);
}
_AESEngineInitialized = true;
}
}
/**
* Query the log manager for this context, which may in turn have its own
* set of configuration settings (loaded from the context's properties).
* Each context's logManager keeps its own isolated set of Log instances with
* their own log levels, output locations, and rotation configuration.
*/
public LogManager logManager() {
if (!_logManagerInitialized)
initializeLogManager();
return _logManager;
}
private void initializeLogManager() {
synchronized (this) {
if (_logManager == null)
_logManager = new LogManager(this);
_logManagerInitialized = true;
}
}
/**
* There is absolutely no good reason to make this context specific,
* other than for consistency, and perhaps later we'll want to
* include some stats.
*/
public HMACGenerator hmac() {
if (!_hmacInitialized)
initializeHMAC();
return _hmac;
}
private void initializeHMAC() {
synchronized (this) {
if (_hmac == null) {
_hmac= new HMACGenerator(this);
}
_hmacInitialized = true;
}
}
public HMAC256Generator hmac256() {
if (!_hmac256Initialized)
initializeHMAC256();
return _hmac256;
}
private void initializeHMAC256() {
synchronized (this) {
if (_hmac256 == null) {
_hmac256 = new HMAC256Generator(this);
}
_hmac256Initialized = true;
}
}
/**
* Our SHA256 instance (see the hmac discussion for why its context specific)
*
*/
public SHA256Generator sha() {
if (!_shaInitialized)
initializeSHA();
return _sha;
}
private void initializeSHA() {
synchronized (this) {
if (_sha == null)
_sha= new SHA256Generator(this);
_shaInitialized = true;
}
}
/**
* Our DSA engine (see HMAC and SHA above)
*
*/
public DSAEngine dsa() {
if (!_dsaInitialized)
initializeDSA();
return _dsa;
}
private void initializeDSA() {
synchronized (this) {
if (_dsa == null) {
if ("off".equals(getProperty("i2p.encryption", "on")))
_dsa = new DummyDSAEngine(this);
else
_dsa = new DSAEngine(this);
}
_dsaInitialized = true;
}
}
/**
* Component to generate ElGamal, DSA, and Session keys. For why it is in
* the appContext, see the DSA, HMAC, and SHA comments above.
*/
public KeyGenerator keyGenerator() {
if (!_keyGeneratorInitialized)
initializeKeyGenerator();
return _keyGenerator;
}
private void initializeKeyGenerator() {
synchronized (this) {
if (_keyGenerator == null)
_keyGenerator = new KeyGenerator(this);
_keyGeneratorInitialized = true;
}
}
/**
* The context's synchronized clock, which is kept context specific only to
* enable simulators to play with clock skew among different instances.
*
*/
public Clock clock() { // overridden in RouterContext
if (!_clockInitialized)
initializeClock();
return _clock;
}
protected void initializeClock() { // overridden in RouterContext
synchronized (this) {
if (_clock == null)
_clock = new Clock(this);
_clockInitialized = true;
}
}
/**
* Determine how much do we want to mess with the keys to turn them
* into something we can route. This is context specific because we
* may want to test out how things react when peers don't agree on
* how to skew.
*
*/
public RoutingKeyGenerator routingKeyGenerator() {
if (!_routingKeyGeneratorInitialized)
initializeRoutingKeyGenerator();
return _routingKeyGenerator;
}
private void initializeRoutingKeyGenerator() {
synchronized (this) {
if (_routingKeyGenerator == null)
_routingKeyGenerator = new RoutingKeyGenerator(this);
_routingKeyGeneratorInitialized = true;
}
}
/**
* Basic hash map
*/
public KeyRing keyRing() {
if (!_keyRingInitialized)
initializeKeyRing();
return _keyRing;
}
protected void initializeKeyRing() {
synchronized (this) {
if (_keyRing == null)
_keyRing = new KeyRing();
_keyRingInitialized = true;
}
}
/**
* [insert snarky comment here]
*
*/
public RandomSource random() {
if (!_randomInitialized)
initializeRandom();
return _random;
}
private void initializeRandom() {
synchronized (this) {
if (_random == null) {
if (true)
_random = new FortunaRandomSource(this);
else if ("true".equals(getProperty("i2p.weakPRNG", "false")))
_random = new DummyPooledRandomSource(this);
else
_random = new PooledRandomSource(this);
}
_randomInitialized = true;
}
}
public void addShutdownTask(Runnable task) {
_shutdownTasks.add(task);
}
public Set<Runnable> getShutdownTasks() {
return new HashSet(_shutdownTasks);
}
}
|
pid dir defaults to system temp dir
|
core/java/src/net/i2p/I2PAppContext.java
|
pid dir defaults to system temp dir
|
|
Java
|
apache-2.0
|
9a50c6649e254631e122790037724f5a9b94a646
| 0
|
rspieldenner/msl,Netflix/msl,Netflix/msl,Netflix/msl,rspieldenner/msl,rspieldenner/msl,Netflix/msl,Netflix/msl,Netflix/msl
|
/**
* Copyright (c) 2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package mslcli.client;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import java.io.Console;
import java.io.IOException;
import java.net.ConnectException;
import java.net.URL;
import java.security.Security;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import com.netflix.msl.MslConstants;
import com.netflix.msl.MslConstants.ResponseCode;
import com.netflix.msl.MslError;
import com.netflix.msl.MslException;
import com.netflix.msl.MslKeyExchangeException;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.keyx.AsymmetricWrappedExchange;
import com.netflix.msl.msg.ConsoleFilterStreamFactory;
import com.netflix.msl.msg.MslControl;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.ServiceToken;
import com.netflix.msl.tokens.UserIdToken;
import com.netflix.msl.userauth.EmailPasswordAuthenticationData;
import com.netflix.msl.userauth.UserAuthenticationData;
import mslcli.common.Pair;
import mslcli.client.msg.MessageConfig;
import mslcli.client.util.UserAuthenticationDataHandle;
import mslcli.common.util.AppContext;
import mslcli.common.util.ConfigurationException;
import mslcli.common.util.ConfigurationRuntimeException;
import mslcli.common.util.MslProperties;
import mslcli.common.util.MslStoreWrapper;
import mslcli.common.util.SharedUtil;
import static mslcli.client.CmdArguments.*;
/**
* MSL client launcher program. Allows to configure message security policies and key exchange mechanism.
*
* @author Vadim Spector <vspector@netflix.com>
*/
public final class ClientApp {
// Add BouncyCastle provider.
static {
Security.addProvider(new BouncyCastleProvider());
}
private static final String CMD_PROMPT = "args"; // command prompt
private static final String APP_ID = "client_app"; // client app id
private static final String HELP_FILE = "mslclient_manual.txt";
private static final String CMD_HELP = "help";
private static final String CMD_LIST = "list";
private static final String CMD_QUIT = "quit";
private static final String CMD_HINT = "?";
public enum Status {
OK(0, "Success"),
ARG_ERROR (1, "Invalid Arguments"),
CFG_ERROR (2, "Configuration File Error"),
MSL_EXC_ERROR(3, "MSL Exception"),
MSL_ERROR (4, "Server MSL Error Reply"),
COMM_ERROR (5, "Server Communication Error"),
EXE_ERROR (6, "Internal Execution Error");
private final int code;
private final String info;
Status(final int code, final String info) {
this.code = code;
this.info = info;
}
@Override
public String toString() {
return String.format("%d: %s", code, info);
}
}
private final CmdArguments cmdParam;
private final MslProperties mslProp;
private final AppContext appCtx;
private Client client;
private String clientId = null;
/*
* Launcher of MSL CLI client. See user manual in HELP_FILE.
*/
public static void main(String[] args) {
Status status = Status.OK;
try {
if (args.length == 0) {
System.err.println("Use " + CMD_HELP + " for help");
status = Status.ARG_ERROR;
} else if (CMD_HELP.equalsIgnoreCase(args[0])) {
help();
status = Status.OK;
} else {
final CmdArguments cmdParam = new CmdArguments(args);
final ClientApp clientApp = new ClientApp(cmdParam);
if (cmdParam.isInteractive()) {
clientApp.sendMultipleRequests();
status = Status.OK;
} else {
status = clientApp.sendSingleRequest();
}
}
} catch (ConfigurationException e) {
System.err.println(e.getMessage());
status = Status.CFG_ERROR;
} catch (IllegalCmdArgumentException e) {
System.err.println(e.getMessage());
status = Status.ARG_ERROR;
} catch (IOException e) {
System.err.println(e.getMessage());
status = Status.EXE_ERROR;
SharedUtil.getRootCause(e).printStackTrace(System.err);
} catch (RuntimeException e) {
System.err.println(e.getMessage());
status = Status.EXE_ERROR;
SharedUtil.getRootCause(e).printStackTrace(System.err);
}
System.out.println("Exit Status " + status);
System.exit(status.code);
}
/*
* ClientApp holds the instance of one Client and some other objects which are global for the application.
* Instance of Client is supposed to be re-instantiated only when its entity identity changes,
* which is only applicable in the interactive mode. Changing entity identity within a given Client
* instance would be too convoluted; it makes sense to permanently bind Client with its entity ID.
*
* @param encapsulation of command-line arguments
*/
public ClientApp(final CmdArguments cmdParam) throws ConfigurationException, IllegalCmdArgumentException, IOException {
// save command-line arguments
this.cmdParam = cmdParam;
// load configuration from the configuration file
this.mslProp = MslProperties.getInstance(SharedUtil.loadPropertiesFromFile(cmdParam.getConfigFilePath()));
// initialize application context
this.appCtx = AppContext.getInstance(mslProp, APP_ID);
// initialize MSL Store - use wrapper to intercept selected MSL Store calls
this.appCtx.setMslStoreWrapper(new AppMslStoreWrapper(appCtx));
}
/*
* In a loop as a user to modify command-line arguments and then send a single request,
* until a user enters "-quit" command.
*
* @return true if configuration was succesfully modified or left unchanged; false if QUIT option was entered
* @throws IOException in case of user input reading error
*/
public void sendMultipleRequests() throws IllegalCmdArgumentException, IOException {
while (true) {
final String options = SharedUtil.readInput(CMD_PROMPT);
if (CMD_QUIT.equalsIgnoreCase(options)) {
return;
}
if (CMD_HELP.equalsIgnoreCase(options)) {
help();
continue;
}
if (CMD_LIST.equalsIgnoreCase(options)) {
System.out.println(cmdParam.getParameters());
continue;
}
if (CMD_HINT.equalsIgnoreCase(options)) {
hint();
continue;
}
try {
// parse entered parameters just like command-line arguments
if (options != null && !options.trim().isEmpty()) {
final CmdArguments p = new CmdArguments(SharedUtil.split(options));
cmdParam.merge(p);
}
final Status status = sendSingleRequest();
if (status != Status.OK) {
System.out.println("Status: " + status.toString());
}
} catch (IllegalCmdArgumentException e) {
System.err.println(e.getMessage());
} catch (RuntimeException e) {
System.err.println(e.getMessage());
}
}
}
/*
* send single request
*/
public Status sendSingleRequest() {
Status status = Status.OK;
try_label: try {
// set verbose mode
if (cmdParam.isVerbose()) {
appCtx.getMslControl().setFilterFactory(new ConsoleFilterStreamFactory());
}
System.out.println("Options: " + cmdParam.getParameters());
// initialize Client for the first time or whenever its identity changes
if (!cmdParam.getEntityId().equals(clientId) || (client == null)) {
clientId = cmdParam.getEntityId();
client = null; // required for keeping the state, in case the next line throws exception
client = new Client(appCtx, clientId);
}
client.setUserAuthenticationDataHandle(new AppUserAuthenticationDataHandle(cmdParam.getUserId(), mslProp, cmdParam.isInteractive()));
// set message mslProperties
final MessageConfig mcfg = new MessageConfig();
mcfg.userId = cmdParam.getUserId();
mcfg.isEncrypted = cmdParam.isEncrypted();
mcfg.isIntegrityProtected = cmdParam.isIntegrityProtected();
mcfg.isNonReplayable = cmdParam.isNonReplayable();
// set key exchange scheme / mechanism
final String kx = cmdParam.getKeyExchangeScheme();
if (kx != null) {
final String kxm = cmdParam.getKeyExchangeMechanism();
client.setKeyRequestData(kx, kxm);
}
// set request payload
byte[] requestPayload = null;
final String inputFile = cmdParam.getPayloadInputFile();
requestPayload = cmdParam.getPayloadMessage();
if (inputFile != null && requestPayload != null) {
appCtx.error("Input File and Input Message cannot be both specified");
status = Status.ARG_ERROR;
break try_label;
}
if (inputFile != null) {
requestPayload = SharedUtil.readFromFile(inputFile);
} else {
if (requestPayload == null) {
requestPayload = new byte[0];
}
}
// send request and process response
final String outputFile = cmdParam.getPayloadOutputFile();
final URL url = cmdParam.getUrl();
final Client.Response response = client.sendRequest(requestPayload, mcfg, url);
// Non-NULL response payload - good
if (response.getPayload() != null) {
if (outputFile != null) {
SharedUtil.saveToFile(outputFile, response.getPayload());
} else {
System.out.println("Response: " + new String(response.getPayload(), MslConstants.DEFAULT_CHARSET));
}
status = Status.OK;
} else if (response.getErrorHeader() != null) {
if (response.getErrorHeader().getErrorMessage() != null) {
System.err.println(String.format("MSL RESPONSE ERROR: error_code %d, error_msg \"%s\"",
response.getErrorHeader().getErrorCode().intValue(),
response.getErrorHeader().getErrorMessage()));
} else {
System.err.println(String.format("ERROR: %s" + response.getErrorHeader().toJSONString()));
}
status = Status.MSL_ERROR;
} else {
System.out.println("Response with no payload or error header ???");
status = Status.MSL_ERROR;
}
} catch (MslException e) {
System.err.println(SharedUtil.getMslExceptionInfo(e));
status = Status.MSL_EXC_ERROR;
} catch (ConfigurationException e) {
System.err.println("Error: " + e.getMessage());
status = Status.CFG_ERROR;
} catch (ConfigurationRuntimeException e) {
System.err.println("Error: " + e.getCause().getMessage());
status = Status.CFG_ERROR;
} catch (IllegalCmdArgumentException e) {
System.err.println("Error: " + e.getMessage());
status = Status.ARG_ERROR;
} catch (ConnectException e) {
System.err.println("Error: " + e.getMessage());
status = Status.COMM_ERROR;
} catch (ExecutionException e) {
final Throwable thr = SharedUtil.getRootCause(e);
if (thr instanceof ConfigurationException) {
System.err.println("Error: " + thr.getMessage());
status = Status.CFG_ERROR;
} else if (thr instanceof MslException) {
System.err.println(SharedUtil.getMslExceptionInfo((MslException)thr));
status = Status.MSL_EXC_ERROR;
} else if (thr instanceof ConnectException) {
System.err.println("Error: " + thr.getMessage());
status = Status.COMM_ERROR;
} else {
System.err.println("Error: " + thr.getMessage());
thr.printStackTrace(System.err);
status = Status.EXE_ERROR;
}
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
SharedUtil.getRootCause(e).printStackTrace(System.err);
status = Status.EXE_ERROR;
} catch (InterruptedException e) {
System.err.println("Error: " + e.getMessage());
SharedUtil.getRootCause(e).printStackTrace(System.err);
status = Status.EXE_ERROR;
} catch (RuntimeException e) {
System.err.println("Error: " + e.getMessage());
SharedUtil.getRootCause(e).printStackTrace(System.err);
status = Status.EXE_ERROR;
}
return status;
}
/*
* This class facilitates on-demand fetching of user authentication data.
* Other implementations may prompt users to enter their credentials from the console.
*/
private static final class AppUserAuthenticationDataHandle implements UserAuthenticationDataHandle {
AppUserAuthenticationDataHandle(final String userId, final MslProperties mslProp, final boolean interactive) {
this.userId = userId;
this.mslProp = mslProp;
this.interactive = interactive;
}
@Override
public UserAuthenticationData getUserAuthenticationData() {
System.out.println("UserAuthentication Data requested");
if (userId != null) {
try {
final Pair<String,String> ep = mslProp.getEmailPassword(userId);
return new EmailPasswordAuthenticationData(ep.x, ep.y);
} catch (ConfigurationException e) {
if (interactive) {
final Console cons = System.console();
if (cons != null) {
final String email = cons.readLine("Email> ");
final char[] pwd = cons.readPassword("Password> ");
return new EmailPasswordAuthenticationData(email, new String(pwd));
} else {
throw new IllegalArgumentException("Invalid Email-Password Configuration for User " + userId);
}
} else {
throw new IllegalArgumentException("Invalid Email-Password Configuration for User " + userId);
}
}
} else {
return null;
}
}
private final String userId;
private final MslProperties mslProp;
private final boolean interactive;
}
/*
* This is a class to serve as an interceptor to all MslStore calls.
* It can override only the methods in MslStore the app cares about.
* This sample implementation just prints out the information about
* calling some selected MslStore methods.
*/
private static final class AppMslStoreWrapper extends MslStoreWrapper {
private AppMslStoreWrapper(final AppContext appCtx) {
if (appCtx == null) {
throw new IllegalArgumentException("NULL app context");
}
this.appCtx = appCtx;
}
@Override
public void setCryptoContext(final MasterToken masterToken, final ICryptoContext cryptoContext) {
if (masterToken == null) {
appCtx.info("MslStore: setting crypto context with NULL MasterToken???");
} else {
appCtx.info(String.format("MslStore: %s %s",
(cryptoContext != null)? "Adding" : "Removing", SharedUtil.getMasterTokenInfo(masterToken)));
}
super.setCryptoContext(masterToken, cryptoContext);
}
@Override
public void removeCryptoContext(final MasterToken masterToken) {
appCtx.info("MslStore: Removing Crypto Context for " + SharedUtil.getMasterTokenInfo(masterToken));
super.removeCryptoContext(masterToken);
}
@Override
public void clearCryptoContexts() {
appCtx.info("MslStore: Clear Crypto Contexts");
super.clearCryptoContexts();
}
@Override
public void addUserIdToken(final String userId, final UserIdToken userIdToken) throws MslException {
appCtx.info(String.format("MslStore: Adding %s for userId %s", SharedUtil.getUserIdTokenInfo(userIdToken), userId));
super.addUserIdToken(userId, userIdToken);
}
@Override
public void removeUserIdToken(final UserIdToken userIdToken) {
appCtx.info("MslStore: Removing " + SharedUtil.getUserIdTokenInfo(userIdToken));
super.removeUserIdToken(userIdToken);
}
@Override
public UserIdToken getUserIdToken(final String userId) {
appCtx.info("MslStore: Getting UserIdToken for user ID " + userId);
return super.getUserIdToken(userId);
}
@Override
public void addServiceTokens(final Set<ServiceToken> tokens) throws MslException {
if (tokens != null && !tokens.isEmpty()) {
final StringBuilder sb = new StringBuilder();
for (ServiceToken st : tokens) {
sb.append(SharedUtil.getServiceTokenInfo(st)).append("\n");
}
appCtx.info("MslStore: Adding Service Tokens\n" + sb.toString());
}
super.addServiceTokens(tokens);
}
@Override
public void removeServiceTokens(final String name, final MasterToken masterToken, final UserIdToken userIdToken) throws MslException {
appCtx.info(String.format("MslStore: Removing Service Tokens %s for %s %s", name,
SharedUtil.getMasterTokenInfo(masterToken), SharedUtil.getUserIdTokenInfo(userIdToken)));
super.removeServiceTokens(name, masterToken, userIdToken);
}
private final AppContext appCtx;
}
/*
* helper - print help file
*/
private static void help() {
try {
System.out.println(new String(SharedUtil.readFromFile(HELP_FILE), MslConstants.DEFAULT_CHARSET));
} catch (IOException e) {
System.err.println(String.format("Cannot read help file %s: %s", HELP_FILE, e.getMessage()));
}
}
/*
* helper - interactive mode hint
*/
private static void hint() {
System.out.println("Choices:");
System.out.println("a) Modify Command-line arguments, if any need to be modified, and press Enter to send a message.");
System.out.println(" Use exactly the same syntax as from the command line.");
System.out.println("b) Type \"list\" for listing currently selected command-line arguments.");
System.out.println("c) Type \"help\" for the detailed instructions on using this tool.");
System.out.println("d) Type \"quit\" to quit this tool.");
}
}
|
src/examples/java/mslcli/src/mslcli/client/ClientApp.java
|
/**
* Copyright (c) 2014 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package mslcli.client;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import java.io.Console;
import java.io.IOException;
import java.net.ConnectException;
import java.net.URL;
import java.security.Security;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import com.netflix.msl.MslConstants;
import com.netflix.msl.MslConstants.ResponseCode;
import com.netflix.msl.MslError;
import com.netflix.msl.MslException;
import com.netflix.msl.MslKeyExchangeException;
import com.netflix.msl.crypto.ICryptoContext;
import com.netflix.msl.keyx.AsymmetricWrappedExchange;
import com.netflix.msl.msg.ConsoleFilterStreamFactory;
import com.netflix.msl.msg.MslControl;
import com.netflix.msl.tokens.MasterToken;
import com.netflix.msl.tokens.ServiceToken;
import com.netflix.msl.tokens.UserIdToken;
import com.netflix.msl.userauth.EmailPasswordAuthenticationData;
import com.netflix.msl.userauth.UserAuthenticationData;
import mslcli.common.Pair;
import mslcli.client.msg.MessageConfig;
import mslcli.client.util.UserAuthenticationDataHandle;
import mslcli.common.util.AppContext;
import mslcli.common.util.ConfigurationException;
import mslcli.common.util.ConfigurationRuntimeException;
import mslcli.common.util.MslProperties;
import mslcli.common.util.MslStoreWrapper;
import mslcli.common.util.SharedUtil;
import static mslcli.client.CmdArguments.*;
/**
* MSL client launcher program. Allows to configure message security policies and key exchange mechanism.
*
* @author Vadim Spector <vspector@netflix.com>
*/
public final class ClientApp {
// Add BouncyCastle provider.
static {
Security.addProvider(new BouncyCastleProvider());
}
private static final String CMD_PROMPT = "args"; // command prompt
private static final String APP_ID = "client_app"; // client app id
private static final String HELP_FILE = "mslclient_manual.txt";
private static final String CMD_HELP = "help";
private static final String CMD_LIST = "list";
private static final String CMD_QUIT = "quit";
private static final String CMD_HINT = "?";
public enum Status {
OK(0, "Success"),
ARG_ERROR (1, "Invalid Arguments"),
CFG_ERROR (2, "Configuration File Error"),
MSL_EXC_ERROR(3, "MSL Exception"),
MSL_ERROR (4, "Server MSL Error Reply"),
COMM_ERROR (5, "Server Communication Error"),
EXE_ERROR (6, "Internal Execution Error");
private final int code;
private final String info;
Status(final int code, final String info) {
this.code = code;
this.info = info;
}
@Override
public String toString() {
return String.format("%d: %s", code, info);
}
}
private final CmdArguments cmdParam;
private final MslProperties mslProp;
private final AppContext appCtx;
private Client client;
private String clientId = null;
/*
* Launcher of MSL CLI client. See user manual in HELP_FILE.
*/
public static void main(String[] args) {
Status status = Status.OK;
try {
if (Arrays.asList(args).contains(CMD_HELP)) {
help();
status = Status.OK;
} else if (args.length == 0) {
System.err.println("Use " + CMD_HELP + " for help");
status = Status.ARG_ERROR;
} else {
final CmdArguments cmdParam = new CmdArguments(args);
final ClientApp clientApp = new ClientApp(cmdParam);
if (cmdParam.isInteractive()) {
clientApp.sendMultipleRequests();
status = Status.OK;
} else {
status = clientApp.sendSingleRequest();
}
}
} catch (ConfigurationException e) {
System.err.println(e.getMessage());
status = Status.CFG_ERROR;
} catch (IllegalCmdArgumentException e) {
System.err.println(e.getMessage());
status = Status.ARG_ERROR;
} catch (IOException e) {
System.err.println(e.getMessage());
status = Status.EXE_ERROR;
SharedUtil.getRootCause(e).printStackTrace(System.err);
} catch (RuntimeException e) {
System.err.println(e.getMessage());
status = Status.EXE_ERROR;
SharedUtil.getRootCause(e).printStackTrace(System.err);
}
System.out.println("Exit Status " + status);
System.exit(status.code);
}
/*
* ClientApp holds the instance of one Client and some other objects which are global for the application.
* Instance of Client is supposed to be re-instantiated only when its entity identity changes,
* which is only applicable in the interactive mode. Changing entity identity within a given Client
* instance would be too convoluted; it makes sense to permanently bind Client with its entity ID.
*
* @param encapsulation of command-line arguments
*/
public ClientApp(final CmdArguments cmdParam) throws ConfigurationException, IllegalCmdArgumentException, IOException {
// save command-line arguments
this.cmdParam = cmdParam;
// load configuration from the configuration file
this.mslProp = MslProperties.getInstance(SharedUtil.loadPropertiesFromFile(cmdParam.getConfigFilePath()));
// initialize application context
this.appCtx = AppContext.getInstance(mslProp, APP_ID);
// initialize MSL Store - use wrapper to intercept selected MSL Store calls
this.appCtx.setMslStoreWrapper(new AppMslStoreWrapper(appCtx));
}
/*
* In a loop as a user to modify command-line arguments and then send a single request,
* until a user enters "-quit" command.
*
* @return true if configuration was succesfully modified or left unchanged; false if QUIT option was entered
* @throws IOException in case of user input reading error
*/
public void sendMultipleRequests() throws IllegalCmdArgumentException, IOException {
while (true) {
final String options = SharedUtil.readInput(CMD_PROMPT);
if (CMD_QUIT.equalsIgnoreCase(options)) {
return;
}
if (CMD_HELP.equalsIgnoreCase(options)) {
help();
continue;
}
if (CMD_LIST.equalsIgnoreCase(options)) {
System.out.println(cmdParam.getParameters());
continue;
}
if (CMD_HINT.equalsIgnoreCase(options)) {
hint();
continue;
}
try {
// parse entered parameters just like command-line arguments
if (options != null && !options.trim().isEmpty()) {
final CmdArguments p = new CmdArguments(SharedUtil.split(options));
cmdParam.merge(p);
}
final Status status = sendSingleRequest();
if (status != Status.OK) {
System.out.println("Status: " + status.toString());
}
} catch (IllegalCmdArgumentException e) {
System.err.println(e.getMessage());
} catch (RuntimeException e) {
System.err.println(e.getMessage());
}
}
}
/*
* send single request
*/
public Status sendSingleRequest() {
Status status = Status.OK;
try_label: try {
// set verbose mode
if (cmdParam.isVerbose()) {
appCtx.getMslControl().setFilterFactory(new ConsoleFilterStreamFactory());
}
System.out.println("Options: " + cmdParam.getParameters());
// initialize Client for the first time or whenever its identity changes
if (!cmdParam.getEntityId().equals(clientId) || (client == null)) {
clientId = cmdParam.getEntityId();
client = null; // required for keeping the state, in case the next line throws exception
client = new Client(appCtx, clientId);
}
client.setUserAuthenticationDataHandle(new AppUserAuthenticationDataHandle(cmdParam.getUserId(), mslProp, cmdParam.isInteractive()));
// set message mslProperties
final MessageConfig mcfg = new MessageConfig();
mcfg.userId = cmdParam.getUserId();
mcfg.isEncrypted = cmdParam.isEncrypted();
mcfg.isIntegrityProtected = cmdParam.isIntegrityProtected();
mcfg.isNonReplayable = cmdParam.isNonReplayable();
// set key exchange scheme / mechanism
final String kx = cmdParam.getKeyExchangeScheme();
if (kx != null) {
final String kxm = cmdParam.getKeyExchangeMechanism();
client.setKeyRequestData(kx, kxm);
}
// set request payload
byte[] requestPayload = null;
final String inputFile = cmdParam.getPayloadInputFile();
requestPayload = cmdParam.getPayloadMessage();
if (inputFile != null && requestPayload != null) {
appCtx.error("Input File and Input Message cannot be both specified");
status = Status.ARG_ERROR;
break try_label;
}
if (inputFile != null) {
requestPayload = SharedUtil.readFromFile(inputFile);
} else {
if (requestPayload == null) {
requestPayload = new byte[0];
}
}
// send request and process response
final String outputFile = cmdParam.getPayloadOutputFile();
final URL url = cmdParam.getUrl();
final Client.Response response = client.sendRequest(requestPayload, mcfg, url);
// Non-NULL response payload - good
if (response.getPayload() != null) {
if (outputFile != null) {
SharedUtil.saveToFile(outputFile, response.getPayload());
} else {
System.out.println("Response: " + new String(response.getPayload(), MslConstants.DEFAULT_CHARSET));
}
status = Status.OK;
} else if (response.getErrorHeader() != null) {
if (response.getErrorHeader().getErrorMessage() != null) {
System.err.println(String.format("MSL RESPONSE ERROR: error_code %d, error_msg \"%s\"",
response.getErrorHeader().getErrorCode().intValue(),
response.getErrorHeader().getErrorMessage()));
} else {
System.err.println(String.format("ERROR: %s" + response.getErrorHeader().toJSONString()));
}
status = Status.MSL_ERROR;
} else {
System.out.println("Response with no payload or error header ???");
status = Status.MSL_ERROR;
}
} catch (MslException e) {
System.err.println(SharedUtil.getMslExceptionInfo(e));
status = Status.MSL_EXC_ERROR;
} catch (ConfigurationException e) {
System.err.println("Error: " + e.getMessage());
status = Status.CFG_ERROR;
} catch (ConfigurationRuntimeException e) {
System.err.println("Error: " + e.getCause().getMessage());
status = Status.CFG_ERROR;
} catch (IllegalCmdArgumentException e) {
System.err.println("Error: " + e.getMessage());
status = Status.ARG_ERROR;
} catch (ConnectException e) {
System.err.println("Error: " + e.getMessage());
status = Status.COMM_ERROR;
} catch (ExecutionException e) {
final Throwable thr = SharedUtil.getRootCause(e);
if (thr instanceof ConfigurationException) {
System.err.println("Error: " + thr.getMessage());
status = Status.CFG_ERROR;
} else if (thr instanceof MslException) {
System.err.println(SharedUtil.getMslExceptionInfo((MslException)thr));
status = Status.MSL_EXC_ERROR;
} else if (thr instanceof ConnectException) {
System.err.println("Error: " + thr.getMessage());
status = Status.COMM_ERROR;
} else {
System.err.println("Error: " + thr.getMessage());
thr.printStackTrace(System.err);
status = Status.EXE_ERROR;
}
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
SharedUtil.getRootCause(e).printStackTrace(System.err);
status = Status.EXE_ERROR;
} catch (InterruptedException e) {
System.err.println("Error: " + e.getMessage());
SharedUtil.getRootCause(e).printStackTrace(System.err);
status = Status.EXE_ERROR;
} catch (RuntimeException e) {
System.err.println("Error: " + e.getMessage());
SharedUtil.getRootCause(e).printStackTrace(System.err);
status = Status.EXE_ERROR;
}
return status;
}
/*
* This class facilitates on-demand fetching of user authentication data.
* Other implementations may prompt users to enter their credentials from the console.
*/
private static final class AppUserAuthenticationDataHandle implements UserAuthenticationDataHandle {
AppUserAuthenticationDataHandle(final String userId, final MslProperties mslProp, final boolean interactive) {
this.userId = userId;
this.mslProp = mslProp;
this.interactive = interactive;
}
@Override
public UserAuthenticationData getUserAuthenticationData() {
System.out.println("UserAuthentication Data requested");
if (userId != null) {
try {
final Pair<String,String> ep = mslProp.getEmailPassword(userId);
return new EmailPasswordAuthenticationData(ep.x, ep.y);
} catch (ConfigurationException e) {
if (interactive) {
final Console cons = System.console();
if (cons != null) {
final String email = cons.readLine("Email> ");
final char[] pwd = cons.readPassword("Password> ");
return new EmailPasswordAuthenticationData(email, new String(pwd));
} else {
throw new IllegalArgumentException("Invalid Email-Password Configuration for User " + userId);
}
} else {
throw new IllegalArgumentException("Invalid Email-Password Configuration for User " + userId);
}
}
} else {
return null;
}
}
private final String userId;
private final MslProperties mslProp;
private final boolean interactive;
}
/*
* This is a class to serve as an interceptor to all MslStore calls.
* It can override only the methods in MslStore the app cares about.
* This sample implementation just prints out the information about
* calling some selected MslStore methods.
*/
private static final class AppMslStoreWrapper extends MslStoreWrapper {
private AppMslStoreWrapper(final AppContext appCtx) {
if (appCtx == null) {
throw new IllegalArgumentException("NULL app context");
}
this.appCtx = appCtx;
}
@Override
public void setCryptoContext(final MasterToken masterToken, final ICryptoContext cryptoContext) {
if (masterToken == null) {
appCtx.info("MslStore: setting crypto context with NULL MasterToken???");
} else {
appCtx.info(String.format("MslStore: %s %s",
(cryptoContext != null)? "Adding" : "Removing", SharedUtil.getMasterTokenInfo(masterToken)));
}
super.setCryptoContext(masterToken, cryptoContext);
}
@Override
public void removeCryptoContext(final MasterToken masterToken) {
appCtx.info("MslStore: Removing Crypto Context for " + SharedUtil.getMasterTokenInfo(masterToken));
super.removeCryptoContext(masterToken);
}
@Override
public void clearCryptoContexts() {
appCtx.info("MslStore: Clear Crypto Contexts");
super.clearCryptoContexts();
}
@Override
public void addUserIdToken(final String userId, final UserIdToken userIdToken) throws MslException {
appCtx.info(String.format("MslStore: Adding %s for userId %s", SharedUtil.getUserIdTokenInfo(userIdToken), userId));
super.addUserIdToken(userId, userIdToken);
}
@Override
public void removeUserIdToken(final UserIdToken userIdToken) {
appCtx.info("MslStore: Removing " + SharedUtil.getUserIdTokenInfo(userIdToken));
super.removeUserIdToken(userIdToken);
}
@Override
public UserIdToken getUserIdToken(final String userId) {
appCtx.info("MslStore: Getting UserIdToken for user ID " + userId);
return super.getUserIdToken(userId);
}
@Override
public void addServiceTokens(final Set<ServiceToken> tokens) throws MslException {
if (tokens != null && !tokens.isEmpty()) {
final StringBuilder sb = new StringBuilder();
for (ServiceToken st : tokens) {
sb.append(SharedUtil.getServiceTokenInfo(st)).append("\n");
}
appCtx.info("MslStore: Adding Service Tokens\n" + sb.toString());
}
super.addServiceTokens(tokens);
}
@Override
public void removeServiceTokens(final String name, final MasterToken masterToken, final UserIdToken userIdToken) throws MslException {
appCtx.info(String.format("MslStore: Removing Service Tokens %s for %s %s", name,
SharedUtil.getMasterTokenInfo(masterToken), SharedUtil.getUserIdTokenInfo(userIdToken)));
super.removeServiceTokens(name, masterToken, userIdToken);
}
private final AppContext appCtx;
}
/*
* helper - print help file
*/
private static void help() {
try {
System.out.println(new String(SharedUtil.readFromFile(HELP_FILE), MslConstants.DEFAULT_CHARSET));
} catch (IOException e) {
System.err.println(String.format("Cannot read help file %s: %s", HELP_FILE, e.getMessage()));
}
}
/*
* helper - interactive mode hint
*/
private static void hint() {
System.out.println("Choices:");
System.out.println("a) Modify Command-line arguments, if any need to be modified, and press Enter to send a message.");
System.out.println(" Use exactly the same syntax as from the command line.");
System.out.println("b) Type \"list\" for listing currently selected command-line arguments.");
System.out.println("c) Type \"help\" for the detailed instructions on using this tool.");
System.out.println("d) Type \"quit\" to quit this tool.");
}
}
|
small changes
|
src/examples/java/mslcli/src/mslcli/client/ClientApp.java
|
small changes
|
|
Java
|
apache-2.0
|
394f62db59f514686e60ddc71f385e703b7f95ec
| 0
|
fmtn/a,northlander/a,fmtn/a
|
package com.libzter.a;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Map.Entry;
import java.util.Properties;
import javax.jms.BytesMessage;
import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.QueueBrowser;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A - An ActiveMQ/JMS testing and admin tool
*/
public class A {
private static final Logger logger = LoggerFactory.getLogger(A.class);
protected ActiveMQConnectionFactory cf;
protected Connection conn;
protected Session sess,tsess;
protected CommandLine cmdLine;
public static void main(String[] args) throws ParseException, InterruptedException{
A a = new A();
a.run(args);
}
public void run(String[] args) throws InterruptedException{
Options opts = new Options();
opts.addOption("b", "broker", true, "URL to broker. defaults to: tcp://localhost:61616");
opts.addOption("g","get", false, "Get a message from destination");
opts.addOption("p","put", true, "Put a message. Specify data. if starts with @, a file is assumed and loaded");
opts.addOption("t","type",true, "Message type to put, [bytes, text] - defaults to text");
opts.addOption("e","encoding",true,"Encoding of input file data. Default UTF-8");
opts.addOption("n","non-persistent",false,"Set message to non persistent.");
opts.addOption("r","reply-to",true,"Set reply to destination, i.e. queue:reply");
opts.addOption("o","output",true,"file to write payload to. If multiple messages, a -1.<ext> will be added to the file. BytesMessage will be written as-is, TextMessage will be written in UTF-8");
opts.addOption("c","count",true,"A number of messages to browse,get or put (put will put the same message <count> times). 0 means all messages.");
opts.addOption("j","jms-headers",false,"Print JMS headers");
opts.addOption("C","copy-queue",true,"Copy all messages from this to target");
opts.addOption("M","move-queue",true,"Move all messages from this to target");
opts.addOption("f", "find", true, "Search for messages in queue with this value in payload. Use with browse.");
opts.addOption("s","selector",true,"Browse or get with selector");
@SuppressWarnings("static-access")
Option property = OptionBuilder.withArgName("property=value" )
.hasArgs(2)
.withValueSeparator()
.withDescription( "use value for given property. Can be used several times." )
.create( "H" );
opts.addOption(property);
if( args.length == 0){
HelpFormatter helpFormatter = new HelpFormatter();
helpFormatter.printHelp("java -jar a.jar", opts, true);
System.exit(0);
}
CommandLineParser cmdParser = new PosixParser();
try {
cmdLine = cmdParser.parse(opts, args);
connect(cmdLine.getOptionValue("b", "tcp://localhost:61616"),
cmdLine.getOptionValue("user"),
cmdLine.getOptionValue("pass"));
long startTime = System.currentTimeMillis();
if( cmdLine.hasOption("g")){
executeGet(cmdLine);
}else if(cmdLine.hasOption("p") ){
executePut(cmdLine);
}else if( cmdLine.hasOption("C")){
executeCopy(cmdLine);
}else if( cmdLine.hasOption("M")){
executeMove(cmdLine);
}else{
executeBrowse(cmdLine);
}
long stopTime = System.currentTimeMillis();
long elapsedTime = stopTime - startTime;
System.out.println("Operation completed in " + elapsedTime + "ms (excluding connect)");
} catch (ParseException pe) {
pe.printStackTrace();
return;
} catch (JMSException je){
je.printStackTrace();
return;
} catch (Exception e){
e.printStackTrace();
return;
} finally{
try {
sess.close();
conn.close();
} catch (JMSException e2) {
e2.printStackTrace();
}
}
logger.debug("Active threads " + Thread.activeCount());
logger.debug("At the end of the road");
}
private void executeMove(CommandLine cmdLine) throws JMSException, UnsupportedEncodingException, IOException {
Queue tq = tsess.createQueue(cmdLine.getArgs()[0]);
Queue q = tsess.createQueue(cmdLine.getOptionValue("M")); // Source
MessageConsumer mq = null;
MessageProducer mp = tsess.createProducer(tq);
if( cmdLine.hasOption("s")){ // Selectors
mq = tsess.createConsumer(q,cmdLine.getOptionValue("s"));
}else{
mq = tsess.createConsumer(q);
}
int count = Integer.parseInt(cmdLine.getOptionValue("c","0"));
int i = 0, j = 0;
while(i < count || count == 0 ){
Message msg = mq.receive(100L);
if( msg == null){
break;
}else{
// if search is enabled
if( cmdLine.hasOption("f")){
if( msg instanceof TextMessage){
String haystack = ((TextMessage)msg).getText();
String needle = cmdLine.getOptionValue("f");
if( haystack != null && haystack.contains(needle)){
mp.send(msg);
tsess.commit();
++j;
}
}
}else{
mp.send(msg);
tsess.commit();
++j;
}
++i;
}
}
output(j + " msgs moved from " + cmdLine.getArgs()[0] + " to " + cmdLine.getOptionValue("M"));
}
private void executeCopy(CommandLine cmdLine) throws JMSException {
Queue tq = sess.createQueue(cmdLine.getArgs()[0]);
Queue q = sess.createQueue(cmdLine.getOptionValue("C")); // Source
QueueBrowser qb = null;
MessageProducer mp = sess.createProducer(tq);
if( cmdLine.hasOption("s")){ // Selectors
qb = sess.createBrowser(q,cmdLine.getOptionValue("s"));
}else{
qb = sess.createBrowser(q);
}
int count = Integer.parseInt(cmdLine.getOptionValue("c","0"));
int i = 0, j = 0;
@SuppressWarnings("unchecked")
Enumeration<Message> en = qb.getEnumeration();
while((i < count || count == 0) && en.hasMoreElements()){
Message msg = en.nextElement();
if( msg == null){
break;
}else{
// if search is enabled
if( cmdLine.hasOption("f")){
if( msg instanceof TextMessage){
String haystack = ((TextMessage)msg).getText();
String needle = cmdLine.getOptionValue("f");
if( haystack != null && haystack.contains(needle)){
mp.send(msg);
++j;
}
}
}else{
mp.send(msg);
++j;
}
++i;
}
}
output(j + " msgs copied from " + cmdLine.getArgs()[0] + " to " + cmdLine.getOptionValue("C"));
}
private void connect(String optionValue,String user, String password) throws JMSException {
cf = new ActiveMQConnectionFactory();
if( user != null && password != null){
conn = (Connection) cf.createConnection(user, password);
}else{
conn = cf.createConnection();
}
sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
tsess = conn.createSession(true, Session.AUTO_ACKNOWLEDGE);
conn.start();
}
private void executeGet(CommandLine cmdLine) throws JMSException, UnsupportedEncodingException, IOException {
Queue q = sess.createQueue(cmdLine.getArgs()[0]);
MessageConsumer mq = null;
if( cmdLine.hasOption("s")){ // Selectors
mq = sess.createConsumer(q,cmdLine.getOptionValue("s"));
}else{
mq = sess.createConsumer(q);
}
int count = Integer.parseInt(cmdLine.getOptionValue("c","1"));
int i = 0;
while(i < count || i == 0 ){
Message msg = mq.receive();
if( msg == null){
System.out.println("Null message");
break;
}else{
outputMessage(msg,cmdLine.hasOption("j"));
++i;
}
}
}
/**
* Put a message to a queue
* @param cmdLine [description]
* @throws IOException [description]
* @throws JMSException [description]
*/
private void executePut(CommandLine cmdLine) throws IOException, JMSException {
// Check if we have properties to put
Properties props = cmdLine.getOptionProperties("H");
String type = cmdLine.getOptionValue("t","text");
String encoding = cmdLine.getOptionValue("e","UTF-8");
Message outMsg = null;
// figure out input data
String data = cmdLine.getOptionValue("p");
if( data.startsWith("@")){
// Load file.
byte[] bytes = FileUtils.readFileToByteArray(new File(data.substring(1)));
if( type.equals("text")){
TextMessage textMsg = sess.createTextMessage(new String(bytes,encoding));
outMsg = textMsg;
}else{
BytesMessage bytesMsg = sess.createBytesMessage();
bytesMsg.writeBytes(bytes);
}
}else{
TextMessage textMsg = sess.createTextMessage(data);
outMsg = textMsg;
}
MessageProducer mp = sess.createProducer(createDestination(cmdLine.getArgs()[0]));
if( cmdLine.hasOption("n")){;
mp.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
}
// enrich headers.
for(Entry<Object,Object> p : props.entrySet()){
outMsg.setObjectProperty((String)p.getKey(), p.getValue());
}
if( cmdLine.hasOption("r")){
outMsg.setJMSReplyTo(createDestination(cmdLine.getOptionValue("r")));
}
// send multiple messages?
if( cmdLine.hasOption("c")){
int count = Integer.parseInt(cmdLine.getOptionValue("c"));
for(int i=0;i<count;i++){
mp.send(outMsg);
}
System.out.println("" + count + " messages sent");
}else{
mp.send(outMsg);
System.out.println("Message sent");
}
}
private Destination createDestination(String name) throws JMSException {
// support queue:// as well.
name = name.replace("/","");
if( name.toLowerCase().startsWith("queue:")){
return sess.createQueue(name.substring("queue:".length()));
}else if( name.toLowerCase().startsWith("topic:")){
return sess.createTopic(name.substring("topic:".length()));
}else{
return sess.createQueue(name);
}
}
private void executeBrowse(CommandLine cmdLine) throws JMSException, UnsupportedEncodingException, IOException {
Queue q = sess.createQueue(cmdLine.getArgs()[0]);
QueueBrowser qb = null;
// Selector aware?
if( cmdLine.hasOption("s")){
qb = sess.createBrowser(q,cmdLine.getOptionValue("s"));
}else{
qb = sess.createBrowser(q);
}
@SuppressWarnings("rawtypes")
Enumeration en = qb.getEnumeration();
int count = Integer.parseInt(cmdLine.getOptionValue("c","0"));
int i = 0;
while(en.hasMoreElements() && (i < count || i == 0 )){
Object obj = en.nextElement();
Message msg = (Message)obj;
if( cmdLine.hasOption("f")){
String needle = cmdLine.getOptionValue("f");
// need to search for some payload value
if( msg instanceof TextMessage){
String haystack = ((TextMessage)msg).getText();
if(haystack.contains(needle)){
outputMessage(msg,cmdLine.hasOption("j"));
}
}
}else{
outputMessage(msg,cmdLine.hasOption("j"));
}
++i;
}
}
private void outputMessage(Message msg,boolean printJMSHeaders) throws JMSException, UnsupportedEncodingException, IOException {
output("-----------------");
if( printJMSHeaders ){
outputHeaders(msg);
}
outputProperties(msg);
// Output to file?
FileOutputStream fos = null;
File file = null;
if( cmdLine.hasOption("o")){
file = getNextFilename(cmdLine.getOptionValue("o","amsg"),0);
if( file != null ) {
fos = new FileOutputStream(file);
}
}
if( msg instanceof TextMessage){
TextMessage txtMsg = (TextMessage)msg;
if( fos != null){
fos.write(txtMsg.getText().getBytes(cmdLine.getOptionValue("e","UTF-8")));
fos.close();
output("Payload written to file " + file.getAbsolutePath());
}else{
output("Payload:");
output(txtMsg.getText());
}
}else if( msg instanceof BytesMessage){
BytesMessage bmsg = (BytesMessage)msg;
byte[] bytes = new byte[(int) bmsg.getBodyLength()];
bmsg.readBytes(bytes);
if( fos != null ){
fos.write(bytes);
fos.close();
output("Payload written to file " + file.getAbsolutePath());
}else{
output("Hex Payload:");
output(bytesToHex(bytes));
}
}else{
System.out.println("Unsupported message type: " + msg.getClass().getName());
}
}
private File getNextFilename(String suggestedFilename, int i) {
String filename = suggestedFilename;
if( i > 0 ){
int idx = filename.lastIndexOf('.');
if( idx == -1 ){
filename = suggestedFilename + "-" + i;
}else{
// take care of the extension.
filename = filename.substring(0,idx) + "-" + i + filename.substring(idx);
}
}
File f = new File(filename);
if( f.exists() ){
return getNextFilename(suggestedFilename, ++i);
}else{
return f;
}
}
private void outputHeaders(Message msg){
output("Message Headers");
try {
String deliveryMode = msg.getJMSDeliveryMode() == DeliveryMode.PERSISTENT?"persistent":"non-persistent";
output(" JMSCorrelationID: " + msg.getJMSCorrelationID());
output(" JMSExpiration: " + timestampToString(msg.getJMSExpiration()));
output(" JMSDeliveryMode: " + deliveryMode);
output(" JMSMessageID: " + msg.getJMSMessageID());
output(" JMSPriority: " + msg.getJMSPriority());
output(" JMSTimestamp: " + timestampToString(msg.getJMSTimestamp()));
output(" JMSType: " + msg.getJMSType());
output(" JMSDestination: " + (msg.getJMSDestination() != null ? msg.getJMSDestination().toString() : "Not set"));
output(" JMSRedelivered: " + Boolean.toString(msg.getJMSRedelivered()));
output(" JMSReplyTo: " + (msg.getJMSReplyTo() != null ? msg.getJMSReplyTo().toString() : "Not set"));
} catch (JMSException e) {
// nothing to do here. just ignore.
logger.debug("Cannot print JMS headers." + e.getMessage());
}
}
private String timestampToString(long timestamp){
Date date = new Date(timestamp);
Format format = new SimpleDateFormat("yyyy MM dd HH:mm:ss");
String timeString = format.format(date).toString();
return timeString;
}
private void outputProperties(Message msg) throws JMSException {
output("Message Properties");
@SuppressWarnings("unchecked")
Enumeration<String> en = msg.getPropertyNames();
while(en.hasMoreElements()){
String name = en.nextElement();
Object property = msg.getObjectProperty(name);
output(" " + name + ": " + property.toString());
}
}
private void output(String... args){
for(String arg : args){
System.out.println(arg);
}
}
final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
public String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for ( int j = 0; j < bytes.length; j++ ) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
}
|
src/main/java/com/libzter/a/A.java
|
package com.libzter.a;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Map.Entry;
import java.util.Properties;
import javax.jms.BytesMessage;
import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.QueueBrowser;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A - An ActiveMQ/JMS testing and admin tool
*/
public class A {
private static final Logger logger = LoggerFactory.getLogger(A.class);
protected ActiveMQConnectionFactory cf;
protected Connection conn;
protected Session sess,tsess;
protected CommandLine cmdLine;
public static void main(String[] args) throws ParseException, InterruptedException{
A a = new A();
a.run(args);
}
public void run(String[] args) throws InterruptedException{
Options opts = new Options();
opts.addOption("b", "broker", true, "URL to broker. defaults to: tcp://localhost:61616");
opts.addOption("g","get", false, "Get a message from destination");
opts.addOption("p","put", true, "Put a message. Specify data. if starts with @, a file is assumed and loaded");
opts.addOption("t","type",true, "Message type to put, [bytes, text] - defaults to text");
opts.addOption("e","encoding",true,"Encoding of input file data. Default UTF-8");
opts.addOption("n","non-persistent",false,"Set message to non persistent.");
opts.addOption("r","reply-to",true,"Set reply to destination, i.e. queue:reply");
opts.addOption("o","output",true,"file to write payload to. If multiple messages, a -1.<ext> will be added to the file. BytesMessage will be written as-is, TextMessage will be written in UTF-8");
opts.addOption("c","count",true,"A number of messages to browse,get or put (put will put the same message <count> times). 0 means all messages.");
opts.addOption("j","jms-headers",false,"Print JMS headers");
opts.addOption("C","copy-queue",true,"Copy all messages from this to target");
opts.addOption("M","move-queue",true,"Move all messages from this to target");
opts.addOption("f", "find", true, "Search for messages in queue with this value in payload. Use with browse.");
opts.addOption("s","selector",true,"Browse or get with selector");
@SuppressWarnings("static-access")
Option property = OptionBuilder.withArgName("property=value" )
.hasArgs(2)
.withValueSeparator()
.withDescription( "use value for given property. Can be used several times." )
.create( "H" );
opts.addOption(property);
if( args.length == 0){
HelpFormatter helpFormatter = new HelpFormatter();
helpFormatter.printHelp("java -jar a.jar", opts, true);
System.exit(0);
}
CommandLineParser cmdParser = new PosixParser();
try {
cmdLine = cmdParser.parse(opts, args);
connect(cmdLine.getOptionValue("b", "tcp://localhost:61616"),
cmdLine.getOptionValue("user"),
cmdLine.getOptionValue("pass"));
long startTime = System.currentTimeMillis();
if( cmdLine.hasOption("g")){
executeGet(cmdLine);
}else if(cmdLine.hasOption("p") ){
executePut(cmdLine);
}else if( cmdLine.hasOption("C")){
executeCopy(cmdLine);
}else if( cmdLine.hasOption("M")){
executeMove(cmdLine);
}else{
executeBrowse(cmdLine);
}
long stopTime = System.currentTimeMillis();
long elapsedTime = stopTime - startTime;
System.out.println("Operation completed in " + elapsedTime + "ms (excluding connect)");
} catch (ParseException pe) {
pe.printStackTrace();
return;
} catch (JMSException je){
je.printStackTrace();
return;
} catch (Exception e){
e.printStackTrace();
return;
} finally{
try {
sess.close();
conn.close();
} catch (JMSException e2) {
e2.printStackTrace();
}
}
logger.debug("Active threads " + Thread.activeCount());
logger.debug("At the end of the road");
}
private void executeMove(CommandLine cmdLine) throws JMSException, UnsupportedEncodingException, IOException {
Queue tq = tsess.createQueue(cmdLine.getArgs()[0]);
Queue q = tsess.createQueue(cmdLine.getOptionValue("C")); // Source
MessageConsumer mq = null;
MessageProducer mp = tsess.createProducer(tq);
if( cmdLine.hasOption("s")){ // Selectors
mq = tsess.createConsumer(q,cmdLine.getOptionValue("s"));
}else{
mq = tsess.createConsumer(q);
}
int count = Integer.parseInt(cmdLine.getOptionValue("c","0"));
int i = 0, j = 0;
while(i < count || count == 0 ){
Message msg = mq.receive();
if( msg == null){
break;
}else{
// if search is enabled
if( cmdLine.hasOption("f")){
if( msg instanceof TextMessage){
String haystack = ((TextMessage)msg).getText();
String needle = cmdLine.getOptionValue("f");
if( haystack != null && haystack.contains(needle)){
mp.send(msg);
tsess.commit();
++j;
}
}
}else{
mp.send(msg);
tsess.commit();
++j;
}
++i;
}
}
output(j + " msgs moved from " + cmdLine.getArgs()[0] + " to " + cmdLine.getOptionValue("C"));
}
private void executeCopy(CommandLine cmdLine) throws JMSException {
Queue tq = sess.createQueue(cmdLine.getArgs()[0]);
Queue q = sess.createQueue(cmdLine.getOptionValue("C")); // Source
QueueBrowser qb = null;
MessageProducer mp = sess.createProducer(tq);
if( cmdLine.hasOption("s")){ // Selectors
qb = sess.createBrowser(q,cmdLine.getOptionValue("s"));
}else{
qb = sess.createBrowser(q);
}
int count = Integer.parseInt(cmdLine.getOptionValue("c","0"));
int i = 0, j = 0;
@SuppressWarnings("unchecked")
Enumeration<Message> en = qb.getEnumeration();
while((i < count || count == 0) && en.hasMoreElements()){
Message msg = en.nextElement();
if( msg == null){
break;
}else{
// if search is enabled
if( cmdLine.hasOption("f")){
if( msg instanceof TextMessage){
String haystack = ((TextMessage)msg).getText();
String needle = cmdLine.getOptionValue("f");
if( haystack != null && haystack.contains(needle)){
mp.send(msg);
++j;
}
}
}else{
mp.send(msg);
++j;
}
++i;
}
}
output(j + " msgs copied from " + cmdLine.getArgs()[0] + " to " + cmdLine.getOptionValue("C"));
}
private void connect(String optionValue,String user, String password) throws JMSException {
cf = new ActiveMQConnectionFactory();
if( user != null && password != null){
conn = (Connection) cf.createConnection(user, password);
}else{
conn = cf.createConnection();
}
sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
tsess = conn.createSession(true, Session.AUTO_ACKNOWLEDGE);
conn.start();
}
private void executeGet(CommandLine cmdLine) throws JMSException, UnsupportedEncodingException, IOException {
Queue q = sess.createQueue(cmdLine.getArgs()[0]);
MessageConsumer mq = null;
if( cmdLine.hasOption("s")){ // Selectors
mq = sess.createConsumer(q,cmdLine.getOptionValue("s"));
}else{
mq = sess.createConsumer(q);
}
int count = Integer.parseInt(cmdLine.getOptionValue("c","1"));
int i = 0;
while(i < count || i == 0 ){
Message msg = mq.receive();
if( msg == null){
System.out.println("Null message");
break;
}else{
outputMessage(msg,cmdLine.hasOption("j"));
++i;
}
}
}
/**
* Put a message to a queue
* @param cmdLine [description]
* @throws IOException [description]
* @throws JMSException [description]
*/
private void executePut(CommandLine cmdLine) throws IOException, JMSException {
// Check if we have properties to put
Properties props = cmdLine.getOptionProperties("H");
String type = cmdLine.getOptionValue("t","text");
String encoding = cmdLine.getOptionValue("e","UTF-8");
Message outMsg = null;
// figure out input data
String data = cmdLine.getOptionValue("p");
if( data.startsWith("@")){
// Load file.
byte[] bytes = FileUtils.readFileToByteArray(new File(data.substring(1)));
if( type.equals("text")){
TextMessage textMsg = sess.createTextMessage(new String(bytes,encoding));
outMsg = textMsg;
}else{
BytesMessage bytesMsg = sess.createBytesMessage();
bytesMsg.writeBytes(bytes);
}
}else{
TextMessage textMsg = sess.createTextMessage(data);
outMsg = textMsg;
}
MessageProducer mp = sess.createProducer(createDestination(cmdLine.getArgs()[0]));
if( cmdLine.hasOption("n")){;
mp.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
}
// enrich headers.
for(Entry<Object,Object> p : props.entrySet()){
outMsg.setObjectProperty((String)p.getKey(), p.getValue());
}
if( cmdLine.hasOption("r")){
outMsg.setJMSReplyTo(createDestination(cmdLine.getOptionValue("r")));
}
// send multiple messages?
if( cmdLine.hasOption("c")){
int count = Integer.parseInt(cmdLine.getOptionValue("c"));
for(int i=0;i<count;i++){
mp.send(outMsg);
}
System.out.println("" + count + " messages sent");
}else{
mp.send(outMsg);
System.out.println("Message sent");
}
}
private Destination createDestination(String name) throws JMSException {
// support queue:// as well.
name = name.replace("/","");
if( name.toLowerCase().startsWith("queue:")){
return sess.createQueue(name.substring("queue:".length()));
}else if( name.toLowerCase().startsWith("topic:")){
return sess.createTopic(name.substring("topic:".length()));
}else{
return sess.createQueue(name);
}
}
private void executeBrowse(CommandLine cmdLine) throws JMSException, UnsupportedEncodingException, IOException {
Queue q = sess.createQueue(cmdLine.getArgs()[0]);
QueueBrowser qb = null;
// Selector aware?
if( cmdLine.hasOption("s")){
qb = sess.createBrowser(q,cmdLine.getOptionValue("s"));
}else{
qb = sess.createBrowser(q);
}
@SuppressWarnings("rawtypes")
Enumeration en = qb.getEnumeration();
int count = Integer.parseInt(cmdLine.getOptionValue("c","0"));
int i = 0;
while(en.hasMoreElements() && (i < count || i == 0 )){
Object obj = en.nextElement();
Message msg = (Message)obj;
if( cmdLine.hasOption("f")){
String needle = cmdLine.getOptionValue("f");
// need to search for some payload value
if( msg instanceof TextMessage){
String haystack = ((TextMessage)msg).getText();
if(haystack.contains(needle)){
outputMessage(msg,cmdLine.hasOption("j"));
}
}
}else{
outputMessage(msg,cmdLine.hasOption("j"));
}
++i;
}
}
private void outputMessage(Message msg,boolean printJMSHeaders) throws JMSException, UnsupportedEncodingException, IOException {
output("-----------------");
if( printJMSHeaders ){
outputHeaders(msg);
}
outputProperties(msg);
// Output to file?
FileOutputStream fos = null;
File file = null;
if( cmdLine.hasOption("o")){
file = getNextFilename(cmdLine.getOptionValue("o","amsg"),0);
if( file != null ) {
fos = new FileOutputStream(file);
}
}
if( msg instanceof TextMessage){
TextMessage txtMsg = (TextMessage)msg;
if( fos != null){
fos.write(txtMsg.getText().getBytes(cmdLine.getOptionValue("e","UTF-8")));
fos.close();
output("Payload written to file " + file.getAbsolutePath());
}else{
output("Payload:");
output(txtMsg.getText());
}
}else if( msg instanceof BytesMessage){
BytesMessage bmsg = (BytesMessage)msg;
byte[] bytes = new byte[(int) bmsg.getBodyLength()];
bmsg.readBytes(bytes);
if( fos != null ){
fos.write(bytes);
fos.close();
output("Payload written to file " + file.getAbsolutePath());
}else{
output("Hex Payload:");
output(bytesToHex(bytes));
}
}else{
System.out.println("Unsupported message type: " + msg.getClass().getName());
}
}
private File getNextFilename(String suggestedFilename, int i) {
String filename = suggestedFilename;
if( i > 0 ){
int idx = filename.lastIndexOf('.');
if( idx == -1 ){
filename = suggestedFilename + "-" + i;
}else{
// take care of the extension.
filename = filename.substring(0,idx) + "-" + i + filename.substring(idx);
}
}
File f = new File(filename);
if( f.exists() ){
return getNextFilename(suggestedFilename, ++i);
}else{
return f;
}
}
private void outputHeaders(Message msg){
output("Message Headers");
try {
String deliveryMode = msg.getJMSDeliveryMode() == DeliveryMode.PERSISTENT?"persistent":"non-persistent";
output(" JMSCorrelationID: " + msg.getJMSCorrelationID());
output(" JMSExpiration: " + timestampToString(msg.getJMSExpiration()));
output(" JMSDeliveryMode: " + deliveryMode);
output(" JMSMessageID: " + msg.getJMSMessageID());
output(" JMSPriority: " + msg.getJMSPriority());
output(" JMSTimestamp: " + timestampToString(msg.getJMSTimestamp()));
output(" JMSType: " + msg.getJMSType());
output(" JMSDestination: " + (msg.getJMSDestination() != null ? msg.getJMSDestination().toString() : "Not set"));
output(" JMSRedelivered: " + Boolean.toString(msg.getJMSRedelivered()));
output(" JMSReplyTo: " + (msg.getJMSReplyTo() != null ? msg.getJMSReplyTo().toString() : "Not set"));
} catch (JMSException e) {
// nothing to do here. just ignore.
logger.debug("Cannot print JMS headers." + e.getMessage());
}
}
private String timestampToString(long timestamp){
Date date = new Date(timestamp);
Format format = new SimpleDateFormat("yyyy MM dd HH:mm:ss");
String timeString = format.format(date).toString();
return timeString;
}
private void outputProperties(Message msg) throws JMSException {
output("Message Properties");
@SuppressWarnings("unchecked")
Enumeration<String> en = msg.getPropertyNames();
while(en.hasMoreElements()){
String name = en.nextElement();
Object property = msg.getObjectProperty(name);
output(" " + name + ": " + property.toString());
}
}
private void output(String... args){
for(String arg : args){
System.out.println(arg);
}
}
final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
public String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for ( int j = 0; j < bytes.length; j++ ) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
}
|
Fixed some NPEs
|
src/main/java/com/libzter/a/A.java
|
Fixed some NPEs
|
|
Java
|
apache-2.0
|
d0d9dd5e9465db2d2521100e05cbafb260aee7d0
| 0
|
krizsan/rest-example
|
package se.ivankrizsan.restexample.restadapter;
import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.stereotype.Component;
/**
* Jersey configuration.
* Cannot rely on classpath scanning, due to a bug in Jersey making it unable
* to scan nested JAR-files.
*
* @author Ivan Krizsan
*/
@Component
public class JerseyConfig extends ResourceConfig {
public JerseyConfig() {
register(CircleResource.class);
register(RectangleResource.class);
register(DrawingResource.class);
}
}
|
src/main/java/se/ivankrizsan/restexample/restadapter/JerseyConfig.java
|
package se.ivankrizsan.restexample.restadapter;
import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.stereotype.Component;
/**
* Jersey configuration.
*
* @author Ivan Krizsan
*/
@Component
public class JerseyConfig extends ResourceConfig {
public JerseyConfig() {
/* All resource classes are to be located in the same package as this class. */
packages(this.getClass().getPackage().getName());
}
}
|
Fix to make the Spring Boot standalone JAR runnable.
|
src/main/java/se/ivankrizsan/restexample/restadapter/JerseyConfig.java
|
Fix to make the Spring Boot standalone JAR runnable.
|
|
Java
|
apache-2.0
|
5c17437ba6c25f2e5fe0be4b5fcb399051defb43
| 0
|
Plonk42/mytracks
|
/*
* Copyright 2011 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.android.apps.mytracks.content;
import static com.google.android.apps.mytracks.Constants.MAX_LOCATION_AGE_MS;
import static com.google.android.apps.mytracks.Constants.TAG;
import com.google.android.apps.mytracks.Constants;
import com.google.android.apps.mytracks.content.DataSourceManager.DataSourceListener;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils.LocationIterator;
import com.google.android.apps.mytracks.content.TrackDataListener.ProviderState;
import com.google.android.apps.mytracks.content.TrackDataListeners.ListenerRegistration;
import com.google.android.apps.mytracks.util.ApiFeatures;
import com.google.android.apps.mytracks.util.LocationUtils;
import com.google.android.maps.mytracks.R;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.hardware.GeomagneticField;
import android.location.Location;
import android.location.LocationManager;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;
import android.widget.Toast;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Set;
/**
* Track data hub, which receives data (both live and recorded) from many
* different sources and distributes it to those interested after some standard
* processing.
*
* @author Rodrigo Damazio
*/
public class TrackDataHub {
// Preference keys
private final String SELECTED_TRACK_KEY;
private final String RECORDING_TRACK_KEY;
private final String MIN_REQUIRED_ACCURACY_KEY;
private final String METRIC_UNITS_KEY;
private final String SPEED_REPORTING_KEY;
/** Types of data that we can expose. */
public static enum ListenerDataType {
/** Listen to when the selected track changes. */
SELECTED_TRACK_CHANGED,
/** Listen to when the tracks change. */
TRACK_UPDATES,
/** Listen to when the waypoints change. */
WAYPOINT_UPDATES,
/** Listen to when the current track points change. */
POINT_UPDATES,
/**
* Listen to sampled-out points.
* Listening to this without listening to {@link #SAMPLED_POINT_UPDATES}
* makes no sense and may yield unexpected results.
*/
SAMPLED_OUT_POINT_UPDATES,
/** Listen to updates to the current location. */
LOCATION_UPDATES,
/** Listen to updates to the current heading. */
COMPASS_UPDATES,
/** Listens to changes in display preferences. */
DISPLAY_PREFERENCES;
}
/** Listener which receives events from the system. */
private class HubDataSourceListener implements DataSourceListener {
@Override
public void notifyTrackUpdated() {
TrackDataHub.this.notifyTrackUpdated(getListenersFor(ListenerDataType.TRACK_UPDATES));
}
@Override
public void notifyWaypointUpdated() {
TrackDataHub.this.notifyWaypointUpdated(getListenersFor(ListenerDataType.WAYPOINT_UPDATES));
}
@Override
public void notifyPointsUpdated() {
TrackDataHub.this.notifyPointsUpdated(true, 0,
getListenersFor(ListenerDataType.POINT_UPDATES),
getListenersFor(ListenerDataType.SAMPLED_OUT_POINT_UPDATES));
}
@Override
public void notifyPreferenceChanged(String key) {
TrackDataHub.this.notifyPreferenceChanged(key);
}
@Override
public void notifyLocationProviderEnabled(boolean enabled) {
hasProviderEnabled = enabled;
TrackDataHub.this.notifyFixType();
}
@Override
public void notifyLocationChanged(Location loc) {
TrackDataHub.this.notifyLocationChanged(loc,
getListenersFor(ListenerDataType.LOCATION_UPDATES));
}
@Override
public void notifyHeadingChanged(float heading) {
lastSeenMagneticHeading = heading;
maybeUpdateDeclination();
TrackDataHub.this.notifyHeadingChanged(getListenersFor(ListenerDataType.COMPASS_UPDATES));
}
}
// Application services
private final Context context;
private final MyTracksProviderUtils providerUtils;
private final SharedPreferences preferences;
// Get content notifications on the main thread, send listener callbacks in another.
// This ensures listener calls are serialized.
private final HandlerThread listenerHandlerThread;
private final Handler listenerHandler;
/** Manager for external listeners (those from activities). */
private final TrackDataListeners listeners;
/** Wrapper for interacting with system data managers. */
private final DataSourcesWrapper dataSources;
/** Manager for system data listener registrations. */
private final DataSourceManager dataSourceManager;
/** Condensed listener for system data listener events. */
private final DataSourceListener dataSourceListener = new HubDataSourceListener();
/** Whether we've been started. */
private boolean started;
// Cached preference values
private int minRequiredAccuracy;
private boolean useMetricUnits;
private boolean reportSpeed;
// Cached sensor readings
private float declination;
private long lastDeclinationUpdate;
private float lastSeenMagneticHeading;
// Cached GPS readings
private Location lastSeenLocation;
private boolean hasProviderEnabled = true;
private boolean hasFix;
private boolean hasGoodFix;
// Transient state about the selected track
private long selectedTrackId;
private long firstSeenLocationId;
private long lastSeenLocationId;
private int numLoadedPoints;
private int lastSamplingFrequency;
/**
* Default constructor.
*/
public TrackDataHub(Context ctx, SharedPreferences preferences,
MyTracksProviderUtils providerUtils) {
this(ctx, new DataSourcesWrapperImpl(ctx, preferences), new TrackDataListeners(),
preferences, providerUtils);
}
/**
* Injection constructor.
*/
// @VisibleForTesting
TrackDataHub(Context ctx, DataSourcesWrapper dataSources, TrackDataListeners listeners,
SharedPreferences preferences, MyTracksProviderUtils providerUtils) {
this.context = ctx;
this.listeners = listeners;
this.preferences = preferences;
this.providerUtils = providerUtils;
this.dataSources = dataSources;
this.dataSourceManager = new DataSourceManager(dataSourceListener, dataSources);
SELECTED_TRACK_KEY = context.getString(R.string.selected_track_key);
RECORDING_TRACK_KEY = context.getString(R.string.recording_track_key);
MIN_REQUIRED_ACCURACY_KEY = context.getString(R.string.min_required_accuracy_key);
METRIC_UNITS_KEY = context.getString(R.string.metric_units_key);
SPEED_REPORTING_KEY = context.getString(R.string.report_speed_key);
listenerHandlerThread = new HandlerThread("trackDataContentThread");
listenerHandlerThread.start();
listenerHandler = new Handler(listenerHandlerThread.getLooper());
}
/**
* Starts listening to data sources and reporting the data to external
* listeners.
*/
public void start() {
Log.i(TAG, "TrackDataHub.start");
if (started) {
Log.w(TAG, "Already started, ignoring");
return;
}
started = true;
// This may or may not register internal listeners, depending on whether
// we already had external listeners.
dataSourceManager.updateAllListeners(getNeededListenerTypes());
loadSharedPreferences();
// If there were listeners already registered, make sure they become up-to-date.
// TODO: This should really only send new data (in a start-stop-start cycle).
loadDataForAllListeners();
}
private void loadSharedPreferences() {
selectedTrackId = preferences.getLong(SELECTED_TRACK_KEY, -1);
useMetricUnits = preferences.getBoolean(METRIC_UNITS_KEY, true);
reportSpeed = preferences.getBoolean(SPEED_REPORTING_KEY, true);
minRequiredAccuracy = preferences.getInt(MIN_REQUIRED_ACCURACY_KEY,
Constants.DEFAULT_MIN_REQUIRED_ACCURACY);
}
/**
* Stops listening to data sources and reporting the data to external
* listeners.
*/
public void stop() {
Log.i(TAG, "TrackDataHub.stop");
if (!started) {
Log.w(TAG, "Not started, ignoring");
return;
}
// Unregister internal listeners even if there are external listeners registered.
dataSourceManager.unregisterAllListeners();
started = false;
}
/** Permanently invalidates and throws away all resources used by this class. */
public void destroy() {
if (started) {
throw new IllegalStateException("Can only destroy the data hub after it's been stopped");
}
ApiFeatures.getInstance().getApiPlatformAdapter()
.stopHandlerThread(listenerHandlerThread);
}
/** Updates known magnetic declination if needed. */
private void maybeUpdateDeclination() {
if (lastSeenLocation == null) {
// We still don't know where we are.
return;
}
// Update the declination every hour
long now = System.currentTimeMillis();
if (now - lastDeclinationUpdate < 60 * 60 * 1000) {
return;
}
lastDeclinationUpdate = now;
long timestamp = lastSeenLocation.getTime();
if (timestamp == 0) {
// Hack for Samsung phones which don't populate the time field
timestamp = now;
}
declination = getDeclinationFor(lastSeenLocation, timestamp);
Log.i(TAG, "Updated magnetic declination to " + declination);
}
// @VisibleForTesting
protected float getDeclinationFor(Location location, long timestamp) {
GeomagneticField field = new GeomagneticField(
(float) location.getLatitude(),
(float) location.getLongitude(),
(float) location.getAltitude(),
timestamp);
return field.getDeclination();
}
/**
* Forces the current location to be updated and reported to all listeners.
* The reported location may be from the network provider if the GPS provider
* is not available or doesn't have a fix.
*/
public void forceUpdateLocation() {
Log.i(TAG, "Forcing location update");
Location loc = dataSources.getLastKnownLocation();
if (loc != null) {
notifyLocationChanged(loc, getListenersFor(ListenerDataType.LOCATION_UPDATES));
}
}
/** Returns the ID of the currently-selected track. */
public long getSelectedTrackId() {
if (!started) {
loadSharedPreferences();
}
return selectedTrackId;
}
/** Returns whether there's a track currently selected. */
public boolean isATrackSelected() {
return getSelectedTrackId() > 0;
}
/** Returns whether we're currently recording a track. */
public boolean isRecording() {
if (!started) {
loadSharedPreferences();
}
return preferences.getLong(RECORDING_TRACK_KEY, -1) > 0;
}
/** Returns whether the selected track is still being recorded. */
public boolean isRecordingSelected() {
if (!started) {
loadSharedPreferences();
}
long recordingTrackId = preferences.getLong(RECORDING_TRACK_KEY, -1);
return recordingTrackId > 0 && recordingTrackId == selectedTrackId;
}
/**
* Loads the given track and makes it the currently-selected one.
* It is ok to call this method before {@link start}, and in that case
* the data will only be passed to listeners when {@link start} is called.
*
* @param trackId the ID of the track to load
*/
public void loadTrack(long trackId) {
if (trackId == selectedTrackId) {
Log.w(TAG, "Not reloading track, id=" + trackId);
return;
}
// Save the selection to memory and flash.
ApiFeatures.getInstance().getApiPlatformAdapter().applyPreferenceChanges(
preferences.edit().putLong(SELECTED_TRACK_KEY, trackId));
selectedTrackId = trackId;
// Force it to reload data from the beginning.
firstSeenLocationId = -1;
lastSeenLocationId = -1;
numLoadedPoints = 0;
loadDataForAllListeners();
}
/**
* Unloads the currently-selected track.
*/
public void unloadCurrentTrack() {
loadTrack(-1);
}
public void registerTrackDataListener(
TrackDataListener listener, EnumSet<ListenerDataType> dataTypes) {
synchronized (listeners) {
ListenerRegistration registration = listeners.registerTrackDataListener(listener, dataTypes);
// Don't load any data or start internal listeners if start() hasn't been
// called. When it is called, we'll do both things.
if (!started) return;
reloadDataForListener(registration);
dataSourceManager.updateAllListeners(getNeededListenerTypes());
}
}
public void unregisterTrackDataListener(TrackDataListener listener) {
synchronized (listeners) {
listeners.unregisterTrackDataListener(listener);
// Don't load any data or start internal listeners if start() hasn't been
// called. When it is called, we'll do both things.
if (!started) return;
dataSourceManager.updateAllListeners(getNeededListenerTypes());
}
}
/**
* Reloads all track data received so far into the specified listeners.
*/
public void reloadDataForListener(TrackDataListener listener) {
ListenerRegistration registration;
synchronized (listeners) {
registration = listeners.getRegistration(listener);
}
reloadDataForListener(registration);
}
/**
* Reloads all track data received so far into the specified listeners.
*/
private void reloadDataForListener(final ListenerRegistration registration) {
if (!started) {
Log.w(TAG, "Not started, not reloading");
return;
}
if (registration == null) {
return;
}
runInListenerThread(new Runnable() {
@SuppressWarnings("unchecked")
@Override
public void run() {
// Reload everything if either it's a different track, or the track has been resampled
// (this also covers the case of a new registration).
boolean reloadAll = registration.lastTrackId != selectedTrackId ||
registration.lastSamplingFrequency != lastSamplingFrequency;
Log.d(TAG, "Doing a " + (reloadAll ? "full" : "partial") + " reload for " + registration);
TrackDataListener listener = registration.listener;
Set<TrackDataListener> listenerSet = Collections.singleton(listener);
if (registration.isInterestedIn(ListenerDataType.DISPLAY_PREFERENCES)) {
reloadAll |= listener.onUnitsChanged(useMetricUnits);
reloadAll |= listener.onReportSpeedChanged(reportSpeed);
}
if (reloadAll && registration.isInterestedIn(ListenerDataType.SELECTED_TRACK_CHANGED)) {
notifySelectedTrackChanged(selectedTrackId, listenerSet);
}
if (registration.isInterestedIn(ListenerDataType.TRACK_UPDATES)) {
notifyTrackUpdated(listenerSet);
}
boolean interestedInPoints =
registration.isInterestedIn(ListenerDataType.POINT_UPDATES);
boolean interestedInSampledOutPoints =
registration.isInterestedIn(ListenerDataType.SAMPLED_OUT_POINT_UPDATES);
if (interestedInPoints || interestedInSampledOutPoints) {
if (reloadAll) notifyPointsCleared(listenerSet);
notifyPointsUpdated(false,
reloadAll ? 0 : registration.lastPointId + 1,
listenerSet,
interestedInSampledOutPoints ? listenerSet : Collections.EMPTY_SET);
}
if (registration.isInterestedIn(ListenerDataType.WAYPOINT_UPDATES)) {
notifyWaypointUpdated(listenerSet);
}
if (registration.isInterestedIn(ListenerDataType.LOCATION_UPDATES)) {
if (lastSeenLocation != null) {
notifyLocationChanged(lastSeenLocation, true, listenerSet);
} else {
notifyFixType();
}
}
if (registration.isInterestedIn(ListenerDataType.COMPASS_UPDATES)) {
notifyHeadingChanged(listenerSet);
}
}
});
}
/**
* Reloads all track data received so far into the specified listeners.
*/
private void loadDataForAllListeners() {
if (!started) {
Log.w(TAG, "Not started, not reloading");
return;
}
synchronized (listeners) {
if (!listeners.hasListeners()) {
Log.d(TAG, "No listeners, not reloading");
return;
}
}
runInListenerThread(new Runnable() {
@Override
public void run() {
// Ignore the return values here, we're already sending the full data set anyway
for (TrackDataListener listener :
getListenersFor(ListenerDataType.DISPLAY_PREFERENCES)) {
listener.onUnitsChanged(useMetricUnits);
listener.onReportSpeedChanged(reportSpeed);
}
notifySelectedTrackChanged(selectedTrackId,
getListenersFor(ListenerDataType.SELECTED_TRACK_CHANGED));
notifyTrackUpdated(getListenersFor(ListenerDataType.TRACK_UPDATES));
Set<TrackDataListener> pointListeners =
getListenersFor(ListenerDataType.POINT_UPDATES);
Set<TrackDataListener> sampledOutPointListeners =
getListenersFor(ListenerDataType.SAMPLED_OUT_POINT_UPDATES);
notifyPointsCleared(pointListeners);
notifyPointsUpdated(true, 0, pointListeners, sampledOutPointListeners);
notifyWaypointUpdated(getListenersFor(ListenerDataType.WAYPOINT_UPDATES));
if (lastSeenLocation != null) {
notifyLocationChanged(lastSeenLocation, true,
getListenersFor(ListenerDataType.LOCATION_UPDATES));
} else {
notifyFixType();
}
notifyHeadingChanged(getListenersFor(ListenerDataType.COMPASS_UPDATES));
}
});
}
/**
* Called when a preference changes.
*
* @param key the key to the preference that changed
*/
private void notifyPreferenceChanged(String key) {
if (MIN_REQUIRED_ACCURACY_KEY.equals(key)) {
minRequiredAccuracy = preferences.getInt(MIN_REQUIRED_ACCURACY_KEY,
Constants.DEFAULT_MIN_REQUIRED_ACCURACY);
} else if (METRIC_UNITS_KEY.equals(key)) {
useMetricUnits = preferences.getBoolean(METRIC_UNITS_KEY, true);
notifyUnitsChanged();
} else if (SPEED_REPORTING_KEY.equals(key)) {
reportSpeed = preferences.getBoolean(SPEED_REPORTING_KEY, true);
notifySpeedReportingChanged();
}
}
/** Called when the speed/pace reporting preference changes. */
private void notifySpeedReportingChanged() {
if (!started) return;
runInListenerThread(new Runnable() {
@Override
public void run() {
Set<TrackDataListener> displayListeners =
getListenersFor(ListenerDataType.DISPLAY_PREFERENCES);
for (TrackDataListener listener : displayListeners) {
// TODO: Do the reloading just once for all interested listeners
if (listener.onReportSpeedChanged(reportSpeed)) {
synchronized (listeners) {
reloadDataForListener(listeners.getRegistration(listener));
}
}
}
}
});
}
/** Called when the metric units setting changes. */
private void notifyUnitsChanged() {
if (!started) return;
runInListenerThread(new Runnable() {
@Override
public void run() {
Set<TrackDataListener> displayListeners = getListenersFor(ListenerDataType.DISPLAY_PREFERENCES);
for (TrackDataListener listener : displayListeners) {
if (listener.onUnitsChanged(useMetricUnits)) {
synchronized (listeners) {
reloadDataForListener(listeners.getRegistration(listener));
}
}
}
}
});
}
/** Notifies about the current GPS fix state. */
private void notifyFixType() {
final TrackDataListener.ProviderState state;
if (!hasProviderEnabled) {
state = ProviderState.DISABLED;
// Give a global warning about this state.
Toast.makeText(context, R.string.error_no_gps_location_provider, Toast.LENGTH_LONG).show();
} else if (!hasFix) {
state = ProviderState.NO_FIX;
} else if (!hasGoodFix) {
state = ProviderState.BAD_FIX;
} else {
state = ProviderState.GOOD_FIX;
}
runInListenerThread(new Runnable() {
@Override
public void run() {
// Notify to everyone.
Log.d(TAG, "Notifying fix type: " + state);
for (TrackDataListener listener :
getListenersFor(ListenerDataType.LOCATION_UPDATES)) {
listener.onProviderStateChange(state);
}
}
});
}
/**
* Notifies the the current location has changed, without any filtering.
* If the state of GPS fix has changed, that will also be reported.
*
* @param location the current location
* @param listeners the listeners to notify
*/
private void notifyLocationChanged(Location location, Set<TrackDataListener> listeners) {
notifyLocationChanged(location, false, listeners);
}
/**
* Notifies that the current location has changed, without any filtering.
* If the state of GPS fix has changed, that will also be reported.
*
* @param location the current location
* @param forceUpdate whether to force the notifications to happen
* @param listeners the listeners to notify
*/
private void notifyLocationChanged(final Location location, boolean forceUpdate,
final Set<TrackDataListener> listeners) {
if (location == null) return;
if (listeners.isEmpty()) return;
boolean isGpsLocation = location.getProvider().equals(LocationManager.GPS_PROVIDER);
boolean oldHasFix = hasFix;
boolean oldHasGoodFix = hasGoodFix;
// We consider a good fix to be a recent one with reasonable accuracy.
if (isGpsLocation) {
lastSeenLocation = location;
hasFix = (location != null && System.currentTimeMillis() - location.getTime() <= MAX_LOCATION_AGE_MS);
hasGoodFix = (location != null && location.getAccuracy() <= minRequiredAccuracy);
if (hasFix != oldHasFix || hasGoodFix != oldHasGoodFix || forceUpdate) {
notifyFixType();
}
}
runInListenerThread(new Runnable() {
@Override
public void run() {
for (TrackDataListener listener : listeners) {
listener.onCurrentLocationChanged(location);
}
}
});
}
/**
* Notifies that the current heading has changed.
*
* @param listeners the listeners to notify
*/
private void notifyHeadingChanged(final Set<TrackDataListener> listeners) {
if (listeners.isEmpty()) return;
runInListenerThread(new Runnable() {
@Override
public void run() {
float heading = lastSeenMagneticHeading + declination;
for (TrackDataListener listener : listeners) {
listener.onCurrentHeadingChanged(heading);
}
}
});
}
/**
* Notifies that a new track has been selected..
*
* @param track the new selected track
* @param listeners the listeners to notify
*/
private void notifySelectedTrackChanged(long trackId,
final Set<TrackDataListener> listeners) {
if (listeners.isEmpty()) return;
Log.i(TAG, "New track selected, id=" + trackId);
final Track track = providerUtils.getTrack(trackId);
runInListenerThread(new Runnable() {
@Override
public void run() {
for (TrackDataListener listener : listeners) {
listener.onSelectedTrackChanged(track, isRecordingSelected());
if (track != null) {
listener.onTrackUpdated(track);
}
}
}
});
}
/**
* Notifies that the currently-selected track's data has been updated.
*
* @param listeners the listeners to notify
*/
private void notifyTrackUpdated(final Set<TrackDataListener> listeners) {
if (listeners.isEmpty()) return;
final Track track = providerUtils.getTrack(selectedTrackId);
runInListenerThread(new Runnable() {
@Override
public void run() {
for (TrackDataListener listener : listeners) {
listener.onTrackUpdated(track);
}
}
});
}
/**
* Notifies that waypoints have been updated.
* We assume few waypoints, so we reload them all every time.
*
* @param listeners the listeners to notify
*/
private void notifyWaypointUpdated(final Set<TrackDataListener> listeners) {
if (listeners.isEmpty()) return;
// Always reload all the waypoints.
final Cursor cursor = providerUtils.getWaypointsCursor(
selectedTrackId, 0L, Constants.MAX_DISPLAYED_WAYPOINTS_POINTS);
runInListenerThread(new Runnable() {
@Override
public void run() {
Log.d(TAG, "Reloading waypoints");
for (TrackDataListener listener : listeners) {
listener.clearWaypoints();
}
try {
if (cursor != null && cursor.moveToFirst()) {
do {
Waypoint waypoint = providerUtils.createWaypoint(cursor);
if (!LocationUtils.isValidLocation(waypoint.getLocation())) {
continue;
}
for (TrackDataListener listener : listeners) {
listener.onNewWaypoint(waypoint);
}
} while (cursor.moveToNext());
}
} finally {
if (cursor != null) {
cursor.close();
}
}
for (TrackDataListener listener : listeners) {
listener.onNewWaypointsDone();
}
}
});
}
/**
* Tells listeners to clear the current list of points.
*
* @param listeners the listeners to notify
*/
private void notifyPointsCleared(final Set<TrackDataListener> listeners) {
if (listeners.isEmpty()) return;
runInListenerThread(new Runnable() {
@Override
public void run() {
for (TrackDataListener listener : listeners) {
listener.clearTrackPoints();
}
}
});
}
/**
* Notifies the given listeners about track points in the given ID range.
*
* @param keepState whether to load and save state about the already-notified points.
* If true, only new points are reported.
* If false, then the whole track will be loaded, without affecting the store.
* @param minPointId the first point ID to notify, inclusive
*/
private void notifyPointsUpdated(final boolean keepState,
final long minPointId, final Set<TrackDataListener> sampledListeners,
final Set<TrackDataListener> sampledOutListeners) {
if (sampledListeners.isEmpty() && sampledOutListeners.isEmpty()) return;
runInListenerThread(new Runnable() {
@Override
public void run() {
notifyPointsUpdatedSync(keepState, minPointId, sampledListeners, sampledOutListeners);
}
});
}
/**
* Asynchronous version of the above method.
*/
private void notifyPointsUpdatedSync(boolean keepState,
long minPointId, Set<TrackDataListener> sampledListeners,
Set<TrackDataListener> sampledOutListeners) {
// If we're loading state, start from after the last seen point up to the last recorded one
// (all new points)
// If we're not loading state, then notify about all the previously-seen points.
if (minPointId <= 0) {
minPointId = keepState ? lastSeenLocationId + 1 : 0;
}
long maxPointId = keepState ? -1 : lastSeenLocationId;
// TODO: Move (re)sampling to a separate class.
if (numLoadedPoints >= Constants.MAX_DISPLAYED_TRACK_POINTS) {
// We're about to exceed the maximum allowed number of points, so reload
// the whole track with fewer points (the sampling frequency will be
// lower). We do this for every listener even if we were loading just for
// a few of them (why miss the oportunity?).
Log.i(TAG, "Resampling point set after " + numLoadedPoints + " points.");
firstSeenLocationId = -1;
lastSeenLocationId = -1;
numLoadedPoints = 0;
synchronized (listeners) {
sampledListeners = getListenersFor(ListenerDataType.POINT_UPDATES);
sampledOutListeners = getListenersFor(ListenerDataType.SAMPLED_OUT_POINT_UPDATES);
}
maxPointId = -1;
minPointId = 0;
keepState = true;
for (TrackDataListener listener : sampledListeners) {
listener.clearTrackPoints();
}
}
// Keep the originally selected track ID so we can stop if it changes.
long currentSelectedTrackId = selectedTrackId;
// If we're ignoring state, start from the beginning of the track
int localNumLoadedPoints = keepState ? numLoadedPoints : 0;
long localFirstSeenLocationId = keepState ? firstSeenLocationId : 0;
long localLastSeenLocationId = minPointId;
long lastStoredLocationId = providerUtils.getLastLocationId(currentSelectedTrackId);
int pointSamplingFrequency = -1;
// Create a double-buffering location provider.
MyTracksProviderUtils.DoubleBufferedLocationFactory locationFactory =
new MyTracksProviderUtils.DoubleBufferedLocationFactory();
LocationIterator it = providerUtils.getLocationIterator(
currentSelectedTrackId, minPointId, false, locationFactory);
while (it.hasNext()) {
if (currentSelectedTrackId != selectedTrackId) {
// The selected track changed beneath us, stop.
break;
}
Location location = it.next();
long locationId = it.getLocationId();
// If past the last wanted point, stop.
// This happens when adding a new listener after data has already been loaded,
// in which case we only want to bring that listener up to the point where the others
// were. In case it does happen, we should be wasting few points (only the ones not
// yet notified to other listeners).
if (maxPointId > 0 && locationId > maxPointId) {
break;
}
if (localFirstSeenLocationId == -1) {
// This was our first point, keep its ID
localFirstSeenLocationId = locationId;
}
if (pointSamplingFrequency == -1) {
// Now we already have at least one point, calculate the sampling
// frequency.
long numTotalPoints = lastStoredLocationId - localFirstSeenLocationId;
pointSamplingFrequency =
(int) (1 + numTotalPoints / Constants.TARGET_DISPLAYED_TRACK_POINTS);
}
notifyNewPoint(location, locationId, lastStoredLocationId,
localNumLoadedPoints, pointSamplingFrequency, sampledListeners, sampledOutListeners);
localNumLoadedPoints++;
localLastSeenLocationId = locationId;
}
it.close();
if (keepState) {
numLoadedPoints = localNumLoadedPoints;
firstSeenLocationId = localFirstSeenLocationId;
lastSeenLocationId = localLastSeenLocationId;
}
// Always keep the sampling frequency - if it changes we'll do a full reload above anyway.
lastSamplingFrequency = pointSamplingFrequency;
// Update the listener state
// TODO: Optimize this (sampledOutListeners should be a subset of sampledListeners, plus
// getRegistration does a lookup for every listener, and this is in the critical path).
updateListenersState(sampledListeners,
currentSelectedTrackId, localLastSeenLocationId, pointSamplingFrequency);
updateListenersState(sampledOutListeners,
currentSelectedTrackId, localLastSeenLocationId, pointSamplingFrequency);
for (TrackDataListener listener : sampledListeners) {
listener.onNewTrackPointsDone();
}
}
private void updateListenersState(Set<TrackDataListener> sampledListeners,
long trackId, long lastPointId, int samplingFrequency) {
synchronized (listeners) {
for (TrackDataListener listener : sampledListeners) {
ListenerRegistration registration = listeners.getRegistration(listener);
if (registration != null) {
registration.lastTrackId = trackId;
registration.lastPointId = lastPointId;
registration.lastSamplingFrequency = samplingFrequency;
}
}
}
}
private void notifyNewPoint(Location location,
long locationId,
long lastStoredLocationId,
int numLoadedPoints,
int pointSamplingFrequency,
Set<TrackDataListener> sampledListeners,
Set<TrackDataListener> sampledOutListeners) {
boolean isValid = LocationUtils.isValidLocation(location);
if (!isValid) {
// Invalid points are segment splits - report those separately.
// TODO: Always send last valid point before and first valid point after a split
for (TrackDataListener listener : sampledListeners) {
listener.onSegmentSplit();
}
return;
}
// Include a point if it fits one of the following criteria:
// - Has the mod for the sampling frequency (includes first point).
// - Is the last point and we are not recording this track.
boolean includeInSample =
(numLoadedPoints % pointSamplingFrequency == 0 ||
(!isRecordingSelected() && locationId == lastStoredLocationId));
if (!includeInSample) {
for (TrackDataListener listener : sampledOutListeners) {
listener.onSampledOutTrackPoint(location);
}
return;
}
// Point is valid and included in sample.
for (TrackDataListener listener : sampledListeners) {
// No need to allocate a new location (we can safely reuse the existing).
listener.onNewTrackPoint(location);
}
}
// @VisibleForTesting
protected void runInListenerThread(Runnable runnable) {
listenerHandler.post(runnable);
}
private Set<TrackDataListener> getListenersFor(ListenerDataType type) {
synchronized (listeners) {
return listeners.getListenersFor(type);
}
}
private EnumSet<ListenerDataType> getNeededListenerTypes() {
EnumSet<ListenerDataType> neededTypes = listeners.getAllRegisteredTypes();
// We always want preference updates.
neededTypes.add(ListenerDataType.DISPLAY_PREFERENCES);
return neededTypes;
}
}
|
MyTracks/src/com/google/android/apps/mytracks/content/TrackDataHub.java
|
/*
* Copyright 2011 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.android.apps.mytracks.content;
import static com.google.android.apps.mytracks.Constants.MAX_LOCATION_AGE_MS;
import static com.google.android.apps.mytracks.Constants.TAG;
import com.google.android.apps.mytracks.Constants;
import com.google.android.apps.mytracks.content.DataSourceManager.DataSourceListener;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils.LocationIterator;
import com.google.android.apps.mytracks.content.TrackDataListener.ProviderState;
import com.google.android.apps.mytracks.content.TrackDataListeners.ListenerRegistration;
import com.google.android.apps.mytracks.util.ApiFeatures;
import com.google.android.apps.mytracks.util.LocationUtils;
import com.google.android.maps.mytracks.R;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.hardware.GeomagneticField;
import android.location.Location;
import android.location.LocationManager;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;
import android.widget.Toast;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Set;
/**
* Track data hub, which receives data (both live and recorded) from many
* different sources and distributes it to those interested after some standard
* processing.
*
* @author Rodrigo Damazio
*/
public class TrackDataHub {
// Preference keys
private final String SELECTED_TRACK_KEY;
private final String RECORDING_TRACK_KEY;
private final String MIN_REQUIRED_ACCURACY_KEY;
private final String METRIC_UNITS_KEY;
private final String SPEED_REPORTING_KEY;
/** Types of data that we can expose. */
public static enum ListenerDataType {
/** Listen to when the selected track changes. */
SELECTED_TRACK_CHANGED,
/** Listen to when the tracks change. */
TRACK_UPDATES,
/** Listen to when the waypoints change. */
WAYPOINT_UPDATES,
/** Listen to when the current track points change. */
POINT_UPDATES,
/**
* Listen to sampled-out points.
* Listening to this without listening to {@link #SAMPLED_POINT_UPDATES}
* makes no sense and may yield unexpected results.
*/
SAMPLED_OUT_POINT_UPDATES,
/** Listen to updates to the current location. */
LOCATION_UPDATES,
/** Listen to updates to the current heading. */
COMPASS_UPDATES,
/** Listens to changes in display preferences. */
DISPLAY_PREFERENCES;
}
/** Listener which receives events from the system. */
private class HubDataSourceListener implements DataSourceListener {
@Override
public void notifyTrackUpdated() {
TrackDataHub.this.notifyTrackUpdated(getListenersFor(ListenerDataType.TRACK_UPDATES));
}
@Override
public void notifyWaypointUpdated() {
TrackDataHub.this.notifyWaypointUpdated(getListenersFor(ListenerDataType.WAYPOINT_UPDATES));
}
@Override
public void notifyPointsUpdated() {
TrackDataHub.this.notifyPointsUpdated(true, 0,
getListenersFor(ListenerDataType.POINT_UPDATES),
getListenersFor(ListenerDataType.SAMPLED_OUT_POINT_UPDATES));
}
@Override
public void notifyPreferenceChanged(String key) {
TrackDataHub.this.notifyPreferenceChanged(key);
}
@Override
public void notifyLocationProviderEnabled(boolean enabled) {
hasProviderEnabled = enabled;
TrackDataHub.this.notifyFixType();
}
@Override
public void notifyLocationChanged(Location loc) {
TrackDataHub.this.notifyLocationChanged(loc,
getListenersFor(ListenerDataType.LOCATION_UPDATES));
}
@Override
public void notifyHeadingChanged(float heading) {
lastSeenMagneticHeading = heading;
maybeUpdateDeclination();
TrackDataHub.this.notifyHeadingChanged(getListenersFor(ListenerDataType.COMPASS_UPDATES));
}
}
// Application services
private final Context context;
private final MyTracksProviderUtils providerUtils;
private final SharedPreferences preferences;
// Get content notifications on the main thread, send listener callbacks in another.
// This ensures listener calls are serialized.
private final HandlerThread listenerHandlerThread;
private final Handler listenerHandler;
/** Manager for external listeners (those from activities). */
private final TrackDataListeners listeners;
/** Wrapper for interacting with system data managers. */
private final DataSourcesWrapper dataSources;
/** Manager for system data listener registrations. */
private final DataSourceManager dataSourceManager;
/** Condensed listener for system data listener events. */
private final DataSourceListener dataSourceListener = new HubDataSourceListener();
/** Whether we've been started. */
private boolean started;
// Cached preference values
private int minRequiredAccuracy;
private boolean useMetricUnits;
private boolean reportSpeed;
// Cached sensor readings
private float declination;
private long lastDeclinationUpdate;
private float lastSeenMagneticHeading;
// Cached GPS readings
private Location lastSeenLocation;
private boolean hasProviderEnabled;
private boolean hasFix;
private boolean hasGoodFix;
// Transient state about the selected track
private long selectedTrackId;
private long firstSeenLocationId;
private long lastSeenLocationId;
private int numLoadedPoints;
private int lastSamplingFrequency;
/**
* Default constructor.
*/
public TrackDataHub(Context ctx, SharedPreferences preferences,
MyTracksProviderUtils providerUtils) {
this(ctx, new DataSourcesWrapperImpl(ctx, preferences), new TrackDataListeners(),
preferences, providerUtils);
}
/**
* Injection constructor.
*/
// @VisibleForTesting
TrackDataHub(Context ctx, DataSourcesWrapper dataSources, TrackDataListeners listeners,
SharedPreferences preferences, MyTracksProviderUtils providerUtils) {
this.context = ctx;
this.listeners = listeners;
this.preferences = preferences;
this.providerUtils = providerUtils;
this.dataSources = dataSources;
this.dataSourceManager = new DataSourceManager(dataSourceListener, dataSources);
SELECTED_TRACK_KEY = context.getString(R.string.selected_track_key);
RECORDING_TRACK_KEY = context.getString(R.string.recording_track_key);
MIN_REQUIRED_ACCURACY_KEY = context.getString(R.string.min_required_accuracy_key);
METRIC_UNITS_KEY = context.getString(R.string.metric_units_key);
SPEED_REPORTING_KEY = context.getString(R.string.report_speed_key);
listenerHandlerThread = new HandlerThread("trackDataContentThread");
listenerHandlerThread.start();
listenerHandler = new Handler(listenerHandlerThread.getLooper());
}
/**
* Starts listening to data sources and reporting the data to external
* listeners.
*/
public void start() {
Log.i(TAG, "TrackDataHub.start");
if (started) {
Log.w(TAG, "Already started, ignoring");
return;
}
started = true;
// This may or may not register internal listeners, depending on whether
// we already had external listeners.
dataSourceManager.updateAllListeners(getNeededListenerTypes());
loadSharedPreferences();
// If there were listeners already registered, make sure they become up-to-date.
// TODO: This should really only send new data (in a start-stop-start cycle).
loadDataForAllListeners();
}
private void loadSharedPreferences() {
selectedTrackId = preferences.getLong(SELECTED_TRACK_KEY, -1);
useMetricUnits = preferences.getBoolean(METRIC_UNITS_KEY, true);
reportSpeed = preferences.getBoolean(SPEED_REPORTING_KEY, true);
minRequiredAccuracy = preferences.getInt(MIN_REQUIRED_ACCURACY_KEY,
Constants.DEFAULT_MIN_REQUIRED_ACCURACY);
}
/**
* Stops listening to data sources and reporting the data to external
* listeners.
*/
public void stop() {
Log.i(TAG, "TrackDataHub.stop");
if (!started) {
Log.w(TAG, "Not started, ignoring");
return;
}
// Unregister internal listeners even if there are external listeners registered.
dataSourceManager.unregisterAllListeners();
started = false;
}
/** Permanently invalidates and throws away all resources used by this class. */
public void destroy() {
if (started) {
throw new IllegalStateException("Can only destroy the data hub after it's been stopped");
}
ApiFeatures.getInstance().getApiPlatformAdapter()
.stopHandlerThread(listenerHandlerThread);
}
/** Updates known magnetic declination if needed. */
private void maybeUpdateDeclination() {
if (lastSeenLocation == null) {
// We still don't know where we are.
return;
}
// Update the declination every hour
long now = System.currentTimeMillis();
if (now - lastDeclinationUpdate < 60 * 60 * 1000) {
return;
}
lastDeclinationUpdate = now;
long timestamp = lastSeenLocation.getTime();
if (timestamp == 0) {
// Hack for Samsung phones which don't populate the time field
timestamp = now;
}
declination = getDeclinationFor(lastSeenLocation, timestamp);
Log.i(TAG, "Updated magnetic declination to " + declination);
}
// @VisibleForTesting
protected float getDeclinationFor(Location location, long timestamp) {
GeomagneticField field = new GeomagneticField(
(float) location.getLatitude(),
(float) location.getLongitude(),
(float) location.getAltitude(),
timestamp);
return field.getDeclination();
}
/**
* Forces the current location to be updated and reported to all listeners.
* The reported location may be from the network provider if the GPS provider
* is not available or doesn't have a fix.
*/
public void forceUpdateLocation() {
Log.i(TAG, "Forcing location update");
Location loc = dataSources.getLastKnownLocation();
if (loc != null) {
notifyLocationChanged(loc, getListenersFor(ListenerDataType.LOCATION_UPDATES));
}
}
/** Returns the ID of the currently-selected track. */
public long getSelectedTrackId() {
if (!started) {
loadSharedPreferences();
}
return selectedTrackId;
}
/** Returns whether there's a track currently selected. */
public boolean isATrackSelected() {
return getSelectedTrackId() > 0;
}
/** Returns whether we're currently recording a track. */
public boolean isRecording() {
if (!started) {
loadSharedPreferences();
}
return preferences.getLong(RECORDING_TRACK_KEY, -1) > 0;
}
/** Returns whether the selected track is still being recorded. */
public boolean isRecordingSelected() {
if (!started) {
loadSharedPreferences();
}
long recordingTrackId = preferences.getLong(RECORDING_TRACK_KEY, -1);
return recordingTrackId > 0 && recordingTrackId == selectedTrackId;
}
/**
* Loads the given track and makes it the currently-selected one.
* It is ok to call this method before {@link start}, and in that case
* the data will only be passed to listeners when {@link start} is called.
*
* @param trackId the ID of the track to load
*/
public void loadTrack(long trackId) {
if (trackId == selectedTrackId) {
Log.w(TAG, "Not reloading track, id=" + trackId);
return;
}
// Save the selection to memory and flash.
ApiFeatures.getInstance().getApiPlatformAdapter().applyPreferenceChanges(
preferences.edit().putLong(SELECTED_TRACK_KEY, trackId));
selectedTrackId = trackId;
// Force it to reload data from the beginning.
firstSeenLocationId = -1;
lastSeenLocationId = -1;
numLoadedPoints = 0;
loadDataForAllListeners();
}
/**
* Unloads the currently-selected track.
*/
public void unloadCurrentTrack() {
loadTrack(-1);
}
public void registerTrackDataListener(
TrackDataListener listener, EnumSet<ListenerDataType> dataTypes) {
synchronized (listeners) {
ListenerRegistration registration = listeners.registerTrackDataListener(listener, dataTypes);
// Don't load any data or start internal listeners if start() hasn't been
// called. When it is called, we'll do both things.
if (!started) return;
reloadDataForListener(registration);
dataSourceManager.updateAllListeners(getNeededListenerTypes());
}
}
public void unregisterTrackDataListener(TrackDataListener listener) {
synchronized (listeners) {
listeners.unregisterTrackDataListener(listener);
// Don't load any data or start internal listeners if start() hasn't been
// called. When it is called, we'll do both things.
if (!started) return;
dataSourceManager.updateAllListeners(getNeededListenerTypes());
}
}
/**
* Reloads all track data received so far into the specified listeners.
*/
public void reloadDataForListener(TrackDataListener listener) {
ListenerRegistration registration;
synchronized (listeners) {
registration = listeners.getRegistration(listener);
}
reloadDataForListener(registration);
}
/**
* Reloads all track data received so far into the specified listeners.
*/
private void reloadDataForListener(final ListenerRegistration registration) {
if (!started) {
Log.w(TAG, "Not started, not reloading");
return;
}
if (registration == null) {
return;
}
runInListenerThread(new Runnable() {
@SuppressWarnings("unchecked")
@Override
public void run() {
// Reload everything if either it's a different track, or the track has been resampled
// (this also covers the case of a new registration).
boolean reloadAll = registration.lastTrackId != selectedTrackId ||
registration.lastSamplingFrequency != lastSamplingFrequency;
Log.d(TAG, "Doing a " + (reloadAll ? "full" : "partial") + " reload for " + registration);
TrackDataListener listener = registration.listener;
Set<TrackDataListener> listenerSet = Collections.singleton(listener);
if (registration.isInterestedIn(ListenerDataType.DISPLAY_PREFERENCES)) {
reloadAll |= listener.onUnitsChanged(useMetricUnits);
reloadAll |= listener.onReportSpeedChanged(reportSpeed);
}
if (reloadAll && registration.isInterestedIn(ListenerDataType.SELECTED_TRACK_CHANGED)) {
notifySelectedTrackChanged(selectedTrackId, listenerSet);
}
if (registration.isInterestedIn(ListenerDataType.TRACK_UPDATES)) {
notifyTrackUpdated(listenerSet);
}
boolean interestedInPoints =
registration.isInterestedIn(ListenerDataType.POINT_UPDATES);
boolean interestedInSampledOutPoints =
registration.isInterestedIn(ListenerDataType.SAMPLED_OUT_POINT_UPDATES);
if (interestedInPoints || interestedInSampledOutPoints) {
if (reloadAll) notifyPointsCleared(listenerSet);
notifyPointsUpdated(false,
reloadAll ? 0 : registration.lastPointId + 1,
listenerSet,
interestedInSampledOutPoints ? listenerSet : Collections.EMPTY_SET);
}
if (registration.isInterestedIn(ListenerDataType.WAYPOINT_UPDATES)) {
notifyWaypointUpdated(listenerSet);
}
if (registration.isInterestedIn(ListenerDataType.LOCATION_UPDATES)) {
if (lastSeenLocation != null) {
notifyLocationChanged(lastSeenLocation, true, listenerSet);
} else {
notifyFixType();
}
}
if (registration.isInterestedIn(ListenerDataType.COMPASS_UPDATES)) {
notifyHeadingChanged(listenerSet);
}
}
});
}
/**
* Reloads all track data received so far into the specified listeners.
*/
private void loadDataForAllListeners() {
if (!started) {
Log.w(TAG, "Not started, not reloading");
return;
}
synchronized (listeners) {
if (!listeners.hasListeners()) {
Log.d(TAG, "No listeners, not reloading");
return;
}
}
runInListenerThread(new Runnable() {
@Override
public void run() {
// Ignore the return values here, we're already sending the full data set anyway
for (TrackDataListener listener :
getListenersFor(ListenerDataType.DISPLAY_PREFERENCES)) {
listener.onUnitsChanged(useMetricUnits);
listener.onReportSpeedChanged(reportSpeed);
}
notifySelectedTrackChanged(selectedTrackId,
getListenersFor(ListenerDataType.SELECTED_TRACK_CHANGED));
notifyTrackUpdated(getListenersFor(ListenerDataType.TRACK_UPDATES));
Set<TrackDataListener> pointListeners =
getListenersFor(ListenerDataType.POINT_UPDATES);
Set<TrackDataListener> sampledOutPointListeners =
getListenersFor(ListenerDataType.SAMPLED_OUT_POINT_UPDATES);
notifyPointsCleared(pointListeners);
notifyPointsUpdated(true, 0, pointListeners, sampledOutPointListeners);
notifyWaypointUpdated(getListenersFor(ListenerDataType.WAYPOINT_UPDATES));
if (lastSeenLocation != null) {
notifyLocationChanged(lastSeenLocation, true,
getListenersFor(ListenerDataType.LOCATION_UPDATES));
} else {
notifyFixType();
}
notifyHeadingChanged(getListenersFor(ListenerDataType.COMPASS_UPDATES));
}
});
}
/**
* Called when a preference changes.
*
* @param key the key to the preference that changed
*/
private void notifyPreferenceChanged(String key) {
if (MIN_REQUIRED_ACCURACY_KEY.equals(key)) {
minRequiredAccuracy = preferences.getInt(MIN_REQUIRED_ACCURACY_KEY,
Constants.DEFAULT_MIN_REQUIRED_ACCURACY);
} else if (METRIC_UNITS_KEY.equals(key)) {
useMetricUnits = preferences.getBoolean(METRIC_UNITS_KEY, true);
notifyUnitsChanged();
} else if (SPEED_REPORTING_KEY.equals(key)) {
reportSpeed = preferences.getBoolean(SPEED_REPORTING_KEY, true);
notifySpeedReportingChanged();
}
}
/** Called when the speed/pace reporting preference changes. */
private void notifySpeedReportingChanged() {
if (!started) return;
runInListenerThread(new Runnable() {
@Override
public void run() {
Set<TrackDataListener> displayListeners =
getListenersFor(ListenerDataType.DISPLAY_PREFERENCES);
for (TrackDataListener listener : displayListeners) {
// TODO: Do the reloading just once for all interested listeners
if (listener.onReportSpeedChanged(reportSpeed)) {
synchronized (listeners) {
reloadDataForListener(listeners.getRegistration(listener));
}
}
}
}
});
}
/** Called when the metric units setting changes. */
private void notifyUnitsChanged() {
if (!started) return;
runInListenerThread(new Runnable() {
@Override
public void run() {
Set<TrackDataListener> displayListeners = getListenersFor(ListenerDataType.DISPLAY_PREFERENCES);
for (TrackDataListener listener : displayListeners) {
if (listener.onUnitsChanged(useMetricUnits)) {
synchronized (listeners) {
reloadDataForListener(listeners.getRegistration(listener));
}
}
}
}
});
}
/** Notifies about the current GPS fix state. */
private void notifyFixType() {
final TrackDataListener.ProviderState state;
if (!hasProviderEnabled) {
state = ProviderState.DISABLED;
// Give a global warning about this state.
Toast.makeText(context, R.string.error_no_gps_location_provider, Toast.LENGTH_LONG).show();
} else if (!hasFix) {
state = ProviderState.NO_FIX;
} else if (!hasGoodFix) {
state = ProviderState.BAD_FIX;
} else {
state = ProviderState.GOOD_FIX;
}
runInListenerThread(new Runnable() {
@Override
public void run() {
// Notify to everyone.
Log.d(TAG, "Notifying fix type: " + state);
for (TrackDataListener listener :
getListenersFor(ListenerDataType.LOCATION_UPDATES)) {
listener.onProviderStateChange(state);
}
}
});
}
/**
* Notifies the the current location has changed, without any filtering.
* If the state of GPS fix has changed, that will also be reported.
*
* @param location the current location
* @param listeners the listeners to notify
*/
private void notifyLocationChanged(Location location, Set<TrackDataListener> listeners) {
notifyLocationChanged(location, false, listeners);
}
/**
* Notifies that the current location has changed, without any filtering.
* If the state of GPS fix has changed, that will also be reported.
*
* @param location the current location
* @param forceUpdate whether to force the notifications to happen
* @param listeners the listeners to notify
*/
private void notifyLocationChanged(final Location location, boolean forceUpdate,
final Set<TrackDataListener> listeners) {
if (location == null) return;
if (listeners.isEmpty()) return;
boolean isGpsLocation = location.getProvider().equals(LocationManager.GPS_PROVIDER);
boolean oldHasFix = hasFix;
boolean oldHasGoodFix = hasGoodFix;
// We consider a good fix to be a recent one with reasonable accuracy.
if (isGpsLocation) {
lastSeenLocation = location;
hasFix = (location != null && System.currentTimeMillis() - location.getTime() <= MAX_LOCATION_AGE_MS);
hasGoodFix = (location != null && location.getAccuracy() <= minRequiredAccuracy);
if (hasFix != oldHasFix || hasGoodFix != oldHasGoodFix || forceUpdate) {
notifyFixType();
}
}
runInListenerThread(new Runnable() {
@Override
public void run() {
for (TrackDataListener listener : listeners) {
listener.onCurrentLocationChanged(location);
}
}
});
}
/**
* Notifies that the current heading has changed.
*
* @param listeners the listeners to notify
*/
private void notifyHeadingChanged(final Set<TrackDataListener> listeners) {
if (listeners.isEmpty()) return;
runInListenerThread(new Runnable() {
@Override
public void run() {
float heading = lastSeenMagneticHeading + declination;
for (TrackDataListener listener : listeners) {
listener.onCurrentHeadingChanged(heading);
}
}
});
}
/**
* Notifies that a new track has been selected..
*
* @param track the new selected track
* @param listeners the listeners to notify
*/
private void notifySelectedTrackChanged(long trackId,
final Set<TrackDataListener> listeners) {
if (listeners.isEmpty()) return;
Log.i(TAG, "New track selected, id=" + trackId);
final Track track = providerUtils.getTrack(trackId);
runInListenerThread(new Runnable() {
@Override
public void run() {
for (TrackDataListener listener : listeners) {
listener.onSelectedTrackChanged(track, isRecordingSelected());
if (track != null) {
listener.onTrackUpdated(track);
}
}
}
});
}
/**
* Notifies that the currently-selected track's data has been updated.
*
* @param listeners the listeners to notify
*/
private void notifyTrackUpdated(final Set<TrackDataListener> listeners) {
if (listeners.isEmpty()) return;
final Track track = providerUtils.getTrack(selectedTrackId);
runInListenerThread(new Runnable() {
@Override
public void run() {
for (TrackDataListener listener : listeners) {
listener.onTrackUpdated(track);
}
}
});
}
/**
* Notifies that waypoints have been updated.
* We assume few waypoints, so we reload them all every time.
*
* @param listeners the listeners to notify
*/
private void notifyWaypointUpdated(final Set<TrackDataListener> listeners) {
if (listeners.isEmpty()) return;
// Always reload all the waypoints.
final Cursor cursor = providerUtils.getWaypointsCursor(
selectedTrackId, 0L, Constants.MAX_DISPLAYED_WAYPOINTS_POINTS);
runInListenerThread(new Runnable() {
@Override
public void run() {
Log.d(TAG, "Reloading waypoints");
for (TrackDataListener listener : listeners) {
listener.clearWaypoints();
}
try {
if (cursor != null && cursor.moveToFirst()) {
do {
Waypoint waypoint = providerUtils.createWaypoint(cursor);
if (!LocationUtils.isValidLocation(waypoint.getLocation())) {
continue;
}
for (TrackDataListener listener : listeners) {
listener.onNewWaypoint(waypoint);
}
} while (cursor.moveToNext());
}
} finally {
if (cursor != null) {
cursor.close();
}
}
for (TrackDataListener listener : listeners) {
listener.onNewWaypointsDone();
}
}
});
}
/**
* Tells listeners to clear the current list of points.
*
* @param listeners the listeners to notify
*/
private void notifyPointsCleared(final Set<TrackDataListener> listeners) {
if (listeners.isEmpty()) return;
runInListenerThread(new Runnable() {
@Override
public void run() {
for (TrackDataListener listener : listeners) {
listener.clearTrackPoints();
}
}
});
}
/**
* Notifies the given listeners about track points in the given ID range.
*
* @param keepState whether to load and save state about the already-notified points.
* If true, only new points are reported.
* If false, then the whole track will be loaded, without affecting the store.
* @param minPointId the first point ID to notify, inclusive
*/
private void notifyPointsUpdated(final boolean keepState,
final long minPointId, final Set<TrackDataListener> sampledListeners,
final Set<TrackDataListener> sampledOutListeners) {
if (sampledListeners.isEmpty() && sampledOutListeners.isEmpty()) return;
runInListenerThread(new Runnable() {
@Override
public void run() {
notifyPointsUpdatedSync(keepState, minPointId, sampledListeners, sampledOutListeners);
}
});
}
/**
* Asynchronous version of the above method.
*/
private void notifyPointsUpdatedSync(boolean keepState,
long minPointId, Set<TrackDataListener> sampledListeners,
Set<TrackDataListener> sampledOutListeners) {
// If we're loading state, start from after the last seen point up to the last recorded one
// (all new points)
// If we're not loading state, then notify about all the previously-seen points.
if (minPointId <= 0) {
minPointId = keepState ? lastSeenLocationId + 1 : 0;
}
long maxPointId = keepState ? -1 : lastSeenLocationId;
// TODO: Move (re)sampling to a separate class.
if (numLoadedPoints >= Constants.MAX_DISPLAYED_TRACK_POINTS) {
// We're about to exceed the maximum allowed number of points, so reload
// the whole track with fewer points (the sampling frequency will be
// lower). We do this for every listener even if we were loading just for
// a few of them (why miss the oportunity?).
Log.i(TAG, "Resampling point set after " + numLoadedPoints + " points.");
firstSeenLocationId = -1;
lastSeenLocationId = -1;
numLoadedPoints = 0;
synchronized (listeners) {
sampledListeners = getListenersFor(ListenerDataType.POINT_UPDATES);
sampledOutListeners = getListenersFor(ListenerDataType.SAMPLED_OUT_POINT_UPDATES);
}
maxPointId = -1;
minPointId = 0;
keepState = true;
for (TrackDataListener listener : sampledListeners) {
listener.clearTrackPoints();
}
}
// Keep the originally selected track ID so we can stop if it changes.
long currentSelectedTrackId = selectedTrackId;
// If we're ignoring state, start from the beginning of the track
int localNumLoadedPoints = keepState ? numLoadedPoints : 0;
long localFirstSeenLocationId = keepState ? firstSeenLocationId : 0;
long localLastSeenLocationId = minPointId;
long lastStoredLocationId = providerUtils.getLastLocationId(currentSelectedTrackId);
int pointSamplingFrequency = -1;
// Create a double-buffering location provider.
MyTracksProviderUtils.DoubleBufferedLocationFactory locationFactory =
new MyTracksProviderUtils.DoubleBufferedLocationFactory();
LocationIterator it = providerUtils.getLocationIterator(
currentSelectedTrackId, minPointId, false, locationFactory);
while (it.hasNext()) {
if (currentSelectedTrackId != selectedTrackId) {
// The selected track changed beneath us, stop.
break;
}
Location location = it.next();
long locationId = it.getLocationId();
// If past the last wanted point, stop.
// This happens when adding a new listener after data has already been loaded,
// in which case we only want to bring that listener up to the point where the others
// were. In case it does happen, we should be wasting few points (only the ones not
// yet notified to other listeners).
if (maxPointId > 0 && locationId > maxPointId) {
break;
}
if (localFirstSeenLocationId == -1) {
// This was our first point, keep its ID
localFirstSeenLocationId = locationId;
}
if (pointSamplingFrequency == -1) {
// Now we already have at least one point, calculate the sampling
// frequency.
long numTotalPoints = lastStoredLocationId - localFirstSeenLocationId;
pointSamplingFrequency =
(int) (1 + numTotalPoints / Constants.TARGET_DISPLAYED_TRACK_POINTS);
}
notifyNewPoint(location, locationId, lastStoredLocationId,
localNumLoadedPoints, pointSamplingFrequency, sampledListeners, sampledOutListeners);
localNumLoadedPoints++;
localLastSeenLocationId = locationId;
}
it.close();
if (keepState) {
numLoadedPoints = localNumLoadedPoints;
firstSeenLocationId = localFirstSeenLocationId;
lastSeenLocationId = localLastSeenLocationId;
}
// Always keep the sampling frequency - if it changes we'll do a full reload above anyway.
lastSamplingFrequency = pointSamplingFrequency;
// Update the listener state
// TODO: Optimize this (sampledOutListeners should be a subset of sampledListeners, plus
// getRegistration does a lookup for every listener, and this is in the critical path).
updateListenersState(sampledListeners,
currentSelectedTrackId, localLastSeenLocationId, pointSamplingFrequency);
updateListenersState(sampledOutListeners,
currentSelectedTrackId, localLastSeenLocationId, pointSamplingFrequency);
for (TrackDataListener listener : sampledListeners) {
listener.onNewTrackPointsDone();
}
}
private void updateListenersState(Set<TrackDataListener> sampledListeners,
long trackId, long lastPointId, int samplingFrequency) {
synchronized (listeners) {
for (TrackDataListener listener : sampledListeners) {
ListenerRegistration registration = listeners.getRegistration(listener);
if (registration != null) {
registration.lastTrackId = trackId;
registration.lastPointId = lastPointId;
registration.lastSamplingFrequency = samplingFrequency;
}
}
}
}
private void notifyNewPoint(Location location,
long locationId,
long lastStoredLocationId,
int numLoadedPoints,
int pointSamplingFrequency,
Set<TrackDataListener> sampledListeners,
Set<TrackDataListener> sampledOutListeners) {
boolean isValid = LocationUtils.isValidLocation(location);
if (!isValid) {
// Invalid points are segment splits - report those separately.
// TODO: Always send last valid point before and first valid point after a split
for (TrackDataListener listener : sampledListeners) {
listener.onSegmentSplit();
}
return;
}
// Include a point if it fits one of the following criteria:
// - Has the mod for the sampling frequency (includes first point).
// - Is the last point and we are not recording this track.
boolean includeInSample =
(numLoadedPoints % pointSamplingFrequency == 0 ||
(!isRecordingSelected() && locationId == lastStoredLocationId));
if (!includeInSample) {
for (TrackDataListener listener : sampledOutListeners) {
listener.onSampledOutTrackPoint(location);
}
return;
}
// Point is valid and included in sample.
for (TrackDataListener listener : sampledListeners) {
// No need to allocate a new location (we can safely reuse the existing).
listener.onNewTrackPoint(location);
}
}
// @VisibleForTesting
protected void runInListenerThread(Runnable runnable) {
listenerHandler.post(runnable);
}
private Set<TrackDataListener> getListenersFor(ListenerDataType type) {
synchronized (listeners) {
return listeners.getListenersFor(type);
}
}
private EnumSet<ListenerDataType> getNeededListenerTypes() {
EnumSet<ListenerDataType> neededTypes = listeners.getAllRegisteredTypes();
// We always want preference updates.
neededTypes.add(ListenerDataType.DISPLAY_PREFERENCES);
return neededTypes;
}
}
|
Assuming that we have a GPS provider until we're told otherwise
(this avoid a startup toast saying we have no GPS).
|
MyTracks/src/com/google/android/apps/mytracks/content/TrackDataHub.java
|
Assuming that we have a GPS provider until we're told otherwise (this avoid a startup toast saying we have no GPS).
|
|
Java
|
apache-2.0
|
34b85b4177c5cf063a087386dd82ab59e079bef0
| 0
|
ronsigal/xerces,RackerWilliams/xercesj,jimma/xerces,jimma/xerces,ronsigal/xerces,ronsigal/xerces,RackerWilliams/xercesj,jimma/xerces,RackerWilliams/xercesj
|
/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.apache.org. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.xerces.dom;
import java.io.*;
import java.util.Enumeration;
import java.util.Vector;
import org.w3c.dom.*;
/**
* Elements represent most of the "markup" and structure of the
* document. They contain both the data for the element itself
* (element name and attributes), and any contained nodes, including
* document text (as children).
* <P>
* Elements may have Attributes associated with them; the API for this is
* defined in Node, but the function is implemented here. In general, XML
* applications should retrive Attributes as Nodes, since they may contain
* entity references and hence be a fairly complex sub-tree. HTML users will
* be dealing with simple string values, and convenience methods are provided
* to work in terms of Strings.
* <P>
* ElementImpl does not support Namespaces. ElementNSImpl, which inherits from
* it, does.
* @see ElementNSImpl
*
* @version
* @since PR-DOM-Level-1-19980818.
*/
public class ElementImpl
extends ChildAndParentNode
implements Element {
//
// Constants
//
/** Serialization version. */
static final long serialVersionUID = 3717253516652722278L;
//
// Data
//
/** Element name. */
protected String name;
/** Attributes. */
protected AttributeMap attributes;
//
// Constructors
//
/** Factory constructor. */
public ElementImpl(DocumentImpl ownerDoc, String name) {
super(ownerDoc);
this.name = name;
needsSyncData(true); // synchronizeData will initialize attributes
}
// for ElementNSImpl
protected ElementImpl() {}
//
// Node methods
//
/**
* A short integer indicating what type of node this is. The named
* constants for this value are defined in the org.w3c.dom.Node interface.
*/
public short getNodeType() {
return Node.ELEMENT_NODE;
}
/**
* Returns the element name
*/
public String getNodeName() {
if (needsSyncData()) {
synchronizeData();
}
return name;
}
/**
* Retrieve all the Attributes as a set. Note that this API is inherited
* from Node rather than specified on Element; in fact only Elements will
* ever have Attributes, but they want to allow folks to "blindly" operate
* on the tree as a set of Nodes.
*/
public NamedNodeMap getAttributes() {
if (needsSyncData()) {
synchronizeData();
}
if (attributes == null) {
attributes = new AttributeMap(this, null);
}
return attributes;
} // getAttributes():NamedNodeMap
/**
* Return a duplicate copy of this Element. Note that its children
* will not be copied unless the "deep" flag is true, but Attributes
* are <i>always</i> replicated.
*
* @see org.w3c.dom.Node#cloneNode(boolean)
*/
public Node cloneNode(boolean deep) {
if (needsSyncData()) {
synchronizeData();
}
ElementImpl newnode = (ElementImpl) super.cloneNode(deep);
// Replicate NamedNodeMap rather than sharing it.
if (attributes != null) {
newnode.attributes = (AttributeMap) attributes.cloneMap(newnode);
}
return newnode;
} // cloneNode(boolean):Node
/**
* NON-DOM
* set the ownerDocument of this node, its children, and its attributes
*/
void setOwnerDocument(DocumentImpl doc) {
super.setOwnerDocument(doc);
if (attributes != null) {
attributes.setOwnerDocument(doc);
}
}
//
// Element methods
//
/**
* Look up a single Attribute by name. Returns the Attribute's
* string value, or an empty string (NOT null!) to indicate that the
* name did not map to a currently defined attribute.
* <p>
* Note: Attributes may contain complex node trees. This method
* returns the "flattened" string obtained from Attribute.getValue().
* If you need the structure information, see getAttributeNode().
*/
public String getAttribute(String name) {
if (needsSyncData()) {
synchronizeData();
}
if (attributes == null) {
return "";
}
Attr attr = (Attr)(attributes.getNamedItem(name));
return (attr == null) ? "" : attr.getValue();
} // getAttribute(String):String
/**
* Look up a single Attribute by name. Returns the Attribute Node,
* so its complete child tree is available. This could be important in
* XML, where the string rendering may not be sufficient information.
* <p>
* If no matching attribute is available, returns null.
*/
public Attr getAttributeNode(String name) {
if (needsSyncData()) {
synchronizeData();
}
if (attributes == null) {
return null;
}
return (Attr)attributes.getNamedItem(name);
} // getAttributeNode(String):Attr
/**
* Returns a NodeList of all descendent nodes (children,
* grandchildren, and so on) which are Elements and which have the
* specified tag name.
* <p>
* Note: NodeList is a "live" view of the DOM. Its contents will
* change as the DOM changes, and alterations made to the NodeList
* will be reflected in the DOM.
*
* @param tagname The type of element to gather. To obtain a list of
* all elements no matter what their names, use the wild-card tag
* name "*".
*
* @see DeepNodeListImpl
*/
public NodeList getElementsByTagName(String tagname) {
return new DeepNodeListImpl(this,tagname);
}
/**
* Returns the name of the Element. Note that Element.nodeName() is
* defined to also return the tag name.
* <p>
* This is case-preserving in XML. HTML should uppercasify it on the
* way in.
*/
public String getTagName() {
if (needsSyncData()) {
synchronizeData();
}
return name;
}
/**
* In "normal form" (as read from a source file), there will never be two
* Text children in succession. But DOM users may create successive Text
* nodes in the course of manipulating the document. Normalize walks the
* sub-tree and merges adjacent Texts, as if the DOM had been written out
* and read back in again. This simplifies implementation of higher-level
* functions that may want to assume that the document is in standard form.
* <p>
* To normalize a Document, normalize its top-level Element child.
* <p>
* As of PR-DOM-Level-1-19980818, CDATA -- despite being a subclass of
* Text -- is considered "markup" and will _not_ be merged either with
* normal Text or with other CDATASections.
*/
public void normalize() {
Node kid, next;
for (kid = getFirstChild(); kid != null; kid = next) {
next = kid.getNextSibling();
// If kid and next are both Text nodes (but _not_ CDATASection,
// which is a subclass of Text), they can be merged.
if (next != null
&& kid.getNodeType() == Node.TEXT_NODE
&& next.getNodeType() == Node.TEXT_NODE)
{
((Text)kid).appendData(next.getNodeValue());
removeChild(next);
next = kid; // Don't advance; there might be another.
}
// Otherwise it might be an Element, which is handled recursively
else if (kid.getNodeType() == Node.ELEMENT_NODE) {
((Element)kid).normalize();
}
}
// changed() will have occurred when the removeChild() was done,
// so does not have to be reissued.
} // normalize()
/**
* Remove the named attribute from this Element. If the removed
* Attribute has a default value, it is immediately replaced thereby.
* <P>
* The default logic is actually implemented in NamedNodeMapImpl.
* PR-DOM-Level-1-19980818 doesn't fully address the DTD, so some
* of this behavior is likely to change in future versions. ?????
* <P>
* Note that this call "succeeds" even if no attribute by this name
* existed -- unlike removeAttributeNode, which will throw a not-found
* exception in that case.
*
* @throws DOMException(NO_MODIFICATION_ALLOWED_ERR) if the node is
* readonly.
*/
public void removeAttribute(String name) {
if (isReadOnly()) {
throw new DOMExceptionImpl(
DOMException.NO_MODIFICATION_ALLOWED_ERR,
"DOM001 Modification not allowed");
}
if (needsSyncData()) {
synchronizeData();
}
if (attributes == null) {
return;
}
attributes.safeRemoveNamedItem(name);
} // removeAttribute(String)
/**
* Remove the specified attribute/value pair. If the removed
* Attribute has a default value, it is immediately replaced.
* <p>
* NOTE: Specifically removes THIS NODE -- not the node with this
* name, nor the node with these contents. If the specific Attribute
* object passed in is not stored in this Element, we throw a
* DOMException. If you really want to remove an attribute by name,
* use removeAttribute().
*
* @return the Attribute object that was removed.
* @throws DOMException(NOT_FOUND_ERR) if oldattr is not an attribute of
* this Element.
* @throws DOMException(NO_MODIFICATION_ALLOWED_ERR) if the node is
* readonly.
*/
public Attr removeAttributeNode(Attr oldAttr)
throws DOMException
{
if (isReadOnly()) {
throw new DOMExceptionImpl(
DOMException.NO_MODIFICATION_ALLOWED_ERR,
"DOM001 Modification not allowed");
}
if (needsSyncData()) {
synchronizeData();
}
if (attributes == null) {
throw new DOMExceptionImpl(DOMException.NOT_FOUND_ERR,
"DOM008 Not found");
}
return (Attr) attributes.removeNamedItem(oldAttr.getName());
} // removeAttributeNode(Attr):Attr
/**
* Add a new name/value pair, or replace the value of the existing
* attribute having that name.
*
* Note: this method supports only the simplest kind of Attribute,
* one whose value is a string contained in a single Text node.
* If you want to assert a more complex value (which XML permits,
* though HTML doesn't), see setAttributeNode().
*
* The attribute is created with specified=true, meaning it's an
* explicit value rather than inherited from the DTD as a default.
* Again, setAttributeNode can be used to achieve other results.
*
* @throws DOMException(INVALID_NAME_ERR) if the name is not acceptable.
* (Attribute factory will do that test for us.)
*
* @throws DOMException(NO_MODIFICATION_ALLOWED_ERR) if the node is
* readonly.
*/
public void setAttribute(String name, String value) {
if (isReadOnly()) {
throw new DOMExceptionImpl(
DOMException.NO_MODIFICATION_ALLOWED_ERR,
"DOM001 Modification not allowed");
}
if (needsSyncData()) {
synchronizeData();
}
Attr newAttr = getAttributeNode(name);
if (newAttr == null) {
newAttr = getOwnerDocument().createAttribute(name);
if (attributes == null) {
attributes = new AttributeMap(this, null);
}
attributes.setNamedItem(newAttr);
}
newAttr.setNodeValue(value);
} // setAttribute(String,String)
/**
* Add a new attribute/value pair, or replace the value of the
* existing attribute with that name.
* <P>
* This method allows you to add an Attribute that has already been
* constructed, and hence avoids the limitations of the simple
* setAttribute() call. It can handle attribute values that have
* arbitrarily complex tree structure -- in particular, those which
* had entity references mixed into their text.
*
* @throws DOMException(INUSE_ATTRIBUTE_ERR) if the Attribute object
* has already been assigned to another Element.
*/
public Attr setAttributeNode(Attr newAttr)
throws DOMException
{
if (isReadOnly()) {
throw new DOMExceptionImpl(
DOMException.NO_MODIFICATION_ALLOWED_ERR,
"DOM001 Modification not allowed");
}
if (needsSyncData()) {
synchronizeData();
}
if (ownerDocument.errorChecking
&& newAttr.getOwnerDocument() != ownerDocument) {
throw new DOMExceptionImpl(DOMException.WRONG_DOCUMENT_ERR,
"DOM005 Wrong document");
}
if (attributes == null) {
attributes = new AttributeMap(this, null);
}
// This will throw INUSE if necessary
return (Attr) attributes.setNamedItem(newAttr);
} // setAttributeNode(Attr):Attr
//
// DOM2: Namespace methods
//
/**
* Introduced in DOM Level 2. <p>
*
* Retrieves an attribute value by local name and namespace URI.
*
* @param namespaceURI
* The namespace URI of the attribute to
* retrieve.
* @param localName The local name of the attribute to retrieve.
* @return String The Attr value as a string, or null
* if that attribute
* does not have a specified or default value.
* @since WD-DOM-Level-2-19990923
*/
public String getAttributeNS(String namespaceURI, String localName) {
if (needsSyncData()) {
synchronizeData();
}
if (attributes == null) {
return "";
}
Attr attr = (Attr)(attributes.getNamedItemNS(namespaceURI, localName));
return (attr == null) ? null : attr.getValue();
} // getAttributeNS(String,String):String
/**
* Introduced in DOM Level 2. <p>
*
* Adds a new attribute.
* If the given namespaceURI is null or an empty string and
* the qualifiedName has a prefix that is "xml", the new attribute is bound to the
* predefined namespace "http://www.w3.org/XML/1998/namespace" [Namespaces].
* If an attribute with the same local name and namespace URI is already present on
* the element, its prefix is changed to be the prefix part of the qualifiedName, and
* its value is changed to be the value parameter. This value is a simple string, it is not
* parsed as it is being set. So any markup (such as syntax to be recognized as an
* entity reference) is treated as literal text, and needs to be appropriately escaped by
* the implementation when it is written out. In order to assign an attribute value that
* contains entity references, the user must create an Attr node plus any Text and
* EntityReference nodes, build the appropriate subtree, and use
* setAttributeNodeNS or setAttributeNode to assign it as the value of an
* attribute.
* @param namespaceURI
* The namespace URI of the attribute to create
* or alter.
* @param localName The local name of the attribute to create or
* alter.
* @param value The value to set in string form.
* @throws INVALID_CHARACTER_ERR: Raised if the specified
* name contains an invalid character.
*
* @throws NO_MODIFICATION_ALLOWED_ERR: Raised if this
* node is readonly.
*
* @throws NAMESPACE_ERR: Raised if the qualifiedName
* has a prefix that is "xml" and the namespaceURI is
* neither null nor an empty string nor
* "http://www.w3.org/XML/1998/namespace", or if the
* qualifiedName has a prefix that is "xmlns" but the
* namespaceURI is neither null nor an empty string, or
* if if the qualifiedName has a prefix different from
* "xml" and "xmlns" and the namespaceURI is null or an
* empty string.
* @since WD-DOM-Level-2-19990923
*/
public void setAttributeNS(String namespaceURI, String localName, String value) {
if (isReadOnly()) {
throw new DOMExceptionImpl(
DOMException.NO_MODIFICATION_ALLOWED_ERR,
"DOM001 Modification not allowed");
}
if (needsSyncData()) {
synchronizeData();
}
Attr newAttr = getAttributeNodeNS(namespaceURI, localName);
if (newAttr == null) {
newAttr =
getOwnerDocument().createAttributeNS(namespaceURI, localName);
if (attributes == null) {
attributes = new AttributeMap(this, null);
}
attributes.setNamedItemNS(newAttr);
}
newAttr.setNodeValue(value);
} // setAttributeNS(String,String,String)
/**
* Introduced in DOM Level 2. <p>
*
* Removes an attribute by local name and namespace URI. If the removed
* attribute has a default value it is immediately replaced.
* The replacing attribute has the same namespace URI and local name,
* as well as the original prefix.<p>
*
* @param namespaceURI The namespace URI of the attribute to remove.
*
* @param localName The local name of the attribute to remove.
* @throws NO_MODIFICATION_ALLOWED_ERR: Raised if this
* node is readonly.
* @since WD-DOM-Level-2-19990923
*/
public void removeAttributeNS(String namespaceURI, String localName) {
if (isReadOnly()) {
throw new DOMExceptionImpl(
DOMException.NO_MODIFICATION_ALLOWED_ERR,
"DOM001 Modification not allowed");
}
if (needsSyncData()) {
synchronizeData();
}
if (attributes == null) {
return;
}
attributes.safeRemoveNamedItemNS(namespaceURI, localName);
} // removeAttributeNS(String,String)
/**
* Retrieves an Attr node by local name and namespace URI.
*
* @param namespaceURI The namespace URI of the attribute to
* retrieve.
* @param localName The local name of the attribute to retrieve.
* @return Attr The Attr node with the specified attribute
* local name and namespace
* URI or null if there is no such attribute.
* @since WD-DOM-Level-2-19990923
*/
public Attr getAttributeNodeNS(String namespaceURI, String localName){
if (needsSyncData()) {
synchronizeData();
}
if (attributes == null) {
return null;
}
return (Attr)attributes.getNamedItemNS(namespaceURI, localName);
} // getAttributeNodeNS(String,String):Attr
/**
* Introduced in DOM Level 2. <p>
*
* Adds a new attribute. If an attribute with that local name and
* namespace URI is already present in the element, it is replaced
* by the new one.
*
* @param Attr The Attr node to add to the attribute list. When
* the Node has no namespaceURI, this method behaves
* like setAttributeNode.
* @return Attr If the newAttr attribute replaces an existing attribute with the same
* local name and namespace URI, the previously existing Attr node is
* returned, otherwise null is returned.
* @throws WRONG_DOCUMENT_ERR: Raised if newAttr
* was created from a different document than the one that
* created the element.
*
* @throws NO_MODIFICATION_ALLOWED_ERR: Raised if
* this node is readonly.
*
* @throws INUSE_ATTRIBUTE_ERR: Raised if newAttr is
* already an attribute of another Element object. The
* DOM user must explicitly clone Attr nodes to re-use
* them in other elements.
* @since WD-DOM-Level-2-19990923
*/
public Attr setAttributeNodeNS(Attr newAttr)
throws DOMException
{
if (isReadOnly()) {
throw new DOMExceptionImpl(
DOMException.NO_MODIFICATION_ALLOWED_ERR,
"DOM001 Modification not allowed");
}
if (needsSyncData()) {
synchronizeData();
}
if (ownerDocument.errorChecking
&& newAttr.getOwnerDocument() != ownerDocument) {
throw new DOMExceptionImpl(DOMException.WRONG_DOCUMENT_ERR,
"DOM005 Wrong document");
}
if (attributes == null) {
attributes = new AttributeMap(this, null);
}
// This will throw INUSE if necessary
return (Attr) attributes.setNamedItemNS(newAttr);
} // setAttributeNodeNS(Attr):Attr
/**
* Introduced in DOM Level 2.
*/
public boolean hasAttributes() {
if (needsSyncData()) {
synchronizeData();
}
return (attributes != null && attributes.getLength() != 0);
}
/**
* Introduced in DOM Level 2.
*/
public boolean hasAttribute(String name) {
return getAttributeNode(name) != null;
}
/**
* Introduced in DOM Level 2.
*/
public boolean hasAttributeNS(String namespaceURI, String localName) {
return getAttributeNodeNS(namespaceURI, localName) != null;
}
/**
* Introduced in DOM Level 2. <p>
*
* Returns a NodeList of all the Elements with a given local name and
* namespace URI in the order in which they would be encountered in a preorder
* traversal of the Document tree, starting from this node.
*
* @param namespaceURI The namespace URI of the elements to match
* on. The special value "*" matches all
* namespaces. When it is null or an empty
* string, this method behaves like
* getElementsByTagName.
* @param localName The local name of the elements to match on.
* The special value "*" matches all local names.
* @return NodeList A new NodeList object containing all the matched Elements.
* @since WD-DOM-Level-2-19990923
*/
public NodeList getElementsByTagNameNS(String namespaceURI, String localName) {
return new DeepNodeListImpl(this, namespaceURI, localName);
}
//
// Public methods
//
/**
* NON-DOM: Subclassed to flip the attributes' readonly switch as well.
* @see NodeImpl#setReadOnly
*/
public void setReadOnly(boolean readOnly, boolean deep) {
super.setReadOnly(readOnly,deep);
if (attributes != null) {
attributes.setReadOnly(readOnly,true);
}
}
//
// Protected methods
//
/** Synchronizes the data (name and value) for fast nodes. */
protected void synchronizeData() {
// no need to sync in the future
needsSyncData(false);
// attributes
setupDefaultAttributes();
} // synchronizeData()
/** Setup the default attributes. */
protected void setupDefaultAttributes() {
NamedNodeMapImpl defaults = getDefaultAttributes();
if (defaults != null) {
attributes = new AttributeMap(this, defaults);
}
}
/** Get the default attributes. */
protected NamedNodeMapImpl getDefaultAttributes() {
DocumentTypeImpl doctype =
(DocumentTypeImpl) ownerDocument.getDoctype();
if (doctype == null) {
return null;
}
ElementDefinitionImpl eldef =
(ElementDefinitionImpl)doctype.getElements()
.getNamedItem(getNodeName());
if (eldef == null) {
return null;
}
return (NamedNodeMapImpl) eldef.getAttributes();
} // setupAttributes(DocumentImpl)
} // class ElementImpl
|
src/org/apache/xerces/dom/ElementImpl.java
|
/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.apache.org. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.xerces.dom;
import java.io.*;
import java.util.Enumeration;
import java.util.Vector;
import org.w3c.dom.*;
/**
* Elements represent most of the "markup" and structure of the
* document. They contain both the data for the element itself
* (element name and attributes), and any contained nodes, including
* document text (as children).
* <P>
* Elements may have Attributes associated with them; the API for this is
* defined in Node, but the function is implemented here. In general, XML
* applications should retrive Attributes as Nodes, since they may contain
* entity references and hence be a fairly complex sub-tree. HTML users will
* be dealing with simple string values, and convenience methods are provided
* to work in terms of Strings.
* <P>
* ElementImpl does not support Namespaces. ElementNSImpl, which inherits from
* it, does.
* @see ElementNSImpl
*
* @version
* @since PR-DOM-Level-1-19980818.
*/
public class ElementImpl
extends ChildAndParentNode
implements Element {
//
// Constants
//
/** Serialization version. */
static final long serialVersionUID = 3717253516652722278L;
//
// Data
//
/** Element name. */
protected String name;
/** Attributes. */
protected AttributeMap attributes;
//
// Constructors
//
/** Factory constructor. */
public ElementImpl(DocumentImpl ownerDoc, String name) {
super(ownerDoc);
this.name = name;
needsSyncData(true); // synchronizeData will initialize attributes
}
// for ElementNSImpl
protected ElementImpl() {}
//
// Node methods
//
/**
* A short integer indicating what type of node this is. The named
* constants for this value are defined in the org.w3c.dom.Node interface.
*/
public short getNodeType() {
return Node.ELEMENT_NODE;
}
/**
* Returns the element name
*/
public String getNodeName() {
if (needsSyncData()) {
synchronizeData();
}
return name;
}
/**
* Retrieve all the Attributes as a set. Note that this API is inherited
* from Node rather than specified on Element; in fact only Elements will
* ever have Attributes, but they want to allow folks to "blindly" operate
* on the tree as a set of Nodes.
*/
public NamedNodeMap getAttributes() {
if (needsSyncData()) {
synchronizeData();
}
if (attributes == null) {
attributes = new AttributeMap(this, null);
}
return attributes;
} // getAttributes():NamedNodeMap
/**
* Return a duplicate copy of this Element. Note that its children
* will not be copied unless the "deep" flag is true, but Attributes
* are <i>always</i> replicated.
*
* @see org.w3c.dom.Node#cloneNode(boolean)
*/
public Node cloneNode(boolean deep) {
if (needsSyncData()) {
synchronizeData();
}
ElementImpl newnode = (ElementImpl) super.cloneNode(deep);
// Replicate NamedNodeMap rather than sharing it.
if (attributes != null) {
newnode.attributes = (AttributeMap) attributes.cloneMap(newnode);
}
return newnode;
} // cloneNode(boolean):Node
/**
* NON-DOM
* set the ownerDocument of this node, its children, and its attributes
*/
void setOwnerDocument(DocumentImpl doc) {
super.setOwnerDocument(doc);
if (attributes != null) {
attributes.setOwnerDocument(doc);
}
}
//
// Element methods
//
/**
* Look up a single Attribute by name. Returns the Attribute's
* string value, or an empty string (NOT null!) to indicate that the
* name did not map to a currently defined attribute.
* <p>
* Note: Attributes may contain complex node trees. This method
* returns the "flattened" string obtained from Attribute.getValue().
* If you need the structure information, see getAttributeNode().
*/
public String getAttribute(String name) {
if (needsSyncData()) {
synchronizeData();
}
if (attributes == null) {
return "";
}
Attr attr = (Attr)(attributes.getNamedItem(name));
return (attr == null) ? "" : attr.getValue();
} // getAttribute(String):String
/**
* Look up a single Attribute by name. Returns the Attribute Node,
* so its complete child tree is available. This could be important in
* XML, where the string rendering may not be sufficient information.
* <p>
* If no matching attribute is available, returns null.
*/
public Attr getAttributeNode(String name) {
if (needsSyncData()) {
synchronizeData();
}
if (attributes == null) {
return null;
}
return (Attr)attributes.getNamedItem(name);
} // getAttributeNode(String):Attr
/**
* Returns a NodeList of all descendent nodes (children,
* grandchildren, and so on) which are Elements and which have the
* specified tag name.
* <p>
* Note: NodeList is a "live" view of the DOM. Its contents will
* change as the DOM changes, and alterations made to the NodeList
* will be reflected in the DOM.
*
* @param tagname The type of element to gather. To obtain a list of
* all elements no matter what their names, use the wild-card tag
* name "*".
*
* @see DeepNodeListImpl
*/
public NodeList getElementsByTagName(String tagname) {
return new DeepNodeListImpl(this,tagname);
}
/**
* Returns the name of the Element. Note that Element.nodeName() is
* defined to also return the tag name.
* <p>
* This is case-preserving in XML. HTML should uppercasify it on the
* way in.
*/
public String getTagName() {
if (needsSyncData()) {
synchronizeData();
}
return name;
}
/**
* In "normal form" (as read from a source file), there will never be two
* Text children in succession. But DOM users may create successive Text
* nodes in the course of manipulating the document. Normalize walks the
* sub-tree and merges adjacent Texts, as if the DOM had been written out
* and read back in again. This simplifies implementation of higher-level
* functions that may want to assume that the document is in standard form.
* <p>
* To normalize a Document, normalize its top-level Element child.
* <p>
* As of PR-DOM-Level-1-19980818, CDATA -- despite being a subclass of
* Text -- is considered "markup" and will _not_ be merged either with
* normal Text or with other CDATASections.
*/
public void normalize() {
Node kid, next;
for (kid = getFirstChild(); kid != null; kid = next) {
next = kid.getNextSibling();
// If kid and next are both Text nodes (but _not_ CDATASection,
// which is a subclass of Text), they can be merged.
if (next != null
&& kid.getNodeType() == Node.TEXT_NODE
&& next.getNodeType() == Node.TEXT_NODE)
{
((Text)kid).appendData(next.getNodeValue());
removeChild(next);
next = kid; // Don't advance; there might be another.
}
// Otherwise it might be an Element, which is handled recursively
else if (kid.getNodeType() == Node.ELEMENT_NODE) {
((Element)kid).normalize();
}
}
// changed() will have occurred when the removeChild() was done,
// so does not have to be reissued.
} // normalize()
/**
* Remove the named attribute from this Element. If the removed
* Attribute has a default value, it is immediately replaced thereby.
* <P>
* The default logic is actually implemented in NamedNodeMapImpl.
* PR-DOM-Level-1-19980818 doesn't fully address the DTD, so some
* of this behavior is likely to change in future versions. ?????
* <P>
* Note that this call "succeeds" even if no attribute by this name
* existed -- unlike removeAttributeNode, which will throw a not-found
* exception in that case.
*
* @throws DOMException(NO_MODIFICATION_ALLOWED_ERR) if the node is
* readonly.
*/
public void removeAttribute(String name) {
if (isReadOnly()) {
throw new DOMExceptionImpl(
DOMException.NO_MODIFICATION_ALLOWED_ERR,
"DOM001 Modification not allowed");
}
if (needsSyncData()) {
synchronizeData();
}
if (attributes == null) {
return;
}
attributes.safeRemoveNamedItem(name);
} // removeAttribute(String)
/**
* Remove the specified attribute/value pair. If the removed
* Attribute has a default value, it is immediately replaced.
* <p>
* NOTE: Specifically removes THIS NODE -- not the node with this
* name, nor the node with these contents. If the specific Attribute
* object passed in is not stored in this Element, we throw a
* DOMException. If you really want to remove an attribute by name,
* use removeAttribute().
*
* @return the Attribute object that was removed.
* @throws DOMException(NOT_FOUND_ERR) if oldattr is not an attribute of
* this Element.
* @throws DOMException(NO_MODIFICATION_ALLOWED_ERR) if the node is
* readonly.
*/
public Attr removeAttributeNode(Attr oldAttr)
throws DOMException
{
if (isReadOnly()) {
throw new DOMExceptionImpl(
DOMException.NO_MODIFICATION_ALLOWED_ERR,
"DOM001 Modification not allowed");
}
if (needsSyncData()) {
synchronizeData();
}
if (attributes == null) {
throw new DOMExceptionImpl(DOMException.NOT_FOUND_ERR,
"DOM008 Not found");
}
return (Attr) attributes.removeNamedItem(oldAttr.getName());
} // removeAttributeNode(Attr):Attr
/**
* Add a new name/value pair, or replace the value of the existing
* attribute having that name.
*
* Note: this method supports only the simplest kind of Attribute,
* one whose value is a string contained in a single Text node.
* If you want to assert a more complex value (which XML permits,
* though HTML doesn't), see setAttributeNode().
*
* The attribute is created with specified=true, meaning it's an
* explicit value rather than inherited from the DTD as a default.
* Again, setAttributeNode can be used to achieve other results.
*
* @throws DOMException(INVALID_NAME_ERR) if the name is not acceptable.
* (Attribute factory will do that test for us.)
*
* @throws DOMException(NO_MODIFICATION_ALLOWED_ERR) if the node is
* readonly.
*/
public void setAttribute(String name, String value) {
if (isReadOnly()) {
throw new DOMExceptionImpl(
DOMException.NO_MODIFICATION_ALLOWED_ERR,
"DOM001 Modification not allowed");
}
if (needsSyncData()) {
synchronizeData();
}
Attr newAttr = getAttributeNode(name);
if (newAttr == null) {
newAttr = getOwnerDocument().createAttribute(name);
if (attributes == null) {
attributes = new AttributeMap(this, null);
}
attributes.setNamedItem(newAttr);
}
newAttr.setNodeValue(value);
} // setAttribute(String,String)
/**
* Add a new attribute/value pair, or replace the value of the
* existing attribute with that name.
* <P>
* This method allows you to add an Attribute that has already been
* constructed, and hence avoids the limitations of the simple
* setAttribute() call. It can handle attribute values that have
* arbitrarily complex tree structure -- in particular, those which
* had entity references mixed into their text.
*
* @throws DOMException(INUSE_ATTRIBUTE_ERR) if the Attribute object
* has already been assigned to another Element.
*/
public Attr setAttributeNode(Attr newAttr)
throws DOMException
{
if (isReadOnly()) {
throw new DOMExceptionImpl(
DOMException.NO_MODIFICATION_ALLOWED_ERR,
"DOM001 Modification not allowed");
}
if (needsSyncData()) {
synchronizeData();
}
if (ownerDocument.errorChecking
&& newAttr.getOwnerDocument() != ownerDocument) {
throw new DOMExceptionImpl(DOMException.WRONG_DOCUMENT_ERR,
"DOM005 Wrong document");
}
if (attributes == null) {
attributes = new AttributeMap(this, null);
}
// This will throw INUSE if necessary
return (Attr) attributes.setNamedItem(newAttr);
} // setAttributeNode(Attr):Attr
//
// DOM2: Namespace methods
//
/**
* Introduced in DOM Level 2. <p>
*
* Retrieves an attribute value by local name and namespace URI.
*
* @param namespaceURI
* The namespace URI of the attribute to
* retrieve.
* @param localName The local name of the attribute to retrieve.
* @return String The Attr value as a string, or null
* if that attribute
* does not have a specified or default value.
* @since WD-DOM-Level-2-19990923
*/
public String getAttributeNS(String namespaceURI, String localName) {
if (needsSyncData()) {
synchronizeData();
}
if (attributes == null) {
return "";
}
Attr attr = (Attr)(attributes.getNamedItemNS(namespaceURI, localName));
return (attr == null) ? null : attr.getValue();
} // getAttributeNS(String,String):String
/**
* Introduced in DOM Level 2. <p>
*
* Adds a new attribute.
* If the given namespaceURI is null or an empty string and
* the qualifiedName has a prefix that is "xml", the new attribute is bound to the
* predefined namespace "http://www.w3.org/XML/1998/namespace" [Namespaces].
* If an attribute with the same local name and namespace URI is already present on
* the element, its prefix is changed to be the prefix part of the qualifiedName, and
* its value is changed to be the value parameter. This value is a simple string, it is not
* parsed as it is being set. So any markup (such as syntax to be recognized as an
* entity reference) is treated as literal text, and needs to be appropriately escaped by
* the implementation when it is written out. In order to assign an attribute value that
* contains entity references, the user must create an Attr node plus any Text and
* EntityReference nodes, build the appropriate subtree, and use
* setAttributeNodeNS or setAttributeNode to assign it as the value of an
* attribute.
* @param namespaceURI
* The namespace URI of the attribute to create
* or alter.
* @param localName The local name of the attribute to create or
* alter.
* @param value The value to set in string form.
* @throws INVALID_CHARACTER_ERR: Raised if the specified
* name contains an invalid character.
*
* @throws NO_MODIFICATION_ALLOWED_ERR: Raised if this
* node is readonly.
*
* @throws NAMESPACE_ERR: Raised if the qualifiedName
* has a prefix that is "xml" and the namespaceURI is
* neither null nor an empty string nor
* "http://www.w3.org/XML/1998/namespace", or if the
* qualifiedName has a prefix that is "xmlns" but the
* namespaceURI is neither null nor an empty string, or
* if if the qualifiedName has a prefix different from
* "xml" and "xmlns" and the namespaceURI is null or an
* empty string.
* @since WD-DOM-Level-2-19990923
*/
public void setAttributeNS(String namespaceURI, String localName, String value) {
if (isReadOnly()) {
throw new DOMExceptionImpl(
DOMException.NO_MODIFICATION_ALLOWED_ERR,
"DOM001 Modification not allowed");
}
if (needsSyncData()) {
synchronizeData();
}
Attr newAttr = getAttributeNodeNS(namespaceURI, localName);
if (newAttr == null) {
newAttr =
getOwnerDocument().createAttributeNS(namespaceURI, localName);
if (attributes == null) {
attributes = new AttributeMap(this, null);
}
attributes.setNamedItemNS(newAttr);
}
newAttr.setNodeValue(value);
} // setAttributeNS(String,String,String)
/**
* Introduced in DOM Level 2. <p>
*
* Removes an attribute by local name and namespace URI. If the removed
* attribute has a default value it is immediately replaced.
* The replacing attribute has the same namespace URI and local name,
* as well as the original prefix.<p>
*
* @param namespaceURI The namespace URI of the attribute to remove.
*
* @param localName The local name of the attribute to remove.
* @throws NO_MODIFICATION_ALLOWED_ERR: Raised if this
* node is readonly.
* @since WD-DOM-Level-2-19990923
*/
public void removeAttributeNS(String namespaceURI, String localName) {
if (isReadOnly()) {
throw new DOMExceptionImpl(
DOMException.NO_MODIFICATION_ALLOWED_ERR,
"DOM001 Modification not allowed");
}
if (needsSyncData()) {
synchronizeData();
}
if (attributes == null) {
return;
}
attributes.safeRemoveNamedItemNS(namespaceURI, localName);
} // removeAttributeNS(String,String)
/**
* Retrieves an Attr node by local name and namespace URI.
*
* @param namespaceURI The namespace URI of the attribute to
* retrieve.
* @param localName The local name of the attribute to retrieve.
* @return Attr The Attr node with the specified attribute
* local name and namespace
* URI or null if there is no such attribute.
* @since WD-DOM-Level-2-19990923
*/
public Attr getAttributeNodeNS(String namespaceURI, String localName){
if (needsSyncData()) {
synchronizeData();
}
if (attributes == null) {
return null;
}
return (Attr)attributes.getNamedItemNS(namespaceURI, localName);
} // getAttributeNodeNS(String,String):Attr
/**
* Introduced in DOM Level 2. <p>
*
* Adds a new attribute. If an attribute with that local name and
* namespace URI is already present in the element, it is replaced
* by the new one.
*
* @param Attr The Attr node to add to the attribute list. When
* the Node has no namespaceURI, this method behaves
* like setAttributeNode.
* @return Attr If the newAttr attribute replaces an existing attribute with the same
* local name and namespace URI, the previously existing Attr node is
* returned, otherwise null is returned.
* @throws WRONG_DOCUMENT_ERR: Raised if newAttr
* was created from a different document than the one that
* created the element.
*
* @throws NO_MODIFICATION_ALLOWED_ERR: Raised if
* this node is readonly.
*
* @throws INUSE_ATTRIBUTE_ERR: Raised if newAttr is
* already an attribute of another Element object. The
* DOM user must explicitly clone Attr nodes to re-use
* them in other elements.
* @since WD-DOM-Level-2-19990923
*/
public Attr setAttributeNodeNS(Attr newAttr)
throws DOMException
{
if (isReadOnly()) {
throw new DOMExceptionImpl(
DOMException.NO_MODIFICATION_ALLOWED_ERR,
"DOM001 Modification not allowed");
}
if (needsSyncData()) {
synchronizeData();
}
if (ownerDocument.errorChecking
&& newAttr.getOwnerDocument() != ownerDocument) {
throw new DOMExceptionImpl(DOMException.WRONG_DOCUMENT_ERR,
"DOM005 Wrong document");
}
if (attributes == null) {
attributes = new AttributeMap(this, null);
}
// This will throw INUSE if necessary
return (Attr) attributes.setNamedItemNS(newAttr);
} // setAttributeNodeNS(Attr):Attr
/**
* Introduced in DOM Level 2.
*/
public boolean hasAttributes() {
return (attributes != null && attributes.getLength() != 0);
}
/**
* Introduced in DOM Level 2.
*/
public boolean hasAttribute(String name) {
return getAttributeNode(name) != null;
}
/**
* Introduced in DOM Level 2.
*/
public boolean hasAttributeNS(String namespaceURI, String localName) {
return getAttributeNodeNS(namespaceURI, localName) != null;
}
/**
* Introduced in DOM Level 2. <p>
*
* Returns a NodeList of all the Elements with a given local name and
* namespace URI in the order in which they would be encountered in a preorder
* traversal of the Document tree, starting from this node.
*
* @param namespaceURI The namespace URI of the elements to match
* on. The special value "*" matches all
* namespaces. When it is null or an empty
* string, this method behaves like
* getElementsByTagName.
* @param localName The local name of the elements to match on.
* The special value "*" matches all local names.
* @return NodeList A new NodeList object containing all the matched Elements.
* @since WD-DOM-Level-2-19990923
*/
public NodeList getElementsByTagNameNS(String namespaceURI, String localName) {
return new DeepNodeListImpl(this, namespaceURI, localName);
}
//
// Public methods
//
/**
* NON-DOM: Subclassed to flip the attributes' readonly switch as well.
* @see NodeImpl#setReadOnly
*/
public void setReadOnly(boolean readOnly, boolean deep) {
super.setReadOnly(readOnly,deep);
if (attributes != null) {
attributes.setReadOnly(readOnly,true);
}
}
//
// Protected methods
//
/** Synchronizes the data (name and value) for fast nodes. */
protected void synchronizeData() {
// no need to sync in the future
needsSyncData(false);
// attributes
setupDefaultAttributes();
} // synchronizeData()
/** Setup the default attributes. */
protected void setupDefaultAttributes() {
NamedNodeMapImpl defaults = getDefaultAttributes();
if (defaults != null) {
attributes = new AttributeMap(this, defaults);
}
}
/** Get the default attributes. */
protected NamedNodeMapImpl getDefaultAttributes() {
DocumentTypeImpl doctype =
(DocumentTypeImpl) ownerDocument.getDoctype();
if (doctype == null) {
return null;
}
ElementDefinitionImpl eldef =
(ElementDefinitionImpl)doctype.getElements()
.getNamedItem(getNodeName());
if (eldef == null) {
return null;
}
return (NamedNodeMapImpl) eldef.getAttributes();
} // setupAttributes(DocumentImpl)
} // class ElementImpl
|
added call to synchronizeData to new method hasAttributes()
git-svn-id: 21df804813e9d3638e43477f308dd0be51e5f30f@315944 13f79535-47bb-0310-9956-ffa450edef68
|
src/org/apache/xerces/dom/ElementImpl.java
|
added call to synchronizeData to new method hasAttributes()
|
|
Java
|
bsd-3-clause
|
cab5eb77140e2019adeaa3e7309dbdf9db401931
| 0
|
EmilHernvall/tregmine,EmilHernvall/tregmine,Clunker5/tregmine-2.0,Clunker5/tregmine-2.0,EmilHernvall/tregmine
|
package info.tregmine.portals;
import info.tregmine.Tregmine;
//import info.tregmine.api.TregminePlayer;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.Inventory;
public class Portals implements Listener {
private final Tregmine plugin;
public Portals(Tregmine instance) {
plugin = instance;
plugin.getServer();
}
private void portalButton(int button, Block block, Player player, Location loc) {
Inventory inventory = player.getInventory();
if(button == info.tregmine.api.math.Checksum.block(block)){
for (int i = 0; i < inventory.getSize(); i++) {
if (inventory.getItem(i) != null) {
player.sendMessage(ChatColor.RED + "You are carrying too much for the portal's magic to work.");
return;
}
}
loc.getWorld().loadChunk(loc.getWorld().getChunkAt(loc));
if (loc.getWorld().isChunkLoaded(loc.getWorld().getChunkAt(loc))){
player.teleport(loc);
player.sendMessage(ChatColor.YELLOW + "Thanks for traveling with TregPort!");
} else {
player.sendMessage(ChatColor.RED + "Portal needs some preperation please try again!");
}
}
}
@EventHandler
public void buttons(PlayerInteractEvent event) {
if(event.getAction() == Action.LEFT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_AIR) return;
Block block = event.getClickedBlock();
// TregminePlayer player = plugin.getPlayer(event.getPlayer());
Player player = event.getPlayer();
// Portal in tower of einhome
portalButton(-1488547832, block, player, this.plugin.getServer().getWorld("world").getSpawnLocation());
// Portal in elva
portalButton(-1559526734, block, player, this.plugin.getServer().getWorld("world").getSpawnLocation());
portalButton(-1349166371, block, player, this.plugin.getServer().getWorld("treton").getSpawnLocation());
portalButton(1371197620, block, player, this.plugin.getServer().getWorld("citadel").getSpawnLocation());
// portals in world
portalButton(-973919203, block, player, this.plugin.getServer().getWorld("treton").getSpawnLocation());
portalButton(-777405698, block, player, this.plugin.getServer().getWorld("treton").getSpawnLocation());
portalButton(1259780606, block, player, this.plugin.getServer().getWorld("citadel").getSpawnLocation());
portalButton(690186900, block, player, this.plugin.getServer().getWorld("elva").getSpawnLocation());
portalButton(209068875, block, player, this.plugin.getServer().getWorld("einhome").getSpawnLocation());
// portals in TRETON
portalButton(45939467, block, player, this.plugin.getServer().getWorld("world").getSpawnLocation());
portalButton(-1408237330, block, player, this.plugin.getServer().getWorld("citadel").getSpawnLocation());
portalButton(559131756, block, player, this.plugin.getServer().getWorld("elva").getSpawnLocation());
// portals in CITADEL
portalButton(1609346891, block, player, this.plugin.getServer().getWorld("world").getSpawnLocation());
portalButton(-449465967, block, player, this.plugin.getServer().getWorld("treton").getSpawnLocation());
portalButton(1112623336, block, player, this.plugin.getServer().getWorld("elva").getSpawnLocation());
}
//-1488547832
}
|
tregmine/src/info/tregmine/portals/Portals.java
|
package info.tregmine.portals;
import info.tregmine.Tregmine;
import info.tregmine.api.TregminePlayer;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.Inventory;
public class Portals implements Listener {
private final Tregmine plugin;
public Portals(Tregmine instance) {
plugin = instance;
plugin.getServer();
}
private void portalButton(int button, Block block, Player player, Location loc) {
Inventory inventory = player.getInventory();
if(button == info.tregmine.api.math.Checksum.block(block)){
for (int i = 0; i < inventory.getSize(); i++) {
if (inventory.getItem(i) != null) {
player.sendMessage(ChatColor.RED + "You are carrying too much for the portal's magic to work.");
return;
}
}
loc.getWorld().loadChunk(loc.getWorld().getChunkAt(loc));
if (loc.getWorld().isChunkLoaded(loc.getWorld().getChunkAt(loc))){
player.teleport(loc);
player.sendMessage(ChatColor.YELLOW + "Thanks for traveling with TregPort!");
} else {
player.sendMessage(ChatColor.RED + "Portal needs some preperation please try again!");
}
}
}
@EventHandler
public void buttons(PlayerInteractEvent event) {
if(event.getAction() == Action.LEFT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_AIR) return;
Block block = event.getClickedBlock();
// TregminePlayer player = plugin.getPlayer(event.getPlayer());
Player player = event.getPlayer();
// Portal in tower of einhome
portalButton(-1488547832, block, player, this.plugin.getServer().getWorld("world").getSpawnLocation());
// Portal in elva
portalButton(-1559526734, block, player, this.plugin.getServer().getWorld("world").getSpawnLocation());
portalButton(-1349166371, block, player, this.plugin.getServer().getWorld("treton").getSpawnLocation());
portalButton(1371197620, block, player, this.plugin.getServer().getWorld("citadel").getSpawnLocation());
// portals in world
portalButton(-973919203, block, player, this.plugin.getServer().getWorld("treton").getSpawnLocation());
portalButton(-777405698, block, player, this.plugin.getServer().getWorld("treton").getSpawnLocation());
portalButton(1259780606, block, player, this.plugin.getServer().getWorld("citadel").getSpawnLocation());
portalButton(690186900, block, player, this.plugin.getServer().getWorld("elva").getSpawnLocation());
portalButton(209068875, block, player, this.plugin.getServer().getWorld("einhome").getSpawnLocation());
// portals in TRETON
portalButton(45939467, block, player, this.plugin.getServer().getWorld("world").getSpawnLocation());
portalButton(-1408237330, block, player, this.plugin.getServer().getWorld("citadel").getSpawnLocation());
portalButton(559131756, block, player, this.plugin.getServer().getWorld("elva").getSpawnLocation());
// portals in CITADEL
portalButton(1609346891, block, player, this.plugin.getServer().getWorld("world").getSpawnLocation());
portalButton(-449465967, block, player, this.plugin.getServer().getWorld("treton").getSpawnLocation());
portalButton(1112623336, block, player, this.plugin.getServer().getWorld("elva").getSpawnLocation());
}
//-1488547832
}
|
fixed one thing
|
tregmine/src/info/tregmine/portals/Portals.java
|
fixed one thing
|
|
Java
|
cc0-1.0
|
c81dfd7d87ca09f6d66848b87d2f43d3625e3dbe
| 0
|
TheElk205/KillTheNerd
|
core/src/at/gamejam/ktn/game/entities/Player.java
|
package at.gamejam.ktn.game.entities;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.CircleShape;
import com.badlogic.gdx.physics.box2d.Fixture;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.RayCastCallback;
import com.badlogic.gdx.physics.box2d.World;
/**
* Created by Lukas on 11.04.2015.
*/
public class Player extends GameObject {
public static final float JUMP_FORCE = 9f;
private static final float ACCELERATION = 0.5f;
private static final float MAX_SPEED = 3f;
private TextureRegion texture;
private final World b2World;
private Body b2Body;
private boolean left;
private boolean right;
private boolean touchingGround;
private Sound sound;
public Player(final Vector2 position, final World b2World) {
super();
this.b2World = b2World;
this.position = position;
this.init();
}
private void init() {
this.dimension.set(0.2f, 0.2f);
this.origin.x = this.dimension.x / 2;
this.origin.y = this.dimension.y / 2;
this.texture = this.assets.findRegion("player");
// this.sound = Gdx.audio.newSound(Gdx.files.internal("bounce.mp3"));
this.initPhysics();
}
@Override
public void initPhysics() {
// create body definition
final BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyDef.BodyType.DynamicBody;
bodyDef.position.set(this.position.x, this.position.y);
// create body in world
this.b2Body = this.b2World.createBody(bodyDef);
// create shape
final CircleShape circleShape = new CircleShape();
circleShape.setRadius(this.dimension.x / 2);
// create fixture to attach shape to body
final FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = circleShape;
fixtureDef.density = 1f;
fixtureDef.friction = 1f;
fixtureDef.restitution = 0;
this.b2Body.createFixture(fixtureDef);
this.b2Body.setLinearDamping(1f);
this.b2Body.setBullet(true);
circleShape.dispose(); // clean up!!
this.b2Body.setUserData(this);
}
@Override
public void render(final SpriteBatch batch) {
batch.draw(this.texture, this.position.x - (this.dimension.x / 2), this.position.y - (this.dimension.y / 2), this.origin.x, this.origin.y, this.dimension.x, this.dimension.y, this.scale.x,
this.scale.y, this.rotation);
}
@Override
public void update(final float deltaTime) {
this.touchingGround = false;
this.move();
this.position = this.b2Body.getPosition();
this.rotation = this.b2Body.getAngle() * MathUtils.radiansToDegrees;
}
public void move() {
final Vector2 toApply = new Vector2();
if (this.left) {
toApply.x = -Player.ACCELERATION;
} else
if (this.right) {
toApply.x = Player.ACCELERATION;
} else {
toApply.x = 0;
}
/*if (((this.b2Body.getLinearVelocity().x > Player.MAX_SPEED) && (toApply.x > 0)) || ((this.b2Body.getLinearVelocity().x < -Player.MAX_SPEED) && (toApply.x < 0))) {
toApply.x = 0;
}*/
this.b2Body.applyForceToCenter(toApply, true);
}
public void setLeft(final boolean left) {
this.left = left;
}
public void setRight(final boolean right) {
this.right = right;
}
public void jump() {
this.testGround();
if (this.touchingGround) {
// this.sound.play();
this.b2Body.applyForceToCenter(0, Player.JUMP_FORCE, true);
}
}
public void testGround() {
this.b2World.rayCast(new RayCastCallback() {
@Override
public float reportRayFixture(final Fixture fixture, final Vector2 point, final Vector2 normal, final float fraction) {
if (fixture != null) {
if (fraction < 0.8f) {
Player.this.touchingGround = true;
}
}
return 0;
}
}, this.b2Body.getWorldCenter(), new Vector2(this.b2Body.getWorldCenter().x, this.b2Body.getWorldCenter().y - 0.2f));
}
public Body getBody() {
return this.b2Body;
}
}
|
BIIIIIIIIIIIIIIIIIIIIIG Change
|
core/src/at/gamejam/ktn/game/entities/Player.java
|
BIIIIIIIIIIIIIIIIIIIIIG Change
|
||
Java
|
mit
|
e23a2335366f867ed84035f01f7955b71f88ee49
| 0
|
UniversityOfBrightonComputing/iCirclesOriginal
|
package icircles.decomposition;
import icircles.abstractdescription.AbstractBasicRegion;
import icircles.abstractdescription.AbstractCurve;
import icircles.abstractdescription.AbstractDescription;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* An innermost abstract contour has the fewest abstract basic regions inside
*/
public class DecompositionStrategyInnermost extends DecompositionStrategy {
List<AbstractCurve> getContoursToRemove(AbstractDescription ad) {
List<AbstractCurve> result = new ArrayList<>();
ad.getCurvesUnmodifiable()
.stream()
.reduce((curve1, curve2) -> ad.getNumZonesIn(curve1) < ad.getNumZonesIn(curve2) ? curve1 : curve2)
.ifPresent(result::add);
return result;
}
}
|
src/main/java/icircles/decomposition/DecompositionStrategyInnermost.java
|
package icircles.decomposition;
import icircles.abstractdescription.AbstractBasicRegion;
import icircles.abstractdescription.AbstractCurve;
import icircles.abstractdescription.AbstractDescription;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class DecompositionStrategyInnermost extends DecompositionStrategy {
List<AbstractCurve> getContoursToRemove(AbstractDescription ad) {
List<AbstractCurve> result = new ArrayList<>();
// an innermost abstract contour has the fewest abstract basic regions inside
int best_num_zones = ad.getNumZones() + 1;
AbstractCurve best_contour = null;
for (AbstractCurve curve : ad.getCurvesUnmodifiable()) {
int numZones = 0;
for (AbstractBasicRegion zone : ad.getZonesUnmodifiable()) {
if (zone.contains(curve)) {
numZones++;
}
}
if (numZones < best_num_zones) {
best_num_zones = numZones;
best_contour = curve;
}
}
result.add(best_contour);
return result;
}
}
|
refactored to streams
|
src/main/java/icircles/decomposition/DecompositionStrategyInnermost.java
|
refactored to streams
|
|
Java
|
mit
|
b6c128bbd8992508ef1389f1b4ba1640244bea73
| 0
|
amirbawab/EasyCC
|
package sidebar;
import data.LexicalEdgeJSON;
import data.LexicalMachineJSON;
import data.LexicalStateJSON;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LeftSideBar extends JPanel {
// Components
private JComboBox<String> stateType, stateBacktrack, fromState, toState;
private JTextField stateName, finalStateToken, edgeLabel;
private JButton addStateButton, deleteStateButton, deleteEdgeButton, verifyDFAButton, addEdgeButton, clearAllButton, exportButton, importButton;
private JTable edgesTable;
private JScrollPane edgesTableSP;
private DefaultTableModel edgeTableModel;
// Store machine
private LexicalMachineJSON lexicalMachineJSON;
// Listener
private LeftSideBarListener leftTopSideBarListener;
// Values
private String[] typeValues = { "initial", "normal", "final"};
private String[] backtrackValues = { "Yes", "No"};
public LeftSideBar() {
JPanel statePanel, edgePanel, otherPanel;
// Init components
stateType = new JComboBox<>(typeValues);
stateBacktrack = new JComboBox<>(backtrackValues);
fromState = new JComboBox<>();
toState = new JComboBox<>();
finalStateToken = new JTextField(10);
edgeLabel = new JTextField(10);
stateName = new JTextField(10);
addStateButton = new JButton("Add new state");
addEdgeButton = new JButton("Add new edge");
deleteStateButton = new JButton("Delete state by Name");
deleteEdgeButton = new JButton("Delete selected Edge");
verifyDFAButton = new JButton("Verify DFA");
clearAllButton = new JButton("Clear all");
exportButton = new JButton("Export JSON");
importButton = new JButton("Import JSON");
statePanel = new JPanel();
edgePanel = new JPanel();
otherPanel = new JPanel();
edgeTableModel = new DefaultTableModel(null, new Object[]{"From", "To", "Label"});
edgesTable = new JTable(edgeTableModel);
edgesTableSP = new JScrollPane(edgesTable);
// Set layout
setLayout(new GridBagLayout());
statePanel.setLayout(new GridBagLayout());
edgePanel.setLayout(new GridBagLayout());
otherPanel.setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
// Set border
setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
statePanel.setBorder(BorderFactory.createTitledBorder("Add State"));
edgePanel.setBorder(BorderFactory.createTitledBorder("Add Edge"));
otherPanel.setBorder(BorderFactory.createTitledBorder("Other"));
// Add listeners
addListeners();
// Configure components
configureComponents();
gc.fill = GridBagConstraints.NONE;
gc.weightx = 1;
gc.weighty = 1;
gc.anchor = GridBagConstraints.FIRST_LINE_START;
gc.insets = new Insets(5,5,5,5);
// Add components to state panel
gc.gridx=0;
gc.gridy=0;
statePanel.add(new JLabel("Name: "), gc);
gc.gridx=1;
statePanel.add(stateName, gc);
gc.gridx=0;
gc.gridy++;
statePanel.add(new JLabel("Type: "), gc);
gc.gridx=1;
statePanel.add(stateType, gc);
gc.gridx=0;
gc.gridy++;
statePanel.add(new JLabel("Backtrack: "), gc);
gc.gridx=1;
statePanel.add(stateBacktrack, gc);
gc.gridx=0;
gc.gridy++;
statePanel.add(new JLabel("Token: "), gc);
gc.gridx=1;
statePanel.add(finalStateToken, gc);
gc.anchor = GridBagConstraints.CENTER;
gc.gridx=0;
gc.gridy++;
gc.gridwidth = 2;
statePanel.add(addStateButton, gc);
gc.gridx=0;
gc.gridy++;
statePanel.add(deleteStateButton, gc);
gc.gridx=0;
gc.gridy=0;
gc.gridwidth = 1;
edgePanel.add(new JLabel("From: "), gc);
gc.gridx=1;
edgePanel.add(fromState, gc);
gc.gridx=0;
gc.gridy++;
edgePanel.add(new JLabel("To: "), gc);
gc.gridx=1;
edgePanel.add(toState, gc);
gc.gridx=0;
gc.gridy++;
edgePanel.add(new JLabel("Label: "), gc);
gc.gridx=1;
edgePanel.add(edgeLabel, gc);
gc.gridx=0;
gc.gridy++;
gc.gridwidth = 2;
edgePanel.add(addEdgeButton, gc);
gc.gridx=0;
gc.gridy++;
edgePanel.add(edgesTableSP, gc);
gc.gridx=0;
gc.gridy++;
edgePanel.add(deleteEdgeButton, gc);
gc.gridx=0;
gc.gridy=0;
otherPanel.add(verifyDFAButton, gc);
gc.gridx=0;
gc.gridy++;
otherPanel.add(clearAllButton, gc);
gc.gridx=0;
gc.gridy++;
otherPanel.add(exportButton, gc);
gc.gridx=0;
gc.gridy++;
otherPanel.add(importButton, gc);
// Add components to left panel
gc.anchor = GridBagConstraints.CENTER;
gc.fill = GridBagConstraints.HORIZONTAL;
gc.gridwidth = 1;
gc.gridx=0;
gc.gridy=0;
add(statePanel, gc);
gc.gridx=0;
gc.gridy++;
add(edgePanel, gc);
gc.gridx=0;
gc.gridy++;
add(otherPanel, gc);
}
public void configureComponents() {
// By default
stateBacktrack.setEnabled(false);
finalStateToken.setEnabled(false);
edgesTable.setDefaultEditor(Object.class, null);
// Configure edges table
edgesTableSP.setPreferredSize(new Dimension(200, 200));
edgesTable.getTableHeader().setReorderingAllowed(false);
}
/**
* Add buttons listeners
*/
public void addListeners() {
JFrame frame = (JFrame)SwingUtilities.getRoot(LeftSideBar.this);
addStateButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
if( (stateType.getSelectedIndex() == 2 && finalStateToken.getText().isEmpty() ) || stateName.getText().isEmpty()) {
JOptionPane.showMessageDialog(frame, "Please fill all the state fields", "State not created", JOptionPane.ERROR_MESSAGE);
} else {
// Get data
String name = stateName.getText();
String type = (String) stateType.getSelectedItem();
String backtrack = stateBacktrack.getSelectedIndex() == 0 ? "true" : "false";
String token = finalStateToken.getText();
for(LexicalStateJSON lexicalStateJSON : lexicalMachineJSON.getStates()) {
// If more than one initial
if(type.equals(typeValues[0]) && lexicalStateJSON.getType().equals(typeValues[0])) {
JOptionPane.showMessageDialog(frame, "Cannot have more than one initial state", "State not created", JOptionPane.ERROR_MESSAGE);
return;
}
// If already exists
if(lexicalStateJSON.getName().equals(name)) {
JOptionPane.showMessageDialog(frame, "State name already exists", "State not created", JOptionPane.ERROR_MESSAGE);
return;
}
}
// Create state
LexicalStateJSON lexicalStateJSON = new LexicalStateJSON();
lexicalStateJSON.setName(name);
lexicalStateJSON.setBacktrack(backtrack);
lexicalStateJSON.setType(type);
lexicalStateJSON.setToken(token);
lexicalMachineJSON.getStates().add(lexicalStateJSON);
// Update from to states for edge panel
fromState.addItem(name);
toState.addItem(name);
// Refresh all
leftTopSideBarListener.refresh();
}
}
});
addEdgeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
if(fromState.getSelectedIndex() < 0 || toState.getSelectedIndex() < 0 || edgeLabel.getText().isEmpty()) {
JFrame frame = (JFrame)SwingUtilities.getRoot(LeftSideBar.this);
JOptionPane.showMessageDialog(frame, "Please fill all the edge fields", "Edge not created", JOptionPane.ERROR_MESSAGE);
} else {
// Get data
String from = (String) fromState.getSelectedItem();
String to = (String) toState.getSelectedItem();
String label = edgeLabel.getText();
// Check if already exists
for(LexicalEdgeJSON lexicalEdgeJSON : lexicalMachineJSON.getEdges()) {
if(lexicalEdgeJSON.getFrom().equals(from) && lexicalEdgeJSON.getTo().equals(to) && lexicalEdgeJSON.getValue().equals(label)) {
JOptionPane.showMessageDialog(frame, "Edge already exists", "Edge not created", JOptionPane.ERROR_MESSAGE);
return;
}
}
// Create edge
LexicalEdgeJSON lexicalEdgeJSON = new LexicalEdgeJSON();
lexicalEdgeJSON.setFrom(from);
lexicalEdgeJSON.setTo(to);
lexicalEdgeJSON.setValue(label);
lexicalMachineJSON.getEdges().add(lexicalEdgeJSON);
// Add entry in table
edgeTableModel.addRow(new Object[]{from, to, label});
// Refresh all
leftTopSideBarListener.refresh();
}
}
});
stateType.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
// If final state
if(stateType.getSelectedIndex() == 2) {
stateBacktrack.setEnabled(true);
finalStateToken.setEnabled(true);
} else {
stateBacktrack.setEnabled(false);
finalStateToken.setEnabled(false);
finalStateToken.setText("");
}
}
});
deleteStateButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
if(stateName.getText().isEmpty()) {
JOptionPane.showMessageDialog(frame, "Please enter a state name to delete", "State not deleted", JOptionPane.ERROR_MESSAGE);
} else {
boolean found = false;
String name = stateName.getText();
for(int i=0; i < lexicalMachineJSON.getStates().size(); i++) {
if(name.equals(lexicalMachineJSON.getStates().get(i).getName())) {
lexicalMachineJSON.getStates().remove(i);
fromState.removeItemAt(i);
toState.removeItemAt(i);
found = true;
break;
}
}
if(!found) {
JOptionPane.showMessageDialog(frame, "State name does not exist", "State not deleted", JOptionPane.ERROR_MESSAGE);
} else {
for(int i=0; i < lexicalMachineJSON.getEdges().size();i++) {
LexicalEdgeJSON lexicalEdgeJSON = lexicalMachineJSON.getEdges().get(i);
if(lexicalEdgeJSON.getFrom().equals(name) || lexicalEdgeJSON.getTo().equals(name)) {
lexicalMachineJSON.getEdges().remove(i);
edgeTableModel.removeRow(i);
i--;
}
}
}
}
}
});
deleteEdgeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
if(edgesTable.getSelectedRow() < 0) {
JOptionPane.showMessageDialog(frame, "Please select an edge to delete", "Edge not deleted", JOptionPane.ERROR_MESSAGE);
} else {
lexicalMachineJSON.getEdges().remove(edgesTable.getSelectedRow());
edgeTableModel.removeRow(edgesTable.getSelectedRow());
}
}
});
clearAllButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
while(edgeTableModel.getRowCount() > 0) {
edgeTableModel.removeRow(0);
}
lexicalMachineJSON.getEdges().clear();
lexicalMachineJSON.getStates().clear();
leftTopSideBarListener.refresh();
}
});
}
/**
* Set listener
* @param leftTopSideBarListener
*/
public void setLeftTopSideBarListener(LeftSideBarListener leftTopSideBarListener) {
this.leftTopSideBarListener = leftTopSideBarListener;
}
/**
* Set lexical machine
* @param lexicalMachineJSON
*/
public void setLexicalMachineJSON(LexicalMachineJSON lexicalMachineJSON) {
this.lexicalMachineJSON = lexicalMachineJSON;
}
}
|
lexical-analysis/lexical-generator/src/main/java/sidebar/LeftSideBar.java
|
package sidebar;
import data.LexicalEdgeJSON;
import data.LexicalMachineJSON;
import data.LexicalStateJSON;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LeftSideBar extends JPanel {
// Components
private JComboBox<String> stateType, stateBacktrack, fromState, toState;
private JTextField stateName, finalStateToken, edgeLabel;
private JButton addStateButton, deleteStateButton, deleteEdgeButton, verifyDFAButton, addEdgeButton, clearAllButton, exportButton, importButton;
private JTable edgesTable;
private JScrollPane edgesTableSP;
private DefaultTableModel edgeTableModel;
// Store machine
private LexicalMachineJSON lexicalMachineJSON;
// Listener
private LeftSideBarListener leftTopSideBarListener;
// Values
private String[] typeValues = { "initial", "normal", "final"};
private String[] backtrackValues = { "Yes", "No"};
public LeftSideBar() {
JPanel statePanel, edgePanel, otherPanel;
// Init components
stateType = new JComboBox<>(typeValues);
stateBacktrack = new JComboBox<>(backtrackValues);
fromState = new JComboBox<>();
toState = new JComboBox<>();
finalStateToken = new JTextField(10);
edgeLabel = new JTextField(10);
stateName = new JTextField(10);
addStateButton = new JButton("Add new state");
addEdgeButton = new JButton("Add new edge");
deleteStateButton = new JButton("Delete state by Name");
deleteEdgeButton = new JButton("Delete selected Edge");
verifyDFAButton = new JButton("Verify DFA");
clearAllButton = new JButton("Clear all");
exportButton = new JButton("Export JSON");
importButton = new JButton("Import JSON");
statePanel = new JPanel();
edgePanel = new JPanel();
otherPanel = new JPanel();
edgeTableModel = new DefaultTableModel(null, new Object[]{"From", "To", "Label"});
edgesTable = new JTable(edgeTableModel);
edgesTableSP = new JScrollPane(edgesTable);
// Set layout
setLayout(new GridBagLayout());
statePanel.setLayout(new GridBagLayout());
edgePanel.setLayout(new GridBagLayout());
otherPanel.setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
// Set border
setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
statePanel.setBorder(BorderFactory.createTitledBorder("Add State"));
edgePanel.setBorder(BorderFactory.createTitledBorder("Add Edge"));
otherPanel.setBorder(BorderFactory.createTitledBorder("Other"));
// Add listeners
addListeners();
// Configure components
configureComponents();
gc.fill = GridBagConstraints.NONE;
gc.weightx = 1;
gc.weighty = 1;
gc.anchor = GridBagConstraints.FIRST_LINE_START;
gc.insets = new Insets(5,5,5,5);
// Add components to state panel
gc.gridx=0;
gc.gridy=0;
statePanel.add(new JLabel("Name: "), gc);
gc.gridx=1;
statePanel.add(stateName, gc);
gc.gridx=0;
gc.gridy++;
statePanel.add(new JLabel("Type: "), gc);
gc.gridx=1;
statePanel.add(stateType, gc);
gc.gridx=0;
gc.gridy++;
statePanel.add(new JLabel("Backtrack: "), gc);
gc.gridx=1;
statePanel.add(stateBacktrack, gc);
gc.gridx=0;
gc.gridy++;
statePanel.add(new JLabel("Token: "), gc);
gc.gridx=1;
statePanel.add(finalStateToken, gc);
gc.anchor = GridBagConstraints.CENTER;
gc.gridx=0;
gc.gridy++;
gc.gridwidth = 2;
statePanel.add(addStateButton, gc);
gc.gridx=0;
gc.gridy++;
statePanel.add(deleteStateButton, gc);
gc.gridx=0;
gc.gridy=0;
gc.gridwidth = 1;
edgePanel.add(new JLabel("From: "), gc);
gc.gridx=1;
edgePanel.add(fromState, gc);
gc.gridx=0;
gc.gridy++;
edgePanel.add(new JLabel("To: "), gc);
gc.gridx=1;
edgePanel.add(toState, gc);
gc.gridx=0;
gc.gridy++;
edgePanel.add(new JLabel("Label: "), gc);
gc.gridx=1;
edgePanel.add(edgeLabel, gc);
gc.gridx=0;
gc.gridy++;
gc.gridwidth = 2;
edgePanel.add(addEdgeButton, gc);
gc.gridx=0;
gc.gridy++;
edgePanel.add(edgesTableSP, gc);
gc.gridx=0;
gc.gridy++;
edgePanel.add(deleteEdgeButton, gc);
gc.gridx=0;
gc.gridy=0;
otherPanel.add(verifyDFAButton, gc);
gc.gridx=0;
gc.gridy++;
otherPanel.add(clearAllButton, gc);
gc.gridx=0;
gc.gridy++;
otherPanel.add(exportButton, gc);
gc.gridx=0;
gc.gridy++;
otherPanel.add(importButton, gc);
// Add components to left panel
gc.anchor = GridBagConstraints.CENTER;
gc.fill = GridBagConstraints.HORIZONTAL;
gc.gridwidth = 1;
gc.gridx=0;
gc.gridy=0;
add(statePanel, gc);
gc.gridx=0;
gc.gridy++;
add(edgePanel, gc);
gc.gridx=0;
gc.gridy++;
add(otherPanel, gc);
}
public void configureComponents() {
// By default
stateBacktrack.setEnabled(false);
finalStateToken.setEnabled(false);
edgesTable.setDefaultEditor(Object.class, null);
// Configure edges table
edgesTableSP.setPreferredSize(new Dimension(200, 200));
edgesTable.getTableHeader().setReorderingAllowed(false);
}
/**
* Add buttons listeners
*/
public void addListeners() {
JFrame frame = (JFrame)SwingUtilities.getRoot(LeftSideBar.this);
addStateButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
if( (stateType.getSelectedIndex() == 2 && finalStateToken.getText().isEmpty() ) || stateName.getText().isEmpty()) {
JOptionPane.showMessageDialog(frame, "Please fill all the state fields", "State not created", JOptionPane.ERROR_MESSAGE);
} else {
// Get data
String name = stateName.getText();
String type = (String) stateType.getSelectedItem();
String backtrack = stateBacktrack.getSelectedIndex() == 0 ? "true" : "false";
String token = finalStateToken.getText();
for(LexicalStateJSON lexicalStateJSON : lexicalMachineJSON.getStates()) {
// If more than one initial
if(type.equals(typeValues[0]) && lexicalStateJSON.getType().equals(typeValues[0])) {
JOptionPane.showMessageDialog(frame, "Cannot have more than one initial state", "State not created", JOptionPane.ERROR_MESSAGE);
return;
}
// If already exists
if(lexicalStateJSON.getName().equals(name)) {
JOptionPane.showMessageDialog(frame, "State name already exists", "State not created", JOptionPane.ERROR_MESSAGE);
return;
}
}
// Create state
LexicalStateJSON lexicalStateJSON = new LexicalStateJSON();
lexicalStateJSON.setName(name);
lexicalStateJSON.setBacktrack(backtrack);
lexicalStateJSON.setType(type);
lexicalStateJSON.setToken(token);
lexicalMachineJSON.getStates().add(lexicalStateJSON);
// Update from to states for edge panel
fromState.addItem(name);
toState.addItem(name);
// Refresh all
leftTopSideBarListener.refresh();
}
}
});
addEdgeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
if(fromState.getSelectedIndex() < 0 || toState.getSelectedIndex() < 0 || edgeLabel.getText().isEmpty()) {
JFrame frame = (JFrame)SwingUtilities.getRoot(LeftSideBar.this);
JOptionPane.showMessageDialog(frame, "Please fill all the edge fields", "Edge not created", JOptionPane.ERROR_MESSAGE);
} else {
// Get data
String from = (String) fromState.getSelectedItem();
String to = (String) toState.getSelectedItem();
String label = edgeLabel.getText();
// Check if already exists
for(LexicalEdgeJSON lexicalEdgeJSON : lexicalMachineJSON.getEdges()) {
if(lexicalEdgeJSON.getFrom().equals(from) && lexicalEdgeJSON.getTo().equals(to) && lexicalEdgeJSON.getValue().equals(label)) {
JOptionPane.showMessageDialog(frame, "Edge already exists", "Edge not created", JOptionPane.ERROR_MESSAGE);
return;
}
}
// Create edge
LexicalEdgeJSON lexicalEdgeJSON = new LexicalEdgeJSON();
lexicalEdgeJSON.setFrom(from);
lexicalEdgeJSON.setTo(to);
lexicalEdgeJSON.setValue(label);
lexicalMachineJSON.getEdges().add(lexicalEdgeJSON);
// Add entry in table
edgeTableModel.addRow(new Object[]{from, to, label});
// Refresh all
leftTopSideBarListener.refresh();
}
}
});
stateType.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
// If final state
if(stateType.getSelectedIndex() == 2) {
stateBacktrack.setEnabled(true);
finalStateToken.setEnabled(true);
} else {
stateBacktrack.setEnabled(false);
finalStateToken.setEnabled(false);
finalStateToken.setText("");
}
}
});
deleteStateButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
if(stateName.getText().isEmpty()) {
JOptionPane.showMessageDialog(frame, "Please enter a state name to delete", "State not deleted", JOptionPane.ERROR_MESSAGE);
} else {
boolean found = false;
String name = stateName.getText();
for(int i=0; i < lexicalMachineJSON.getStates().size(); i++) {
if(name.equals(lexicalMachineJSON.getStates().get(i).getName())) {
lexicalMachineJSON.getStates().remove(i);
fromState.removeItemAt(i);
toState.removeItemAt(i);
found = true;
break;
}
}
if(!found) {
JOptionPane.showMessageDialog(frame, "State name does not exist", "State not deleted", JOptionPane.ERROR_MESSAGE);
} else {
for(int i=0; i < lexicalMachineJSON.getEdges().size();i++) {
LexicalEdgeJSON lexicalEdgeJSON = lexicalMachineJSON.getEdges().get(i);
if(lexicalEdgeJSON.getFrom().equals(name) || lexicalEdgeJSON.getTo().equals(name)) {
lexicalMachineJSON.getEdges().remove(i);
edgeTableModel.removeRow(i);
i--;
}
}
}
}
}
});
clearAllButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
while(edgeTableModel.getRowCount() > 0) {
edgeTableModel.removeRow(0);
}
lexicalMachineJSON.getEdges().clear();
lexicalMachineJSON.getStates().clear();
leftTopSideBarListener.refresh();
}
});
}
/**
* Set listener
* @param leftTopSideBarListener
*/
public void setLeftTopSideBarListener(LeftSideBarListener leftTopSideBarListener) {
this.leftTopSideBarListener = leftTopSideBarListener;
}
/**
* Set lexical machine
* @param lexicalMachineJSON
*/
public void setLexicalMachineJSON(LexicalMachineJSON lexicalMachineJSON) {
this.lexicalMachineJSON = lexicalMachineJSON;
}
}
|
Added delete edge
|
lexical-analysis/lexical-generator/src/main/java/sidebar/LeftSideBar.java
|
Added delete edge
|
|
Java
|
mit
|
5cce7fec1a65b62469a988582dd8158e784e58dd
| 0
|
B-Stefan/Risiko
|
package configuration;
import com.sun.javaws.exceptions.InvalidArgumentException;
/**
* Created by Stefan on 29.06.14.
*/
public class ServerConfiguration {
/**
* Default Server Konfiguration
*/
public final static ServerConfiguration DEFAULT = new ServerConfiguration(
6789,
"localhost",
"GameManagerService");
/**
* Erstellt aus einem String array String eine Server Konfiguration
* @param args Stringarray
* [0] - HOST
* [1] - PORT
* [2] - GAME_SERVICE_NAME
* @return
* @throws InvalidArgumentException
* @throws ClassCastException
*/
public static ServerConfiguration fromArgs(String[] args) throws InvalidArgumentException, ClassCastException{
if(args.length < 3){
throw new InvalidArgumentException(args);
}
return new ServerConfiguration(Integer.parseInt(args[0]),args[1],args[2]);
}
public final int PORT;
public final String SERVER_HOST;
public final String SERVICE_NAME;
public ServerConfiguration(int PORT, String SERVER_HOST, String SERVICE_NAME){
this.PORT = PORT;
this.SERVER_HOST = SERVER_HOST;
this.SERVICE_NAME = SERVICE_NAME;
}
}
|
Commons/src/configuration/ServerConfiguration.java
|
package configuration;
/**
* Created by Stefan on 30.06.14.
*/
public class ServerConfiguration {
}
|
Update Server Configuration
|
Commons/src/configuration/ServerConfiguration.java
|
Update Server Configuration
|
|
Java
|
mit
|
e851b5e0240956d4cd7fc40530c4603754414ccf
| 0
|
stephenc/jenkins,recena/jenkins,ikedam/jenkins,jenkinsci/jenkins,ikedam/jenkins,damianszczepanik/jenkins,MarkEWaite/jenkins,pjanouse/jenkins,daniel-beck/jenkins,stephenc/jenkins,Jochen-A-Fuerbacher/jenkins,oleg-nenashev/jenkins,daniel-beck/jenkins,viqueen/jenkins,ikedam/jenkins,daniel-beck/jenkins,patbos/jenkins,MarkEWaite/jenkins,DanielWeber/jenkins,damianszczepanik/jenkins,v1v/jenkins,godfath3r/jenkins,jenkinsci/jenkins,MarkEWaite/jenkins,pjanouse/jenkins,DanielWeber/jenkins,rsandell/jenkins,oleg-nenashev/jenkins,Vlatombe/jenkins,jenkinsci/jenkins,pjanouse/jenkins,bkmeneguello/jenkins,bkmeneguello/jenkins,oleg-nenashev/jenkins,daniel-beck/jenkins,pjanouse/jenkins,Jochen-A-Fuerbacher/jenkins,patbos/jenkins,Jochen-A-Fuerbacher/jenkins,Jochen-A-Fuerbacher/jenkins,ikedam/jenkins,viqueen/jenkins,v1v/jenkins,daniel-beck/jenkins,DanielWeber/jenkins,oleg-nenashev/jenkins,viqueen/jenkins,MarkEWaite/jenkins,pjanouse/jenkins,v1v/jenkins,Vlatombe/jenkins,jenkinsci/jenkins,viqueen/jenkins,v1v/jenkins,v1v/jenkins,recena/jenkins,godfath3r/jenkins,pjanouse/jenkins,patbos/jenkins,rsandell/jenkins,oleg-nenashev/jenkins,bkmeneguello/jenkins,stephenc/jenkins,damianszczepanik/jenkins,recena/jenkins,damianszczepanik/jenkins,Vlatombe/jenkins,damianszczepanik/jenkins,jenkinsci/jenkins,MarkEWaite/jenkins,ikedam/jenkins,recena/jenkins,jenkinsci/jenkins,stephenc/jenkins,ikedam/jenkins,DanielWeber/jenkins,damianszczepanik/jenkins,stephenc/jenkins,DanielWeber/jenkins,rsandell/jenkins,rsandell/jenkins,patbos/jenkins,MarkEWaite/jenkins,daniel-beck/jenkins,v1v/jenkins,Vlatombe/jenkins,pjanouse/jenkins,daniel-beck/jenkins,DanielWeber/jenkins,Vlatombe/jenkins,DanielWeber/jenkins,bkmeneguello/jenkins,damianszczepanik/jenkins,ikedam/jenkins,Jochen-A-Fuerbacher/jenkins,patbos/jenkins,viqueen/jenkins,recena/jenkins,bkmeneguello/jenkins,Vlatombe/jenkins,oleg-nenashev/jenkins,godfath3r/jenkins,MarkEWaite/jenkins,viqueen/jenkins,oleg-nenashev/jenkins,rsandell/jenkins,godfath3r/jenkins,jenkinsci/jenkins,Vlatombe/jenkins,MarkEWaite/jenkins,patbos/jenkins,godfath3r/jenkins,godfath3r/jenkins,Jochen-A-Fuerbacher/jenkins,stephenc/jenkins,stephenc/jenkins,recena/jenkins,rsandell/jenkins,godfath3r/jenkins,rsandell/jenkins,patbos/jenkins,viqueen/jenkins,Jochen-A-Fuerbacher/jenkins,v1v/jenkins,jenkinsci/jenkins,daniel-beck/jenkins,damianszczepanik/jenkins,recena/jenkins,ikedam/jenkins,bkmeneguello/jenkins,rsandell/jenkins,bkmeneguello/jenkins
|
/*
* The MIT License
*
* Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi,
* Eric Lefevre-Ardant, Erik Ramfelt, Michael B. Donohue, Alan Harder,
* Manufacture Francaise des Pneumatiques Michelin, Romain Seguy
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson;
import com.google.common.annotations.VisibleForTesting;
import com.jcraft.jzlib.GZIPInputStream;
import com.jcraft.jzlib.GZIPOutputStream;
import hudson.Launcher.LocalLauncher;
import hudson.Launcher.RemoteLauncher;
import hudson.model.AbstractProject;
import hudson.model.Computer;
import hudson.model.Item;
import hudson.model.TaskListener;
import hudson.os.PosixAPI;
import hudson.os.PosixException;
import hudson.remoting.Callable;
import hudson.remoting.Channel;
import hudson.remoting.DelegatingCallable;
import hudson.remoting.Future;
import hudson.remoting.LocalChannel;
import hudson.remoting.Pipe;
import hudson.remoting.RemoteInputStream;
import hudson.remoting.RemoteInputStream.Flag;
import hudson.remoting.RemoteOutputStream;
import hudson.remoting.VirtualChannel;
import hudson.remoting.Which;
import hudson.security.AccessControlled;
import hudson.util.DaemonThreadFactory;
import hudson.util.DirScanner;
import hudson.util.ExceptionCatchingThreadFactory;
import hudson.util.FileVisitor;
import hudson.util.FormValidation;
import hudson.util.HeadBufferingStream;
import hudson.util.IOUtils;
import hudson.util.NamingThreadFactory;
import hudson.util.io.Archiver;
import hudson.util.io.ArchiverFactory;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.io.Serializable;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.FileSystemException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.LinkOption;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import jenkins.FilePathFilter;
import jenkins.MasterToSlaveFileCallable;
import jenkins.SlaveToMasterFileCallable;
import jenkins.SoloFilePathFilter;
import jenkins.model.Jenkins;
import jenkins.security.MasterToSlaveCallable;
import jenkins.util.ContextResettingExecutorService;
import jenkins.util.VirtualFile;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.io.input.CountingInputStream;
import org.apache.commons.lang.StringUtils;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.jenkinsci.remoting.RoleChecker;
import org.jenkinsci.remoting.RoleSensitive;
import org.jenkinsci.remoting.SerializableOnlyOverRemoting;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.Function;
import org.kohsuke.stapler.Stapler;
import static hudson.FilePath.TarCompression.GZIP;
import static hudson.Util.fileToPath;
import static hudson.Util.fixEmpty;
import java.io.NotSerializableException;
import java.util.Collections;
import org.apache.tools.ant.BuildException;
/**
* {@link File} like object with remoting support.
*
* <p>
* Unlike {@link File}, which always implies a file path on the current computer,
* {@link FilePath} represents a file path on a specific agent or the master.
*
* Despite that, {@link FilePath} can be used much like {@link File}. It exposes
* a bunch of operations (and we should add more operations as long as they are
* generally useful), and when invoked against a file on a remote node, {@link FilePath}
* executes the necessary code remotely, thereby providing semi-transparent file
* operations.
*
* <h2>Using {@link FilePath} smartly</h2>
* <p>
* The transparency makes it easy to write plugins without worrying too much about
* remoting, by making it works like NFS, where remoting happens at the file-system
* layer.
*
* <p>
* But one should note that such use of remoting may not be optional. Sometimes,
* it makes more sense to move some computation closer to the data, as opposed to
* move the data to the computation. For example, if you are just computing a MD5
* digest of a file, then it would make sense to do the digest on the host where
* the file is located, as opposed to send the whole data to the master and do MD5
* digesting there.
*
* <p>
* {@link FilePath} supports this "code migration" by in the
* {@link #act(FileCallable)} method. One can pass in a custom implementation
* of {@link FileCallable}, to be executed on the node where the data is located.
* The following code shows the example:
*
* <pre>
* void someMethod(FilePath file) {
* // make 'file' a fresh empty directory.
* file.act(new Freshen());
* }
* // if 'file' is on a different node, this FileCallable will
* // be transferred to that node and executed there.
* private static final class Freshen implements FileCallable<Void> {
* private static final long serialVersionUID = 1;
* @Override public Void invoke(File f, VirtualChannel channel) {
* // f and file represent the same thing
* f.deleteContents();
* f.mkdirs();
* return null;
* }
* }
* </pre>
*
* <p>
* When {@link FileCallable} is transferred to a remote node, it will be done so
* by using the same Java serialization scheme that the remoting module uses.
* See {@link Channel} for more about this.
*
* <p>
* {@link FilePath} itself can be sent over to a remote node as a part of {@link Callable}
* serialization. For example, sending a {@link FilePath} of a remote node to that
* node causes {@link FilePath} to become "local". Similarly, sending a
* {@link FilePath} that represents the local computer causes it to become "remote."
*
* @author Kohsuke Kawaguchi
* @see VirtualFile
*/
public final class FilePath implements SerializableOnlyOverRemoting {
/**
* Maximum http redirects we will follow. This defaults to the same number as Firefox/Chrome tolerates.
*/
private static final int MAX_REDIRECTS = 20;
/**
* When this {@link FilePath} represents the remote path,
* this field is always non-null on master (the field represents
* the channel to the remote agent.) When transferred to a agent via remoting,
* this field reverts back to null, since it's transient.
*
* When this {@link FilePath} represents a path on the master,
* this field is null on master. When transferred to a agent via remoting,
* this field becomes non-null, representing the {@link Channel}
* back to the master.
*
* This is used to determine whether we are running on the master or the agent.
*/
private transient VirtualChannel channel;
/**
* Represent the path to the file in the master or the agent
* Since the platform of the agent might be different, can't use java.io.File
*
* The field could not be final since it's modified in {@link #readResolve()}
*/
private /*final*/ String remote;
/**
* If this {@link FilePath} is deserialized to handle file access request from a remote computer,
* this field is set to the filter that performs access control.
*
* <p>
* If null, no access control is needed.
*
* @see #filterNonNull()
*/
private transient @Nullable
SoloFilePathFilter filter;
/**
* Creates a {@link FilePath} that represents a path on the given node.
*
* @param channel
* To create a path that represents a remote path, pass in a {@link Channel}
* that's connected to that machine. If {@code null}, that means the local file path.
*/
public FilePath(@CheckForNull VirtualChannel channel, @Nonnull String remote) {
this.channel = channel instanceof LocalChannel ? null : channel;
this.remote = normalize(remote);
}
/**
* To create {@link FilePath} that represents a "local" path.
*
* <p>
* A "local" path means a file path on the computer where the
* constructor invocation happened.
*/
public FilePath(@Nonnull File localPath) {
this.channel = null;
this.remote = normalize(localPath.getPath());
}
/**
* Construct a path starting with a base location.
* @param base starting point for resolution, and defines channel
* @param rel a path which if relative will be resolved against base
*/
public FilePath(@Nonnull FilePath base, @Nonnull String rel) {
this.channel = base.channel;
this.remote = normalize(resolvePathIfRelative(base, rel));
}
private Object readResolve() {
this.remote = normalize(this.remote);
return this;
}
private String resolvePathIfRelative(@Nonnull FilePath base, @Nonnull String rel) {
if(isAbsolute(rel)) return rel;
if(base.isUnix()) {
// shouldn't need this replace, but better safe than sorry
return base.remote+'/'+rel.replace('\\','/');
} else {
// need this replace, see Slave.getWorkspaceFor and AbstractItem.getFullName, nested jobs on Windows
// agents will always have a rel containing at least one '/' character. JENKINS-13649
return base.remote+'\\'+rel.replace('/','\\');
}
}
/**
* Is the given path name an absolute path?
*/
private static boolean isAbsolute(@Nonnull String rel) {
return rel.startsWith("/") || DRIVE_PATTERN.matcher(rel).matches() || UNC_PATTERN.matcher(rel).matches();
}
private static final Pattern DRIVE_PATTERN = Pattern.compile("[A-Za-z]:[\\\\/].*"),
UNC_PATTERN = Pattern.compile("^\\\\\\\\.*"),
ABSOLUTE_PREFIX_PATTERN = Pattern.compile("^(\\\\\\\\|(?:[A-Za-z]:)?[\\\\/])[\\\\/]*");
/**
* {@link File#getParent()} etc cannot handle ".." and "." in the path component very well,
* so remove them.
*/
@Restricted(NoExternalUse.class)
public static String normalize(@Nonnull String path) {
StringBuilder buf = new StringBuilder();
// Check for prefix designating absolute path
Matcher m = ABSOLUTE_PREFIX_PATTERN.matcher(path);
if (m.find()) {
buf.append(m.group(1));
path = path.substring(m.end());
}
boolean isAbsolute = buf.length() > 0;
// Split remaining path into tokens, trimming any duplicate or trailing separators
List<String> tokens = new ArrayList<>();
int s = 0, end = path.length();
for (int i = 0; i < end; i++) {
char c = path.charAt(i);
if (c == '/' || c == '\\') {
tokens.add(path.substring(s, i));
s = i;
// Skip any extra separator chars
//noinspection StatementWithEmptyBody
while (++i < end && ((c = path.charAt(i)) == '/' || c == '\\'))
;
// Add token for separator unless we reached the end
if (i < end) tokens.add(path.substring(s, s+1));
s = i;
}
}
if (s < end) tokens.add(path.substring(s));
// Look through tokens for "." or ".."
for (int i = 0; i < tokens.size();) {
String token = tokens.get(i);
if (token.equals(".")) {
tokens.remove(i);
if (tokens.size() > 0)
tokens.remove(i > 0 ? i - 1 : i);
} else if (token.equals("..")) {
if (i == 0) {
// If absolute path, just remove: /../something
// If relative path, not collapsible so leave as-is
tokens.remove(0);
if (tokens.size() > 0) token += tokens.remove(0);
if (!isAbsolute) buf.append(token);
} else {
// Normalize: remove something/.. plus separator before/after
i -= 2;
for (int j = 0; j < 3; j++) tokens.remove(i);
if (i > 0) tokens.remove(i-1);
else if (tokens.size() > 0) tokens.remove(0);
}
} else
i += 2;
}
// Recombine tokens
for (String token : tokens) buf.append(token);
if (buf.length() == 0) buf.append('.');
return buf.toString();
}
/**
* Checks if the remote path is Unix.
*/
boolean isUnix() {
// if the path represents a local path, there' no need to guess.
if(!isRemote())
return File.pathSeparatorChar!=';';
// note that we can't use the usual File.pathSeparator and etc., as the OS of
// the machine where this code runs and the OS that this FilePath refers to may be different.
// Windows absolute path is 'X:\...', so this is usually a good indication of Windows path
if(remote.length()>3 && remote.charAt(1)==':' && remote.charAt(2)=='\\')
return false;
// Windows can handle '/' as a path separator but Unix can't,
// so err on Unix side
return !remote.contains("\\");
}
/**
* Gets the full path of the file on the remote machine.
*
*/
public String getRemote() {
return remote;
}
/**
* Creates a zip file from this directory or a file and sends that to the given output stream.
*
* @deprecated as of 1.315. Use {@link #zip(OutputStream)} that has more consistent name.
*/
@Deprecated
public void createZipArchive(OutputStream os) throws IOException, InterruptedException {
zip(os);
}
/**
* Creates a zip file from this directory or a file and sends that to the given output stream.
*/
public void zip(OutputStream os) throws IOException, InterruptedException {
zip(os,(FileFilter)null);
}
public void zip(FilePath dst) throws IOException, InterruptedException {
try (OutputStream os = dst.write()) {
zip(os);
}
}
/**
* Creates a zip file from this directory by using the specified filter,
* and sends the result to the given output stream.
*
* @param filter
* Must be serializable since it may be executed remotely. Can be null to add all files.
*
* @since 1.315
*/
public void zip(OutputStream os, FileFilter filter) throws IOException, InterruptedException {
archive(ArchiverFactory.ZIP,os,filter);
}
/**
* Creates a zip file from this directory by only including the files that match the given glob.
*
* @param glob
* Ant style glob, like "**/*.xml". If empty or null, this method
* works like {@link #createZipArchive(OutputStream)}
*
* @since 1.129
* @deprecated as of 1.315
* Use {@link #zip(OutputStream,String)} that has more consistent name.
*/
@Deprecated
public void createZipArchive(OutputStream os, final String glob) throws IOException, InterruptedException {
archive(ArchiverFactory.ZIP,os,glob);
}
/**
* Creates a zip file from this directory by only including the files that match the given glob.
*
* @param glob
* Ant style glob, like "**/*.xml". If empty or null, this method
* works like {@link #createZipArchive(OutputStream)}, inserting a top-level directory into the ZIP.
*
* @since 1.315
*/
public void zip(OutputStream os, final String glob) throws IOException, InterruptedException {
archive(ArchiverFactory.ZIP,os,glob);
}
/**
* Uses the given scanner on 'this' directory to list up files and then archive it to a zip stream.
*/
public int zip(OutputStream out, DirScanner scanner) throws IOException, InterruptedException {
return archive(ArchiverFactory.ZIP, out, scanner);
}
/**
* Archives this directory into the specified archive format, to the given {@link OutputStream}, by using
* {@link DirScanner} to choose what files to include.
*
* @return
* number of files/directories archived. This is only really useful to check for a situation where nothing
* is archived.
*/
public int archive(final ArchiverFactory factory, OutputStream os, final DirScanner scanner) throws IOException, InterruptedException {
final OutputStream out = (channel!=null)?new RemoteOutputStream(os):os;
return act(new Archive(factory, out, scanner));
}
private class Archive extends SecureFileCallable<Integer> {
private final ArchiverFactory factory;
private final OutputStream out;
private final DirScanner scanner;
Archive(ArchiverFactory factory, OutputStream out, DirScanner scanner) {
this.factory = factory;
this.out = out;
this.scanner = scanner;
}
@Override
public Integer invoke(File f, VirtualChannel channel) throws IOException {
Archiver a = factory.create(out);
try {
scanner.scan(f,reading(a));
} finally {
a.close();
}
return a.countEntries();
}
private static final long serialVersionUID = 1L;
}
public int archive(final ArchiverFactory factory, OutputStream os, final FileFilter filter) throws IOException, InterruptedException {
return archive(factory,os,new DirScanner.Filter(filter));
}
public int archive(final ArchiverFactory factory, OutputStream os, final String glob) throws IOException, InterruptedException {
return archive(factory,os,new DirScanner.Glob(glob,null));
}
/**
* When this {@link FilePath} represents a zip file, extracts that zip file.
*
* @param target
* Target directory to expand files to. All the necessary directories will be created.
* @since 1.248
* @see #unzipFrom(InputStream)
*/
public void unzip(final FilePath target) throws IOException, InterruptedException {
// TODO: post release, re-unite two branches by introducing FileStreamCallable that resolves InputStream
if (this.channel!=target.channel) {// local -> remote or remote->local
final RemoteInputStream in = new RemoteInputStream(read(), Flag.GREEDY);
target.act(new UnzipRemote(in));
} else {// local -> local or remote->remote
target.act(new UnzipLocal());
}
}
private class UnzipRemote extends SecureFileCallable<Void> {
private final RemoteInputStream in;
UnzipRemote(RemoteInputStream in) {
this.in = in;
}
@Override
public Void invoke(File dir, VirtualChannel channel) throws IOException, InterruptedException {
unzip(dir, in);
return null;
}
private static final long serialVersionUID = 1L;
}
private class UnzipLocal extends SecureFileCallable<Void> {
@Override
public Void invoke(File dir, VirtualChannel channel) throws IOException, InterruptedException {
assert !FilePath.this.isRemote(); // this.channel==target.channel above
unzip(dir, reading(new File(FilePath.this.getRemote()))); // shortcut to local file
return null;
}
private static final long serialVersionUID = 1L;
}
/**
* When this {@link FilePath} represents a tar file, extracts that tar file.
*
* @param target
* Target directory to expand files to. All the necessary directories will be created.
* @param compression
* Compression mode of this tar file.
* @since 1.292
* @see #untarFrom(InputStream, TarCompression)
*/
public void untar(final FilePath target, final TarCompression compression) throws IOException, InterruptedException {
// TODO: post release, re-unite two branches by introducing FileStreamCallable that resolves InputStream
if (this.channel!=target.channel) {// local -> remote or remote->local
final RemoteInputStream in = new RemoteInputStream(read(), Flag.GREEDY);
target.act(new UntarRemote(compression, in));
} else {// local -> local or remote->remote
target.act(new UntarLocal(compression));
}
}
private class UntarRemote extends SecureFileCallable<Void> {
private final TarCompression compression;
private final RemoteInputStream in;
UntarRemote(TarCompression compression, RemoteInputStream in) {
this.compression = compression;
this.in = in;
}
@Override
public Void invoke(File dir, VirtualChannel channel) throws IOException, InterruptedException {
readFromTar(FilePath.this.getName(), dir, compression.extract(in));
return null;
}
private static final long serialVersionUID = 1L;
}
private class UntarLocal extends SecureFileCallable<Void> {
private final TarCompression compression;
UntarLocal(TarCompression compression) {
this.compression = compression;
}
@Override
public Void invoke(File dir, VirtualChannel channel) throws IOException, InterruptedException {
readFromTar(FilePath.this.getName(), dir, compression.extract(FilePath.this.read()));
return null;
}
private static final long serialVersionUID = 1L;
}
/**
* Reads the given InputStream as a zip file and extracts it into this directory.
*
* @param _in
* The stream will be closed by this method after it's fully read.
* @since 1.283
* @see #unzip(FilePath)
*/
public void unzipFrom(InputStream _in) throws IOException, InterruptedException {
final InputStream in = new RemoteInputStream(_in, Flag.GREEDY);
act(new UnzipFrom(in));
}
private class UnzipFrom extends SecureFileCallable<Void> {
private final InputStream in;
UnzipFrom(InputStream in) {
this.in = in;
}
@Override
public Void invoke(File dir, VirtualChannel channel) throws IOException {
unzip(dir, in);
return null;
}
private static final long serialVersionUID = 1L;
}
private void unzip(File dir, InputStream in) throws IOException {
File tmpFile = File.createTempFile("tmpzip", null); // uses java.io.tmpdir
try {
// TODO why does this not simply use ZipInputStream?
IOUtils.copy(in, tmpFile);
unzip(dir,tmpFile);
}
finally {
tmpFile.delete();
}
}
private void unzip(File dir, File zipFile) throws IOException {
dir = dir.getAbsoluteFile(); // without absolutization, getParentFile below seems to fail
ZipFile zip = new ZipFile(zipFile);
Enumeration<ZipEntry> entries = zip.getEntries();
try {
while (entries.hasMoreElements()) {
ZipEntry e = entries.nextElement();
File f = new File(dir, e.getName());
if (!f.getCanonicalPath().startsWith(dir.getCanonicalPath())) {
throw new IOException(
"Zip " + zipFile.getPath() + " contains illegal file name that breaks out of the target directory: " + e.getName());
}
if (e.isDirectory()) {
mkdirs(f);
} else {
File p = f.getParentFile();
if (p != null) {
mkdirs(p);
}
try (InputStream input = zip.getInputStream(e)) {
IOUtils.copy(input, writing(f));
}
try {
FilePath target = new FilePath(f);
int mode = e.getUnixMode();
if (mode!=0) // Ant returns 0 if the archive doesn't record the access mode
target.chmod(mode);
} catch (InterruptedException ex) {
LOGGER.log(Level.WARNING, "unable to set permissions", ex);
}
f.setLastModified(e.getTime());
}
}
} finally {
zip.close();
}
}
/**
* Absolutizes this {@link FilePath} and returns the new one.
*/
public FilePath absolutize() throws IOException, InterruptedException {
return new FilePath(channel, act(new Absolutize()));
}
private static class Absolutize extends SecureFileCallable<String> {
private static final long serialVersionUID = 1L;
public String invoke(File f, VirtualChannel channel) throws IOException {
return f.getAbsolutePath();
}
}
/**
* Creates a symlink to the specified target.
*
* @param target
* The file that the symlink should point to.
* @param listener
* If symlink creation requires a help of an external process, the error will be reported here.
* @since 1.456
*/
public void symlinkTo(final String target, final TaskListener listener) throws IOException, InterruptedException {
act(new SymlinkTo(target, listener));
}
private class SymlinkTo extends SecureFileCallable<Void> {
private final String target;
private final TaskListener listener;
SymlinkTo(String target, TaskListener listener) {
this.target = target;
this.listener = listener;
}
private static final long serialVersionUID = 1L;
@Override
public Void invoke(File f, VirtualChannel channel) throws IOException, InterruptedException {
symlinking(f);
Util.createSymlink(f.getParentFile(), target, f.getName(), listener);
return null;
}
}
/**
* Resolves symlink, if the given file is a symlink. Otherwise return null.
* <p>
* If the resolution fails, report an error.
*
* @since 1.456
*/
public String readLink() throws IOException, InterruptedException {
return act(new ReadLink());
}
private class ReadLink extends SecureFileCallable<String> {
private static final long serialVersionUID = 1L;
@Override
public String invoke(File f, VirtualChannel channel) throws IOException, InterruptedException {
return Util.resolveSymlink(reading(f));
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
FilePath that = (FilePath) o;
if (channel != null ? !channel.equals(that.channel) : that.channel != null) return false;
return remote.equals(that.remote);
}
@Override
public int hashCode() {
return 31 * (channel != null ? channel.hashCode() : 0) + remote.hashCode();
}
/**
* Supported tar file compression methods.
*/
public enum TarCompression {
NONE {
public InputStream extract(InputStream in) {
return in;
}
public OutputStream compress(OutputStream out) {
return out;
}
},
GZIP {
public InputStream extract(InputStream _in) throws IOException {
HeadBufferingStream in = new HeadBufferingStream(_in,SIDE_BUFFER_SIZE);
try {
return new GZIPInputStream(in, 8192, true);
} catch (IOException e) {
// various people reported "java.io.IOException: Not in GZIP format" here, so diagnose this problem better
in.fillSide();
throw new IOException(e.getMessage()+"\nstream="+Util.toHexString(in.getSideBuffer()),e);
}
}
public OutputStream compress(OutputStream out) throws IOException {
return new GZIPOutputStream(new BufferedOutputStream(out));
}
};
public abstract InputStream extract(InputStream in) throws IOException;
public abstract OutputStream compress(OutputStream in) throws IOException;
}
/**
* Reads the given InputStream as a tar file and extracts it into this directory.
*
* @param _in
* The stream will be closed by this method after it's fully read.
* @param compression
* The compression method in use.
* @since 1.292
*/
public void untarFrom(InputStream _in, final TarCompression compression) throws IOException, InterruptedException {
try {
final InputStream in = new RemoteInputStream(_in, Flag.GREEDY);
act(new UntarFrom(compression, in));
} finally {
_in.close();
}
}
private class UntarFrom extends SecureFileCallable<Void> {
private final TarCompression compression;
private final InputStream in;
UntarFrom(TarCompression compression, InputStream in) {
this.compression = compression;
this.in = in;
}
@Override
public Void invoke(File dir, VirtualChannel channel) throws IOException {
readFromTar("input stream",dir, compression.extract(in));
return null;
}
private static final long serialVersionUID = 1L;
}
/**
* Given a tgz/zip file, extracts it to the given target directory, if necessary.
*
* <p>
* This method is a convenience method designed for installing a binary package to a location
* that supports upgrade and downgrade. Specifically,
*
* <ul>
* <li>If the target directory doesn't exist {@linkplain #mkdirs() it will be created}.
* <li>The timestamp of the archive is left in the installation directory upon extraction.
* <li>If the timestamp left in the directory does not match the timestamp of the current archive file,
* the directory contents will be discarded and the archive file will be re-extracted.
* <li>If the connection is refused but the target directory already exists, it is left alone.
* </ul>
*
* @param archive
* The resource that represents the tgz/zip file. This URL must support the {@code Last-Modified} header.
* (For example, you could use {@link ClassLoader#getResource}.)
* @param listener
* If non-null, a message will be printed to this listener once this method decides to
* extract an archive, or if there is any issue.
* @param message a message to be printed in case extraction will proceed.
* @return
* true if the archive was extracted. false if the extraction was skipped because the target directory
* was considered up to date.
* @since 1.299
*/
public boolean installIfNecessaryFrom(@Nonnull URL archive, @CheckForNull TaskListener listener, @Nonnull String message) throws IOException, InterruptedException {
return installIfNecessaryFrom(archive, listener, message, MAX_REDIRECTS);
}
private boolean installIfNecessaryFrom(@Nonnull URL archive, @CheckForNull TaskListener listener, @Nonnull String message, int maxRedirects) throws InterruptedException, IOException {
try {
FilePath timestamp = this.child(".timestamp");
long lastModified = timestamp.lastModified();
URLConnection con;
try {
con = ProxyConfiguration.open(archive);
if (lastModified != 0) {
con.setIfModifiedSince(lastModified);
}
con.connect();
} catch (IOException x) {
if (this.exists()) {
// Cannot connect now, so assume whatever was last unpacked is still OK.
if (listener != null) {
listener.getLogger().println("Skipping installation of " + archive + " to " + remote + ": " + x);
}
return false;
} else {
throw x;
}
}
if (con instanceof HttpURLConnection) {
HttpURLConnection httpCon = (HttpURLConnection) con;
int responseCode = httpCon.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_MOVED_PERM
|| responseCode == HttpURLConnection.HTTP_MOVED_TEMP) {
// follows redirect
if (maxRedirects > 0) {
String location = httpCon.getHeaderField("Location");
listener.getLogger().println("Following redirect " + archive.toExternalForm() + " -> " + location);
return installIfNecessaryFrom(getUrlFactory().newURL(location), listener, message, maxRedirects - 1);
} else {
listener.getLogger().println("Skipping installation of " + archive + " to " + remote + " due to too many redirects.");
return false;
}
}
if (lastModified != 0) {
if (responseCode == HttpURLConnection.HTTP_NOT_MODIFIED) {
return false;
} else if (responseCode != HttpURLConnection.HTTP_OK) {
listener.getLogger().println("Skipping installation of " + archive + " to " + remote + " due to server error: " + responseCode + " " + httpCon.getResponseMessage());
return false;
}
}
}
long sourceTimestamp = con.getLastModified();
if(this.exists()) {
if (lastModified != 0 && sourceTimestamp == lastModified)
return false; // already up to date
this.deleteContents();
} else {
this.mkdirs();
}
if(listener!=null)
listener.getLogger().println(message);
if (isRemote()) {
// First try to download from the agent machine.
try {
act(new Unpack(archive));
timestamp.touch(sourceTimestamp);
return true;
} catch (IOException x) {
if (listener != null) {
Functions.printStackTrace(x, listener.error("Failed to download " + archive + " from agent; will retry from master"));
}
}
}
// for HTTP downloads, enable automatic retry for added resilience
InputStream in = archive.getProtocol().startsWith("http") ? ProxyConfiguration.getInputStream(archive) : con.getInputStream();
CountingInputStream cis = new CountingInputStream(in);
try {
if(archive.toExternalForm().endsWith(".zip"))
unzipFrom(cis);
else
untarFrom(cis,GZIP);
} catch (IOException e) {
throw new IOException(String.format("Failed to unpack %s (%d bytes read of total %d)",
archive,cis.getByteCount(),con.getContentLength()),e);
}
timestamp.touch(sourceTimestamp);
return true;
} catch (IOException e) {
throw new IOException("Failed to install "+archive+" to "+remote,e);
}
}
// this reads from arbitrary URL
private final class Unpack extends MasterToSlaveFileCallable<Void> {
private final URL archive;
Unpack(URL archive) {
this.archive = archive;
}
@Override public Void invoke(File dir, VirtualChannel channel) throws IOException, InterruptedException {
try (InputStream in = archive.openStream()) {
CountingInputStream cis = new CountingInputStream(in);
try {
if (archive.toExternalForm().endsWith(".zip")) {
unzip(dir, cis);
} else {
readFromTar("input stream", dir, GZIP.extract(cis));
}
} catch (IOException x) {
throw new IOException(String.format("Failed to unpack %s (%d bytes read)", archive, cis.getByteCount()), x);
}
}
return null;
}
}
/**
* Reads the URL on the current VM, and streams the data to this file using the Remoting channel.
* <p>This is different from resolving URL remotely.
* If you instead wished to open an HTTP(S) URL on the remote side,
* prefer <a href="http://javadoc.jenkins.io/plugin/apache-httpcomponents-client-4-api/io/jenkins/plugins/httpclient/RobustHTTPClient.html#copyFromRemotely-hudson.FilePath-java.net.URL-hudson.model.TaskListener-">{@code RobustHTTPClient.copyFromRemotely}</a>.
* @since 1.293
*/
public void copyFrom(URL url) throws IOException, InterruptedException {
try (InputStream in = url.openStream()) {
copyFrom(in);
}
}
/**
* Replaces the content of this file by the data from the given {@link InputStream}.
*
* @since 1.293
*/
public void copyFrom(InputStream in) throws IOException, InterruptedException {
try (OutputStream os = write()) {
org.apache.commons.io.IOUtils.copy(in, os);
}
}
/**
* Convenience method to call {@link FilePath#copyTo(FilePath)}.
*
* @since 1.311
*/
public void copyFrom(FilePath src) throws IOException, InterruptedException {
src.copyTo(this);
}
/**
* Place the data from {@link FileItem} into the file location specified by this {@link FilePath} object.
*/
public void copyFrom(FileItem file) throws IOException, InterruptedException {
if(channel==null) {
try {
file.write(writing(new File(remote)));
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw new IOException(e);
}
} else {
try (InputStream i = file.getInputStream();
OutputStream o = write()) {
org.apache.commons.io.IOUtils.copy(i,o);
}
}
}
/**
* Code that gets executed on the machine where the {@link FilePath} is local.
* Used to act on {@link FilePath}.
* <strong>Warning:</strong> implementations must be serializable, so prefer a static nested class to an inner class.
*
* <p>
* Subtypes would likely want to extend from either {@link MasterToSlaveCallable}
* or {@link SlaveToMasterFileCallable}.
*
* @see FilePath#act(FileCallable)
*/
public interface FileCallable<T> extends Serializable, RoleSensitive {
/**
* Performs the computational task on the node where the data is located.
*
* <p>
* All the exceptions are forwarded to the caller.
*
* @param f
* {@link File} that represents the local file that {@link FilePath} has represented.
* @param channel
* The "back pointer" of the {@link Channel} that represents the communication
* with the node from where the code was sent.
*/
T invoke(File f, VirtualChannel channel) throws IOException, InterruptedException;
}
/**
* {@link FileCallable}s that can be executed anywhere, including the master.
*
* The code is the same as {@link SlaveToMasterFileCallable}, but used as a marker to
* designate those impls that use {@link FilePathFilter}.
*/
/*package*/ static abstract class SecureFileCallable<T> extends SlaveToMasterFileCallable<T> {
}
/**
* Executes some program on the machine that this {@link FilePath} exists,
* so that one can perform local file operations.
*/
public <T> T act(final FileCallable<T> callable) throws IOException, InterruptedException {
return act(callable,callable.getClass().getClassLoader());
}
private <T> T act(final FileCallable<T> callable, ClassLoader cl) throws IOException, InterruptedException {
if(channel!=null) {
// run this on a remote system
try {
DelegatingCallable<T,IOException> wrapper = new FileCallableWrapper<>(callable, cl);
for (FileCallableWrapperFactory factory : ExtensionList.lookup(FileCallableWrapperFactory.class)) {
wrapper = factory.wrap(wrapper);
}
return channel.call(wrapper);
} catch (TunneledInterruptedException e) {
throw (InterruptedException)new InterruptedException(e.getMessage()).initCause(e);
}
} else {
// the file is on the local machine.
return callable.invoke(new File(remote), localChannel);
}
}
/**
* This extension point allows to contribute a wrapper around a fileCallable so that a plugin can "intercept" a
* call.
* <p>The {@link #wrap(hudson.remoting.DelegatingCallable)} method itself will be executed on master
* (and may collect contextual data if needed) and the returned wrapper will be executed on remote.
*
* @since 1.482
* @see AbstractInterceptorCallableWrapper
*/
public static abstract class FileCallableWrapperFactory implements ExtensionPoint {
public abstract <T> DelegatingCallable<T,IOException> wrap(DelegatingCallable<T,IOException> callable);
}
/**
* Abstract {@link DelegatingCallable} that exposes an Before/After pattern for
* {@link hudson.FilePath.FileCallableWrapperFactory} that want to implement AOP-style interceptors
* @since 1.482
*/
public static abstract class AbstractInterceptorCallableWrapper<T> implements DelegatingCallable<T, IOException> {
private static final long serialVersionUID = 1L;
private final DelegatingCallable<T, IOException> callable;
public AbstractInterceptorCallableWrapper(DelegatingCallable<T, IOException> callable) {
this.callable = callable;
}
@Override
public final ClassLoader getClassLoader() {
return callable.getClassLoader();
}
public final T call() throws IOException {
before();
try {
return callable.call();
} finally {
after();
}
}
/**
* Executed before the actual FileCallable is invoked. This code will run on remote
*/
protected void before() {}
/**
* Executed after the actual FileCallable is invoked (even if this one failed). This code will run on remote
*/
protected void after() {}
}
/**
* Executes some program on the machine that this {@link FilePath} exists,
* so that one can perform local file operations.
*/
public <T> Future<T> actAsync(final FileCallable<T> callable) throws IOException, InterruptedException {
try {
DelegatingCallable<T,IOException> wrapper = new FileCallableWrapper<>(callable);
for (FileCallableWrapperFactory factory : ExtensionList.lookup(FileCallableWrapperFactory.class)) {
wrapper = factory.wrap(wrapper);
}
return (channel!=null ? channel : localChannel)
.callAsync(wrapper);
} catch (IOException e) {
// wrap it into a new IOException so that we get the caller's stack trace as well.
throw new IOException("remote file operation failed",e);
}
}
/**
* Executes some program on the machine that this {@link FilePath} exists,
* so that one can perform local file operations.
*/
public <V,E extends Throwable> V act(Callable<V,E> callable) throws IOException, InterruptedException, E {
if(channel!=null) {
// run this on a remote system
return channel.call(callable);
} else {
// the file is on the local machine
return callable.call();
}
}
/**
* Takes a {@link FilePath}+{@link FileCallable} pair and returns the equivalent {@link Callable}.
* When executing the resulting {@link Callable}, it executes {@link FileCallable#act(FileCallable)}
* on this {@link FilePath}.
*
* @since 1.522
*/
public <V> Callable<V,IOException> asCallableWith(final FileCallable<V> task) {
return new CallableWith<>(task);
}
private class CallableWith<V> implements Callable<V, IOException> {
private final FileCallable<V> task;
CallableWith(FileCallable<V> task) {
this.task = task;
}
@Override
public V call() throws IOException {
try {
return act(task);
} catch (InterruptedException e) {
throw (IOException)new InterruptedIOException().initCause(e);
}
}
@Override
public void checkRoles(RoleChecker checker) throws SecurityException {
task.checkRoles(checker);
}
private static final long serialVersionUID = 1L;
}
/**
* Converts this file to the URI, relative to the machine
* on which this file is available.
*/
public URI toURI() throws IOException, InterruptedException {
return act(new ToURI());
}
private static class ToURI extends SecureFileCallable<URI> {
private static final long serialVersionUID = 1L;
@Override
public URI invoke(File f, VirtualChannel channel) {
return f.toURI();
}
}
/**
* Gets the {@link VirtualFile} representation of this {@link FilePath}
*
* @since 1.532
*/
public VirtualFile toVirtualFile() {
return VirtualFile.forFilePath(this);
}
/**
* If this {@link FilePath} represents a file on a particular {@link Computer}, return it.
* Otherwise null.
* @since 1.571
*/
public @CheckForNull Computer toComputer() {
Jenkins j = Jenkins.getInstanceOrNull();
if (j != null) {
for (Computer c : j.getComputers()) {
if (getChannel()==c.getChannel()) {
return c;
}
}
}
return null;
}
/**
* Creates this directory.
*/
public void mkdirs() throws IOException, InterruptedException {
if (!act(new Mkdirs())) {
throw new IOException("Failed to mkdirs: " + remote);
}
}
private class Mkdirs extends SecureFileCallable<Boolean> {
private static final long serialVersionUID = 1L;
@Override
public Boolean invoke(File f, VirtualChannel channel) throws IOException, InterruptedException {
if(mkdirs(f) || f.exists())
return true; // OK
// following Ant <mkdir> task to avoid possible race condition.
Thread.sleep(10);
return mkdirs(f) || f.exists();
}
}
/**
* Deletes this directory, including all its contents recursively.
*/
public void deleteRecursive() throws IOException, InterruptedException {
act(new DeleteRecursive());
}
private class DeleteRecursive extends SecureFileCallable<Void> {
private static final long serialVersionUID = 1L;
@Override
public Void invoke(File f, VirtualChannel channel) throws IOException {
Util.deleteRecursive(fileToPath(f), path -> deleting(path.toFile()));
return null;
}
}
/**
* Deletes all the contents of this directory, but not the directory itself
*/
public void deleteContents() throws IOException, InterruptedException {
act(new DeleteContents());
}
private class DeleteContents extends SecureFileCallable<Void> {
private static final long serialVersionUID = 1L;
@Override
public Void invoke(File f, VirtualChannel channel) throws IOException {
Util.deleteContentsRecursive(fileToPath(f), path -> deleting(path.toFile()));
return null;
}
}
/**
* Gets the file name portion except the extension.
*
* For example, "foo" for "foo.txt" and "foo.tar" for "foo.tar.gz".
*/
public String getBaseName() {
String n = getName();
int idx = n.lastIndexOf('.');
if (idx<0) return n;
return n.substring(0,idx);
}
/**
* Gets just the file name portion without directories.
*
* For example, "foo.txt" for "../abc/foo.txt"
*/
public String getName() {
String r = remote;
if(r.endsWith("\\") || r.endsWith("/"))
r = r.substring(0,r.length()-1);
int len = r.length()-1;
while(len>=0) {
char ch = r.charAt(len);
if(ch=='\\' || ch=='/')
break;
len--;
}
return r.substring(len+1);
}
/**
* Short for {@code getParent().child(rel)}. Useful for getting other files in the same directory.
*/
public FilePath sibling(String rel) {
return getParent().child(rel);
}
/**
* Returns a {@link FilePath} by adding the given suffix to this path name.
*/
public FilePath withSuffix(String suffix) {
return new FilePath(channel,remote+suffix);
}
/**
* The same as {@link FilePath#FilePath(FilePath,String)} but more OO.
* @param relOrAbsolute a relative or absolute path
* @return a file on the same channel
*/
public @Nonnull FilePath child(String relOrAbsolute) {
return new FilePath(this,relOrAbsolute);
}
/**
* Gets the parent file.
* @return parent FilePath or null if there is no parent
*/
public FilePath getParent() {
int i = remote.length() - 2;
for (; i >= 0; i--) {
char ch = remote.charAt(i);
if(ch=='\\' || ch=='/')
break;
}
return i >= 0 ? new FilePath( channel, remote.substring(0,i+1) ) : null;
}
/**
* Creates a temporary file in the directory that this {@link FilePath} object designates.
*
* @param prefix
* The prefix string to be used in generating the file's name; must be
* at least three characters long
* @param suffix
* The suffix string to be used in generating the file's name; may be
* null, in which case the suffix ".tmp" will be used
* @return
* The new FilePath pointing to the temporary file
* @see File#createTempFile(String, String)
*/
public FilePath createTempFile(final String prefix, final String suffix) throws IOException, InterruptedException {
try {
return new FilePath(this, act(new CreateTempFile(prefix, suffix)));
} catch (IOException e) {
throw new IOException("Failed to create a temp file on "+remote,e);
}
}
private class CreateTempFile extends SecureFileCallable<String> {
private final String prefix;
private final String suffix;
CreateTempFile(String prefix, String suffix) {
this.prefix = prefix;
this.suffix = suffix;
}
private static final long serialVersionUID = 1L;
@Override
public String invoke(File dir, VirtualChannel channel) throws IOException {
File f = writing(File.createTempFile(prefix, suffix, dir));
return f.getName();
}
}
/**
* Creates a temporary file in this directory and set the contents to the
* given text (encoded in the platform default encoding)
*
* @param prefix
* The prefix string to be used in generating the file's name; must be
* at least three characters long
* @param suffix
* The suffix string to be used in generating the file's name; may be
* null, in which case the suffix ".tmp" will be used
* @param contents
* The initial contents of the temporary file.
* @return
* The new FilePath pointing to the temporary file
* @see File#createTempFile(String, String)
*/
public FilePath createTextTempFile(final String prefix, final String suffix, final String contents) throws IOException, InterruptedException {
return createTextTempFile(prefix,suffix,contents,true);
}
/**
* Creates a temporary file in this directory (or the system temporary
* directory) and set the contents to the given text (encoded in the
* platform default encoding)
*
* @param prefix
* The prefix string to be used in generating the file's name; must be
* at least three characters long
* @param suffix
* The suffix string to be used in generating the file's name; may be
* null, in which case the suffix ".tmp" will be used
* @param contents
* The initial contents of the temporary file.
* @param inThisDirectory
* If true, then create this temporary in the directory pointed to by
* this.
* If false, then the temporary file is created in the system temporary
* directory (java.io.tmpdir)
* @return
* The new FilePath pointing to the temporary file
* @see File#createTempFile(String, String)
*/
public FilePath createTextTempFile(final String prefix, final String suffix, final String contents, final boolean inThisDirectory) throws IOException, InterruptedException {
try {
return new FilePath(channel, act(new CreateTextTempFile(inThisDirectory, prefix, suffix, contents)));
} catch (IOException e) {
throw new IOException("Failed to create a temp file on "+remote,e);
}
}
private final class CreateTextTempFile extends SecureFileCallable<String> {
private static final long serialVersionUID = 1L;
private final boolean inThisDirectory;
private final String prefix;
private final String suffix;
private final String contents;
CreateTextTempFile(boolean inThisDirectory, String prefix, String suffix, String contents) {
this.inThisDirectory = inThisDirectory;
this.prefix = prefix;
this.suffix = suffix;
this.contents = contents;
}
@Override
public String invoke(File dir, VirtualChannel channel) throws IOException {
if(!inThisDirectory)
dir = new File(System.getProperty("java.io.tmpdir"));
else
mkdirs(dir);
File f;
try {
f = creating(File.createTempFile(prefix, suffix, dir));
} catch (IOException e) {
throw new IOException("Failed to create a temporary directory in "+dir,e);
}
try (Writer w = new FileWriter(writing(f))) {
w.write(contents);
}
return f.getAbsolutePath();
}
}
/**
* Creates a temporary directory inside the directory represented by 'this'
*
* @param prefix
* The prefix string to be used in generating the directory's name;
* must be at least three characters long
* @param suffix
* The suffix string to be used in generating the directory's name; may
* be null, in which case the suffix ".tmp" will be used
* @return
* The new FilePath pointing to the temporary directory
* @since 1.311
* @see Files#createTempDirectory(Path, String, FileAttribute[])
*/
public FilePath createTempDir(final String prefix, final String suffix) throws IOException, InterruptedException {
try {
String[] s;
if (StringUtils.isBlank(suffix)) {
s = new String[]{prefix, "tmp"}; // see File.createTempFile - tmp is used if suffix is null
} else {
s = new String[]{prefix, suffix};
}
String name = StringUtils.join(s, ".");
return new FilePath(this, act(new CreateTempDir(name)));
} catch (IOException e) {
throw new IOException("Failed to create a temp directory on "+remote,e);
}
}
private class CreateTempDir extends SecureFileCallable<String> {
private final String name;
CreateTempDir(String name) {
this.name = name;
}
private static final long serialVersionUID = 1L;
@Override
public String invoke(File dir, VirtualChannel channel) throws IOException {
Path tempPath;
final boolean isPosix = FileSystems.getDefault().supportedFileAttributeViews().contains("posix");
if (isPosix) {
tempPath = Files.createTempDirectory(Util.fileToPath(dir), name,
PosixFilePermissions.asFileAttribute(EnumSet.allOf(PosixFilePermission.class)));
} else {
tempPath = Files.createTempDirectory(Util.fileToPath(dir), name, new FileAttribute<?>[] {});
}
if (tempPath.toFile() == null) {
throw new IOException("Failed to obtain file from path " + dir + " on " + remote);
}
return tempPath.toFile().getName();
}
}
/**
* Deletes this file.
* @throws IOException if it exists but could not be successfully deleted
* @return true, for a modicum of compatibility
*/
public boolean delete() throws IOException, InterruptedException {
act(new Delete());
return true;
}
private class Delete extends SecureFileCallable<Void> {
private static final long serialVersionUID = 1L;
@Override
public Void invoke(File f, VirtualChannel channel) throws IOException {
Util.deleteFile(deleting(f));
return null;
}
}
/**
* Checks if the file exists.
*/
public boolean exists() throws IOException, InterruptedException {
return act(new Exists());
}
private class Exists extends SecureFileCallable<Boolean> {
private static final long serialVersionUID = 1L;
@Override
public Boolean invoke(File f, VirtualChannel channel) throws IOException {
return stating(f).exists();
}
}
/**
* Gets the last modified time stamp of this file, by using the clock
* of the machine where this file actually resides.
*
* @see File#lastModified()
* @see #touch(long)
*/
public long lastModified() throws IOException, InterruptedException {
return act(new LastModified());
}
private class LastModified extends SecureFileCallable<Long> {
private static final long serialVersionUID = 1L;
@Override
public Long invoke(File f, VirtualChannel channel) throws IOException {
return stating(f).lastModified();
}
}
/**
* Creates a file (if not already exist) and sets the timestamp.
*
* @since 1.299
*/
public void touch(final long timestamp) throws IOException, InterruptedException {
act(new Touch(timestamp));
}
private class Touch extends SecureFileCallable<Void> {
private final long timestamp;
Touch(long timestamp) {
this.timestamp = timestamp;
}
private static final long serialVersionUID = -5094638816500738429L;
@Override
public Void invoke(File f, VirtualChannel channel) throws IOException {
if(!f.exists()) {
Files.newOutputStream(fileToPath(creating(f))).close();
}
if(!stating(f).setLastModified(timestamp))
throw new IOException("Failed to set the timestamp of "+f+" to "+timestamp);
return null;
}
}
private void setLastModifiedIfPossible(final long timestamp) throws IOException, InterruptedException {
String message = act(new SetLastModified(timestamp));
if (message!=null) {
LOGGER.warning(message);
}
}
private class SetLastModified extends SecureFileCallable<String> {
private final long timestamp;
SetLastModified(long timestamp) {
this.timestamp = timestamp;
}
private static final long serialVersionUID = -828220335793641630L;
@Override
public String invoke(File f, VirtualChannel channel) throws IOException {
if(!writing(f).setLastModified(timestamp)) {
if (Functions.isWindows()) {
// On Windows this seems to fail often. See JENKINS-11073
// Therefore don't fail, but just log a warning
return "Failed to set the timestamp of "+f+" to "+timestamp;
} else {
throw new IOException("Failed to set the timestamp of "+f+" to "+timestamp);
}
}
return null;
}
}
/**
* Checks if the file is a directory.
*/
public boolean isDirectory() throws IOException, InterruptedException {
return act(new IsDirectory());
}
private final class IsDirectory extends SecureFileCallable<Boolean> {
private static final long serialVersionUID = 1L;
@Override
public Boolean invoke(File f, VirtualChannel channel) throws IOException {
return stating(f).isDirectory();
}
}
/**
* Returns the file size in bytes.
*
* @since 1.129
*/
public long length() throws IOException, InterruptedException {
return act(new Length());
}
private class Length extends SecureFileCallable<Long> {
private static final long serialVersionUID = 1L;
@Override
public Long invoke(File f, VirtualChannel channel) throws IOException {
return stating(f).length();
}
}
/**
* Returns the number of unallocated bytes in the partition of that file.
* @since 1.542
*/
public long getFreeDiskSpace() throws IOException, InterruptedException {
return act(new GetFreeDiskSpace());
}
private static class GetFreeDiskSpace extends SecureFileCallable<Long> {
private static final long serialVersionUID = 1L;
@Override
public Long invoke(File f, VirtualChannel channel) throws IOException {
return f.getFreeSpace();
}
}
/**
* Returns the total number of bytes in the partition of that file.
* @since 1.542
*/
public long getTotalDiskSpace() throws IOException, InterruptedException {
return act(new GetTotalDiskSpace());
}
private static class GetTotalDiskSpace extends SecureFileCallable<Long> {
private static final long serialVersionUID = 1L;
@Override
public Long invoke(File f, VirtualChannel channel) throws IOException {
return f.getTotalSpace();
}
}
/**
* Returns the number of usable bytes in the partition of that file.
* @since 1.542
*/
public long getUsableDiskSpace() throws IOException, InterruptedException {
return act(new GetUsableDiskSpace());
}
private static class GetUsableDiskSpace extends SecureFileCallable<Long> {
private static final long serialVersionUID = 1L;
@Override
public Long invoke(File f, VirtualChannel channel) throws IOException {
return f.getUsableSpace();
}
}
/**
* Sets the file permission.
*
* On Windows, no-op.
*
* @param mask
* File permission mask. To simplify the permission copying,
* if the parameter is -1, this method becomes no-op.
* <p>
* please note mask is expected to be an octal if you use <a href="http://en.wikipedia.org/wiki/Chmod">chmod command line values</a>,
* so preceded by a '0' in java notation, ie <code>chmod(0644)</code>
* <p>
* Only supports setting read, write, or execute permissions for the
* owner, group, or others, so the largest permissible value is 0777.
* Attempting to set larger values (i.e. the setgid, setuid, or sticky
* bits) will cause an IOException to be thrown.
*
* @since 1.303
* @see #mode()
*/
public void chmod(final int mask) throws IOException, InterruptedException {
if(!isUnix() || mask==-1) return;
act(new Chmod(mask));
}
private class Chmod extends SecureFileCallable<Void> {
private static final long serialVersionUID = 1L;
private final int mask;
Chmod(int mask) {
this.mask = mask;
}
@Override
public Void invoke(File f, VirtualChannel channel) throws IOException {
_chmod(writing(f), mask);
return null;
}
}
/**
* Change permissions via NIO.
*/
private static void _chmod(File f, int mask) throws IOException {
// TODO WindowsPosix actually does something here (WindowsLibC._wchmod); should we let it?
// Anyway the existing calls already skip this method if on Windows.
if (File.pathSeparatorChar==';') return; // noop
if (Util.NATIVE_CHMOD_MODE) {
PosixAPI.jnr().chmod(f.getAbsolutePath(), mask);
} else {
Files.setPosixFilePermissions(fileToPath(f), Util.modeToPermissions(mask));
}
}
private static boolean CHMOD_WARNED = false;
/**
* Gets the file permission bit mask.
*
* @return
* -1 on Windows, since such a concept doesn't make sense.
* @since 1.311
* @see #chmod(int)
*/
public int mode() throws IOException, InterruptedException, PosixException {
if(!isUnix()) return -1;
return act(new Mode());
}
private class Mode extends SecureFileCallable<Integer> {
private static final long serialVersionUID = 1L;
@Override
public Integer invoke(File f, VirtualChannel channel) throws IOException {
return IOUtils.mode(stating(f));
}
}
/**
* List up files and directories in this directory.
*
* <p>
* This method returns direct children of the directory denoted by the 'this' object.
*/
@Nonnull
public List<FilePath> list() throws IOException, InterruptedException {
return list((FileFilter)null);
}
/**
* List up subdirectories.
*
* @return can be empty but never null. Doesn't contain "." and ".."
*/
@Nonnull
public List<FilePath> listDirectories() throws IOException, InterruptedException {
return list(new DirectoryFilter());
}
private static final class DirectoryFilter implements FileFilter, Serializable {
public boolean accept(File f) {
return f.isDirectory();
}
private static final long serialVersionUID = 1L;
}
/**
* List up files in this directory, just like {@link File#listFiles(FileFilter)}.
*
* @param filter
* The optional filter used to narrow down the result.
* If non-null, must be {@link Serializable}.
* If this {@link FilePath} represents a remote path,
* the filter object will be executed on the remote machine.
*/
@Nonnull
public List<FilePath> list(final FileFilter filter) throws IOException, InterruptedException {
if (filter != null && !(filter instanceof Serializable)) {
throw new IllegalArgumentException("Non-serializable filter of " + filter.getClass());
}
return act(new ListFilter(filter), (filter != null ? filter : this).getClass().getClassLoader());
}
private class ListFilter extends SecureFileCallable<List<FilePath>> {
private final FileFilter filter;
ListFilter(FileFilter filter) {
this.filter = filter;
}
private static final long serialVersionUID = 1L;
@Override
public List<FilePath> invoke(File f, VirtualChannel channel) throws IOException {
File[] children = reading(f).listFiles(filter);
if (children == null) {
return Collections.emptyList();
}
ArrayList<FilePath> r = new ArrayList<>(children.length);
for (File child : children)
r.add(new FilePath(child));
return r;
}
}
/**
* List up files in this directory that matches the given Ant-style filter.
*
* @param includes
* See {@link FileSet} for the syntax. String like "foo/*.zip" or "foo/**/*.xml"
* @return
* can be empty but always non-null.
*/
@Nonnull
public FilePath[] list(final String includes) throws IOException, InterruptedException {
return list(includes, null);
}
/**
* List up files in this directory that matches the given Ant-style filter.
*
* @param includes
* @param excludes
* See {@link FileSet} for the syntax. String like "foo/*.zip" or "foo/**/*.xml"
* @return
* can be empty but always non-null.
* @since 1.407
*/
@Nonnull
public FilePath[] list(final String includes, final String excludes) throws IOException, InterruptedException {
return list(includes, excludes, true);
}
/**
* List up files in this directory that matches the given Ant-style filter.
*
* @param includes
* @param excludes
* See {@link FileSet} for the syntax. String like "foo/*.zip" or "foo/**/*.xml"
* @param defaultExcludes whether to use the ant default excludes
* @return
* can be empty but always non-null.
* @since 1.465
*/
@Nonnull
public FilePath[] list(final String includes, final String excludes, final boolean defaultExcludes) throws IOException, InterruptedException {
return act(new ListGlob(includes, excludes, defaultExcludes));
}
private class ListGlob extends SecureFileCallable<FilePath[]> {
private final String includes;
private final String excludes;
private final boolean defaultExcludes;
ListGlob(String includes, String excludes, boolean defaultExcludes) {
this.includes = includes;
this.excludes = excludes;
this.defaultExcludes = defaultExcludes;
}
private static final long serialVersionUID = 1L;
@Override
public FilePath[] invoke(File f, VirtualChannel channel) throws IOException {
String[] files = glob(reading(f), includes, excludes, defaultExcludes);
FilePath[] r = new FilePath[files.length];
for( int i=0; i<r.length; i++ )
r[i] = new FilePath(new File(f,files[i]));
return r;
}
}
/**
* Runs Ant glob expansion.
*
* @return
* A set of relative file names from the base directory.
*/
@Nonnull
private static String[] glob(File dir, String includes, String excludes, boolean defaultExcludes) throws IOException {
if(isAbsolute(includes))
throw new IOException("Expecting Ant GLOB pattern, but saw '"+includes+"'. See http://ant.apache.org/manual/Types/fileset.html for syntax");
FileSet fs = Util.createFileSet(dir,includes,excludes);
fs.setDefaultexcludes(defaultExcludes);
DirectoryScanner ds;
try {
ds = fs.getDirectoryScanner(new Project());
} catch (BuildException x) {
throw new IOException(x.getMessage());
}
return ds.getIncludedFiles();
}
/**
* Reads this file.
*/
public InputStream read() throws IOException, InterruptedException {
if(channel==null) {
return Files.newInputStream(fileToPath(reading(new File(remote))));
}
final Pipe p = Pipe.createRemoteToLocal();
actAsync(new Read(p));
return p.getIn();
}
private class Read extends SecureFileCallable<Void> {
private static final long serialVersionUID = 1L;
private final Pipe p;
Read(Pipe p) {
this.p = p;
}
@Override
public Void invoke(File f, VirtualChannel channel) throws IOException, InterruptedException {
try (InputStream fis = Files.newInputStream(fileToPath(reading(f)));
OutputStream out = p.getOut()) {
org.apache.commons.io.IOUtils.copy(fis, out);
} catch (Exception x) {
p.error(x);
}
return null;
}
}
/**
* Reads this file from the specific offset.
* @since 1.586
*/
public InputStream readFromOffset(final long offset) throws IOException, InterruptedException {
if(channel ==null) {
final RandomAccessFile raf = new RandomAccessFile(new File(remote), "r");
try {
raf.seek(offset);
} catch (IOException e) {
try {
raf.close();
} catch (IOException e1) {
// ignore
}
throw e;
}
return new InputStream() {
@Override
public int read() throws IOException {
return raf.read();
}
@Override
public void close() throws IOException {
raf.close();
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
return raf.read(b, off, len);
}
@Override
public int read(byte[] b) throws IOException {
return raf.read(b);
}
};
}
final Pipe p = Pipe.createRemoteToLocal();
actAsync(new SecureFileCallable<Void>() {
private static final long serialVersionUID = 1L;
public Void invoke(File f, VirtualChannel channel) throws IOException {
try (OutputStream os = p.getOut();
OutputStream out = new java.util.zip.GZIPOutputStream(os, 8192);
RandomAccessFile raf = new RandomAccessFile(reading(f), "r")) {
raf.seek(offset);
byte[] buf = new byte[8192];
int len;
while ((len = raf.read(buf)) >= 0) {
out.write(buf, 0, len);
}
return null;
}
}
});
return new java.util.zip.GZIPInputStream(p.getIn());
}
/**
* Reads this file into a string, by using the current system encoding on the remote machine.
*/
public String readToString() throws IOException, InterruptedException {
return act(new ReadToString());
}
private final class ReadToString extends SecureFileCallable<String> {
private static final long serialVersionUID = 1L;
@Override
public String invoke(File f, VirtualChannel channel) throws IOException, InterruptedException {
return new String(Files.readAllBytes(fileToPath(reading(f))));
}
}
/**
* Writes to this file.
* If this file already exists, it will be overwritten.
* If the directory doesn't exist, it will be created.
*
* <P>
* I/O operation to remote {@link FilePath} happens asynchronously, meaning write operations to the returned
* {@link OutputStream} will return without receiving a confirmation from the remote that the write happened.
* I/O operations also happens asynchronously from the {@link Channel#call(Callable)} operations, so if
* you write to a remote file and then execute {@link Channel#call(Callable)} and try to access the newly copied
* file, it might not be fully written yet.
*
* <p>
*
*/
public OutputStream write() throws IOException, InterruptedException {
if(channel==null) {
File f = new File(remote).getAbsoluteFile();
mkdirs(f.getParentFile());
return Files.newOutputStream(fileToPath(writing(f)));
}
return act(new WritePipe());
}
private class WritePipe extends SecureFileCallable<OutputStream> {
private static final long serialVersionUID = 1L;
@Override
public OutputStream invoke(File f, VirtualChannel channel) throws IOException, InterruptedException {
f = f.getAbsoluteFile();
mkdirs(f.getParentFile());
return new RemoteOutputStream(Files.newOutputStream(fileToPath(writing(f))));
}
}
/**
* Overwrites this file by placing the given String as the content.
*
* @param encoding
* Null to use the platform default encoding on the remote machine.
* @since 1.105
*/
public void write(final String content, final String encoding) throws IOException, InterruptedException {
act(new Write(encoding, content));
}
private class Write extends SecureFileCallable<Void> {
private static final long serialVersionUID = 1L;
private final String encoding;
private final String content;
Write(String encoding, String content) {
this.encoding = encoding;
this.content = content;
}
@Override
public Void invoke(File f, VirtualChannel channel) throws IOException {
mkdirs(f.getParentFile());
try (OutputStream fos = Files.newOutputStream(fileToPath(writing(f)));
Writer w = encoding != null ? new OutputStreamWriter(fos, encoding) : new OutputStreamWriter(fos)) {
w.write(content);
}
return null;
}
}
/**
* Computes the MD5 digest of the file in hex string.
* @see Util#getDigestOf(File)
*/
public String digest() throws IOException, InterruptedException {
return act(new Digest());
}
private class Digest extends SecureFileCallable<String> {
private static final long serialVersionUID = 1L;
@Override
public String invoke(File f, VirtualChannel channel) throws IOException {
return Util.getDigestOf(reading(f));
}
}
/**
* Rename this file/directory to the target filepath. This FilePath and the target must
* be on the some host
*/
public void renameTo(final FilePath target) throws IOException, InterruptedException {
if(this.channel != target.channel) {
throw new IOException("renameTo target must be on the same host");
}
act(new RenameTo(target));
}
private class RenameTo extends SecureFileCallable<Void> {
private final FilePath target;
RenameTo(FilePath target) {
this.target = target;
}
private static final long serialVersionUID = 1L;
@Override
public Void invoke(File f, VirtualChannel channel) throws IOException {
Files.move(fileToPath(reading(f)), fileToPath(creating(new File(target.remote))), LinkOption.NOFOLLOW_LINKS);
return null;
}
}
/**
* Moves all the contents of this directory into the specified directory, then delete this directory itself.
*
* @since 1.308.
*/
public void moveAllChildrenTo(final FilePath target) throws IOException, InterruptedException {
if(this.channel != target.channel) {
throw new IOException("pullUpTo target must be on the same host");
}
act(new MoveAllChildrenTo(target));
}
private class MoveAllChildrenTo extends SecureFileCallable<Void> {
private final FilePath target;
MoveAllChildrenTo(FilePath target) {
this.target = target;
}
private static final long serialVersionUID = 1L;
@Override
public Void invoke(File f, VirtualChannel channel) throws IOException {
// JENKINS-16846: if f.getName() is the same as one of the files/directories in f,
// then the rename op will fail
File tmp = new File(f.getAbsolutePath()+".__rename");
if (!f.renameTo(tmp))
throw new IOException("Failed to rename "+f+" to "+tmp);
File t = new File(target.getRemote());
for(File child : reading(tmp).listFiles()) {
File target = new File(t, child.getName());
if(!stating(child).renameTo(creating(target)))
throw new IOException("Failed to rename "+child+" to "+target);
}
deleting(tmp).delete();
return null;
}
}
/**
* Copies this file to the specified target.
*/
public void copyTo(FilePath target) throws IOException, InterruptedException {
try {
try (OutputStream out = target.write()) {
copyTo(out);
}
} catch (IOException e) {
throw new IOException("Failed to copy "+this+" to "+target,e);
}
}
/**
* Copies this file to the specified target, with file permissions and other meta attributes intact.
* @since 1.311
*/
public void copyToWithPermission(FilePath target) throws IOException, InterruptedException {
// Use NIO copy with StandardCopyOption.COPY_ATTRIBUTES when copying on the same machine.
if (this.channel == target.channel) {
act(new CopyToWithPermission(target));
return;
}
copyTo(target);
// copy file permission
target.chmod(mode());
target.setLastModifiedIfPossible(lastModified());
}
private class CopyToWithPermission extends SecureFileCallable<Void> {
private final FilePath target;
CopyToWithPermission(FilePath target) {
this.target = target;
}
@Override
public Void invoke(File f, VirtualChannel channel) throws IOException {
File targetFile = new File(target.remote);
File targetDir = targetFile.getParentFile();
filterNonNull().mkdirs(targetDir);
Files.createDirectories(fileToPath(targetDir));
Files.copy(fileToPath(reading(f)), fileToPath(writing(targetFile)), StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING);
return null;
}
}
/**
* Sends the contents of this file into the given {@link OutputStream}.
*/
public void copyTo(OutputStream os) throws IOException, InterruptedException {
final OutputStream out = new RemoteOutputStream(os);
act(new CopyTo(out));
// make sure the writes fully got delivered to 'os' before we return.
// this is needed because I/O operation is asynchronous
syncIO();
}
private class CopyTo extends SecureFileCallable<Void> {
private static final long serialVersionUID = 4088559042349254141L;
private final OutputStream out;
CopyTo(OutputStream out) {
this.out = out;
}
@Override
public Void invoke(File f, VirtualChannel channel) throws IOException {
try (InputStream fis = Files.newInputStream(fileToPath(reading(f)))) {
org.apache.commons.io.IOUtils.copy(fis, out);
return null;
} finally {
out.close();
}
}
}
/**
* With fix to JENKINS-11251 (remoting 2.15), this is no longer necessary.
* But I'm keeping it for a while so that users who manually deploy agent.jar has time to deploy new version
* before this goes away.
*/
private void syncIO() throws InterruptedException {
try {
if (channel!=null)
channel.syncLocalIO();
} catch (AbstractMethodError e) {
// legacy agent.jar. Handle this gracefully
try {
LOGGER.log(Level.WARNING,"Looks like an old agent.jar. Please update "+ Which.jarFile(Channel.class)+" to the new version",e);
} catch (IOException ignored) {
// really ignore this time
}
}
}
/**
* A pointless function to work around what appears to be a HotSpot problem. See JENKINS-5756 and bug 6933067
* on BugParade for more details.
*/
private void _syncIO() throws InterruptedException {
channel.syncLocalIO();
}
/**
* Remoting interface used for {@link FilePath#copyRecursiveTo(String, FilePath)}.
*
* TODO: this might not be the most efficient way to do the copy.
*/
interface RemoteCopier {
/**
* @param fileName
* relative path name to the output file. Path separator must be '/'.
*/
void open(String fileName) throws IOException;
void write(byte[] buf, int len) throws IOException;
void close() throws IOException;
}
/**
* Copies the contents of this directory recursively into the specified target directory.
*
* @return
* the number of files copied.
* @since 1.312
*/
public int copyRecursiveTo(FilePath target) throws IOException, InterruptedException {
return copyRecursiveTo("**/*",target);
}
/**
* Copies the files that match the given file mask to the specified target node.
*
* @param fileMask
* Ant GLOB pattern.
* String like "foo/bar/*.xml" Multiple patterns can be separated
* by ',', and whitespace can surround ',' (so that you can write
* "abc, def" and "abc,def" to mean the same thing.
* @return
* the number of files copied.
*/
public int copyRecursiveTo(String fileMask, FilePath target) throws IOException, InterruptedException {
return copyRecursiveTo(fileMask,null,target);
}
/**
* Copies the files that match the given file mask to the specified target node.
*
* @param fileMask
* Ant GLOB pattern.
* String like "foo/bar/*.xml" Multiple patterns can be separated
* by ',', and whitespace can surround ',' (so that you can write
* "abc, def" and "abc,def" to mean the same thing.
* @param excludes
* Files to be excluded. Can be null.
* @return
* the number of files copied.
*/
public int copyRecursiveTo(final String fileMask, final String excludes, final FilePath target) throws IOException, InterruptedException {
return copyRecursiveTo(new DirScanner.Glob(fileMask, excludes), target, fileMask);
}
/**
* Copies files according to a specified scanner to a target node.
* @param scanner a way of enumerating some files (must be serializable for possible delivery to remote side)
* @param target the destination basedir
* @param description a description of the fileset, for logging purposes
* @return the number of files copied
* @since 1.532
*/
public int copyRecursiveTo(final DirScanner scanner, final FilePath target, final String description) throws IOException, InterruptedException {
if(this.channel==target.channel) {
// local to local copy.
return act(new CopyRecursiveLocal(target, scanner));
} else
if(this.channel==null) {
// local -> remote copy
final Pipe pipe = Pipe.createLocalToRemote();
Future<Void> future = target.actAsync(new ReadToTar(pipe, description));
Future<Integer> future2 = actAsync(new WriteToTar(scanner, pipe));
try {
// JENKINS-9540 in case the reading side failed, report that error first
future.get();
return future2.get();
} catch (ExecutionException e) {
throw ioWithCause(e);
}
} else {
// remote -> local copy
final Pipe pipe = Pipe.createRemoteToLocal();
Future<Integer> future = actAsync(new CopyRecursiveRemoteToLocal(pipe, scanner));
try {
readFromTar(remote + '/' + description,new File(target.remote),TarCompression.GZIP.extract(pipe.getIn()));
} catch (IOException e) {// BuildException or IOException
try {
future.get(3,TimeUnit.SECONDS);
throw e; // the remote side completed successfully, so the error must be local
} catch (ExecutionException x) {
// report both errors
e.addSuppressed(x);
throw e;
} catch (TimeoutException ignored) {
// remote is hanging, just throw the original exception
throw e;
}
}
try {
return future.get();
} catch (ExecutionException e) {
throw ioWithCause(e);
}
}
}
private IOException ioWithCause(ExecutionException e) {
Throwable cause = e.getCause();
if (cause == null) cause = e;
return cause instanceof IOException
? (IOException) cause
: new IOException(cause)
;
}
private class CopyRecursiveLocal extends SecureFileCallable<Integer> {
private final FilePath target;
private final DirScanner scanner;
CopyRecursiveLocal(FilePath target, DirScanner scanner) {
this.target = target;
this.scanner = scanner;
}
private static final long serialVersionUID = 1L;
@Override
public Integer invoke(File base, VirtualChannel channel) throws IOException {
if (!base.exists()) {
return 0;
}
assert target.channel == null;
final File dest = new File(target.remote);
final AtomicInteger count = new AtomicInteger();
scanner.scan(base, reading(new FileVisitor() {
private boolean exceptionEncountered;
private boolean logMessageShown;
@Override
public void visit(File f, String relativePath) throws IOException {
if (f.isFile()) {
File target = new File(dest, relativePath);
mkdirsE(target.getParentFile());
Path targetPath = fileToPath(writing(target));
exceptionEncountered = exceptionEncountered || !tryCopyWithAttributes(f, targetPath);
if (exceptionEncountered) {
Files.copy(fileToPath(f), targetPath, StandardCopyOption.REPLACE_EXISTING);
if (!logMessageShown) {
LOGGER.log(Level.INFO,
"JENKINS-52325: Jenkins failed to retain attributes when copying to {0}, so proceeding without attributes.",
dest.getAbsolutePath());
logMessageShown = true;
}
}
count.incrementAndGet();
}
}
private boolean tryCopyWithAttributes(File f, Path targetPath) {
try {
Files.copy(fileToPath(f), targetPath,
StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
LOGGER.log(Level.FINE, "Unable to copy: {0}", e.getMessage());
return false;
}
return true;
}
@Override
public boolean understandsSymlink() {
return true;
}
@Override
public void visitSymlink(File link, String target, String relativePath) throws IOException {
try {
mkdirsE(new File(dest, relativePath).getParentFile());
writing(new File(dest, target));
Util.createSymlink(dest, target, relativePath, TaskListener.NULL);
} catch (InterruptedException x) {
throw new IOException(x);
}
count.incrementAndGet();
}
}));
return count.get();
}
}
private class ReadToTar extends SecureFileCallable<Void> {
private final Pipe pipe;
private final String description;
ReadToTar(Pipe pipe, String description) {
this.pipe = pipe;
this.description = description;
}
private static final long serialVersionUID = 1L;
@Override
public Void invoke(File f, VirtualChannel channel) throws IOException {
try (InputStream in = pipe.getIn()) {
readFromTar(remote + '/' + description, f, TarCompression.GZIP.extract(in));
return null;
}
}
}
private class WriteToTar extends SecureFileCallable<Integer> {
private final DirScanner scanner;
private final Pipe pipe;
WriteToTar(DirScanner scanner, Pipe pipe) {
this.scanner = scanner;
this.pipe = pipe;
}
private static final long serialVersionUID = 1L;
@Override
public Integer invoke(File f, VirtualChannel channel) throws IOException, InterruptedException {
return writeToTar(new File(remote), scanner, TarCompression.GZIP.compress(pipe.getOut()));
}
}
private class CopyRecursiveRemoteToLocal extends SecureFileCallable<Integer> {
private static final long serialVersionUID = 1L;
private final Pipe pipe;
private final DirScanner scanner;
CopyRecursiveRemoteToLocal(Pipe pipe, DirScanner scanner) {
this.pipe = pipe;
this.scanner = scanner;
}
@Override
public Integer invoke(File f, VirtualChannel channel) throws IOException {
try (OutputStream out = pipe.getOut()) {
return writeToTar(f, scanner, TarCompression.GZIP.compress(out));
}
}
}
/**
* Writes files in 'this' directory to a tar stream.
*
* @param glob
* Ant file pattern mask, like "**/*.java".
*/
public int tar(OutputStream out, final String glob) throws IOException, InterruptedException {
return archive(ArchiverFactory.TAR, out, glob);
}
public int tar(OutputStream out, FileFilter filter) throws IOException, InterruptedException {
return archive(ArchiverFactory.TAR, out, filter);
}
/**
* Uses the given scanner on 'this' directory to list up files and then archive it to a tar stream.
*/
public int tar(OutputStream out, DirScanner scanner) throws IOException, InterruptedException {
return archive(ArchiverFactory.TAR, out, scanner);
}
/**
* Writes to a tar stream and stores obtained files to the base dir.
*
* @return
* number of files/directories that are written.
*/
private Integer writeToTar(File baseDir, DirScanner scanner, OutputStream out) throws IOException {
Archiver tw = ArchiverFactory.TAR.create(out);
try {
scanner.scan(baseDir,reading(tw));
} finally {
tw.close();
}
return tw.countEntries();
}
/**
* Reads from a tar stream and stores obtained files to the base dir.
* Supports large files > 10 GB since 1.627 when this was migrated to use commons-compress.
*/
private void readFromTar(String name, File baseDir, InputStream in) throws IOException {
// TarInputStream t = new TarInputStream(in);
try (TarArchiveInputStream t = new TarArchiveInputStream(in)) {
TarArchiveEntry te;
while ((te = t.getNextTarEntry()) != null) {
File f = new File(baseDir, te.getName());
if (!f.toPath().normalize().startsWith(baseDir.toPath())) {
throw new IOException(
"Tar " + name + " contains illegal file name that breaks out of the target directory: " + te.getName());
}
if (te.isDirectory()) {
mkdirs(f);
} else {
File parent = f.getParentFile();
if (parent != null) mkdirs(parent);
writing(f);
if (te.isSymbolicLink()) {
new FilePath(f).symlinkTo(te.getLinkName(), TaskListener.NULL);
} else {
IOUtils.copy(t, f);
f.setLastModified(te.getModTime().getTime());
int mode = te.getMode() & 0777;
if (mode != 0 && !Functions.isWindows()) // be defensive
_chmod(f, mode);
}
}
}
} catch (IOException e) {
throw new IOException("Failed to extract " + name, e);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // process this later
throw new IOException("Failed to extract " + name, e);
}
}
/**
* Creates a {@link Launcher} for starting processes on the node
* that has this file.
* @since 1.89
*/
public Launcher createLauncher(TaskListener listener) throws IOException, InterruptedException {
if(channel==null)
return new LocalLauncher(listener);
else
return new RemoteLauncher(listener,channel,channel.call(new IsUnix()));
}
private static final class IsUnix extends MasterToSlaveCallable<Boolean,IOException> {
@Nonnull
public Boolean call() throws IOException {
return File.pathSeparatorChar==':';
}
private static final long serialVersionUID = 1L;
}
/**
* Validates the ant file mask (like "foo/bar/*.txt, zot/*.jar")
* against this directory, and try to point out the problem.
*
* <p>
* This is useful in conjunction with {@link FormValidation}.
*
* @return
* null if no error was found. Otherwise returns a human readable error message.
* @since 1.90
* @see #validateFileMask(FilePath, String)
* @deprecated use {@link #validateAntFileMask(String, int)} instead
*/
@Deprecated
public String validateAntFileMask(final String fileMasks) throws IOException, InterruptedException {
return validateAntFileMask(fileMasks, Integer.MAX_VALUE);
}
/**
* Same as {@link #validateAntFileMask(String, int, boolean)} with caseSensitive set to true
*/
public String validateAntFileMask(final String fileMasks, final int bound) throws IOException, InterruptedException {
return validateAntFileMask(fileMasks, bound, true);
}
/**
* Default bound for {@link #validateAntFileMask(String, int, boolean)}.
* @since 1.592
*/
public static int VALIDATE_ANT_FILE_MASK_BOUND = Integer.getInteger(FilePath.class.getName() + ".VALIDATE_ANT_FILE_MASK_BOUND", 10000);
/**
* Like {@link #validateAntFileMask(String)} but performing only a bounded number of operations.
* <p>Whereas the unbounded overload is appropriate for calling from cancelable, long-running tasks such as build steps,
* this overload should be used when an answer is needed quickly, such as for {@link #validateFileMask(String)}
* or anything else returning {@link FormValidation}.
* <p>If a positive match is found, {@code null} is returned immediately.
* A message is returned in case the file pattern can definitely be determined to not match anything in the directory within the alloted time.
* If the time runs out without finding a match but without ruling out the possibility that there might be one, {@link InterruptedException} is thrown,
* in which case the calling code should give the user the benefit of the doubt and use {@link hudson.util.FormValidation.Kind#OK} (with or without a message).
* @param bound a maximum number of negative operations (deliberately left vague) to perform before giving up on a precise answer; try {@link #VALIDATE_ANT_FILE_MASK_BOUND}
* @throws InterruptedException not only in case of a channel failure, but also if too many operations were performed without finding any matches
* @since 1.484
*/
public @CheckForNull String validateAntFileMask(final String fileMasks, final int bound, final boolean caseSensitive) throws IOException, InterruptedException {
return act(new ValidateAntFileMask(fileMasks, caseSensitive, bound));
}
private class ValidateAntFileMask extends MasterToSlaveFileCallable<String> {
private final String fileMasks;
private final boolean caseSensitive;
private final int bound;
ValidateAntFileMask(String fileMasks, boolean caseSensitive, int bound) {
this.fileMasks = fileMasks;
this.caseSensitive = caseSensitive;
this.bound = bound;
}
private static final long serialVersionUID = 1;
@Override
public String invoke(File dir, VirtualChannel channel) throws IOException, InterruptedException {
if(fileMasks.startsWith("~"))
return Messages.FilePath_TildaDoesntWork();
StringTokenizer tokens = new StringTokenizer(fileMasks,",");
while(tokens.hasMoreTokens()) {
final String fileMask = tokens.nextToken().trim();
if(hasMatch(dir,fileMask,caseSensitive))
continue; // no error on this portion
// JENKINS-5253 - if we can get some match in case insensitive mode
// and user requested case sensitive match, notify the user
if (caseSensitive && hasMatch(dir, fileMask, false)) {
return Messages.FilePath_validateAntFileMask_matchWithCaseInsensitive(fileMask);
}
// in 1.172 we introduced an incompatible change to stop using ' ' as the separator
// so see if we can match by using ' ' as the separator
if(fileMask.contains(" ")) {
boolean matched = true;
for (String token : Util.tokenize(fileMask))
matched &= hasMatch(dir,token,caseSensitive);
if(matched)
return Messages.FilePath_validateAntFileMask_whitespaceSeparator();
}
// a common mistake is to assume the wrong base dir, and there are two variations
// to this: (1) the user gave us aa/bb/cc/dd where cc/dd was correct
// and (2) the user gave us cc/dd where aa/bb/cc/dd was correct.
{// check the (1) above first
String f=fileMask;
while(true) {
int idx = findSeparator(f);
if(idx==-1) break;
f=f.substring(idx+1);
if(hasMatch(dir,f,caseSensitive))
return Messages.FilePath_validateAntFileMask_doesntMatchAndSuggest(fileMask,f);
}
}
{// check the (2) above next as this is more expensive.
// Try prepending "**/" to see if that results in a match
FileSet fs = Util.createFileSet(reading(dir),"**/"+fileMask);
fs.setCaseSensitive(caseSensitive);
DirectoryScanner ds = fs.getDirectoryScanner(new Project());
if(ds.getIncludedFilesCount()!=0) {
// try shorter name first so that the suggestion results in least amount of changes
String[] names = ds.getIncludedFiles();
Arrays.sort(names,SHORTER_STRING_FIRST);
for( String f : names) {
// now we want to decompose f to the leading portion that matched "**"
// and the trailing portion that matched the file mask, so that
// we can suggest the user error.
//
// this is not a very efficient/clever way to do it, but it's relatively simple
StringBuilder prefix = new StringBuilder();
while(true) {
int idx = findSeparator(f);
if(idx==-1) break;
prefix.append(f.substring(0, idx)).append('/');
f=f.substring(idx+1);
if(hasMatch(dir,prefix+fileMask,caseSensitive))
return Messages.FilePath_validateAntFileMask_doesntMatchAndSuggest(fileMask, prefix+fileMask);
}
}
}
}
{// finally, see if we can identify any sub portion that's valid. Otherwise bail out
String previous = null;
String pattern = fileMask;
while(true) {
if(hasMatch(dir,pattern,caseSensitive)) {
// found a match
if(previous==null)
return Messages.FilePath_validateAntFileMask_portionMatchAndSuggest(fileMask,pattern);
else
return Messages.FilePath_validateAntFileMask_portionMatchButPreviousNotMatchAndSuggest(fileMask,pattern,previous);
}
int idx = findSeparator(pattern);
if(idx<0) {// no more path component left to go back
if(pattern.equals(fileMask))
return Messages.FilePath_validateAntFileMask_doesntMatchAnything(fileMask);
else
return Messages.FilePath_validateAntFileMask_doesntMatchAnythingAndSuggest(fileMask,pattern);
}
// cut off the trailing component and try again
previous = pattern;
pattern = pattern.substring(0,idx);
}
}
}
return null; // no error
}
private boolean hasMatch(File dir, String pattern, boolean bCaseSensitive) throws InterruptedException {
class Cancel extends RuntimeException {}
DirectoryScanner ds = bound == Integer.MAX_VALUE ? new DirectoryScanner() : new DirectoryScanner() {
int ticks;
long start = System.currentTimeMillis();
@Override public synchronized boolean isCaseSensitive() {
if (!filesIncluded.isEmpty() || !dirsIncluded.isEmpty() || ticks++ > bound || System.currentTimeMillis() - start > 5000) {
throw new Cancel();
}
filesNotIncluded.clear();
dirsNotIncluded.clear();
// notFollowedSymlinks might be large, but probably unusual
// scannedDirs will typically be largish, but seems to be needed
return super.isCaseSensitive();
}
};
ds.setBasedir(reading(dir));
ds.setIncludes(new String[] {pattern});
ds.setCaseSensitive(bCaseSensitive);
try {
ds.scan();
} catch (Cancel c) {
if (ds.getIncludedFilesCount()!=0 || ds.getIncludedDirsCount()!=0) {
return true;
} else {
throw new InterruptedException("no matches found within " + bound);
}
}
return ds.getIncludedFilesCount()!=0 || ds.getIncludedDirsCount()!=0;
}
/**
* Finds the position of the first path separator.
*/
private int findSeparator(String pattern) {
int idx1 = pattern.indexOf('\\');
int idx2 = pattern.indexOf('/');
if(idx1==-1) return idx2;
if(idx2==-1) return idx1;
return Math.min(idx1,idx2);
}
}
private static final UrlFactory DEFAULT_URL_FACTORY = new UrlFactory();
@Restricted(NoExternalUse.class)
static class UrlFactory {
public URL newURL(String location) throws MalformedURLException {
return new URL(location);
}
}
private UrlFactory urlFactory;
@VisibleForTesting
@Restricted(NoExternalUse.class)
void setUrlFactory(UrlFactory urlFactory) {
this.urlFactory = urlFactory;
}
private UrlFactory getUrlFactory() {
if (urlFactory != null) {
return urlFactory;
} else {
return DEFAULT_URL_FACTORY;
}
}
/**
* Short for {@code validateFileMask(path, value, true)}
*/
public static FormValidation validateFileMask(@CheckForNull FilePath path, String value) throws IOException {
return FilePath.validateFileMask(path, value, true);
}
/**
* Shortcut for {@link #validateFileMask(String,boolean,boolean)} with {@code errorIfNotExist} true, as the left-hand side can be null.
*/
public static FormValidation validateFileMask(@CheckForNull FilePath path, String value, boolean caseSensitive) throws IOException {
if(path==null) return FormValidation.ok();
return path.validateFileMask(value, true, caseSensitive);
}
/**
* Short for {@code validateFileMask(value, true, true)}
*/
public FormValidation validateFileMask(String value) throws IOException {
return validateFileMask(value, true, true);
}
/**
* Short for {@code validateFileMask(value, errorIfNotExist, true)}
*/
public FormValidation validateFileMask(String value, boolean errorIfNotExist) throws IOException {
return validateFileMask(value, errorIfNotExist, true);
}
/**
* Checks the GLOB-style file mask. See {@link #validateAntFileMask(String)}.
* Requires configure permission on ancestor AbstractProject object in request,
* or admin permission if no such ancestor is found.
* @since 1.294
*/
public FormValidation validateFileMask(String value, boolean errorIfNotExist, boolean caseSensitive) throws IOException {
checkPermissionForValidate();
value = fixEmpty(value);
if(value==null)
return FormValidation.ok();
try {
if(!exists()) // no workspace. can't check
return FormValidation.ok();
String msg = validateAntFileMask(value, VALIDATE_ANT_FILE_MASK_BOUND, caseSensitive);
if(errorIfNotExist) return FormValidation.error(msg);
else return FormValidation.warning(msg);
} catch (InterruptedException e) {
return FormValidation.ok(Messages.FilePath_did_not_manage_to_validate_may_be_too_sl(value));
}
}
/**
* Validates a relative file path from this {@link FilePath}.
* Requires configure permission on ancestor AbstractProject object in request,
* or admin permission if no such ancestor is found.
*
* @param value
* The relative path being validated.
* @param errorIfNotExist
* If true, report an error if the given relative path doesn't exist. Otherwise it's a warning.
* @param expectingFile
* If true, we expect the relative path to point to a file.
* Otherwise, the relative path is expected to be pointing to a directory.
*/
public FormValidation validateRelativePath(String value, boolean errorIfNotExist, boolean expectingFile) throws IOException {
checkPermissionForValidate();
value = fixEmpty(value);
// none entered yet, or something is seriously wrong
if(value==null) return FormValidation.ok();
// a common mistake is to use wildcard
if(value.contains("*")) return FormValidation.error(Messages.FilePath_validateRelativePath_wildcardNotAllowed());
try {
if(!exists()) // no base directory. can't check
return FormValidation.ok();
FilePath path = child(value);
if(path.exists()) {
if (expectingFile) {
if(!path.isDirectory())
return FormValidation.ok();
else
return FormValidation.error(Messages.FilePath_validateRelativePath_notFile(value));
} else {
if(path.isDirectory())
return FormValidation.ok();
else
return FormValidation.error(Messages.FilePath_validateRelativePath_notDirectory(value));
}
}
String msg = expectingFile ? Messages.FilePath_validateRelativePath_noSuchFile(value) :
Messages.FilePath_validateRelativePath_noSuchDirectory(value);
if(errorIfNotExist) return FormValidation.error(msg);
else return FormValidation.warning(msg);
} catch (InterruptedException e) {
return FormValidation.ok();
}
}
private static void checkPermissionForValidate() {
AccessControlled subject = Stapler.getCurrentRequest().findAncestorObject(AbstractProject.class);
if (subject == null)
Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);
else
subject.checkPermission(Item.CONFIGURE);
}
/**
* A convenience method over {@link #validateRelativePath(String, boolean, boolean)}.
*/
public FormValidation validateRelativeDirectory(String value, boolean errorIfNotExist) throws IOException {
return validateRelativePath(value,errorIfNotExist,false);
}
public FormValidation validateRelativeDirectory(String value) throws IOException {
return validateRelativeDirectory(value,true);
}
@Deprecated @Override
public String toString() {
// to make writing JSPs easily, return local
return remote;
}
public VirtualChannel getChannel() {
if(channel!=null) return channel;
else return localChannel;
}
/**
* Returns true if this {@link FilePath} represents a remote file.
*/
public boolean isRemote() {
return channel!=null;
}
private void writeObject(ObjectOutputStream oos) throws IOException {
Channel target = _getChannelForSerialization();
if (channel != null && channel != target) {
throw new IllegalStateException("Can't send a remote FilePath to a different remote channel (current=" + channel + ", target=" + target + ")");
}
oos.defaultWriteObject();
oos.writeBoolean(channel==null);
}
private Channel _getChannelForSerialization() {
try {
return getChannelForSerialization();
} catch (NotSerializableException x) {
LOGGER.log(Level.WARNING, "A FilePath object is being serialized when it should not be, indicating a bug in a plugin. See https://jenkins.io/redirect/filepath-serialization for details.", x);
return null;
}
}
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
Channel channel = _getChannelForSerialization();
ois.defaultReadObject();
if(ois.readBoolean()) {
this.channel = channel;
this.filter = null;
} else {
this.channel = null;
// If the remote channel wants us to create a FilePath that points to a local file,
// we need to make sure the access control takes place.
// This covers the immediate case of FileCallables taking FilePath into reference closure implicitly,
// but it also covers more general case of FilePath sent as a return value or argument.
this.filter = SoloFilePathFilter.wrap(FilePathFilter.current());
}
}
private static final long serialVersionUID = 1L;
public static int SIDE_BUFFER_SIZE = 1024;
private static final Logger LOGGER = Logger.getLogger(FilePath.class.getName());
/**
* Adapts {@link FileCallable} to {@link Callable}.
*/
private class FileCallableWrapper<T> implements DelegatingCallable<T,IOException> {
private final FileCallable<T> callable;
private transient ClassLoader classLoader;
public FileCallableWrapper(FileCallable<T> callable) {
this.callable = callable;
this.classLoader = callable.getClass().getClassLoader();
}
private FileCallableWrapper(FileCallable<T> callable, ClassLoader classLoader) {
this.callable = callable;
this.classLoader = classLoader;
}
public T call() throws IOException {
try {
return callable.invoke(new File(remote), Channel.current());
} catch (InterruptedException e) {
throw new TunneledInterruptedException(e);
}
}
/**
* Role check comes from {@link FileCallable}s.
*/
@Override
public void checkRoles(RoleChecker checker) throws SecurityException {
callable.checkRoles(checker);
}
public ClassLoader getClassLoader() {
return classLoader;
}
@Override
public String toString() {
return callable.toString();
}
private static final long serialVersionUID = 1L;
}
/**
* Used to tunnel {@link InterruptedException} over a Java signature that only allows {@link IOException}
*/
private static class TunneledInterruptedException extends IOException {
private TunneledInterruptedException(InterruptedException cause) {
super(cause);
}
private static final long serialVersionUID = 1L;
}
private static final Comparator<String> SHORTER_STRING_FIRST = new Comparator<String>() {
public int compare(String o1, String o2) {
return o1.length()-o2.length();
}
};
/**
* Gets the {@link FilePath} representation of the "~" directory
* (User's home directory in the Unix sense) of the given channel.
*/
public static FilePath getHomeDirectory(VirtualChannel ch) throws InterruptedException, IOException {
return ch.call(new GetHomeDirectory());
}
private static class GetHomeDirectory extends MasterToSlaveCallable<FilePath, IOException> {
@Override
public FilePath call() throws IOException {
return new FilePath(new File(System.getProperty("user.home")));
}
}
/**
* Helper class to make it easy to send an explicit list of files using {@link FilePath} methods.
* @since 1.532
*/
public static final class ExplicitlySpecifiedDirScanner extends DirScanner {
private static final long serialVersionUID = 1;
private final Map<String,String> files;
/**
* Create a “scanner” (it actually does no scanning).
* @param files a map from logical relative paths as per {@link FileVisitor#visit}, to actual relative paths within the scanned directory
*/
public ExplicitlySpecifiedDirScanner(Map<String,String> files) {
this.files = files;
}
@Override public void scan(File dir, FileVisitor visitor) throws IOException {
for (Map.Entry<String,String> entry : files.entrySet()) {
String archivedPath = entry.getKey();
assert archivedPath.indexOf('\\') == -1;
String workspacePath = entry.getValue();
assert workspacePath.indexOf('\\') == -1;
scanSingle(new File(dir, workspacePath), archivedPath, visitor);
}
}
}
private static final ExecutorService threadPoolForRemoting = new ContextResettingExecutorService(
Executors.newCachedThreadPool(
new ExceptionCatchingThreadFactory(
new NamingThreadFactory(new DaemonThreadFactory(), "FilePath.localPool"))
));
/**
* Channel to the current instance.
*/
@Nonnull
public static final LocalChannel localChannel = new LocalChannel(threadPoolForRemoting);
private @Nonnull SoloFilePathFilter filterNonNull() {
return filter!=null ? filter : UNRESTRICTED;
}
/**
* Wraps {@link FileVisitor} to notify read access to {@link FilePathFilter}.
*/
private FileVisitor reading(final FileVisitor v) {
final FilePathFilter filter = FilePathFilter.current();
if (filter==null) return v;
return new FileVisitor() {
@Override
public void visit(File f, String relativePath) throws IOException {
filter.read(f);
v.visit(f,relativePath);
}
@Override
public void visitSymlink(File link, String target, String relativePath) throws IOException {
filter.read(link);
v.visitSymlink(link, target, relativePath);
}
@Override
public boolean understandsSymlink() {
return v.understandsSymlink();
}
};
}
/**
* Pass through 'f' after ensuring that we can read that file.
*/
private File reading(File f) {
filterNonNull().read(f);
return f;
}
/**
* Pass through 'f' after ensuring that we can access the file attributes.
*/
private File stating(File f) {
filterNonNull().stat(f);
return f;
}
/**
* Pass through 'f' after ensuring that we can create that file/dir.
*/
private File creating(File f) {
filterNonNull().create(f);
return f;
}
/**
* Pass through 'f' after ensuring that we can write to that file.
*/
private File writing(File f) {
FilePathFilter filter = filterNonNull();
if (!f.exists())
filter.create(f);
filter.write(f);
return f;
}
/**
* Pass through 'f' after ensuring that we can create that symlink.
*/
private File symlinking(File f) {
FilePathFilter filter = filterNonNull();
if (!f.exists())
filter.create(f);
filter.symlink(f);
return f;
}
/**
* Pass through 'f' after ensuring that we can delete that file.
*/
private File deleting(File f) {
filterNonNull().delete(f);
return f;
}
private boolean mkdirs(File dir) throws IOException {
if (dir.exists()) return false;
filterNonNull().mkdirs(dir);
Files.createDirectories(fileToPath(dir));
return true;
}
private File mkdirsE(File dir) throws IOException {
if (dir.exists()) {
return dir;
}
filterNonNull().mkdirs(dir);
return IOUtils.mkdirs(dir);
}
/**
* Check if the relative child is really a descendant after symlink resolution if any.
*
* TODO un-restrict it in a weekly after the patch
*/
@Restricted(NoExternalUse.class)
public boolean isDescendant(@Nonnull String potentialChildRelativePath) throws IOException, InterruptedException {
return act(new IsDescendant(potentialChildRelativePath));
}
private class IsDescendant extends SecureFileCallable<Boolean> {
private static final long serialVersionUID = 1L;
private String potentialChildRelativePath;
private IsDescendant(@Nonnull String potentialChildRelativePath){
this.potentialChildRelativePath = potentialChildRelativePath;
}
@Override
public Boolean invoke(@Nonnull File parentFile, @Nonnull VirtualChannel channel) throws IOException, InterruptedException {
if (new File(potentialChildRelativePath).isAbsolute()) {
throw new IllegalArgumentException("Only a relative path is supported, the given path is absolute: " + potentialChildRelativePath);
}
Path parentAbsolutePath = Util.fileToPath(parentFile.getAbsoluteFile());
Path parentRealPath;
try {
if (Functions.isWindows()) {
parentRealPath = this.windowsToRealPath(parentAbsolutePath);
} else {
parentRealPath = parentAbsolutePath.toRealPath();
}
}
catch (NoSuchFileException e) {
LOGGER.log(Level.FINE, String.format("Cannot find the real path to the parentFile: %s", parentAbsolutePath), e);
return false;
}
// example: "a/b/c" that will become "b/c" then just "c", and finally an empty string
String remainingPath = potentialChildRelativePath;
Path currentFilePath = parentFile.toPath();
while (!remainingPath.isEmpty()) {
Path directChild = this.getDirectChild(currentFilePath, remainingPath);
Path childUsingFullPath = currentFilePath.resolve(remainingPath);
String childUsingFullPathAbs = childUsingFullPath.toAbsolutePath().toString();
String directChildAbs = directChild.toAbsolutePath().toString();
if (childUsingFullPathAbs.length() == directChildAbs.length()) {
remainingPath = "";
} else {
// +1 to avoid the last slash
remainingPath = childUsingFullPathAbs.substring(directChildAbs.length() + 1);
}
File childFileSymbolic = Util.resolveSymlinkToFile(directChild.toFile());
if (childFileSymbolic == null) {
currentFilePath = directChild;
} else {
currentFilePath = childFileSymbolic.toPath();
}
Path currentFileAbsolutePath = currentFilePath.toAbsolutePath();
try{
Path child = currentFileAbsolutePath.toRealPath();
if (!child.startsWith(parentRealPath)) {
LOGGER.log(Level.FINE, "Child [{0}] does not start with parent [{1}] => not descendant", new Object[]{ child, parentRealPath });
return false;
}
} catch (NoSuchFileException e) {
// nonexistent file / Windows Server 2016 + MSFT docker
// in case this folder / file will be copied somewhere else,
// it becomes the responsibility of that system to check the isDescendant with the existing links
// we are not taking the parentRealPath to avoid possible problem
Path child = currentFileAbsolutePath.normalize();
Path parent = parentAbsolutePath.normalize();
return child.startsWith(parent);
} catch(FileSystemException e) {
LOGGER.log(Level.WARNING, String.format("Problem during call to the method toRealPath on %s", currentFileAbsolutePath), e);
return false;
}
}
return true;
}
private @CheckForNull Path getDirectChild(Path parentPath, String childPath){
Path current = parentPath.resolve(childPath);
while (current != null && !parentPath.equals(current.getParent())) {
current = current.getParent();
}
return current;
}
private @Nonnull Path windowsToRealPath(@Nonnull Path path) throws IOException {
try {
return path.toRealPath();
}
catch (IOException e) {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE, String.format("relaxedToRealPath cannot use the regular toRealPath on %s, trying with toRealPath(LinkOption.NOFOLLOW_LINKS)", path), e);
}
}
// that's required for specific environment like Windows Server 2016, running MSFT docker
// where the root is a <SYMLINKD>
return path.toRealPath(LinkOption.NOFOLLOW_LINKS);
}
}
private static final SoloFilePathFilter UNRESTRICTED = SoloFilePathFilter.wrap(FilePathFilter.UNRESTRICTED);
}
|
core/src/main/java/hudson/FilePath.java
|
/*
* The MIT License
*
* Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi,
* Eric Lefevre-Ardant, Erik Ramfelt, Michael B. Donohue, Alan Harder,
* Manufacture Francaise des Pneumatiques Michelin, Romain Seguy
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson;
import com.google.common.annotations.VisibleForTesting;
import com.jcraft.jzlib.GZIPInputStream;
import com.jcraft.jzlib.GZIPOutputStream;
import hudson.Launcher.LocalLauncher;
import hudson.Launcher.RemoteLauncher;
import hudson.model.AbstractProject;
import hudson.model.Computer;
import hudson.model.Item;
import hudson.model.TaskListener;
import hudson.os.PosixAPI;
import hudson.os.PosixException;
import hudson.remoting.Callable;
import hudson.remoting.Channel;
import hudson.remoting.DelegatingCallable;
import hudson.remoting.Future;
import hudson.remoting.LocalChannel;
import hudson.remoting.Pipe;
import hudson.remoting.RemoteInputStream;
import hudson.remoting.RemoteInputStream.Flag;
import hudson.remoting.RemoteOutputStream;
import hudson.remoting.VirtualChannel;
import hudson.remoting.Which;
import hudson.security.AccessControlled;
import hudson.util.DaemonThreadFactory;
import hudson.util.DirScanner;
import hudson.util.ExceptionCatchingThreadFactory;
import hudson.util.FileVisitor;
import hudson.util.FormValidation;
import hudson.util.HeadBufferingStream;
import hudson.util.IOUtils;
import hudson.util.NamingThreadFactory;
import hudson.util.io.Archiver;
import hudson.util.io.ArchiverFactory;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.io.Serializable;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.FileSystemException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.LinkOption;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import jenkins.FilePathFilter;
import jenkins.MasterToSlaveFileCallable;
import jenkins.SlaveToMasterFileCallable;
import jenkins.SoloFilePathFilter;
import jenkins.model.Jenkins;
import jenkins.security.MasterToSlaveCallable;
import jenkins.util.ContextResettingExecutorService;
import jenkins.util.VirtualFile;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.io.input.CountingInputStream;
import org.apache.commons.lang.StringUtils;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.jenkinsci.remoting.RoleChecker;
import org.jenkinsci.remoting.RoleSensitive;
import org.jenkinsci.remoting.SerializableOnlyOverRemoting;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.Function;
import org.kohsuke.stapler.Stapler;
import static hudson.FilePath.TarCompression.GZIP;
import static hudson.Util.fileToPath;
import static hudson.Util.fixEmpty;
import java.io.NotSerializableException;
import java.util.Collections;
import org.apache.tools.ant.BuildException;
/**
* {@link File} like object with remoting support.
*
* <p>
* Unlike {@link File}, which always implies a file path on the current computer,
* {@link FilePath} represents a file path on a specific agent or the master.
*
* Despite that, {@link FilePath} can be used much like {@link File}. It exposes
* a bunch of operations (and we should add more operations as long as they are
* generally useful), and when invoked against a file on a remote node, {@link FilePath}
* executes the necessary code remotely, thereby providing semi-transparent file
* operations.
*
* <h2>Using {@link FilePath} smartly</h2>
* <p>
* The transparency makes it easy to write plugins without worrying too much about
* remoting, by making it works like NFS, where remoting happens at the file-system
* layer.
*
* <p>
* But one should note that such use of remoting may not be optional. Sometimes,
* it makes more sense to move some computation closer to the data, as opposed to
* move the data to the computation. For example, if you are just computing a MD5
* digest of a file, then it would make sense to do the digest on the host where
* the file is located, as opposed to send the whole data to the master and do MD5
* digesting there.
*
* <p>
* {@link FilePath} supports this "code migration" by in the
* {@link #act(FileCallable)} method. One can pass in a custom implementation
* of {@link FileCallable}, to be executed on the node where the data is located.
* The following code shows the example:
*
* <pre>
* void someMethod(FilePath file) {
* // make 'file' a fresh empty directory.
* file.act(new Freshen());
* }
* // if 'file' is on a different node, this FileCallable will
* // be transferred to that node and executed there.
* private static final class Freshen implements FileCallable<Void> {
* private static final long serialVersionUID = 1;
* @Override public Void invoke(File f, VirtualChannel channel) {
* // f and file represent the same thing
* f.deleteContents();
* f.mkdirs();
* return null;
* }
* }
* </pre>
*
* <p>
* When {@link FileCallable} is transferred to a remote node, it will be done so
* by using the same Java serialization scheme that the remoting module uses.
* See {@link Channel} for more about this.
*
* <p>
* {@link FilePath} itself can be sent over to a remote node as a part of {@link Callable}
* serialization. For example, sending a {@link FilePath} of a remote node to that
* node causes {@link FilePath} to become "local". Similarly, sending a
* {@link FilePath} that represents the local computer causes it to become "remote."
*
* @author Kohsuke Kawaguchi
* @see VirtualFile
*/
public final class FilePath implements SerializableOnlyOverRemoting {
/**
* Maximum http redirects we will follow. This defaults to the same number as Firefox/Chrome tolerates.
*/
private static final int MAX_REDIRECTS = 20;
/**
* When this {@link FilePath} represents the remote path,
* this field is always non-null on master (the field represents
* the channel to the remote agent.) When transferred to a agent via remoting,
* this field reverts back to null, since it's transient.
*
* When this {@link FilePath} represents a path on the master,
* this field is null on master. When transferred to a agent via remoting,
* this field becomes non-null, representing the {@link Channel}
* back to the master.
*
* This is used to determine whether we are running on the master or the agent.
*/
private transient VirtualChannel channel;
/**
* Represent the path to the file in the master or the agent
* Since the platform of the agent might be different, can't use java.io.File
*
* The field could not be final since it's modified in {@link #readResolve()}
*/
private /*final*/ String remote;
/**
* If this {@link FilePath} is deserialized to handle file access request from a remote computer,
* this field is set to the filter that performs access control.
*
* <p>
* If null, no access control is needed.
*
* @see #filterNonNull()
*/
private transient @Nullable
SoloFilePathFilter filter;
/**
* Creates a {@link FilePath} that represents a path on the given node.
*
* @param channel
* To create a path that represents a remote path, pass in a {@link Channel}
* that's connected to that machine. If {@code null}, that means the local file path.
*/
public FilePath(@CheckForNull VirtualChannel channel, @Nonnull String remote) {
this.channel = channel instanceof LocalChannel ? null : channel;
this.remote = normalize(remote);
}
/**
* To create {@link FilePath} that represents a "local" path.
*
* <p>
* A "local" path means a file path on the computer where the
* constructor invocation happened.
*/
public FilePath(@Nonnull File localPath) {
this.channel = null;
this.remote = normalize(localPath.getPath());
}
/**
* Construct a path starting with a base location.
* @param base starting point for resolution, and defines channel
* @param rel a path which if relative will be resolved against base
*/
public FilePath(@Nonnull FilePath base, @Nonnull String rel) {
this.channel = base.channel;
this.remote = normalize(resolvePathIfRelative(base, rel));
}
private Object readResolve() {
this.remote = normalize(this.remote);
return this;
}
private String resolvePathIfRelative(@Nonnull FilePath base, @Nonnull String rel) {
if(isAbsolute(rel)) return rel;
if(base.isUnix()) {
// shouldn't need this replace, but better safe than sorry
return base.remote+'/'+rel.replace('\\','/');
} else {
// need this replace, see Slave.getWorkspaceFor and AbstractItem.getFullName, nested jobs on Windows
// agents will always have a rel containing at least one '/' character. JENKINS-13649
return base.remote+'\\'+rel.replace('/','\\');
}
}
/**
* Is the given path name an absolute path?
*/
private static boolean isAbsolute(@Nonnull String rel) {
return rel.startsWith("/") || DRIVE_PATTERN.matcher(rel).matches() || UNC_PATTERN.matcher(rel).matches();
}
private static final Pattern DRIVE_PATTERN = Pattern.compile("[A-Za-z]:[\\\\/].*"),
UNC_PATTERN = Pattern.compile("^\\\\\\\\.*"),
ABSOLUTE_PREFIX_PATTERN = Pattern.compile("^(\\\\\\\\|(?:[A-Za-z]:)?[\\\\/])[\\\\/]*");
/**
* {@link File#getParent()} etc cannot handle ".." and "." in the path component very well,
* so remove them.
*/
@Restricted(NoExternalUse.class)
public static String normalize(@Nonnull String path) {
StringBuilder buf = new StringBuilder();
// Check for prefix designating absolute path
Matcher m = ABSOLUTE_PREFIX_PATTERN.matcher(path);
if (m.find()) {
buf.append(m.group(1));
path = path.substring(m.end());
}
boolean isAbsolute = buf.length() > 0;
// Split remaining path into tokens, trimming any duplicate or trailing separators
List<String> tokens = new ArrayList<>();
int s = 0, end = path.length();
for (int i = 0; i < end; i++) {
char c = path.charAt(i);
if (c == '/' || c == '\\') {
tokens.add(path.substring(s, i));
s = i;
// Skip any extra separator chars
//noinspection StatementWithEmptyBody
while (++i < end && ((c = path.charAt(i)) == '/' || c == '\\'));
// Add token for separator unless we reached the end
if (i < end) tokens.add(path.substring(s, s+1));
s = i;
}
}
if (s < end) tokens.add(path.substring(s));
// Look through tokens for "." or ".."
for (int i = 0; i < tokens.size();) {
String token = tokens.get(i);
if (token.equals(".")) {
tokens.remove(i);
if (tokens.size() > 0)
tokens.remove(i > 0 ? i - 1 : i);
} else if (token.equals("..")) {
if (i == 0) {
// If absolute path, just remove: /../something
// If relative path, not collapsible so leave as-is
tokens.remove(0);
if (tokens.size() > 0) token += tokens.remove(0);
if (!isAbsolute) buf.append(token);
} else {
// Normalize: remove something/.. plus separator before/after
i -= 2;
for (int j = 0; j < 3; j++) tokens.remove(i);
if (i > 0) tokens.remove(i-1);
else if (tokens.size() > 0) tokens.remove(0);
}
} else
i += 2;
}
// Recombine tokens
for (String token : tokens) buf.append(token);
if (buf.length() == 0) buf.append('.');
return buf.toString();
}
/**
* Checks if the remote path is Unix.
*/
boolean isUnix() {
// if the path represents a local path, there' no need to guess.
if(!isRemote())
return File.pathSeparatorChar!=';';
// note that we can't use the usual File.pathSeparator and etc., as the OS of
// the machine where this code runs and the OS that this FilePath refers to may be different.
// Windows absolute path is 'X:\...', so this is usually a good indication of Windows path
if(remote.length()>3 && remote.charAt(1)==':' && remote.charAt(2)=='\\')
return false;
// Windows can handle '/' as a path separator but Unix can't,
// so err on Unix side
return !remote.contains("\\");
}
/**
* Gets the full path of the file on the remote machine.
*
*/
public String getRemote() {
return remote;
}
/**
* Creates a zip file from this directory or a file and sends that to the given output stream.
*
* @deprecated as of 1.315. Use {@link #zip(OutputStream)} that has more consistent name.
*/
@Deprecated
public void createZipArchive(OutputStream os) throws IOException, InterruptedException {
zip(os);
}
/**
* Creates a zip file from this directory or a file and sends that to the given output stream.
*/
public void zip(OutputStream os) throws IOException, InterruptedException {
zip(os,(FileFilter)null);
}
public void zip(FilePath dst) throws IOException, InterruptedException {
try (OutputStream os = dst.write()) {
zip(os);
}
}
/**
* Creates a zip file from this directory by using the specified filter,
* and sends the result to the given output stream.
*
* @param filter
* Must be serializable since it may be executed remotely. Can be null to add all files.
*
* @since 1.315
*/
public void zip(OutputStream os, FileFilter filter) throws IOException, InterruptedException {
archive(ArchiverFactory.ZIP,os,filter);
}
/**
* Creates a zip file from this directory by only including the files that match the given glob.
*
* @param glob
* Ant style glob, like "**/*.xml". If empty or null, this method
* works like {@link #createZipArchive(OutputStream)}
*
* @since 1.129
* @deprecated as of 1.315
* Use {@link #zip(OutputStream,String)} that has more consistent name.
*/
@Deprecated
public void createZipArchive(OutputStream os, final String glob) throws IOException, InterruptedException {
archive(ArchiverFactory.ZIP,os,glob);
}
/**
* Creates a zip file from this directory by only including the files that match the given glob.
*
* @param glob
* Ant style glob, like "**/*.xml". If empty or null, this method
* works like {@link #createZipArchive(OutputStream)}, inserting a top-level directory into the ZIP.
*
* @since 1.315
*/
public void zip(OutputStream os, final String glob) throws IOException, InterruptedException {
archive(ArchiverFactory.ZIP,os,glob);
}
/**
* Uses the given scanner on 'this' directory to list up files and then archive it to a zip stream.
*/
public int zip(OutputStream out, DirScanner scanner) throws IOException, InterruptedException {
return archive(ArchiverFactory.ZIP, out, scanner);
}
/**
* Archives this directory into the specified archive format, to the given {@link OutputStream}, by using
* {@link DirScanner} to choose what files to include.
*
* @return
* number of files/directories archived. This is only really useful to check for a situation where nothing
* is archived.
*/
public int archive(final ArchiverFactory factory, OutputStream os, final DirScanner scanner) throws IOException, InterruptedException {
final OutputStream out = (channel!=null)?new RemoteOutputStream(os):os;
return act(new Archive(factory, out, scanner));
}
private class Archive extends SecureFileCallable<Integer> {
private final ArchiverFactory factory;
private final OutputStream out;
private final DirScanner scanner;
Archive(ArchiverFactory factory, OutputStream out, DirScanner scanner) {
this.factory = factory;
this.out = out;
this.scanner = scanner;
}
@Override
public Integer invoke(File f, VirtualChannel channel) throws IOException {
Archiver a = factory.create(out);
try {
scanner.scan(f,reading(a));
} finally {
a.close();
}
return a.countEntries();
}
private static final long serialVersionUID = 1L;
}
public int archive(final ArchiverFactory factory, OutputStream os, final FileFilter filter) throws IOException, InterruptedException {
return archive(factory,os,new DirScanner.Filter(filter));
}
public int archive(final ArchiverFactory factory, OutputStream os, final String glob) throws IOException, InterruptedException {
return archive(factory,os,new DirScanner.Glob(glob,null));
}
/**
* When this {@link FilePath} represents a zip file, extracts that zip file.
*
* @param target
* Target directory to expand files to. All the necessary directories will be created.
* @since 1.248
* @see #unzipFrom(InputStream)
*/
public void unzip(final FilePath target) throws IOException, InterruptedException {
// TODO: post release, re-unite two branches by introducing FileStreamCallable that resolves InputStream
if (this.channel!=target.channel) {// local -> remote or remote->local
final RemoteInputStream in = new RemoteInputStream(read(), Flag.GREEDY);
target.act(new UnzipRemote(in));
} else {// local -> local or remote->remote
target.act(new UnzipLocal());
}
}
private class UnzipRemote extends SecureFileCallable<Void> {
private final RemoteInputStream in;
UnzipRemote(RemoteInputStream in) {
this.in = in;
}
@Override
public Void invoke(File dir, VirtualChannel channel) throws IOException, InterruptedException {
unzip(dir, in);
return null;
}
private static final long serialVersionUID = 1L;
}
private class UnzipLocal extends SecureFileCallable<Void> {
@Override
public Void invoke(File dir, VirtualChannel channel) throws IOException, InterruptedException {
assert !FilePath.this.isRemote(); // this.channel==target.channel above
unzip(dir, reading(new File(FilePath.this.getRemote()))); // shortcut to local file
return null;
}
private static final long serialVersionUID = 1L;
}
/**
* When this {@link FilePath} represents a tar file, extracts that tar file.
*
* @param target
* Target directory to expand files to. All the necessary directories will be created.
* @param compression
* Compression mode of this tar file.
* @since 1.292
* @see #untarFrom(InputStream, TarCompression)
*/
public void untar(final FilePath target, final TarCompression compression) throws IOException, InterruptedException {
// TODO: post release, re-unite two branches by introducing FileStreamCallable that resolves InputStream
if (this.channel!=target.channel) {// local -> remote or remote->local
final RemoteInputStream in = new RemoteInputStream(read(), Flag.GREEDY);
target.act(new UntarRemote(compression, in));
} else {// local -> local or remote->remote
target.act(new UntarLocal(compression));
}
}
private class UntarRemote extends SecureFileCallable<Void> {
private final TarCompression compression;
private final RemoteInputStream in;
UntarRemote(TarCompression compression, RemoteInputStream in) {
this.compression = compression;
this.in = in;
}
@Override
public Void invoke(File dir, VirtualChannel channel) throws IOException, InterruptedException {
readFromTar(FilePath.this.getName(), dir, compression.extract(in));
return null;
}
private static final long serialVersionUID = 1L;
}
private class UntarLocal extends SecureFileCallable<Void> {
private final TarCompression compression;
UntarLocal(TarCompression compression) {
this.compression = compression;
}
@Override
public Void invoke(File dir, VirtualChannel channel) throws IOException, InterruptedException {
readFromTar(FilePath.this.getName(), dir, compression.extract(FilePath.this.read()));
return null;
}
private static final long serialVersionUID = 1L;
}
/**
* Reads the given InputStream as a zip file and extracts it into this directory.
*
* @param _in
* The stream will be closed by this method after it's fully read.
* @since 1.283
* @see #unzip(FilePath)
*/
public void unzipFrom(InputStream _in) throws IOException, InterruptedException {
final InputStream in = new RemoteInputStream(_in, Flag.GREEDY);
act(new UnzipFrom(in));
}
private class UnzipFrom extends SecureFileCallable<Void> {
private final InputStream in;
UnzipFrom(InputStream in) {
this.in = in;
}
@Override
public Void invoke(File dir, VirtualChannel channel) throws IOException {
unzip(dir, in);
return null;
}
private static final long serialVersionUID = 1L;
}
private void unzip(File dir, InputStream in) throws IOException {
File tmpFile = File.createTempFile("tmpzip", null); // uses java.io.tmpdir
try {
// TODO why does this not simply use ZipInputStream?
IOUtils.copy(in, tmpFile);
unzip(dir,tmpFile);
}
finally {
tmpFile.delete();
}
}
private void unzip(File dir, File zipFile) throws IOException {
dir = dir.getAbsoluteFile(); // without absolutization, getParentFile below seems to fail
ZipFile zip = new ZipFile(zipFile);
Enumeration<ZipEntry> entries = zip.getEntries();
try {
while (entries.hasMoreElements()) {
ZipEntry e = entries.nextElement();
File f = new File(dir, e.getName());
if (!f.getCanonicalPath().startsWith(dir.getCanonicalPath())) {
throw new IOException(
"Zip " + zipFile.getPath() + " contains illegal file name that breaks out of the target directory: " + e.getName());
}
if (e.isDirectory()) {
mkdirs(f);
} else {
File p = f.getParentFile();
if (p != null) {
mkdirs(p);
}
try (InputStream input = zip.getInputStream(e)) {
IOUtils.copy(input, writing(f));
}
try {
FilePath target = new FilePath(f);
int mode = e.getUnixMode();
if (mode!=0) // Ant returns 0 if the archive doesn't record the access mode
target.chmod(mode);
} catch (InterruptedException ex) {
LOGGER.log(Level.WARNING, "unable to set permissions", ex);
}
f.setLastModified(e.getTime());
}
}
} finally {
zip.close();
}
}
/**
* Absolutizes this {@link FilePath} and returns the new one.
*/
public FilePath absolutize() throws IOException, InterruptedException {
return new FilePath(channel, act(new Absolutize()));
}
private static class Absolutize extends SecureFileCallable<String> {
private static final long serialVersionUID = 1L;
public String invoke(File f, VirtualChannel channel) throws IOException {
return f.getAbsolutePath();
}
}
/**
* Creates a symlink to the specified target.
*
* @param target
* The file that the symlink should point to.
* @param listener
* If symlink creation requires a help of an external process, the error will be reported here.
* @since 1.456
*/
public void symlinkTo(final String target, final TaskListener listener) throws IOException, InterruptedException {
act(new SymlinkTo(target, listener));
}
private class SymlinkTo extends SecureFileCallable<Void> {
private final String target;
private final TaskListener listener;
SymlinkTo(String target, TaskListener listener) {
this.target = target;
this.listener = listener;
}
private static final long serialVersionUID = 1L;
@Override
public Void invoke(File f, VirtualChannel channel) throws IOException, InterruptedException {
symlinking(f);
Util.createSymlink(f.getParentFile(), target, f.getName(), listener);
return null;
}
}
/**
* Resolves symlink, if the given file is a symlink. Otherwise return null.
* <p>
* If the resolution fails, report an error.
*
* @since 1.456
*/
public String readLink() throws IOException, InterruptedException {
return act(new ReadLink());
}
private class ReadLink extends SecureFileCallable<String> {
private static final long serialVersionUID = 1L;
@Override
public String invoke(File f, VirtualChannel channel) throws IOException, InterruptedException {
return Util.resolveSymlink(reading(f));
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
FilePath that = (FilePath) o;
if (channel != null ? !channel.equals(that.channel) : that.channel != null) return false;
return remote.equals(that.remote);
}
@Override
public int hashCode() {
return 31 * (channel != null ? channel.hashCode() : 0) + remote.hashCode();
}
/**
* Supported tar file compression methods.
*/
public enum TarCompression {
NONE {
public InputStream extract(InputStream in) {
return in;
}
public OutputStream compress(OutputStream out) {
return out;
}
},
GZIP {
public InputStream extract(InputStream _in) throws IOException {
HeadBufferingStream in = new HeadBufferingStream(_in,SIDE_BUFFER_SIZE);
try {
return new GZIPInputStream(in, 8192, true);
} catch (IOException e) {
// various people reported "java.io.IOException: Not in GZIP format" here, so diagnose this problem better
in.fillSide();
throw new IOException(e.getMessage()+"\nstream="+Util.toHexString(in.getSideBuffer()),e);
}
}
public OutputStream compress(OutputStream out) throws IOException {
return new GZIPOutputStream(new BufferedOutputStream(out));
}
};
public abstract InputStream extract(InputStream in) throws IOException;
public abstract OutputStream compress(OutputStream in) throws IOException;
}
/**
* Reads the given InputStream as a tar file and extracts it into this directory.
*
* @param _in
* The stream will be closed by this method after it's fully read.
* @param compression
* The compression method in use.
* @since 1.292
*/
public void untarFrom(InputStream _in, final TarCompression compression) throws IOException, InterruptedException {
try {
final InputStream in = new RemoteInputStream(_in, Flag.GREEDY);
act(new UntarFrom(compression, in));
} finally {
_in.close();
}
}
private class UntarFrom extends SecureFileCallable<Void> {
private final TarCompression compression;
private final InputStream in;
UntarFrom(TarCompression compression, InputStream in) {
this.compression = compression;
this.in = in;
}
@Override
public Void invoke(File dir, VirtualChannel channel) throws IOException {
readFromTar("input stream",dir, compression.extract(in));
return null;
}
private static final long serialVersionUID = 1L;
}
/**
* Given a tgz/zip file, extracts it to the given target directory, if necessary.
*
* <p>
* This method is a convenience method designed for installing a binary package to a location
* that supports upgrade and downgrade. Specifically,
*
* <ul>
* <li>If the target directory doesn't exist {@linkplain #mkdirs() it will be created}.
* <li>The timestamp of the archive is left in the installation directory upon extraction.
* <li>If the timestamp left in the directory does not match the timestamp of the current archive file,
* the directory contents will be discarded and the archive file will be re-extracted.
* <li>If the connection is refused but the target directory already exists, it is left alone.
* </ul>
*
* @param archive
* The resource that represents the tgz/zip file. This URL must support the {@code Last-Modified} header.
* (For example, you could use {@link ClassLoader#getResource}.)
* @param listener
* If non-null, a message will be printed to this listener once this method decides to
* extract an archive, or if there is any issue.
* @param message a message to be printed in case extraction will proceed.
* @return
* true if the archive was extracted. false if the extraction was skipped because the target directory
* was considered up to date.
* @since 1.299
*/
public boolean installIfNecessaryFrom(@Nonnull URL archive, @CheckForNull TaskListener listener, @Nonnull String message) throws IOException, InterruptedException {
return installIfNecessaryFrom(archive, listener, message, MAX_REDIRECTS);
}
private boolean installIfNecessaryFrom(@Nonnull URL archive, @CheckForNull TaskListener listener, @Nonnull String message, int maxRedirects) throws InterruptedException, IOException {
try {
FilePath timestamp = this.child(".timestamp");
long lastModified = timestamp.lastModified();
URLConnection con;
try {
con = ProxyConfiguration.open(archive);
if (lastModified != 0) {
con.setIfModifiedSince(lastModified);
}
con.connect();
} catch (IOException x) {
if (this.exists()) {
// Cannot connect now, so assume whatever was last unpacked is still OK.
if (listener != null) {
listener.getLogger().println("Skipping installation of " + archive + " to " + remote + ": " + x);
}
return false;
} else {
throw x;
}
}
if (con instanceof HttpURLConnection) {
HttpURLConnection httpCon = (HttpURLConnection) con;
int responseCode = httpCon.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_MOVED_PERM
|| responseCode == HttpURLConnection.HTTP_MOVED_TEMP) {
// follows redirect
if (maxRedirects > 0) {
String location = httpCon.getHeaderField("Location");
listener.getLogger().println("Following redirect " + archive.toExternalForm() + " -> " + location);
return installIfNecessaryFrom(getUrlFactory().newURL(location), listener, message, maxRedirects - 1);
} else {
listener.getLogger().println("Skipping installation of " + archive + " to " + remote + " due to too many redirects.");
return false;
}
}
if (lastModified != 0) {
if (responseCode == HttpURLConnection.HTTP_NOT_MODIFIED) {
return false;
} else if (responseCode != HttpURLConnection.HTTP_OK) {
listener.getLogger().println("Skipping installation of " + archive + " to " + remote + " due to server error: " + responseCode + " " + httpCon.getResponseMessage());
return false;
}
}
}
long sourceTimestamp = con.getLastModified();
if(this.exists()) {
if (lastModified != 0 && sourceTimestamp == lastModified)
return false; // already up to date
this.deleteContents();
} else {
this.mkdirs();
}
if(listener!=null)
listener.getLogger().println(message);
if (isRemote()) {
// First try to download from the agent machine.
try {
act(new Unpack(archive));
timestamp.touch(sourceTimestamp);
return true;
} catch (IOException x) {
if (listener != null) {
Functions.printStackTrace(x, listener.error("Failed to download " + archive + " from agent; will retry from master"));
}
}
}
// for HTTP downloads, enable automatic retry for added resilience
InputStream in = archive.getProtocol().startsWith("http") ? ProxyConfiguration.getInputStream(archive) : con.getInputStream();
CountingInputStream cis = new CountingInputStream(in);
try {
if(archive.toExternalForm().endsWith(".zip"))
unzipFrom(cis);
else
untarFrom(cis,GZIP);
} catch (IOException e) {
throw new IOException(String.format("Failed to unpack %s (%d bytes read of total %d)",
archive,cis.getByteCount(),con.getContentLength()),e);
}
timestamp.touch(sourceTimestamp);
return true;
} catch (IOException e) {
throw new IOException("Failed to install "+archive+" to "+remote,e);
}
}
// this reads from arbitrary URL
private final class Unpack extends MasterToSlaveFileCallable<Void> {
private final URL archive;
Unpack(URL archive) {
this.archive = archive;
}
@Override public Void invoke(File dir, VirtualChannel channel) throws IOException, InterruptedException {
try (InputStream in = archive.openStream()) {
CountingInputStream cis = new CountingInputStream(in);
try {
if (archive.toExternalForm().endsWith(".zip")) {
unzip(dir, cis);
} else {
readFromTar("input stream", dir, GZIP.extract(cis));
}
} catch (IOException x) {
throw new IOException(String.format("Failed to unpack %s (%d bytes read)", archive, cis.getByteCount()), x);
}
}
return null;
}
}
/**
* Reads the URL on the current VM, and streams the data to this file using the Remoting channel.
* <p>This is different from resolving URL remotely.
* If you instead wished to open an HTTP(S) URL on the remote side,
* prefer <a href="http://javadoc.jenkins.io/plugin/apache-httpcomponents-client-4-api/io/jenkins/plugins/httpclient/RobustHTTPClient.html#copyFromRemotely-hudson.FilePath-java.net.URL-hudson.model.TaskListener-">{@code RobustHTTPClient.copyFromRemotely}</a>.
* @since 1.293
*/
public void copyFrom(URL url) throws IOException, InterruptedException {
try (InputStream in = url.openStream()) {
copyFrom(in);
}
}
/**
* Replaces the content of this file by the data from the given {@link InputStream}.
*
* @since 1.293
*/
public void copyFrom(InputStream in) throws IOException, InterruptedException {
try (OutputStream os = write()) {
org.apache.commons.io.IOUtils.copy(in, os);
}
}
/**
* Convenience method to call {@link FilePath#copyTo(FilePath)}.
*
* @since 1.311
*/
public void copyFrom(FilePath src) throws IOException, InterruptedException {
src.copyTo(this);
}
/**
* Place the data from {@link FileItem} into the file location specified by this {@link FilePath} object.
*/
public void copyFrom(FileItem file) throws IOException, InterruptedException {
if(channel==null) {
try {
file.write(writing(new File(remote)));
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw new IOException(e);
}
} else {
try (InputStream i = file.getInputStream();
OutputStream o = write()) {
org.apache.commons.io.IOUtils.copy(i,o);
}
}
}
/**
* Code that gets executed on the machine where the {@link FilePath} is local.
* Used to act on {@link FilePath}.
* <strong>Warning:</strong> implementations must be serializable, so prefer a static nested class to an inner class.
*
* <p>
* Subtypes would likely want to extend from either {@link MasterToSlaveCallable}
* or {@link SlaveToMasterFileCallable}.
*
* @see FilePath#act(FileCallable)
*/
public interface FileCallable<T> extends Serializable, RoleSensitive {
/**
* Performs the computational task on the node where the data is located.
*
* <p>
* All the exceptions are forwarded to the caller.
*
* @param f
* {@link File} that represents the local file that {@link FilePath} has represented.
* @param channel
* The "back pointer" of the {@link Channel} that represents the communication
* with the node from where the code was sent.
*/
T invoke(File f, VirtualChannel channel) throws IOException, InterruptedException;
}
/**
* {@link FileCallable}s that can be executed anywhere, including the master.
*
* The code is the same as {@link SlaveToMasterFileCallable}, but used as a marker to
* designate those impls that use {@link FilePathFilter}.
*/
/*package*/ static abstract class SecureFileCallable<T> extends SlaveToMasterFileCallable<T> {
}
/**
* Executes some program on the machine that this {@link FilePath} exists,
* so that one can perform local file operations.
*/
public <T> T act(final FileCallable<T> callable) throws IOException, InterruptedException {
return act(callable,callable.getClass().getClassLoader());
}
private <T> T act(final FileCallable<T> callable, ClassLoader cl) throws IOException, InterruptedException {
if(channel!=null) {
// run this on a remote system
try {
DelegatingCallable<T,IOException> wrapper = new FileCallableWrapper<>(callable, cl);
for (FileCallableWrapperFactory factory : ExtensionList.lookup(FileCallableWrapperFactory.class)) {
wrapper = factory.wrap(wrapper);
}
return channel.call(wrapper);
} catch (TunneledInterruptedException e) {
throw (InterruptedException)new InterruptedException(e.getMessage()).initCause(e);
}
} else {
// the file is on the local machine.
return callable.invoke(new File(remote), localChannel);
}
}
/**
* This extension point allows to contribute a wrapper around a fileCallable so that a plugin can "intercept" a
* call.
* <p>The {@link #wrap(hudson.remoting.DelegatingCallable)} method itself will be executed on master
* (and may collect contextual data if needed) and the returned wrapper will be executed on remote.
*
* @since 1.482
* @see AbstractInterceptorCallableWrapper
*/
public static abstract class FileCallableWrapperFactory implements ExtensionPoint {
public abstract <T> DelegatingCallable<T,IOException> wrap(DelegatingCallable<T,IOException> callable);
}
/**
* Abstract {@link DelegatingCallable} that exposes an Before/After pattern for
* {@link hudson.FilePath.FileCallableWrapperFactory} that want to implement AOP-style interceptors
* @since 1.482
*/
public static abstract class AbstractInterceptorCallableWrapper<T> implements DelegatingCallable<T, IOException> {
private static final long serialVersionUID = 1L;
private final DelegatingCallable<T, IOException> callable;
public AbstractInterceptorCallableWrapper(DelegatingCallable<T, IOException> callable) {
this.callable = callable;
}
@Override
public final ClassLoader getClassLoader() {
return callable.getClassLoader();
}
public final T call() throws IOException {
before();
try {
return callable.call();
} finally {
after();
}
}
/**
* Executed before the actual FileCallable is invoked. This code will run on remote
*/
protected void before() {}
/**
* Executed after the actual FileCallable is invoked (even if this one failed). This code will run on remote
*/
protected void after() {}
}
/**
* Executes some program on the machine that this {@link FilePath} exists,
* so that one can perform local file operations.
*/
public <T> Future<T> actAsync(final FileCallable<T> callable) throws IOException, InterruptedException {
try {
DelegatingCallable<T,IOException> wrapper = new FileCallableWrapper<>(callable);
for (FileCallableWrapperFactory factory : ExtensionList.lookup(FileCallableWrapperFactory.class)) {
wrapper = factory.wrap(wrapper);
}
return (channel!=null ? channel : localChannel)
.callAsync(wrapper);
} catch (IOException e) {
// wrap it into a new IOException so that we get the caller's stack trace as well.
throw new IOException("remote file operation failed",e);
}
}
/**
* Executes some program on the machine that this {@link FilePath} exists,
* so that one can perform local file operations.
*/
public <V,E extends Throwable> V act(Callable<V,E> callable) throws IOException, InterruptedException, E {
if(channel!=null) {
// run this on a remote system
return channel.call(callable);
} else {
// the file is on the local machine
return callable.call();
}
}
/**
* Takes a {@link FilePath}+{@link FileCallable} pair and returns the equivalent {@link Callable}.
* When executing the resulting {@link Callable}, it executes {@link FileCallable#act(FileCallable)}
* on this {@link FilePath}.
*
* @since 1.522
*/
public <V> Callable<V,IOException> asCallableWith(final FileCallable<V> task) {
return new CallableWith<>(task);
}
private class CallableWith<V> implements Callable<V, IOException> {
private final FileCallable<V> task;
CallableWith(FileCallable<V> task) {
this.task = task;
}
@Override
public V call() throws IOException {
try {
return act(task);
} catch (InterruptedException e) {
throw (IOException)new InterruptedIOException().initCause(e);
}
}
@Override
public void checkRoles(RoleChecker checker) throws SecurityException {
task.checkRoles(checker);
}
private static final long serialVersionUID = 1L;
}
/**
* Converts this file to the URI, relative to the machine
* on which this file is available.
*/
public URI toURI() throws IOException, InterruptedException {
return act(new ToURI());
}
private static class ToURI extends SecureFileCallable<URI> {
private static final long serialVersionUID = 1L;
@Override
public URI invoke(File f, VirtualChannel channel) {
return f.toURI();
}
}
/**
* Gets the {@link VirtualFile} representation of this {@link FilePath}
*
* @since 1.532
*/
public VirtualFile toVirtualFile() {
return VirtualFile.forFilePath(this);
}
/**
* If this {@link FilePath} represents a file on a particular {@link Computer}, return it.
* Otherwise null.
* @since 1.571
*/
public @CheckForNull Computer toComputer() {
Jenkins j = Jenkins.getInstanceOrNull();
if (j != null) {
for (Computer c : j.getComputers()) {
if (getChannel()==c.getChannel()) {
return c;
}
}
}
return null;
}
/**
* Creates this directory.
*/
public void mkdirs() throws IOException, InterruptedException {
if (!act(new Mkdirs())) {
throw new IOException("Failed to mkdirs: " + remote);
}
}
private class Mkdirs extends SecureFileCallable<Boolean> {
private static final long serialVersionUID = 1L;
@Override
public Boolean invoke(File f, VirtualChannel channel) throws IOException, InterruptedException {
if(mkdirs(f) || f.exists())
return true; // OK
// following Ant <mkdir> task to avoid possible race condition.
Thread.sleep(10);
return mkdirs(f) || f.exists();
}
}
/**
* Deletes this directory, including all its contents recursively.
*/
public void deleteRecursive() throws IOException, InterruptedException {
act(new DeleteRecursive());
}
private class DeleteRecursive extends SecureFileCallable<Void> {
private static final long serialVersionUID = 1L;
@Override
public Void invoke(File f, VirtualChannel channel) throws IOException {
Util.deleteRecursive(fileToPath(f), path -> deleting(path.toFile()));
return null;
}
}
/**
* Deletes all the contents of this directory, but not the directory itself
*/
public void deleteContents() throws IOException, InterruptedException {
act(new DeleteContents());
}
private class DeleteContents extends SecureFileCallable<Void> {
private static final long serialVersionUID = 1L;
@Override
public Void invoke(File f, VirtualChannel channel) throws IOException {
Util.deleteContentsRecursive(fileToPath(f), path -> deleting(path.toFile()));
return null;
}
}
/**
* Gets the file name portion except the extension.
*
* For example, "foo" for "foo.txt" and "foo.tar" for "foo.tar.gz".
*/
public String getBaseName() {
String n = getName();
int idx = n.lastIndexOf('.');
if (idx<0) return n;
return n.substring(0,idx);
}
/**
* Gets just the file name portion without directories.
*
* For example, "foo.txt" for "../abc/foo.txt"
*/
public String getName() {
String r = remote;
if(r.endsWith("\\") || r.endsWith("/"))
r = r.substring(0,r.length()-1);
int len = r.length()-1;
while(len>=0) {
char ch = r.charAt(len);
if(ch=='\\' || ch=='/')
break;
len--;
}
return r.substring(len+1);
}
/**
* Short for {@code getParent().child(rel)}. Useful for getting other files in the same directory.
*/
public FilePath sibling(String rel) {
return getParent().child(rel);
}
/**
* Returns a {@link FilePath} by adding the given suffix to this path name.
*/
public FilePath withSuffix(String suffix) {
return new FilePath(channel,remote+suffix);
}
/**
* The same as {@link FilePath#FilePath(FilePath,String)} but more OO.
* @param relOrAbsolute a relative or absolute path
* @return a file on the same channel
*/
public @Nonnull FilePath child(String relOrAbsolute) {
return new FilePath(this,relOrAbsolute);
}
/**
* Gets the parent file.
* @return parent FilePath or null if there is no parent
*/
public FilePath getParent() {
int i = remote.length() - 2;
for (; i >= 0; i--) {
char ch = remote.charAt(i);
if(ch=='\\' || ch=='/')
break;
}
return i >= 0 ? new FilePath( channel, remote.substring(0,i+1) ) : null;
}
/**
* Creates a temporary file in the directory that this {@link FilePath} object designates.
*
* @param prefix
* The prefix string to be used in generating the file's name; must be
* at least three characters long
* @param suffix
* The suffix string to be used in generating the file's name; may be
* null, in which case the suffix ".tmp" will be used
* @return
* The new FilePath pointing to the temporary file
* @see File#createTempFile(String, String)
*/
public FilePath createTempFile(final String prefix, final String suffix) throws IOException, InterruptedException {
try {
return new FilePath(this, act(new CreateTempFile(prefix, suffix)));
} catch (IOException e) {
throw new IOException("Failed to create a temp file on "+remote,e);
}
}
private class CreateTempFile extends SecureFileCallable<String> {
private final String prefix;
private final String suffix;
CreateTempFile(String prefix, String suffix) {
this.prefix = prefix;
this.suffix = suffix;
}
private static final long serialVersionUID = 1L;
@Override
public String invoke(File dir, VirtualChannel channel) throws IOException {
File f = writing(File.createTempFile(prefix, suffix, dir));
return f.getName();
}
}
/**
* Creates a temporary file in this directory and set the contents to the
* given text (encoded in the platform default encoding)
*
* @param prefix
* The prefix string to be used in generating the file's name; must be
* at least three characters long
* @param suffix
* The suffix string to be used in generating the file's name; may be
* null, in which case the suffix ".tmp" will be used
* @param contents
* The initial contents of the temporary file.
* @return
* The new FilePath pointing to the temporary file
* @see File#createTempFile(String, String)
*/
public FilePath createTextTempFile(final String prefix, final String suffix, final String contents) throws IOException, InterruptedException {
return createTextTempFile(prefix,suffix,contents,true);
}
/**
* Creates a temporary file in this directory (or the system temporary
* directory) and set the contents to the given text (encoded in the
* platform default encoding)
*
* @param prefix
* The prefix string to be used in generating the file's name; must be
* at least three characters long
* @param suffix
* The suffix string to be used in generating the file's name; may be
* null, in which case the suffix ".tmp" will be used
* @param contents
* The initial contents of the temporary file.
* @param inThisDirectory
* If true, then create this temporary in the directory pointed to by
* this.
* If false, then the temporary file is created in the system temporary
* directory (java.io.tmpdir)
* @return
* The new FilePath pointing to the temporary file
* @see File#createTempFile(String, String)
*/
public FilePath createTextTempFile(final String prefix, final String suffix, final String contents, final boolean inThisDirectory) throws IOException, InterruptedException {
try {
return new FilePath(channel, act(new CreateTextTempFile(inThisDirectory, prefix, suffix, contents)));
} catch (IOException e) {
throw new IOException("Failed to create a temp file on "+remote,e);
}
}
private final class CreateTextTempFile extends SecureFileCallable<String> {
private static final long serialVersionUID = 1L;
private final boolean inThisDirectory;
private final String prefix;
private final String suffix;
private final String contents;
CreateTextTempFile(boolean inThisDirectory, String prefix, String suffix, String contents) {
this.inThisDirectory = inThisDirectory;
this.prefix = prefix;
this.suffix = suffix;
this.contents = contents;
}
@Override
public String invoke(File dir, VirtualChannel channel) throws IOException {
if(!inThisDirectory)
dir = new File(System.getProperty("java.io.tmpdir"));
else
mkdirs(dir);
File f;
try {
f = creating(File.createTempFile(prefix, suffix, dir));
} catch (IOException e) {
throw new IOException("Failed to create a temporary directory in "+dir,e);
}
try (Writer w = new FileWriter(writing(f))) {
w.write(contents);
}
return f.getAbsolutePath();
}
}
/**
* Creates a temporary directory inside the directory represented by 'this'
*
* @param prefix
* The prefix string to be used in generating the directory's name;
* must be at least three characters long
* @param suffix
* The suffix string to be used in generating the directory's name; may
* be null, in which case the suffix ".tmp" will be used
* @return
* The new FilePath pointing to the temporary directory
* @since 1.311
* @see Files#createTempDirectory(Path, String, FileAttribute[])
*/
public FilePath createTempDir(final String prefix, final String suffix) throws IOException, InterruptedException {
try {
String[] s;
if (StringUtils.isBlank(suffix)) {
s = new String[]{prefix, "tmp"}; // see File.createTempFile - tmp is used if suffix is null
} else {
s = new String[]{prefix, suffix};
}
String name = StringUtils.join(s, ".");
return new FilePath(this, act(new CreateTempDir(name)));
} catch (IOException e) {
throw new IOException("Failed to create a temp directory on "+remote,e);
}
}
private class CreateTempDir extends SecureFileCallable<String> {
private final String name;
CreateTempDir(String name) {
this.name = name;
}
private static final long serialVersionUID = 1L;
@Override
public String invoke(File dir, VirtualChannel channel) throws IOException {
Path tempPath;
final boolean isPosix = FileSystems.getDefault().supportedFileAttributeViews().contains("posix");
if (isPosix) {
tempPath = Files.createTempDirectory(Util.fileToPath(dir), name,
PosixFilePermissions.asFileAttribute(EnumSet.allOf(PosixFilePermission.class)));
} else {
tempPath = Files.createTempDirectory(Util.fileToPath(dir), name, new FileAttribute<?>[] {});
}
if (tempPath.toFile() == null) {
throw new IOException("Failed to obtain file from path " + dir + " on " + remote);
}
return tempPath.toFile().getName();
}
}
/**
* Deletes this file.
* @throws IOException if it exists but could not be successfully deleted
* @return true, for a modicum of compatibility
*/
public boolean delete() throws IOException, InterruptedException {
act(new Delete());
return true;
}
private class Delete extends SecureFileCallable<Void> {
private static final long serialVersionUID = 1L;
@Override
public Void invoke(File f, VirtualChannel channel) throws IOException {
Util.deleteFile(deleting(f));
return null;
}
}
/**
* Checks if the file exists.
*/
public boolean exists() throws IOException, InterruptedException {
return act(new Exists());
}
private class Exists extends SecureFileCallable<Boolean> {
private static final long serialVersionUID = 1L;
@Override
public Boolean invoke(File f, VirtualChannel channel) throws IOException {
return stating(f).exists();
}
}
/**
* Gets the last modified time stamp of this file, by using the clock
* of the machine where this file actually resides.
*
* @see File#lastModified()
* @see #touch(long)
*/
public long lastModified() throws IOException, InterruptedException {
return act(new LastModified());
}
private class LastModified extends SecureFileCallable<Long> {
private static final long serialVersionUID = 1L;
@Override
public Long invoke(File f, VirtualChannel channel) throws IOException {
return stating(f).lastModified();
}
}
/**
* Creates a file (if not already exist) and sets the timestamp.
*
* @since 1.299
*/
public void touch(final long timestamp) throws IOException, InterruptedException {
act(new Touch(timestamp));
}
private class Touch extends SecureFileCallable<Void> {
private final long timestamp;
Touch(long timestamp) {
this.timestamp = timestamp;
}
private static final long serialVersionUID = -5094638816500738429L;
@Override
public Void invoke(File f, VirtualChannel channel) throws IOException {
if(!f.exists()) {
Files.newOutputStream(fileToPath(creating(f))).close();
}
if(!stating(f).setLastModified(timestamp))
throw new IOException("Failed to set the timestamp of "+f+" to "+timestamp);
return null;
}
}
private void setLastModifiedIfPossible(final long timestamp) throws IOException, InterruptedException {
String message = act(new SetLastModified(timestamp));
if (message!=null) {
LOGGER.warning(message);
}
}
private class SetLastModified extends SecureFileCallable<String> {
private final long timestamp;
SetLastModified(long timestamp) {
this.timestamp = timestamp;
}
private static final long serialVersionUID = -828220335793641630L;
@Override
public String invoke(File f, VirtualChannel channel) throws IOException {
if(!writing(f).setLastModified(timestamp)) {
if (Functions.isWindows()) {
// On Windows this seems to fail often. See JENKINS-11073
// Therefore don't fail, but just log a warning
return "Failed to set the timestamp of "+f+" to "+timestamp;
} else {
throw new IOException("Failed to set the timestamp of "+f+" to "+timestamp);
}
}
return null;
}
}
/**
* Checks if the file is a directory.
*/
public boolean isDirectory() throws IOException, InterruptedException {
return act(new IsDirectory());
}
private final class IsDirectory extends SecureFileCallable<Boolean> {
private static final long serialVersionUID = 1L;
@Override
public Boolean invoke(File f, VirtualChannel channel) throws IOException {
return stating(f).isDirectory();
}
}
/**
* Returns the file size in bytes.
*
* @since 1.129
*/
public long length() throws IOException, InterruptedException {
return act(new Length());
}
private class Length extends SecureFileCallable<Long> {
private static final long serialVersionUID = 1L;
@Override
public Long invoke(File f, VirtualChannel channel) throws IOException {
return stating(f).length();
}
}
/**
* Returns the number of unallocated bytes in the partition of that file.
* @since 1.542
*/
public long getFreeDiskSpace() throws IOException, InterruptedException {
return act(new GetFreeDiskSpace());
}
private static class GetFreeDiskSpace extends SecureFileCallable<Long> {
private static final long serialVersionUID = 1L;
@Override
public Long invoke(File f, VirtualChannel channel) throws IOException {
return f.getFreeSpace();
}
}
/**
* Returns the total number of bytes in the partition of that file.
* @since 1.542
*/
public long getTotalDiskSpace() throws IOException, InterruptedException {
return act(new GetTotalDiskSpace());
}
private static class GetTotalDiskSpace extends SecureFileCallable<Long> {
private static final long serialVersionUID = 1L;
@Override
public Long invoke(File f, VirtualChannel channel) throws IOException {
return f.getTotalSpace();
}
}
/**
* Returns the number of usable bytes in the partition of that file.
* @since 1.542
*/
public long getUsableDiskSpace() throws IOException, InterruptedException {
return act(new GetUsableDiskSpace());
}
private static class GetUsableDiskSpace extends SecureFileCallable<Long> {
private static final long serialVersionUID = 1L;
@Override
public Long invoke(File f, VirtualChannel channel) throws IOException {
return f.getUsableSpace();
}
}
/**
* Sets the file permission.
*
* On Windows, no-op.
*
* @param mask
* File permission mask. To simplify the permission copying,
* if the parameter is -1, this method becomes no-op.
* <p>
* please note mask is expected to be an octal if you use <a href="http://en.wikipedia.org/wiki/Chmod">chmod command line values</a>,
* so preceded by a '0' in java notation, ie <code>chmod(0644)</code>
* <p>
* Only supports setting read, write, or execute permissions for the
* owner, group, or others, so the largest permissible value is 0777.
* Attempting to set larger values (i.e. the setgid, setuid, or sticky
* bits) will cause an IOException to be thrown.
*
* @since 1.303
* @see #mode()
*/
public void chmod(final int mask) throws IOException, InterruptedException {
if(!isUnix() || mask==-1) return;
act(new Chmod(mask));
}
private class Chmod extends SecureFileCallable<Void> {
private static final long serialVersionUID = 1L;
private final int mask;
Chmod(int mask) {
this.mask = mask;
}
@Override
public Void invoke(File f, VirtualChannel channel) throws IOException {
_chmod(writing(f), mask);
return null;
}
}
/**
* Change permissions via NIO.
*/
private static void _chmod(File f, int mask) throws IOException {
// TODO WindowsPosix actually does something here (WindowsLibC._wchmod); should we let it?
// Anyway the existing calls already skip this method if on Windows.
if (File.pathSeparatorChar==';') return; // noop
if (Util.NATIVE_CHMOD_MODE) {
PosixAPI.jnr().chmod(f.getAbsolutePath(), mask);
} else {
Files.setPosixFilePermissions(fileToPath(f), Util.modeToPermissions(mask));
}
}
private static boolean CHMOD_WARNED = false;
/**
* Gets the file permission bit mask.
*
* @return
* -1 on Windows, since such a concept doesn't make sense.
* @since 1.311
* @see #chmod(int)
*/
public int mode() throws IOException, InterruptedException, PosixException {
if(!isUnix()) return -1;
return act(new Mode());
}
private class Mode extends SecureFileCallable<Integer> {
private static final long serialVersionUID = 1L;
@Override
public Integer invoke(File f, VirtualChannel channel) throws IOException {
return IOUtils.mode(stating(f));
}
}
/**
* List up files and directories in this directory.
*
* <p>
* This method returns direct children of the directory denoted by the 'this' object.
*/
@Nonnull
public List<FilePath> list() throws IOException, InterruptedException {
return list((FileFilter)null);
}
/**
* List up subdirectories.
*
* @return can be empty but never null. Doesn't contain "." and ".."
*/
@Nonnull
public List<FilePath> listDirectories() throws IOException, InterruptedException {
return list(new DirectoryFilter());
}
private static final class DirectoryFilter implements FileFilter, Serializable {
public boolean accept(File f) {
return f.isDirectory();
}
private static final long serialVersionUID = 1L;
}
/**
* List up files in this directory, just like {@link File#listFiles(FileFilter)}.
*
* @param filter
* The optional filter used to narrow down the result.
* If non-null, must be {@link Serializable}.
* If this {@link FilePath} represents a remote path,
* the filter object will be executed on the remote machine.
*/
@Nonnull
public List<FilePath> list(final FileFilter filter) throws IOException, InterruptedException {
if (filter != null && !(filter instanceof Serializable)) {
throw new IllegalArgumentException("Non-serializable filter of " + filter.getClass());
}
return act(new ListFilter(filter), (filter != null ? filter : this).getClass().getClassLoader());
}
private class ListFilter extends SecureFileCallable<List<FilePath>> {
private final FileFilter filter;
ListFilter(FileFilter filter) {
this.filter = filter;
}
private static final long serialVersionUID = 1L;
@Override
public List<FilePath> invoke(File f, VirtualChannel channel) throws IOException {
File[] children = reading(f).listFiles(filter);
if (children == null) {
return Collections.emptyList();
}
ArrayList<FilePath> r = new ArrayList<>(children.length);
for (File child : children)
r.add(new FilePath(child));
return r;
}
}
/**
* List up files in this directory that matches the given Ant-style filter.
*
* @param includes
* See {@link FileSet} for the syntax. String like "foo/*.zip" or "foo/**/*.xml"
* @return
* can be empty but always non-null.
*/
@Nonnull
public FilePath[] list(final String includes) throws IOException, InterruptedException {
return list(includes, null);
}
/**
* List up files in this directory that matches the given Ant-style filter.
*
* @param includes
* @param excludes
* See {@link FileSet} for the syntax. String like "foo/*.zip" or "foo/**/*.xml"
* @return
* can be empty but always non-null.
* @since 1.407
*/
@Nonnull
public FilePath[] list(final String includes, final String excludes) throws IOException, InterruptedException {
return list(includes, excludes, true);
}
/**
* List up files in this directory that matches the given Ant-style filter.
*
* @param includes
* @param excludes
* See {@link FileSet} for the syntax. String like "foo/*.zip" or "foo/**/*.xml"
* @param defaultExcludes whether to use the ant default excludes
* @return
* can be empty but always non-null.
* @since 1.465
*/
@Nonnull
public FilePath[] list(final String includes, final String excludes, final boolean defaultExcludes) throws IOException, InterruptedException {
return act(new ListGlob(includes, excludes, defaultExcludes));
}
private class ListGlob extends SecureFileCallable<FilePath[]> {
private final String includes;
private final String excludes;
private final boolean defaultExcludes;
ListGlob(String includes, String excludes, boolean defaultExcludes) {
this.includes = includes;
this.excludes = excludes;
this.defaultExcludes = defaultExcludes;
}
private static final long serialVersionUID = 1L;
@Override
public FilePath[] invoke(File f, VirtualChannel channel) throws IOException {
String[] files = glob(reading(f), includes, excludes, defaultExcludes);
FilePath[] r = new FilePath[files.length];
for( int i=0; i<r.length; i++ )
r[i] = new FilePath(new File(f,files[i]));
return r;
}
}
/**
* Runs Ant glob expansion.
*
* @return
* A set of relative file names from the base directory.
*/
@Nonnull
private static String[] glob(File dir, String includes, String excludes, boolean defaultExcludes) throws IOException {
if(isAbsolute(includes))
throw new IOException("Expecting Ant GLOB pattern, but saw '"+includes+"'. See http://ant.apache.org/manual/Types/fileset.html for syntax");
FileSet fs = Util.createFileSet(dir,includes,excludes);
fs.setDefaultexcludes(defaultExcludes);
DirectoryScanner ds;
try {
ds = fs.getDirectoryScanner(new Project());
} catch (BuildException x) {
throw new IOException(x.getMessage());
}
return ds.getIncludedFiles();
}
/**
* Reads this file.
*/
public InputStream read() throws IOException, InterruptedException {
if(channel==null) {
return Files.newInputStream(fileToPath(reading(new File(remote))));
}
final Pipe p = Pipe.createRemoteToLocal();
actAsync(new Read(p));
return p.getIn();
}
private class Read extends SecureFileCallable<Void> {
private static final long serialVersionUID = 1L;
private final Pipe p;
Read(Pipe p) {
this.p = p;
}
@Override
public Void invoke(File f, VirtualChannel channel) throws IOException, InterruptedException {
try (InputStream fis = Files.newInputStream(fileToPath(reading(f)));
OutputStream out = p.getOut()) {
org.apache.commons.io.IOUtils.copy(fis, out);
} catch (Exception x) {
p.error(x);
}
return null;
}
}
/**
* Reads this file from the specific offset.
* @since 1.586
*/
public InputStream readFromOffset(final long offset) throws IOException, InterruptedException {
if(channel ==null) {
final RandomAccessFile raf = new RandomAccessFile(new File(remote), "r");
try {
raf.seek(offset);
} catch (IOException e) {
try {
raf.close();
} catch (IOException e1) {
// ignore
}
throw e;
}
return new InputStream() {
@Override
public int read() throws IOException {
return raf.read();
}
@Override
public void close() throws IOException {
raf.close();
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
return raf.read(b, off, len);
}
@Override
public int read(byte[] b) throws IOException {
return raf.read(b);
}
};
}
final Pipe p = Pipe.createRemoteToLocal();
actAsync(new SecureFileCallable<Void>() {
private static final long serialVersionUID = 1L;
public Void invoke(File f, VirtualChannel channel) throws IOException {
try (OutputStream os = p.getOut();
OutputStream out = new java.util.zip.GZIPOutputStream(os, 8192);
RandomAccessFile raf = new RandomAccessFile(reading(f), "r")) {
raf.seek(offset);
byte[] buf = new byte[8192];
int len;
while ((len = raf.read(buf)) >= 0) {
out.write(buf, 0, len);
}
return null;
}
}
});
return new java.util.zip.GZIPInputStream(p.getIn());
}
/**
* Reads this file into a string, by using the current system encoding on the remote machine.
*/
public String readToString() throws IOException, InterruptedException {
return act(new ReadToString());
}
private final class ReadToString extends SecureFileCallable<String> {
private static final long serialVersionUID = 1L;
@Override
public String invoke(File f, VirtualChannel channel) throws IOException, InterruptedException {
return new String(Files.readAllBytes(fileToPath(reading(f))));
}
}
/**
* Writes to this file.
* If this file already exists, it will be overwritten.
* If the directory doesn't exist, it will be created.
*
* <P>
* I/O operation to remote {@link FilePath} happens asynchronously, meaning write operations to the returned
* {@link OutputStream} will return without receiving a confirmation from the remote that the write happened.
* I/O operations also happens asynchronously from the {@link Channel#call(Callable)} operations, so if
* you write to a remote file and then execute {@link Channel#call(Callable)} and try to access the newly copied
* file, it might not be fully written yet.
*
* <p>
*
*/
public OutputStream write() throws IOException, InterruptedException {
if(channel==null) {
File f = new File(remote).getAbsoluteFile();
mkdirs(f.getParentFile());
return Files.newOutputStream(fileToPath(writing(f)));
}
return act(new WritePipe());
}
private class WritePipe extends SecureFileCallable<OutputStream> {
private static final long serialVersionUID = 1L;
@Override
public OutputStream invoke(File f, VirtualChannel channel) throws IOException, InterruptedException {
f = f.getAbsoluteFile();
mkdirs(f.getParentFile());
return new RemoteOutputStream(Files.newOutputStream(fileToPath(writing(f))));
}
}
/**
* Overwrites this file by placing the given String as the content.
*
* @param encoding
* Null to use the platform default encoding on the remote machine.
* @since 1.105
*/
public void write(final String content, final String encoding) throws IOException, InterruptedException {
act(new Write(encoding, content));
}
private class Write extends SecureFileCallable<Void> {
private static final long serialVersionUID = 1L;
private final String encoding;
private final String content;
Write(String encoding, String content) {
this.encoding = encoding;
this.content = content;
}
@Override
public Void invoke(File f, VirtualChannel channel) throws IOException {
mkdirs(f.getParentFile());
try (OutputStream fos = Files.newOutputStream(fileToPath(writing(f)));
Writer w = encoding != null ? new OutputStreamWriter(fos, encoding) : new OutputStreamWriter(fos)) {
w.write(content);
}
return null;
}
}
/**
* Computes the MD5 digest of the file in hex string.
* @see Util#getDigestOf(File)
*/
public String digest() throws IOException, InterruptedException {
return act(new Digest());
}
private class Digest extends SecureFileCallable<String> {
private static final long serialVersionUID = 1L;
@Override
public String invoke(File f, VirtualChannel channel) throws IOException {
return Util.getDigestOf(reading(f));
}
}
/**
* Rename this file/directory to the target filepath. This FilePath and the target must
* be on the some host
*/
public void renameTo(final FilePath target) throws IOException, InterruptedException {
if(this.channel != target.channel) {
throw new IOException("renameTo target must be on the same host");
}
act(new RenameTo(target));
}
private class RenameTo extends SecureFileCallable<Void> {
private final FilePath target;
RenameTo(FilePath target) {
this.target = target;
}
private static final long serialVersionUID = 1L;
@Override
public Void invoke(File f, VirtualChannel channel) throws IOException {
Files.move(fileToPath(reading(f)), fileToPath(creating(new File(target.remote))), LinkOption.NOFOLLOW_LINKS);
return null;
}
}
/**
* Moves all the contents of this directory into the specified directory, then delete this directory itself.
*
* @since 1.308.
*/
public void moveAllChildrenTo(final FilePath target) throws IOException, InterruptedException {
if(this.channel != target.channel) {
throw new IOException("pullUpTo target must be on the same host");
}
act(new MoveAllChildrenTo(target));
}
private class MoveAllChildrenTo extends SecureFileCallable<Void> {
private final FilePath target;
MoveAllChildrenTo(FilePath target) {
this.target = target;
}
private static final long serialVersionUID = 1L;
@Override
public Void invoke(File f, VirtualChannel channel) throws IOException {
// JENKINS-16846: if f.getName() is the same as one of the files/directories in f,
// then the rename op will fail
File tmp = new File(f.getAbsolutePath()+".__rename");
if (!f.renameTo(tmp))
throw new IOException("Failed to rename "+f+" to "+tmp);
File t = new File(target.getRemote());
for(File child : reading(tmp).listFiles()) {
File target = new File(t, child.getName());
if(!stating(child).renameTo(creating(target)))
throw new IOException("Failed to rename "+child+" to "+target);
}
deleting(tmp).delete();
return null;
}
}
/**
* Copies this file to the specified target.
*/
public void copyTo(FilePath target) throws IOException, InterruptedException {
try {
try (OutputStream out = target.write()) {
copyTo(out);
}
} catch (IOException e) {
throw new IOException("Failed to copy "+this+" to "+target,e);
}
}
/**
* Copies this file to the specified target, with file permissions and other meta attributes intact.
* @since 1.311
*/
public void copyToWithPermission(FilePath target) throws IOException, InterruptedException {
// Use NIO copy with StandardCopyOption.COPY_ATTRIBUTES when copying on the same machine.
if (this.channel == target.channel) {
act(new CopyToWithPermission(target));
return;
}
copyTo(target);
// copy file permission
target.chmod(mode());
target.setLastModifiedIfPossible(lastModified());
}
private class CopyToWithPermission extends SecureFileCallable<Void> {
private final FilePath target;
CopyToWithPermission(FilePath target) {
this.target = target;
}
@Override
public Void invoke(File f, VirtualChannel channel) throws IOException {
File targetFile = new File(target.remote);
File targetDir = targetFile.getParentFile();
filterNonNull().mkdirs(targetDir);
Files.createDirectories(fileToPath(targetDir));
Files.copy(fileToPath(reading(f)), fileToPath(writing(targetFile)), StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING);
return null;
}
}
/**
* Sends the contents of this file into the given {@link OutputStream}.
*/
public void copyTo(OutputStream os) throws IOException, InterruptedException {
final OutputStream out = new RemoteOutputStream(os);
act(new CopyTo(out));
// make sure the writes fully got delivered to 'os' before we return.
// this is needed because I/O operation is asynchronous
syncIO();
}
private class CopyTo extends SecureFileCallable<Void> {
private static final long serialVersionUID = 4088559042349254141L;
private final OutputStream out;
CopyTo(OutputStream out) {
this.out = out;
}
@Override
public Void invoke(File f, VirtualChannel channel) throws IOException {
try (InputStream fis = Files.newInputStream(fileToPath(reading(f)))) {
org.apache.commons.io.IOUtils.copy(fis, out);
return null;
} finally {
out.close();
}
}
}
/**
* With fix to JENKINS-11251 (remoting 2.15), this is no longer necessary.
* But I'm keeping it for a while so that users who manually deploy agent.jar has time to deploy new version
* before this goes away.
*/
private void syncIO() throws InterruptedException {
try {
if (channel!=null)
channel.syncLocalIO();
} catch (AbstractMethodError e) {
// legacy agent.jar. Handle this gracefully
try {
LOGGER.log(Level.WARNING,"Looks like an old agent.jar. Please update "+ Which.jarFile(Channel.class)+" to the new version",e);
} catch (IOException ignored) {
// really ignore this time
}
}
}
/**
* A pointless function to work around what appears to be a HotSpot problem. See JENKINS-5756 and bug 6933067
* on BugParade for more details.
*/
private void _syncIO() throws InterruptedException {
channel.syncLocalIO();
}
/**
* Remoting interface used for {@link FilePath#copyRecursiveTo(String, FilePath)}.
*
* TODO: this might not be the most efficient way to do the copy.
*/
interface RemoteCopier {
/**
* @param fileName
* relative path name to the output file. Path separator must be '/'.
*/
void open(String fileName) throws IOException;
void write(byte[] buf, int len) throws IOException;
void close() throws IOException;
}
/**
* Copies the contents of this directory recursively into the specified target directory.
*
* @return
* the number of files copied.
* @since 1.312
*/
public int copyRecursiveTo(FilePath target) throws IOException, InterruptedException {
return copyRecursiveTo("**/*",target);
}
/**
* Copies the files that match the given file mask to the specified target node.
*
* @param fileMask
* Ant GLOB pattern.
* String like "foo/bar/*.xml" Multiple patterns can be separated
* by ',', and whitespace can surround ',' (so that you can write
* "abc, def" and "abc,def" to mean the same thing.
* @return
* the number of files copied.
*/
public int copyRecursiveTo(String fileMask, FilePath target) throws IOException, InterruptedException {
return copyRecursiveTo(fileMask,null,target);
}
/**
* Copies the files that match the given file mask to the specified target node.
*
* @param fileMask
* Ant GLOB pattern.
* String like "foo/bar/*.xml" Multiple patterns can be separated
* by ',', and whitespace can surround ',' (so that you can write
* "abc, def" and "abc,def" to mean the same thing.
* @param excludes
* Files to be excluded. Can be null.
* @return
* the number of files copied.
*/
public int copyRecursiveTo(final String fileMask, final String excludes, final FilePath target) throws IOException, InterruptedException {
return copyRecursiveTo(new DirScanner.Glob(fileMask, excludes), target, fileMask);
}
/**
* Copies files according to a specified scanner to a target node.
* @param scanner a way of enumerating some files (must be serializable for possible delivery to remote side)
* @param target the destination basedir
* @param description a description of the fileset, for logging purposes
* @return the number of files copied
* @since 1.532
*/
public int copyRecursiveTo(final DirScanner scanner, final FilePath target, final String description) throws IOException, InterruptedException {
if(this.channel==target.channel) {
// local to local copy.
return act(new CopyRecursiveLocal(target, scanner));
} else
if(this.channel==null) {
// local -> remote copy
final Pipe pipe = Pipe.createLocalToRemote();
Future<Void> future = target.actAsync(new ReadToTar(pipe, description));
Future<Integer> future2 = actAsync(new WriteToTar(scanner, pipe));
try {
// JENKINS-9540 in case the reading side failed, report that error first
future.get();
return future2.get();
} catch (ExecutionException e) {
throw ioWithCause(e);
}
} else {
// remote -> local copy
final Pipe pipe = Pipe.createRemoteToLocal();
Future<Integer> future = actAsync(new CopyRecursiveRemoteToLocal(pipe, scanner));
try {
readFromTar(remote + '/' + description,new File(target.remote),TarCompression.GZIP.extract(pipe.getIn()));
} catch (IOException e) {// BuildException or IOException
try {
future.get(3,TimeUnit.SECONDS);
throw e; // the remote side completed successfully, so the error must be local
} catch (ExecutionException x) {
// report both errors
e.addSuppressed(x);
throw e;
} catch (TimeoutException ignored) {
// remote is hanging, just throw the original exception
throw e;
}
}
try {
return future.get();
} catch (ExecutionException e) {
throw ioWithCause(e);
}
}
}
private IOException ioWithCause(ExecutionException e) {
Throwable cause = e.getCause();
if (cause == null) cause = e;
return cause instanceof IOException
? (IOException) cause
: new IOException(cause)
;
}
private class CopyRecursiveLocal extends SecureFileCallable<Integer> {
private final FilePath target;
private final DirScanner scanner;
CopyRecursiveLocal(FilePath target, DirScanner scanner) {
this.target = target;
this.scanner = scanner;
}
private static final long serialVersionUID = 1L;
@Override
public Integer invoke(File base, VirtualChannel channel) throws IOException {
if (!base.exists()) {
return 0;
}
assert target.channel == null;
final File dest = new File(target.remote);
final AtomicInteger count = new AtomicInteger();
scanner.scan(base, reading(new FileVisitor() {
private boolean exceptionEncountered;
private boolean logMessageShown;
@Override
public void visit(File f, String relativePath) throws IOException {
if (f.isFile()) {
File target = new File(dest, relativePath);
mkdirsE(target.getParentFile());
Path targetPath = fileToPath(writing(target));
exceptionEncountered = exceptionEncountered || !tryCopyWithAttributes(f, targetPath);
if (exceptionEncountered) {
Files.copy(fileToPath(f), targetPath, StandardCopyOption.REPLACE_EXISTING);
if (!logMessageShown) {
LOGGER.log(Level.INFO,
"JENKINS-52325: Jenkins failed to retain attributes when copying to {0}, so proceeding without attributes.",
dest.getAbsolutePath());
logMessageShown = true;
}
}
count.incrementAndGet();
}
}
private boolean tryCopyWithAttributes(File f, Path targetPath) {
try {
Files.copy(fileToPath(f), targetPath,
StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
LOGGER.log(Level.FINE, "Unable to copy: {0}", e.getMessage());
return false;
}
return true;
}
@Override
public boolean understandsSymlink() {
return true;
}
@Override
public void visitSymlink(File link, String target, String relativePath) throws IOException {
try {
mkdirsE(new File(dest, relativePath).getParentFile());
writing(new File(dest, target));
Util.createSymlink(dest, target, relativePath, TaskListener.NULL);
} catch (InterruptedException x) {
throw new IOException(x);
}
count.incrementAndGet();
}
}));
return count.get();
}
}
private class ReadToTar extends SecureFileCallable<Void> {
private final Pipe pipe;
private final String description;
ReadToTar(Pipe pipe, String description) {
this.pipe = pipe;
this.description = description;
}
private static final long serialVersionUID = 1L;
@Override
public Void invoke(File f, VirtualChannel channel) throws IOException {
try (InputStream in = pipe.getIn()) {
readFromTar(remote + '/' + description, f, TarCompression.GZIP.extract(in));
return null;
}
}
}
private class WriteToTar extends SecureFileCallable<Integer> {
private final DirScanner scanner;
private final Pipe pipe;
WriteToTar(DirScanner scanner, Pipe pipe) {
this.scanner = scanner;
this.pipe = pipe;
}
private static final long serialVersionUID = 1L;
@Override
public Integer invoke(File f, VirtualChannel channel) throws IOException, InterruptedException {
return writeToTar(new File(remote), scanner, TarCompression.GZIP.compress(pipe.getOut()));
}
}
private class CopyRecursiveRemoteToLocal extends SecureFileCallable<Integer> {
private static final long serialVersionUID = 1L;
private final Pipe pipe;
private final DirScanner scanner;
CopyRecursiveRemoteToLocal(Pipe pipe, DirScanner scanner) {
this.pipe = pipe;
this.scanner = scanner;
}
@Override
public Integer invoke(File f, VirtualChannel channel) throws IOException {
try (OutputStream out = pipe.getOut()) {
return writeToTar(f, scanner, TarCompression.GZIP.compress(out));
}
}
}
/**
* Writes files in 'this' directory to a tar stream.
*
* @param glob
* Ant file pattern mask, like "**/*.java".
*/
public int tar(OutputStream out, final String glob) throws IOException, InterruptedException {
return archive(ArchiverFactory.TAR, out, glob);
}
public int tar(OutputStream out, FileFilter filter) throws IOException, InterruptedException {
return archive(ArchiverFactory.TAR, out, filter);
}
/**
* Uses the given scanner on 'this' directory to list up files and then archive it to a tar stream.
*/
public int tar(OutputStream out, DirScanner scanner) throws IOException, InterruptedException {
return archive(ArchiverFactory.TAR, out, scanner);
}
/**
* Writes to a tar stream and stores obtained files to the base dir.
*
* @return
* number of files/directories that are written.
*/
private Integer writeToTar(File baseDir, DirScanner scanner, OutputStream out) throws IOException {
Archiver tw = ArchiverFactory.TAR.create(out);
try {
scanner.scan(baseDir,reading(tw));
} finally {
tw.close();
}
return tw.countEntries();
}
/**
* Reads from a tar stream and stores obtained files to the base dir.
* Supports large files > 10 GB since 1.627 when this was migrated to use commons-compress.
*/
private void readFromTar(String name, File baseDir, InputStream in) throws IOException {
// TarInputStream t = new TarInputStream(in);
try (TarArchiveInputStream t = new TarArchiveInputStream(in)) {
TarArchiveEntry te;
while ((te = t.getNextTarEntry()) != null) {
File f = new File(baseDir, te.getName());
if (!f.toPath().normalize().startsWith(baseDir.toPath())) {
throw new IOException(
"Tar " + name + " contains illegal file name that breaks out of the target directory: " + te.getName());
}
if (te.isDirectory()) {
mkdirs(f);
} else {
File parent = f.getParentFile();
if (parent != null) mkdirs(parent);
writing(f);
if (te.isSymbolicLink()) {
new FilePath(f).symlinkTo(te.getLinkName(), TaskListener.NULL);
} else {
IOUtils.copy(t, f);
f.setLastModified(te.getModTime().getTime());
int mode = te.getMode() & 0777;
if (mode != 0 && !Functions.isWindows()) // be defensive
_chmod(f, mode);
}
}
}
} catch (IOException e) {
throw new IOException("Failed to extract " + name, e);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // process this later
throw new IOException("Failed to extract " + name, e);
}
}
/**
* Creates a {@link Launcher} for starting processes on the node
* that has this file.
* @since 1.89
*/
public Launcher createLauncher(TaskListener listener) throws IOException, InterruptedException {
if(channel==null)
return new LocalLauncher(listener);
else
return new RemoteLauncher(listener,channel,channel.call(new IsUnix()));
}
private static final class IsUnix extends MasterToSlaveCallable<Boolean,IOException> {
@Nonnull
public Boolean call() throws IOException {
return File.pathSeparatorChar==':';
}
private static final long serialVersionUID = 1L;
}
/**
* Validates the ant file mask (like "foo/bar/*.txt, zot/*.jar")
* against this directory, and try to point out the problem.
*
* <p>
* This is useful in conjunction with {@link FormValidation}.
*
* @return
* null if no error was found. Otherwise returns a human readable error message.
* @since 1.90
* @see #validateFileMask(FilePath, String)
* @deprecated use {@link #validateAntFileMask(String, int)} instead
*/
@Deprecated
public String validateAntFileMask(final String fileMasks) throws IOException, InterruptedException {
return validateAntFileMask(fileMasks, Integer.MAX_VALUE);
}
/**
* Same as {@link #validateAntFileMask(String, int, boolean)} with caseSensitive set to true
*/
public String validateAntFileMask(final String fileMasks, final int bound) throws IOException, InterruptedException {
return validateAntFileMask(fileMasks, bound, true);
}
/**
* Default bound for {@link #validateAntFileMask(String, int, boolean)}.
* @since 1.592
*/
public static int VALIDATE_ANT_FILE_MASK_BOUND = Integer.getInteger(FilePath.class.getName() + ".VALIDATE_ANT_FILE_MASK_BOUND", 10000);
/**
* Like {@link #validateAntFileMask(String)} but performing only a bounded number of operations.
* <p>Whereas the unbounded overload is appropriate for calling from cancelable, long-running tasks such as build steps,
* this overload should be used when an answer is needed quickly, such as for {@link #validateFileMask(String)}
* or anything else returning {@link FormValidation}.
* <p>If a positive match is found, {@code null} is returned immediately.
* A message is returned in case the file pattern can definitely be determined to not match anything in the directory within the alloted time.
* If the time runs out without finding a match but without ruling out the possibility that there might be one, {@link InterruptedException} is thrown,
* in which case the calling code should give the user the benefit of the doubt and use {@link hudson.util.FormValidation.Kind#OK} (with or without a message).
* @param bound a maximum number of negative operations (deliberately left vague) to perform before giving up on a precise answer; try {@link #VALIDATE_ANT_FILE_MASK_BOUND}
* @throws InterruptedException not only in case of a channel failure, but also if too many operations were performed without finding any matches
* @since 1.484
*/
public @CheckForNull String validateAntFileMask(final String fileMasks, final int bound, final boolean caseSensitive) throws IOException, InterruptedException {
return act(new ValidateAntFileMask(fileMasks, caseSensitive, bound));
}
private class ValidateAntFileMask extends MasterToSlaveFileCallable<String> {
private final String fileMasks;
private final boolean caseSensitive;
private final int bound;
ValidateAntFileMask(String fileMasks, boolean caseSensitive, int bound) {
this.fileMasks = fileMasks;
this.caseSensitive = caseSensitive;
this.bound = bound;
}
private static final long serialVersionUID = 1;
@Override
public String invoke(File dir, VirtualChannel channel) throws IOException, InterruptedException {
if(fileMasks.startsWith("~"))
return Messages.FilePath_TildaDoesntWork();
StringTokenizer tokens = new StringTokenizer(fileMasks,",");
while(tokens.hasMoreTokens()) {
final String fileMask = tokens.nextToken().trim();
if(hasMatch(dir,fileMask,caseSensitive))
continue; // no error on this portion
// JENKINS-5253 - if we can get some match in case insensitive mode
// and user requested case sensitive match, notify the user
if (caseSensitive && hasMatch(dir, fileMask, false)) {
return Messages.FilePath_validateAntFileMask_matchWithCaseInsensitive(fileMask);
}
// in 1.172 we introduced an incompatible change to stop using ' ' as the separator
// so see if we can match by using ' ' as the separator
if(fileMask.contains(" ")) {
boolean matched = true;
for (String token : Util.tokenize(fileMask))
matched &= hasMatch(dir,token,caseSensitive);
if(matched)
return Messages.FilePath_validateAntFileMask_whitespaceSeparator();
}
// a common mistake is to assume the wrong base dir, and there are two variations
// to this: (1) the user gave us aa/bb/cc/dd where cc/dd was correct
// and (2) the user gave us cc/dd where aa/bb/cc/dd was correct.
{// check the (1) above first
String f=fileMask;
while(true) {
int idx = findSeparator(f);
if(idx==-1) break;
f=f.substring(idx+1);
if(hasMatch(dir,f,caseSensitive))
return Messages.FilePath_validateAntFileMask_doesntMatchAndSuggest(fileMask,f);
}
}
{// check the (2) above next as this is more expensive.
// Try prepending "**/" to see if that results in a match
FileSet fs = Util.createFileSet(reading(dir),"**/"+fileMask);
fs.setCaseSensitive(caseSensitive);
DirectoryScanner ds = fs.getDirectoryScanner(new Project());
if(ds.getIncludedFilesCount()!=0) {
// try shorter name first so that the suggestion results in least amount of changes
String[] names = ds.getIncludedFiles();
Arrays.sort(names,SHORTER_STRING_FIRST);
for( String f : names) {
// now we want to decompose f to the leading portion that matched "**"
// and the trailing portion that matched the file mask, so that
// we can suggest the user error.
//
// this is not a very efficient/clever way to do it, but it's relatively simple
StringBuilder prefix = new StringBuilder();
while(true) {
int idx = findSeparator(f);
if(idx==-1) break;
prefix.append(f.substring(0, idx)).append('/');
f=f.substring(idx+1);
if(hasMatch(dir,prefix+fileMask,caseSensitive))
return Messages.FilePath_validateAntFileMask_doesntMatchAndSuggest(fileMask, prefix+fileMask);
}
}
}
}
{// finally, see if we can identify any sub portion that's valid. Otherwise bail out
String previous = null;
String pattern = fileMask;
while(true) {
if(hasMatch(dir,pattern,caseSensitive)) {
// found a match
if(previous==null)
return Messages.FilePath_validateAntFileMask_portionMatchAndSuggest(fileMask,pattern);
else
return Messages.FilePath_validateAntFileMask_portionMatchButPreviousNotMatchAndSuggest(fileMask,pattern,previous);
}
int idx = findSeparator(pattern);
if(idx<0) {// no more path component left to go back
if(pattern.equals(fileMask))
return Messages.FilePath_validateAntFileMask_doesntMatchAnything(fileMask);
else
return Messages.FilePath_validateAntFileMask_doesntMatchAnythingAndSuggest(fileMask,pattern);
}
// cut off the trailing component and try again
previous = pattern;
pattern = pattern.substring(0,idx);
}
}
}
return null; // no error
}
private boolean hasMatch(File dir, String pattern, boolean bCaseSensitive) throws InterruptedException {
class Cancel extends RuntimeException {}
DirectoryScanner ds = bound == Integer.MAX_VALUE ? new DirectoryScanner() : new DirectoryScanner() {
int ticks;
long start = System.currentTimeMillis();
@Override public synchronized boolean isCaseSensitive() {
if (!filesIncluded.isEmpty() || !dirsIncluded.isEmpty() || ticks++ > bound || System.currentTimeMillis() - start > 5000) {
throw new Cancel();
}
filesNotIncluded.clear();
dirsNotIncluded.clear();
// notFollowedSymlinks might be large, but probably unusual
// scannedDirs will typically be largish, but seems to be needed
return super.isCaseSensitive();
}
};
ds.setBasedir(reading(dir));
ds.setIncludes(new String[] {pattern});
ds.setCaseSensitive(bCaseSensitive);
try {
ds.scan();
} catch (Cancel c) {
if (ds.getIncludedFilesCount()!=0 || ds.getIncludedDirsCount()!=0) {
return true;
} else {
throw new InterruptedException("no matches found within " + bound);
}
}
return ds.getIncludedFilesCount()!=0 || ds.getIncludedDirsCount()!=0;
}
/**
* Finds the position of the first path separator.
*/
private int findSeparator(String pattern) {
int idx1 = pattern.indexOf('\\');
int idx2 = pattern.indexOf('/');
if(idx1==-1) return idx2;
if(idx2==-1) return idx1;
return Math.min(idx1,idx2);
}
}
private static final UrlFactory DEFAULT_URL_FACTORY = new UrlFactory();
@Restricted(NoExternalUse.class)
static class UrlFactory {
public URL newURL(String location) throws MalformedURLException {
return new URL(location);
}
}
private UrlFactory urlFactory;
@VisibleForTesting
@Restricted(NoExternalUse.class)
void setUrlFactory(UrlFactory urlFactory) {
this.urlFactory = urlFactory;
}
private UrlFactory getUrlFactory() {
if (urlFactory != null) {
return urlFactory;
} else {
return DEFAULT_URL_FACTORY;
}
}
/**
* Short for {@code validateFileMask(path, value, true)}
*/
public static FormValidation validateFileMask(@CheckForNull FilePath path, String value) throws IOException {
return FilePath.validateFileMask(path, value, true);
}
/**
* Shortcut for {@link #validateFileMask(String,boolean,boolean)} with {@code errorIfNotExist} true, as the left-hand side can be null.
*/
public static FormValidation validateFileMask(@CheckForNull FilePath path, String value, boolean caseSensitive) throws IOException {
if(path==null) return FormValidation.ok();
return path.validateFileMask(value, true, caseSensitive);
}
/**
* Short for {@code validateFileMask(value, true, true)}
*/
public FormValidation validateFileMask(String value) throws IOException {
return validateFileMask(value, true, true);
}
/**
* Short for {@code validateFileMask(value, errorIfNotExist, true)}
*/
public FormValidation validateFileMask(String value, boolean errorIfNotExist) throws IOException {
return validateFileMask(value, errorIfNotExist, true);
}
/**
* Checks the GLOB-style file mask. See {@link #validateAntFileMask(String)}.
* Requires configure permission on ancestor AbstractProject object in request,
* or admin permission if no such ancestor is found.
* @since 1.294
*/
public FormValidation validateFileMask(String value, boolean errorIfNotExist, boolean caseSensitive) throws IOException {
checkPermissionForValidate();
value = fixEmpty(value);
if(value==null)
return FormValidation.ok();
try {
if(!exists()) // no workspace. can't check
return FormValidation.ok();
String msg = validateAntFileMask(value, VALIDATE_ANT_FILE_MASK_BOUND, caseSensitive);
if(errorIfNotExist) return FormValidation.error(msg);
else return FormValidation.warning(msg);
} catch (InterruptedException e) {
return FormValidation.ok(Messages.FilePath_did_not_manage_to_validate_may_be_too_sl(value));
}
}
/**
* Validates a relative file path from this {@link FilePath}.
* Requires configure permission on ancestor AbstractProject object in request,
* or admin permission if no such ancestor is found.
*
* @param value
* The relative path being validated.
* @param errorIfNotExist
* If true, report an error if the given relative path doesn't exist. Otherwise it's a warning.
* @param expectingFile
* If true, we expect the relative path to point to a file.
* Otherwise, the relative path is expected to be pointing to a directory.
*/
public FormValidation validateRelativePath(String value, boolean errorIfNotExist, boolean expectingFile) throws IOException {
checkPermissionForValidate();
value = fixEmpty(value);
// none entered yet, or something is seriously wrong
if(value==null) return FormValidation.ok();
// a common mistake is to use wildcard
if(value.contains("*")) return FormValidation.error(Messages.FilePath_validateRelativePath_wildcardNotAllowed());
try {
if(!exists()) // no base directory. can't check
return FormValidation.ok();
FilePath path = child(value);
if(path.exists()) {
if (expectingFile) {
if(!path.isDirectory())
return FormValidation.ok();
else
return FormValidation.error(Messages.FilePath_validateRelativePath_notFile(value));
} else {
if(path.isDirectory())
return FormValidation.ok();
else
return FormValidation.error(Messages.FilePath_validateRelativePath_notDirectory(value));
}
}
String msg = expectingFile ? Messages.FilePath_validateRelativePath_noSuchFile(value) :
Messages.FilePath_validateRelativePath_noSuchDirectory(value);
if(errorIfNotExist) return FormValidation.error(msg);
else return FormValidation.warning(msg);
} catch (InterruptedException e) {
return FormValidation.ok();
}
}
private static void checkPermissionForValidate() {
AccessControlled subject = Stapler.getCurrentRequest().findAncestorObject(AbstractProject.class);
if (subject == null)
Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);
else
subject.checkPermission(Item.CONFIGURE);
}
/**
* A convenience method over {@link #validateRelativePath(String, boolean, boolean)}.
*/
public FormValidation validateRelativeDirectory(String value, boolean errorIfNotExist) throws IOException {
return validateRelativePath(value,errorIfNotExist,false);
}
public FormValidation validateRelativeDirectory(String value) throws IOException {
return validateRelativeDirectory(value,true);
}
@Deprecated @Override
public String toString() {
// to make writing JSPs easily, return local
return remote;
}
public VirtualChannel getChannel() {
if(channel!=null) return channel;
else return localChannel;
}
/**
* Returns true if this {@link FilePath} represents a remote file.
*/
public boolean isRemote() {
return channel!=null;
}
private void writeObject(ObjectOutputStream oos) throws IOException {
Channel target = _getChannelForSerialization();
if (channel != null && channel != target) {
throw new IllegalStateException("Can't send a remote FilePath to a different remote channel (current=" + channel + ", target=" + target + ")");
}
oos.defaultWriteObject();
oos.writeBoolean(channel==null);
}
private Channel _getChannelForSerialization() {
try {
return getChannelForSerialization();
} catch (NotSerializableException x) {
LOGGER.log(Level.WARNING, "A FilePath object is being serialized when it should not be, indicating a bug in a plugin. See https://jenkins.io/redirect/filepath-serialization for details.", x);
return null;
}
}
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
Channel channel = _getChannelForSerialization();
ois.defaultReadObject();
if(ois.readBoolean()) {
this.channel = channel;
this.filter = null;
} else {
this.channel = null;
// If the remote channel wants us to create a FilePath that points to a local file,
// we need to make sure the access control takes place.
// This covers the immediate case of FileCallables taking FilePath into reference closure implicitly,
// but it also covers more general case of FilePath sent as a return value or argument.
this.filter = SoloFilePathFilter.wrap(FilePathFilter.current());
}
}
private static final long serialVersionUID = 1L;
public static int SIDE_BUFFER_SIZE = 1024;
private static final Logger LOGGER = Logger.getLogger(FilePath.class.getName());
/**
* Adapts {@link FileCallable} to {@link Callable}.
*/
private class FileCallableWrapper<T> implements DelegatingCallable<T,IOException> {
private final FileCallable<T> callable;
private transient ClassLoader classLoader;
public FileCallableWrapper(FileCallable<T> callable) {
this.callable = callable;
this.classLoader = callable.getClass().getClassLoader();
}
private FileCallableWrapper(FileCallable<T> callable, ClassLoader classLoader) {
this.callable = callable;
this.classLoader = classLoader;
}
public T call() throws IOException {
try {
return callable.invoke(new File(remote), Channel.current());
} catch (InterruptedException e) {
throw new TunneledInterruptedException(e);
}
}
/**
* Role check comes from {@link FileCallable}s.
*/
@Override
public void checkRoles(RoleChecker checker) throws SecurityException {
callable.checkRoles(checker);
}
public ClassLoader getClassLoader() {
return classLoader;
}
@Override
public String toString() {
return callable.toString();
}
private static final long serialVersionUID = 1L;
}
/**
* Used to tunnel {@link InterruptedException} over a Java signature that only allows {@link IOException}
*/
private static class TunneledInterruptedException extends IOException {
private TunneledInterruptedException(InterruptedException cause) {
super(cause);
}
private static final long serialVersionUID = 1L;
}
private static final Comparator<String> SHORTER_STRING_FIRST = new Comparator<String>() {
public int compare(String o1, String o2) {
return o1.length()-o2.length();
}
};
/**
* Gets the {@link FilePath} representation of the "~" directory
* (User's home directory in the Unix sense) of the given channel.
*/
public static FilePath getHomeDirectory(VirtualChannel ch) throws InterruptedException, IOException {
return ch.call(new GetHomeDirectory());
}
private static class GetHomeDirectory extends MasterToSlaveCallable<FilePath, IOException> {
@Override
public FilePath call() throws IOException {
return new FilePath(new File(System.getProperty("user.home")));
}
}
/**
* Helper class to make it easy to send an explicit list of files using {@link FilePath} methods.
* @since 1.532
*/
public static final class ExplicitlySpecifiedDirScanner extends DirScanner {
private static final long serialVersionUID = 1;
private final Map<String,String> files;
/**
* Create a “scanner” (it actually does no scanning).
* @param files a map from logical relative paths as per {@link FileVisitor#visit}, to actual relative paths within the scanned directory
*/
public ExplicitlySpecifiedDirScanner(Map<String,String> files) {
this.files = files;
}
@Override public void scan(File dir, FileVisitor visitor) throws IOException {
for (Map.Entry<String,String> entry : files.entrySet()) {
String archivedPath = entry.getKey();
assert archivedPath.indexOf('\\') == -1;
String workspacePath = entry.getValue();
assert workspacePath.indexOf('\\') == -1;
scanSingle(new File(dir, workspacePath), archivedPath, visitor);
}
}
}
private static final ExecutorService threadPoolForRemoting = new ContextResettingExecutorService(
Executors.newCachedThreadPool(
new ExceptionCatchingThreadFactory(
new NamingThreadFactory(new DaemonThreadFactory(), "FilePath.localPool"))
));
/**
* Channel to the current instance.
*/
@Nonnull
public static final LocalChannel localChannel = new LocalChannel(threadPoolForRemoting);
private @Nonnull SoloFilePathFilter filterNonNull() {
return filter!=null ? filter : UNRESTRICTED;
}
/**
* Wraps {@link FileVisitor} to notify read access to {@link FilePathFilter}.
*/
private FileVisitor reading(final FileVisitor v) {
final FilePathFilter filter = FilePathFilter.current();
if (filter==null) return v;
return new FileVisitor() {
@Override
public void visit(File f, String relativePath) throws IOException {
filter.read(f);
v.visit(f,relativePath);
}
@Override
public void visitSymlink(File link, String target, String relativePath) throws IOException {
filter.read(link);
v.visitSymlink(link, target, relativePath);
}
@Override
public boolean understandsSymlink() {
return v.understandsSymlink();
}
};
}
/**
* Pass through 'f' after ensuring that we can read that file.
*/
private File reading(File f) {
filterNonNull().read(f);
return f;
}
/**
* Pass through 'f' after ensuring that we can access the file attributes.
*/
private File stating(File f) {
filterNonNull().stat(f);
return f;
}
/**
* Pass through 'f' after ensuring that we can create that file/dir.
*/
private File creating(File f) {
filterNonNull().create(f);
return f;
}
/**
* Pass through 'f' after ensuring that we can write to that file.
*/
private File writing(File f) {
FilePathFilter filter = filterNonNull();
if (!f.exists())
filter.create(f);
filter.write(f);
return f;
}
/**
* Pass through 'f' after ensuring that we can create that symlink.
*/
private File symlinking(File f) {
FilePathFilter filter = filterNonNull();
if (!f.exists())
filter.create(f);
filter.symlink(f);
return f;
}
/**
* Pass through 'f' after ensuring that we can delete that file.
*/
private File deleting(File f) {
filterNonNull().delete(f);
return f;
}
private boolean mkdirs(File dir) throws IOException {
if (dir.exists()) return false;
filterNonNull().mkdirs(dir);
Files.createDirectories(fileToPath(dir));
return true;
}
private File mkdirsE(File dir) throws IOException {
if (dir.exists()) {
return dir;
}
filterNonNull().mkdirs(dir);
return IOUtils.mkdirs(dir);
}
/**
* Check if the relative child is really a descendant after symlink resolution if any.
*
* TODO un-restrict it in a weekly after the patch
*/
@Restricted(NoExternalUse.class)
public boolean isDescendant(@Nonnull String potentialChildRelativePath) throws IOException, InterruptedException {
return act(new IsDescendant(potentialChildRelativePath));
}
private class IsDescendant extends SecureFileCallable<Boolean> {
private static final long serialVersionUID = 1L;
private String potentialChildRelativePath;
private IsDescendant(@Nonnull String potentialChildRelativePath){
this.potentialChildRelativePath = potentialChildRelativePath;
}
@Override
public Boolean invoke(@Nonnull File parentFile, @Nonnull VirtualChannel channel) throws IOException, InterruptedException {
if (new File(potentialChildRelativePath).isAbsolute()) {
throw new IllegalArgumentException("Only a relative path is supported, the given path is absolute: " + potentialChildRelativePath);
}
Path parentAbsolutePath = Util.fileToPath(parentFile.getAbsoluteFile());
Path parentRealPath;
try {
if (Functions.isWindows()) {
parentRealPath = this.windowsToRealPath(parentAbsolutePath);
} else {
parentRealPath = parentAbsolutePath.toRealPath();
}
}
catch (NoSuchFileException e) {
LOGGER.log(Level.FINE, String.format("Cannot find the real path to the parentFile: %s", parentAbsolutePath), e);
return false;
}
// example: "a/b/c" that will become "b/c" then just "c", and finally an empty string
String remainingPath = potentialChildRelativePath;
Path currentFilePath = parentFile.toPath();
while (!remainingPath.isEmpty()) {
Path directChild = this.getDirectChild(currentFilePath, remainingPath);
Path childUsingFullPath = currentFilePath.resolve(remainingPath);
String childUsingFullPathAbs = childUsingFullPath.toAbsolutePath().toString();
String directChildAbs = directChild.toAbsolutePath().toString();
if (childUsingFullPathAbs.length() == directChildAbs.length()) {
remainingPath = "";
} else {
// +1 to avoid the last slash
remainingPath = childUsingFullPathAbs.substring(directChildAbs.length() + 1);
}
File childFileSymbolic = Util.resolveSymlinkToFile(directChild.toFile());
if (childFileSymbolic == null) {
currentFilePath = directChild;
} else {
currentFilePath = childFileSymbolic.toPath();
}
Path currentFileAbsolutePath = currentFilePath.toAbsolutePath();
try{
Path child = currentFileAbsolutePath.toRealPath();
if (!child.startsWith(parentRealPath)) {
LOGGER.log(Level.FINE, "Child [{0}] does not start with parent [{1}] => not descendant", new Object[]{ child, parentRealPath });
return false;
}
} catch (NoSuchFileException e) {
// nonexistent file / Windows Server 2016 + MSFT docker
// in case this folder / file will be copied somewhere else,
// it becomes the responsibility of that system to check the isDescendant with the existing links
// we are not taking the parentRealPath to avoid possible problem
Path child = currentFileAbsolutePath.normalize();
Path parent = parentAbsolutePath.normalize();
return child.startsWith(parent);
} catch(FileSystemException e) {
LOGGER.log(Level.WARNING, String.format("Problem during call to the method toRealPath on %s", currentFileAbsolutePath), e);
return false;
}
}
return true;
}
private @CheckForNull Path getDirectChild(Path parentPath, String childPath){
Path current = parentPath.resolve(childPath);
while (current != null && !parentPath.equals(current.getParent())) {
current = current.getParent();
}
return current;
}
private @Nonnull Path windowsToRealPath(@Nonnull Path path) throws IOException {
try {
return path.toRealPath();
}
catch (IOException e) {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE, String.format("relaxedToRealPath cannot use the regular toRealPath on %s, trying with toRealPath(LinkOption.NOFOLLOW_LINKS)", path), e);
}
}
// that's required for specific environment like Windows Server 2016, running MSFT docker
// where the root is a <SYMLINKD>
return path.toRealPath(LinkOption.NOFOLLOW_LINKS);
}
}
private static final SoloFilePathFilter UNRESTRICTED = SoloFilePathFilter.wrap(FilePathFilter.UNRESTRICTED);
}
|
Show empty statement by putting the semicolon on its own line - FilePath.normalize
Co-Authored-By: Daniel Beck <8a7ce20cd6d504c97910234803e6e48549280b89@users.noreply.github.com>
|
core/src/main/java/hudson/FilePath.java
|
Show empty statement by putting the semicolon on its own line - FilePath.normalize
|
|
Java
|
mit
|
7e7b92b232e44a1732a8573b036e73bea2225107
| 0
|
sergiosorias/jscep
|
/*
* Copyright (c) 2009-2010 David Grant
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.google.code.jscep.pkcs7;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import org.bouncycastle.asn1.DERObjectIdentifier;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.DERPrintableString;
import org.bouncycastle.asn1.cms.Attribute;
import org.bouncycastle.asn1.cms.AttributeTable;
import org.bouncycastle.asn1.cms.ContentInfo;
import org.bouncycastle.asn1.cms.SignedData;
import org.bouncycastle.asn1.cms.SignerInfo;
import com.google.code.jscep.asn1.SCEPObjectIdentifiers;
import com.google.code.jscep.transaction.FailInfo;
import com.google.code.jscep.transaction.MessageType;
import com.google.code.jscep.transaction.Nonce;
import com.google.code.jscep.transaction.PkiStatus;
import com.google.code.jscep.transaction.TransactionId;
/**
* This interface represents the <tt>SCEP</tt> <tt>pkiMessage</tt>.
*
* @see <a href="http://tools.ietf.org/html/draft-nourse-scep-20#section-3.1">SCEP Internet-Draft Reference</a>
*/
public class PkiMessage {
private byte[] encoded;
private PkcsPkiEnvelope pkcsPkiEnvelope;
private final SignerInfo signerInfo;
private final ContentInfo contentInfo;
private final SignedData signedData;
PkiMessage(ContentInfo contentInfo) {
this.contentInfo = contentInfo;
this.signedData = SignedData.getInstance(contentInfo.getContent());
this.signerInfo = getSignerSet(signedData).iterator().next();
}
private Set<SignerInfo> getSignerSet(SignedData signedData) {
final Set<SignerInfo> set = new HashSet<SignerInfo>();
final Enumeration<?> signerInfos = signedData.getSignerInfos().getObjects();
while (signerInfos.hasMoreElements()) {
set.add(SignerInfo.getInstance(signerInfos.nextElement()));
}
return set;
}
public boolean isRequest() {
return getPkiStatus() == null;
}
private AttributeTable getAttributeTable() {
return new AttributeTable(signerInfo.getAuthenticatedAttributes());
}
void setPkcsPkiEnvelope(PkcsPkiEnvelope envelope) {
this.pkcsPkiEnvelope = envelope;
}
public PkcsPkiEnvelope getPkcsPkiEnvelope() {
return pkcsPkiEnvelope;
}
public FailInfo getFailInfo() {
final Attribute attr = getAttributeTable().get(SCEPObjectIdentifiers.failInfo);
if (attr == null) {
return null;
}
final DERPrintableString failInfo = (DERPrintableString) attr.getAttrValues().getObjectAt(0);
return FailInfo.valueOf(Integer.parseInt(failInfo.getString()));
}
public PkiStatus getPkiStatus() {
final Attribute attr = getAttributeTable().get(SCEPObjectIdentifiers.pkiStatus);
if (attr == null) {
return null;
}
final DERPrintableString pkiStatus = (DERPrintableString) attr.getAttrValues().getObjectAt(0);
return PkiStatus.valueOf(Integer.parseInt(pkiStatus.toString()));
}
private Nonce getNonce(DERObjectIdentifier oid) {
final Attribute attr = getAttributeTable().get(oid);
if (attr == null) {
return null;
}
final DEROctetString nonce = (DEROctetString) attr.getAttrValues().getObjectAt(0);
return new Nonce(nonce.getOctets());
}
public Nonce getRecipientNonce() {
return getNonce(SCEPObjectIdentifiers.recipientNonce);
}
public Nonce getSenderNonce() {
return getNonce(SCEPObjectIdentifiers.senderNonce);
}
public TransactionId getTransactionId() {
final Attribute attr = getAttributeTable().get(SCEPObjectIdentifiers.transId);
DERPrintableString transId = (DERPrintableString) attr.getAttrValues().getObjectAt(0);
return new TransactionId(transId.getOctets());
}
void setEncoded(byte[] encoded) {
this.encoded = encoded;
}
public byte[] getEncoded() {
return encoded;
}
public MessageType getMessageType() {
final Attribute attr = getAttributeTable().get(SCEPObjectIdentifiers.messageType);
final DERPrintableString msgType = (DERPrintableString) attr.getAttrValues().getObjectAt(0);
return MessageType.valueOf(Integer.parseInt(msgType.getString()));
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if (getPkiStatus() == null) {
sb.append("pkiMessage (request) [\n");
} else {
sb.append("pkiMessage (response) [\n");
}
sb.append("\tcontentType: " + contentInfo.getContentType() + "\n");
sb.append("\ttransactionId: " + getTransactionId() + "\n");
sb.append("\tmessageType: " + getMessageType() + "\n");
if (getPkiStatus() != null) {
sb.append("\tpkiStatus: " + getPkiStatus() + "\n");
}
if (getFailInfo() != null) {
sb.append("\tfailInfo: " + getFailInfo() + "\n");
}
sb.append("\tsenderNonce: " + getSenderNonce() + "\n");
if (getRecipientNonce() != null) {
sb.append("\trecipientNonce: " + getRecipientNonce() + "\n");
}
sb.append("\tpkcsPkiEnvelope: " + pkcsPkiEnvelope.toString().replaceAll("\n", "\n\t") + "\n");
sb.append("]");
return sb.toString();
}
}
|
api/src/main/java/com/google/code/jscep/pkcs7/PkiMessage.java
|
/*
* Copyright (c) 2009-2010 David Grant
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.google.code.jscep.pkcs7;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import org.bouncycastle.asn1.DERObjectIdentifier;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.DERPrintableString;
import org.bouncycastle.asn1.cms.Attribute;
import org.bouncycastle.asn1.cms.AttributeTable;
import org.bouncycastle.asn1.cms.ContentInfo;
import org.bouncycastle.asn1.cms.SignedData;
import org.bouncycastle.asn1.cms.SignerInfo;
import com.google.code.jscep.asn1.SCEPObjectIdentifiers;
import com.google.code.jscep.transaction.FailInfo;
import com.google.code.jscep.transaction.MessageType;
import com.google.code.jscep.transaction.Nonce;
import com.google.code.jscep.transaction.PkiStatus;
import com.google.code.jscep.transaction.TransactionId;
/**
* This interface represents the <tt>SCEP</tt> <tt>pkiMessage</tt>.
*
* @see <a href="http://tools.ietf.org/html/draft-nourse-scep-20#section-3.1">SCEP Internet-Draft Reference</a>
*/
public class PkiMessage {
private byte[] encoded;
private PkcsPkiEnvelope pkcsPkiEnvelope;
private final SignerInfo signerInfo;
private final ContentInfo contentInfo;
private final SignedData signedData;
PkiMessage(ContentInfo contentInfo) {
this.contentInfo = contentInfo;
this.signedData = SignedData.getInstance(contentInfo.getContent());
this.signerInfo = getSignerSet(signedData).iterator().next();
}
private Set<SignerInfo> getSignerSet(SignedData signedData) {
final Set<SignerInfo> set = new HashSet<SignerInfo>();
final Enumeration<?> signerInfos = signedData.getSignerInfos().getObjects();
while (signerInfos.hasMoreElements()) {
set.add(SignerInfo.getInstance(signerInfos.nextElement()));
}
return set;
}
public boolean isRequest() {
return getPkiStatus() == null;
}
private AttributeTable getAttributeTable() {
return new AttributeTable(signerInfo.getAuthenticatedAttributes());
}
void setPkcsPkiEnvelope(PkcsPkiEnvelope envelope) {
this.pkcsPkiEnvelope = envelope;
}
public PkcsPkiEnvelope getPkcsPkiEnvelope() {
return pkcsPkiEnvelope;
}
// void setFailInfo(FailInfo failInfo) {
// this.failInfo = failInfo;
// }
public FailInfo getFailInfo() {
final Attribute attr = getAttributeTable().get(SCEPObjectIdentifiers.failInfo);
if (attr == null) {
return null;
}
final DERPrintableString failInfo = (DERPrintableString) attr.getAttrValues().getObjectAt(0);
return FailInfo.valueOf(Integer.parseInt(failInfo.getString()));
}
public PkiStatus getPkiStatus() {
final Attribute attr = getAttributeTable().get(SCEPObjectIdentifiers.pkiStatus);
if (attr == null) {
return null;
}
final DERPrintableString pkiStatus = (DERPrintableString) attr.getAttrValues().getObjectAt(0);
return PkiStatus.valueOf(Integer.parseInt(pkiStatus.toString()));
}
private Nonce getNonce(DERObjectIdentifier oid) {
final Attribute attr = getAttributeTable().get(oid);
if (attr == null) {
return null;
}
final DEROctetString nonce = (DEROctetString) attr.getAttrValues().getObjectAt(0);
return new Nonce(nonce.getOctets());
}
public Nonce getRecipientNonce() {
return getNonce(SCEPObjectIdentifiers.recipientNonce);
}
public Nonce getSenderNonce() {
return getNonce(SCEPObjectIdentifiers.senderNonce);
}
public TransactionId getTransactionId() {
final Attribute attr = getAttributeTable().get(SCEPObjectIdentifiers.transId);
DERPrintableString transId = (DERPrintableString) attr.getAttrValues().getObjectAt(0);
return new TransactionId(transId.getOctets());
}
void setEncoded(byte[] encoded) {
this.encoded = encoded;
}
public byte[] getEncoded() {
return encoded;
}
public MessageType getMessageType() {
final Attribute attr = getAttributeTable().get(SCEPObjectIdentifiers.messageType);
final DERPrintableString msgType = (DERPrintableString) attr.getAttrValues().getObjectAt(0);
return MessageType.valueOf(Integer.parseInt(msgType.getString()));
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if (getPkiStatus() == null) {
sb.append("pkiMessage (request) [\n");
} else {
sb.append("pkiMessage (response) [\n");
}
sb.append("\tcontentType: " + contentInfo.getContentType() + "\n");
sb.append("\ttransactionId: " + getTransactionId() + "\n");
sb.append("\tmessageType: " + getMessageType() + "\n");
if (getPkiStatus() != null) {
sb.append("\tpkiStatus: " + getPkiStatus() + "\n");
}
if (getFailInfo() != null) {
sb.append("\tfailInfo: " + getFailInfo() + "\n");
}
sb.append("\tsenderNonce: " + getSenderNonce() + "\n");
if (getRecipientNonce() != null) {
sb.append("\trecipientNonce: " + getRecipientNonce() + "\n");
}
sb.append("\tpkcsPkiEnvelope: " + pkcsPkiEnvelope.toString().replaceAll("\n", "\n\t") + "\n");
sb.append("]");
return sb.toString();
}
}
|
Removed unused method.
|
api/src/main/java/com/google/code/jscep/pkcs7/PkiMessage.java
|
Removed unused method.
|
|
Java
|
mit
|
fc9290b5de9cc894a90f3cd37bec74eb86a0869a
| 0
|
evan10s/wake-me-cgm,evan10s/wake-me-cgm
|
package at.str.evan.wakemecgm;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.media.AudioAttributes;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.IBinder;
import android.os.Vibrator;
import android.provider.MediaStore;
import android.support.v7.app.NotificationCompat;
import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import java.util.Map;
public class BgUpdateService extends FirebaseMessagingService {
public BgUpdateService() {
}
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// If the application is in the foreground handle both data and notification messages here.
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
Log.d("WAKEMECGM", "From: " + remoteMessage.getFrom());
//Vibrator vibrate = (Vibrator) getSystemService(VIBRATOR_SERVICE);
//vibrate.vibrate(300);
Log.d("WAKEMECGM", remoteMessage.getData().toString());
int vibrate;
Map<String, String> msgData = remoteMessage.getData();
int bg = Integer.parseInt(msgData.get("latest_bg"));
String trendVal = msgData.get("trend");
String trendSymbol = "";
switch (trendVal) {
case "FLAT":
trendSymbol = "→";
break;
case "UP_45":
trendSymbol = "↗";
break;
case "SINGLE_UP":
trendSymbol = "↑";
break;
case "DOUBLE_UP":
trendSymbol = "⇈";
break;
case "DOWN_45":
trendSymbol = "↘";
break;
case "SINGLE_DOWN":
trendSymbol = "↓";
break;
case "DOUBLE_DOWN":
trendSymbol = "⇊";
break;
}
String title = bg + " " + trendSymbol;
String body;
if (bg < 70) {
vibrate = 1;
body = "Low BG";
} else if (bg > 240) {
vibrate = 2;
body = "High BG";
} else {
vibrate = 3;
body = "OK";
}
sendNotification(title, body,bg);
}
private void sendNotification(String messageTitle, String messageBody,int bg) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* request code */, intent, PendingIntent.FLAG_UPDATE_CURRENT);
long[] vibrateLow = {400, 400, 400, 400, 400, 400};
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if (bg < 130) {
defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
}
NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(messageTitle)
.setContentText(messageBody)
.setVibrate(vibrateLow)
.setAutoCancel(true)
.setLights(Color.BLUE, 1, 1)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent)
.setColor(Color.YELLOW);
Notification bgAlert = notificationBuilder.build();
bgAlert.flags = Notification.FLAG_INSISTENT;
/* long[] vibrateLow = {400, 400, 400, 400, 400, 400};
long[] vibrateHigh = {500, 400, 500, 400};
long[] vibrateOther = {1000};
long[] vibrate;
if (pattern == 1) {
notificationBuilder.setVibrate(vibrateLow);
} else if (pattern == 2) {
notificationBuilder.setVibrate(vibrateHigh);
} else {
notificationBuilder
}*/
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
|
app/src/main/java/at/str/evan/wakemecgm/bgUpdateService.java
|
package at.str.evan.wakemecgm;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.IBinder;
import android.os.Vibrator;
import android.support.v7.app.NotificationCompat;
import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
public class BgUpdateService extends FirebaseMessagingService {
public BgUpdateService() {
}
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// TODO(developer): Handle FCM messages here.
// If the application is in the foreground handle both data and notification messages here.
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
Log.d("WAKEMECGM", "From: " + remoteMessage.getFrom());
//Vibrator vibrate = (Vibrator) getSystemService(VIBRATOR_SERVICE);
//vibrate.vibrate(300);
Log.d("WAKEMECGM", remoteMessage.getData().toString());
int vibrate;
int bg = Integer.parseInt(remoteMessage.getData().get("latest_bg"));
if (bg < 70) {
vibrate = 1;
} else if (bg > 240) {
vibrate = 2;
} else {
vibrate = 3;
}
sendNotification(remoteMessage.getData().get("title"), remoteMessage.getData().get("body"),vibrate);
}
private void sendNotification(String messageTitle, String messageBody,int pattern) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* request code */, intent, PendingIntent.FLAG_UPDATE_CURRENT);
long[] vibrateLow = {400, 400, 400, 400, 400, 400};
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(messageTitle)
.setContentText(messageBody)
.setVibrate(vibrateLow)
.setAutoCancel(true)
.setLights(Color.BLUE, 1, 1)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
/* long[] vibrateLow = {400, 400, 400, 400, 400, 400};
long[] vibrateHigh = {500, 400, 500, 400};
long[] vibrateOther = {1000};
long[] vibrate;
if (pattern == 1) {
notificationBuilder.setVibrate(vibrateLow);
} else if (pattern == 2) {
notificationBuilder.setVibrate(vibrateHigh);
} else {
notificationBuilder
}*/
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
|
Refine notification display, attempt to make sound repeat (unsuccessfully)
|
app/src/main/java/at/str/evan/wakemecgm/bgUpdateService.java
|
Refine notification display, attempt to make sound repeat (unsuccessfully)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.