diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/src/main/java/de/lmu/ifi/dbs/jfeaturelib/features/MeanPatchIntensityHistogram.java b/src/main/java/de/lmu/ifi/dbs/jfeaturelib/features/MeanPatchIntensityHistogram.java
index 9f33d36..f763fea 100644
--- a/src/main/java/de/lmu/ifi/dbs/jfeaturelib/features/MeanPatchIntensityHistogram.java
+++ b/src/main/java/de/lmu/ifi/dbs/jfeaturelib/features/MeanPatchIntensityHistogram.java
@@ -1,199 +1,202 @@
/*
* This file is part of the JFeatureLib project: http://jfeaturelib.googlecode.com
* JFeatureLib is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* JFeatureLib 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with JFeatureLib; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* You are kindly asked to refer to the papers of the according authors which
* should be mentioned in the Javadocs of the respective classes as well as the
* JFeatureLib project itself.
*
* Hints how to cite the projects can be found at
* https://code.google.com/p/jfeaturelib/wiki/Citation
*/
package de.lmu.ifi.dbs.jfeaturelib.features;
import de.lmu.ifi.dbs.jfeaturelib.utils.Histogram;
import de.lmu.ifi.dbs.jfeaturelib.LibProperties;
import de.lmu.ifi.dbs.jfeaturelib.Progress;
import de.lmu.ifi.dbs.jfeaturelib.utils.IntegralImage;
import ij.measure.Measurements;
import ij.process.ByteProcessor;
import ij.process.ImageProcessor;
import ij.process.ImageStatistics;
import java.awt.Rectangle;
import java.io.IOException;
import java.util.EnumSet;
/**
* This descriptor calculates a histogram of mean intensities of specified neighborhood size.
* <p>
* For each pixel in the image, a patch of size
* <code>1 + 2 * size</code> is extracted, where
* <code>size</code> is determined by {@link #setSize(int)}. Mean intensities of all patches are summarized in a
* histogram.
* </p><p>
* Mean intensities are computed efficiently by using {@link IntegralImage}.
* </p>
*
* @author sebp
*/
public class MeanPatchIntensityHistogram extends AbstractFeatureDescriptor {
protected int m_size;
protected int m_bins;
protected double m_histMin;
protected double m_histMax;
protected int m_patchSize;
protected int m_patchArea;
protected IntegralImage m_integralImage;
public MeanPatchIntensityHistogram() {
}
@Override
public String getDescription() {
return "Mean patch intensities";
}
@Override
public EnumSet<Supports> supports() {
return EnumSet.of(
Supports.NoChanges,
Supports.DOES_8G);
}
@Override
public void setProperties(LibProperties properties) throws IOException {
setSize(properties.getInteger(LibProperties.MEAN_PATCH_INTENSITIES_PATCH_SIZE));
setNumberOfBins(properties.getInteger(LibProperties.MEAN_PATCH_INTENSITIES_BINS));
setHistogramRange(
properties.getDouble(LibProperties.MEAN_PATCH_INTENSITIES_HIST_MIN),
properties.getDouble(LibProperties.MEAN_PATCH_INTENSITIES_HIST_MAX));
}
@Override
public void run(ImageProcessor ip) {
firePropertyChange(Progress.START);
createIntegralImage((ByteProcessor) ip);
int yStart, xStart, yEnd, xEnd;
yStart = m_size;
xStart = m_size;
yEnd = ip.getHeight() - m_size;
xEnd = ip.getWidth() - m_size;
if (m_histMin == 0 && m_histMax == 0) {
retrieveMinAndMaxFromImage(ip);
+ // Histogram class excludes the maximum value,
+ // therefore increase it by 1
+ m_histMax++;
}
Histogram hist = new Histogram(m_bins, m_histMin, m_histMax);
for (int y = yStart; y < yEnd; y++) {
for (int x = xStart; x < xEnd; x++) {
hist.add(getMeanIntensity(x, y));
}
int p = (int) (y / (double) yEnd * 100);
firePropertyChange(new Progress(p));
}
addData(hist.getHistogramm());
m_integralImage = null;
firePropertyChange(Progress.END);
}
protected void createIntegralImage(ByteProcessor ip) {
m_integralImage = new IntegralImage();
m_integralImage.compute(ip);
}
protected void retrieveMinAndMaxFromImage(ImageProcessor ip) {
ImageStatistics stats = ImageStatistics.getStatistics(ip, Measurements.MIN_MAX, null);
m_histMin = stats.min;
m_histMax = stats.max;
}
protected float getMeanIntensity(final int x, final int y) {
Rectangle rect = new Rectangle(x - m_size, y - m_size, m_patchSize, m_patchSize);
return m_integralImage.get(rect) / (float) m_patchArea;
}
public int getSize() {
return m_size;
}
/**
* Set size of neighborhood which determines the patch size.
* <p>
* The outer most <tt>size</tt> pixels will not be considered because they have incomplete neighborhoods.
* </p>
*
* @param size
* @throws IllegalArgumentException if <code>size <= 0</code>
*/
public void setSize(int size) {
if (size <= 0) {
throw new IllegalArgumentException("size must be greater zero, but got " + size);
}
m_size = size;
m_patchSize = 1 + 2 * size;
m_patchArea = m_patchSize * m_patchSize;
}
public int getNumberOfBins() {
return m_bins;
}
/**
* Set the number of bins of the histogram.
*
* @param bins
* @throws IllegalArgumentException if <code>bins <= 0</code>
*/
public void setNumberOfBins(int bins) {
if (bins <= 0) {
throw new IllegalArgumentException("number of bins must be greater zero, but got " + bins);
}
m_bins = bins;
}
public double getHistogramMin() {
return m_histMin;
}
public double getHistogramMax() {
return m_histMax;
}
/**
* Set the minimum and maximum value that the histogram should consider.
* <p>
* If both min and max are set to zero (default), limits are retrieved from data.
* </p>
*
* @param min
* @param max
* @throws IllegalArgumentException if <code>min > max</code>
*/
public void setHistogramRange(double min, double max) {
if (min > max) {
throw new IllegalArgumentException("min must be smaller than or equal to max");
}
m_histMin = min;
m_histMax = max;
}
}
| true | true | public void run(ImageProcessor ip) {
firePropertyChange(Progress.START);
createIntegralImage((ByteProcessor) ip);
int yStart, xStart, yEnd, xEnd;
yStart = m_size;
xStart = m_size;
yEnd = ip.getHeight() - m_size;
xEnd = ip.getWidth() - m_size;
if (m_histMin == 0 && m_histMax == 0) {
retrieveMinAndMaxFromImage(ip);
}
Histogram hist = new Histogram(m_bins, m_histMin, m_histMax);
for (int y = yStart; y < yEnd; y++) {
for (int x = xStart; x < xEnd; x++) {
hist.add(getMeanIntensity(x, y));
}
int p = (int) (y / (double) yEnd * 100);
firePropertyChange(new Progress(p));
}
addData(hist.getHistogramm());
m_integralImage = null;
firePropertyChange(Progress.END);
}
| public void run(ImageProcessor ip) {
firePropertyChange(Progress.START);
createIntegralImage((ByteProcessor) ip);
int yStart, xStart, yEnd, xEnd;
yStart = m_size;
xStart = m_size;
yEnd = ip.getHeight() - m_size;
xEnd = ip.getWidth() - m_size;
if (m_histMin == 0 && m_histMax == 0) {
retrieveMinAndMaxFromImage(ip);
// Histogram class excludes the maximum value,
// therefore increase it by 1
m_histMax++;
}
Histogram hist = new Histogram(m_bins, m_histMin, m_histMax);
for (int y = yStart; y < yEnd; y++) {
for (int x = xStart; x < xEnd; x++) {
hist.add(getMeanIntensity(x, y));
}
int p = (int) (y / (double) yEnd * 100);
firePropertyChange(new Progress(p));
}
addData(hist.getHistogramm());
m_integralImage = null;
firePropertyChange(Progress.END);
}
|
diff --git a/src/com/github/andlyticsproject/ChartActivity.java b/src/com/github/andlyticsproject/ChartActivity.java
index 6fed7aa..89d3490 100644
--- a/src/com/github/andlyticsproject/ChartActivity.java
+++ b/src/com/github/andlyticsproject/ChartActivity.java
@@ -1,269 +1,270 @@
package com.github.andlyticsproject;
import java.text.DateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import com.github.andlyticsproject.Preferences.Timeframe;
import com.github.andlyticsproject.chart.Chart.ChartSet;
import com.github.andlyticsproject.model.AppStats;
import com.github.andlyticsproject.model.AppStatsList;
import com.github.andlyticsproject.util.DetachableAsyncTask;
import com.github.andlyticsproject.util.Utils;
public class ChartActivity extends BaseChartActivity {
// private static String LOG_TAG=ChartActivity.class.toString();
private ContentAdapter db;
private ListView historyList;
private ChartListAdapter historyListAdapter;
private TextView historyListFooter;
private View oneEntryHint;
private boolean dataUpdateRequested;
private ChartSet currentChartSet;
private Boolean smoothEnabled;
public List<Date> versionUpdateDates;
private LoadChartData loadChartData;
@Override
protected void executeLoadData(Timeframe timeFrame) {
if (loadChartData != null) {
loadChartData.detach();
}
loadChartData = new LoadChartData(this);
Utils.execute(loadChartData, timeFrame);
}
private void executeLoadDataDefault() {
if (loadChartData != null) {
loadChartData.detach();
}
loadChartData = new LoadChartData(this);
Utils.execute(loadChartData, getCurrentTimeFrame());
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
Bundle b = intent.getExtras();
if (b != null) {
String chartSet = b.getString(Constants.CHART_SET);
if (chartSet != null) {
currentChartSet = ChartSet.valueOf(chartSet);
}
}
if (currentChartSet == null) {
currentChartSet = ChartSet.DOWNLOADS;
}
setCurrentChart(currentChartSet.ordinal(), 1);
}
@Override
public void onCreate(Bundle savedInstanceState) {
smoothEnabled = Preferences.getChartSmooth(this);
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setCurrentChartSet(ChartSet.RATINGS);
Bundle b = getIntent().getExtras();
if (b != null) {
String chartSet = b.getString(Constants.CHART_SET);
if (chartSet != null) {
currentChartSet = ChartSet.valueOf(chartSet);
}
}
if (currentChartSet == null) {
currentChartSet = ChartSet.DOWNLOADS;
}
if (ChartSet.RATINGS.equals(currentChartSet)) {
getSupportActionBar().setTitle(R.string.ratings);
} else {
getSupportActionBar().setTitle(R.string.downloads);
}
db = getDbAdapter();
// chartFrame = (ViewSwitcher) ;
oneEntryHint = (View) findViewById(R.id.base_chart_one_entry_hint);
historyList = (ListView) findViewById(R.id.base_chart_list);
View inflate = getLayoutInflater().inflate(R.layout.chart_list_footer, null);
historyListFooter = (TextView) inflate.findViewById(R.id.chart_footer_text);
historyList.addFooterView(inflate, null, false);
historyListAdapter = new ChartListAdapter(this);
setAdapter(historyListAdapter);
historyListAdapter.setCurrentChart(currentChartSet.ordinal(), 1);
setAllowChangePageSliding(false);
if (getLastNonConfigurationInstance() != null) {
loadChartData = (LoadChartData) getLastNonConfigurationInstance();
loadChartData.attach(this);
if (loadChartData.statsForApp != null) {
- updateView(loadChartData.statsForApp, loadChartData.smoothedValues);
+ // XXX causes NPE? race?
+ //updateView(loadChartData.statsForApp, loadChartData.smoothedValues);
}
}
}
@Override
public Object onRetainNonConfigurationInstance() {
return loadChartData == null ? null : loadChartData.detach();
}
@Override
protected String getChartHint() {
return this.getString(R.string.swipe);
}
@Override
protected void onResume() {
super.onResume();
dataUpdateRequested = true;
// TODO -- do we load data always?
executeLoadDataDefault();
}
public void setCurrentChartSet(ChartSet currentChartSet) {
this.currentChartSet = currentChartSet;
}
public ChartSet getCurrentChartSet() {
return currentChartSet;
}
private static class LoadChartData extends
DetachableAsyncTask<Timeframe, Void, Boolean, ChartActivity> {
LoadChartData(ChartActivity activity) {
super(activity);
}
private List<AppStats> statsForApp;
private boolean smoothedValues = false;
@Override
protected Boolean doInBackground(Timeframe... params) {
if (activity == null) {
return null;
}
if (activity.dataUpdateRequested || statsForApp == null || statsForApp.size() == 0) {
AppStatsList result = activity.db.getStatsForApp(activity.packageName, params[0],
activity.smoothEnabled);
statsForApp = result.getAppStats();
activity.historyListAdapter.setOverallStats(result.getOverall());
activity.versionUpdateDates = activity.db
.getVersionUpdateDates(activity.packageName);
activity.historyListAdapter
.setHeighestRatingChange(result.getHighestRatingChange());
activity.historyListAdapter.setLowestRatingChange(result.getLowestRatingChange());
activity.dataUpdateRequested = false;
smoothedValues = applySmoothedValues(statsForApp);
}
return true;
}
@Override
protected void onPostExecute(Boolean result) {
if (activity == null) {
return;
}
activity.updateView(statsForApp, smoothedValues);
}
}
private static boolean applySmoothedValues(List<AppStats> statsForApp) {
for (AppStats appInfo : statsForApp) {
if (appInfo.isSmoothingApplied()) {
return true;
}
}
return false;
}
private void updateView(List<AppStats> statsForApp, boolean smoothedValues) {
if (statsForApp != null && statsForApp.size() > 0) {
updateCharts(statsForApp);
DateFormat dateFormat = Preferences.getDateFormatLong(this);
timetext = dateFormat.format(statsForApp.get(0).getRequestDate()) + " - "
+ dateFormat.format(statsForApp.get(statsForApp.size() - 1).getRequestDate());
updateChartHeadline();
Collections.reverse(statsForApp);
historyListAdapter.setDownloadInfos(statsForApp);
historyListAdapter.setVersionUpdateDates(versionUpdateDates);
/*
* int page=historyListAdapter.getCurrentPage(); int
* column=historyListAdapter.getCurrentColumn();
* historyListAdapter.setCurrentChart(page, column);
*/
historyListAdapter.notifyDataSetChanged();
if (smoothedValues && currentChartSet.equals(ChartSet.DOWNLOADS)) {
historyListFooter.setVisibility(View.VISIBLE);
} else {
historyListFooter.setVisibility(View.INVISIBLE);
}
if (oneEntryHint != null) {
if (statsForApp.size() == 1) {
oneEntryHint.setVisibility(View.VISIBLE);
} else {
oneEntryHint.setVisibility(View.INVISIBLE);
}
}
// chartFrame.showNext();
}
}
@Override
protected void notifyChangedDataformat() {
dataUpdateRequested = true;
executeLoadDataDefault();
}
@Override
protected void onChartSelected(int page, int column) {
super.onChartSelected(page, column);
if (page != currentChartSet.ordinal()) {
currentChartSet = ChartSet.values()[page];
updateTabbarButtons();
}
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
smoothEnabled = Preferences.getChartSmooth(this);
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setCurrentChartSet(ChartSet.RATINGS);
Bundle b = getIntent().getExtras();
if (b != null) {
String chartSet = b.getString(Constants.CHART_SET);
if (chartSet != null) {
currentChartSet = ChartSet.valueOf(chartSet);
}
}
if (currentChartSet == null) {
currentChartSet = ChartSet.DOWNLOADS;
}
if (ChartSet.RATINGS.equals(currentChartSet)) {
getSupportActionBar().setTitle(R.string.ratings);
} else {
getSupportActionBar().setTitle(R.string.downloads);
}
db = getDbAdapter();
// chartFrame = (ViewSwitcher) ;
oneEntryHint = (View) findViewById(R.id.base_chart_one_entry_hint);
historyList = (ListView) findViewById(R.id.base_chart_list);
View inflate = getLayoutInflater().inflate(R.layout.chart_list_footer, null);
historyListFooter = (TextView) inflate.findViewById(R.id.chart_footer_text);
historyList.addFooterView(inflate, null, false);
historyListAdapter = new ChartListAdapter(this);
setAdapter(historyListAdapter);
historyListAdapter.setCurrentChart(currentChartSet.ordinal(), 1);
setAllowChangePageSliding(false);
if (getLastNonConfigurationInstance() != null) {
loadChartData = (LoadChartData) getLastNonConfigurationInstance();
loadChartData.attach(this);
if (loadChartData.statsForApp != null) {
updateView(loadChartData.statsForApp, loadChartData.smoothedValues);
}
}
}
| public void onCreate(Bundle savedInstanceState) {
smoothEnabled = Preferences.getChartSmooth(this);
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setCurrentChartSet(ChartSet.RATINGS);
Bundle b = getIntent().getExtras();
if (b != null) {
String chartSet = b.getString(Constants.CHART_SET);
if (chartSet != null) {
currentChartSet = ChartSet.valueOf(chartSet);
}
}
if (currentChartSet == null) {
currentChartSet = ChartSet.DOWNLOADS;
}
if (ChartSet.RATINGS.equals(currentChartSet)) {
getSupportActionBar().setTitle(R.string.ratings);
} else {
getSupportActionBar().setTitle(R.string.downloads);
}
db = getDbAdapter();
// chartFrame = (ViewSwitcher) ;
oneEntryHint = (View) findViewById(R.id.base_chart_one_entry_hint);
historyList = (ListView) findViewById(R.id.base_chart_list);
View inflate = getLayoutInflater().inflate(R.layout.chart_list_footer, null);
historyListFooter = (TextView) inflate.findViewById(R.id.chart_footer_text);
historyList.addFooterView(inflate, null, false);
historyListAdapter = new ChartListAdapter(this);
setAdapter(historyListAdapter);
historyListAdapter.setCurrentChart(currentChartSet.ordinal(), 1);
setAllowChangePageSliding(false);
if (getLastNonConfigurationInstance() != null) {
loadChartData = (LoadChartData) getLastNonConfigurationInstance();
loadChartData.attach(this);
if (loadChartData.statsForApp != null) {
// XXX causes NPE? race?
//updateView(loadChartData.statsForApp, loadChartData.smoothedValues);
}
}
}
|
diff --git a/src/org/buttes/shitpreview/preview.java b/src/org/buttes/shitpreview/preview.java
index bbfde92..8bb391a 100644
--- a/src/org/buttes/shitpreview/preview.java
+++ b/src/org/buttes/shitpreview/preview.java
@@ -1,294 +1,295 @@
package org.buttes.shitpreview;
import java.io.IOException;
import java.util.List;
import java.lang.Math;
import java.lang.Thread;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.graphics.PixelFormat;
import android.graphics.ImageFormat;
import android.hardware.Camera;
import android.hardware.Camera.*;
import android.os.Bundle;
import android.view.WindowManager;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.util.Log;
import android.media.AudioTrack;
import android.media.AudioTrack.*;
import android.media.AudioFormat;
import android.media.AudioFormat.*;
import android.media.AudioManager;
class AudioPlayer {
AudioTrack audio;
final int sampleRate = 11025;
final int sampleSize = 2; // in bytes
final int sampleChannelCfg = AudioFormat.CHANNEL_OUT_MONO;
final int sampleEncoding = (sampleSize == 1) ? AudioFormat.ENCODING_PCM_8BIT :
(sampleSize == 2) ? AudioFormat.ENCODING_PCM_16BIT :
AudioFormat.ENCODING_INVALID;
final int minBufferSize = AudioTrack.getMinBufferSize(sampleRate, sampleChannelCfg, sampleEncoding);
final int secondBufferSize = sampleRate * sampleSize;
final int bufferSize = Math.max(minBufferSize, secondBufferSize);
final int sampleBufferN = sampleRate / 5;
final short[] sampleBuffer = new short[sampleBufferN];
final int voicesN = 3;
final long[] voices = new long[voicesN];
public AudioPlayer() {
audio = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRate, sampleChannelCfg, sampleEncoding, bufferSize, AudioTrack.MODE_STREAM);
audio.play();
}
private double getFrequency(double note) {
final double baseExponent = Math.pow(2.0, 1.0 / 12.0);
final double baseFrequency = 55.0;
return baseFrequency * Math.pow(baseExponent, note);
}
private short getNoteSample(long sampleN, long sampleRate, double note, double volume) {
return (short)Math.rint(volume * Short.MAX_VALUE * Math.sin(2.0 * Math.PI * getFrequency(note) * (double)sampleN / (double)sampleRate));
}
public void setSampleBuffer(int voice, double note, double volume) {
if(voice < 0 || voice >= voicesN)
voice = 0;
for(int i = 0; i < sampleBuffer.length; i++)
sampleBuffer[i] = getNoteSample(voices[voice]++, sampleRate, note, volume);
}
public void addSampleBuffer(int voice, double note, double volume) {
if(voice < 0 || voice >= voicesN)
voice = 0;
for(int i = 0; i < sampleBuffer.length; i++)
sampleBuffer[i] += getNoteSample(voices[voice]++, sampleRate, note, volume);
}
public void write() {
audio.write(sampleBuffer, 0, sampleBuffer.length);
}
}
public class preview extends Activity implements SurfaceHolder.Callback, Camera.PreviewCallback
{
Camera camera;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
TextView textViewMessage;
Button buttonPlay;
Button buttonPause;
boolean previewing = false;
/*
* get frame size of a preview image (assuming NV21 format)
*/
private int getFrameSize() {
Camera.Parameters param = camera.getParameters();
int imgformat = param.getPreviewFormat();
int bitsperpixel = ImageFormat.getBitsPerPixel(imgformat);
Camera.Size camerasize = param.getPreviewSize();
return (camerasize.width * camerasize.height * bitsperpixel) / 8;
};
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// find widgets
textViewMessage = (TextView)findViewById(R.id.message);
buttonPlay = (Button)findViewById(R.id.startcamerapreview);
buttonPause = (Button)findViewById(R.id.stopcamerapreview);
surfaceView = (SurfaceView)findViewById(R.id.surfaceview);
getWindow().setFormat(PixelFormat.YCbCr_420_SP);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
// setup start camera button
buttonPlay.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
if(previewing == false) {
//
//
// start up the audio player
//
//
previewing = true;
final Handler handler = new Handler();
new Thread(new Runnable() {
@Override
public void run() {
AudioPlayer player = new AudioPlayer();
handler.post(new Runnable() {
@Override
public void run() {
textViewMessage.setText(String.format("PaperTracker - playback starting!\n"));
}
});
double note = 36.0;
double loud = 1.0;
int voice = 0;
while(previewing) {
player.setSampleBuffer(voice, note, loud);
player.write();
}
}
}).start();
//
//
// start up the camera
//
//
- if((camera = Camera.open())) {
+ camera = Camera.open();
+ if(camera != null) {
try {
camera.setPreviewDisplay(surfaceHolder);
camera.setDisplayOrientation(0);
// final int frameOffset = previewSize.height / 2;
camera.setPreviewCallback(new PreviewCallback() {
final Size previewSize = camera.getParameters().getPreviewSize();
final int frameWidth = previewSize.width;
final long startTime = System.currentTimeMillis();
final int framesPerMessage = 4;
long frameN = 0;
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
// TODO:
// 1. perform 8-bit Y-channel to 16-bit mono PCM conversion
// 2. invert, normalize & stretch pcm
// 3. centroid position and width detection
// 4. select frequency scale or proceedural instrument table
// a. probably not a not fourier basis like DCT-II/II transform pairs,
// b. try equal temperament chromatic scale: base_hz * (2 ** (1/12) ** note_n)
// 5. centroid position, width to frequency, amplitude conversion
// 6. freq to time domain composition and compress range
// 7. lag compensation
// pcmBuffer[i] = (short)(((int)data[frameOffset + i] & 0x00ff) + 128); // convert unsigned 8-bit to signed 16-bit
// pcmBuffer[i] = (short)(255 - pcmBuffer[i]); // invert levels
// pcmBuffer[i] <<= 8; // scale amplitude by 256, or a left-shift of 1 byte
frameN++;
long elapsedTime = System.currentTimeMillis() - startTime;
double secs = (double)elapsedTime / 1000.0;
double fps = (double)frameN / secs;
if(frameN % framesPerMessage == 1) {
textViewMessage.setText(String.format("PaperTracker - #%d %.1fs %.1ffps %.1fhz", frameN, secs, fps, fps * (double)frameWidth));
// textViewMessage.setText(String.format("PaperTracker - #%d %.1fs %dspf %dkB %.1f : %.1f fps X %.1f %.1f hz",
// counters[0], secs, frameWidth, bufferSize >> 10, targetFps, fps, runRate, fps * frameWidth));
}
}
});
camera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
// end of if((camera = Camera.open())) { ... }
}
// end of if(previewing == false) { ... }
}
// end of onClick()
}
});
//
// setup stop camera button
//
buttonPause.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
if(previewing) {
if(camera != null) {
camera.stopPreview();
camera.release();
camera = null;
}
previewing = false;
}
}
});
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
}
}
/*
class Extract implements Camera.PreviewCallback {
}
*/
| true | true | public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// find widgets
textViewMessage = (TextView)findViewById(R.id.message);
buttonPlay = (Button)findViewById(R.id.startcamerapreview);
buttonPause = (Button)findViewById(R.id.stopcamerapreview);
surfaceView = (SurfaceView)findViewById(R.id.surfaceview);
getWindow().setFormat(PixelFormat.YCbCr_420_SP);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
// setup start camera button
buttonPlay.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
if(previewing == false) {
//
//
// start up the audio player
//
//
previewing = true;
final Handler handler = new Handler();
new Thread(new Runnable() {
@Override
public void run() {
AudioPlayer player = new AudioPlayer();
handler.post(new Runnable() {
@Override
public void run() {
textViewMessage.setText(String.format("PaperTracker - playback starting!\n"));
}
});
double note = 36.0;
double loud = 1.0;
int voice = 0;
while(previewing) {
player.setSampleBuffer(voice, note, loud);
player.write();
}
}
}).start();
//
//
// start up the camera
//
//
if((camera = Camera.open())) {
try {
camera.setPreviewDisplay(surfaceHolder);
camera.setDisplayOrientation(0);
// final int frameOffset = previewSize.height / 2;
camera.setPreviewCallback(new PreviewCallback() {
final Size previewSize = camera.getParameters().getPreviewSize();
final int frameWidth = previewSize.width;
final long startTime = System.currentTimeMillis();
final int framesPerMessage = 4;
long frameN = 0;
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
// TODO:
// 1. perform 8-bit Y-channel to 16-bit mono PCM conversion
// 2. invert, normalize & stretch pcm
// 3. centroid position and width detection
// 4. select frequency scale or proceedural instrument table
// a. probably not a not fourier basis like DCT-II/II transform pairs,
// b. try equal temperament chromatic scale: base_hz * (2 ** (1/12) ** note_n)
// 5. centroid position, width to frequency, amplitude conversion
// 6. freq to time domain composition and compress range
// 7. lag compensation
// pcmBuffer[i] = (short)(((int)data[frameOffset + i] & 0x00ff) + 128); // convert unsigned 8-bit to signed 16-bit
// pcmBuffer[i] = (short)(255 - pcmBuffer[i]); // invert levels
// pcmBuffer[i] <<= 8; // scale amplitude by 256, or a left-shift of 1 byte
frameN++;
long elapsedTime = System.currentTimeMillis() - startTime;
double secs = (double)elapsedTime / 1000.0;
double fps = (double)frameN / secs;
if(frameN % framesPerMessage == 1) {
textViewMessage.setText(String.format("PaperTracker - #%d %.1fs %.1ffps %.1fhz", frameN, secs, fps, fps * (double)frameWidth));
// textViewMessage.setText(String.format("PaperTracker - #%d %.1fs %dspf %dkB %.1f : %.1f fps X %.1f %.1f hz",
// counters[0], secs, frameWidth, bufferSize >> 10, targetFps, fps, runRate, fps * frameWidth));
}
}
});
camera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
// end of if((camera = Camera.open())) { ... }
}
// end of if(previewing == false) { ... }
}
// end of onClick()
}
});
//
// setup stop camera button
//
buttonPause.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
if(previewing) {
if(camera != null) {
camera.stopPreview();
camera.release();
camera = null;
}
previewing = false;
}
}
});
}
| public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// find widgets
textViewMessage = (TextView)findViewById(R.id.message);
buttonPlay = (Button)findViewById(R.id.startcamerapreview);
buttonPause = (Button)findViewById(R.id.stopcamerapreview);
surfaceView = (SurfaceView)findViewById(R.id.surfaceview);
getWindow().setFormat(PixelFormat.YCbCr_420_SP);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
// setup start camera button
buttonPlay.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
if(previewing == false) {
//
//
// start up the audio player
//
//
previewing = true;
final Handler handler = new Handler();
new Thread(new Runnable() {
@Override
public void run() {
AudioPlayer player = new AudioPlayer();
handler.post(new Runnable() {
@Override
public void run() {
textViewMessage.setText(String.format("PaperTracker - playback starting!\n"));
}
});
double note = 36.0;
double loud = 1.0;
int voice = 0;
while(previewing) {
player.setSampleBuffer(voice, note, loud);
player.write();
}
}
}).start();
//
//
// start up the camera
//
//
camera = Camera.open();
if(camera != null) {
try {
camera.setPreviewDisplay(surfaceHolder);
camera.setDisplayOrientation(0);
// final int frameOffset = previewSize.height / 2;
camera.setPreviewCallback(new PreviewCallback() {
final Size previewSize = camera.getParameters().getPreviewSize();
final int frameWidth = previewSize.width;
final long startTime = System.currentTimeMillis();
final int framesPerMessage = 4;
long frameN = 0;
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
// TODO:
// 1. perform 8-bit Y-channel to 16-bit mono PCM conversion
// 2. invert, normalize & stretch pcm
// 3. centroid position and width detection
// 4. select frequency scale or proceedural instrument table
// a. probably not a not fourier basis like DCT-II/II transform pairs,
// b. try equal temperament chromatic scale: base_hz * (2 ** (1/12) ** note_n)
// 5. centroid position, width to frequency, amplitude conversion
// 6. freq to time domain composition and compress range
// 7. lag compensation
// pcmBuffer[i] = (short)(((int)data[frameOffset + i] & 0x00ff) + 128); // convert unsigned 8-bit to signed 16-bit
// pcmBuffer[i] = (short)(255 - pcmBuffer[i]); // invert levels
// pcmBuffer[i] <<= 8; // scale amplitude by 256, or a left-shift of 1 byte
frameN++;
long elapsedTime = System.currentTimeMillis() - startTime;
double secs = (double)elapsedTime / 1000.0;
double fps = (double)frameN / secs;
if(frameN % framesPerMessage == 1) {
textViewMessage.setText(String.format("PaperTracker - #%d %.1fs %.1ffps %.1fhz", frameN, secs, fps, fps * (double)frameWidth));
// textViewMessage.setText(String.format("PaperTracker - #%d %.1fs %dspf %dkB %.1f : %.1f fps X %.1f %.1f hz",
// counters[0], secs, frameWidth, bufferSize >> 10, targetFps, fps, runRate, fps * frameWidth));
}
}
});
camera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
// end of if((camera = Camera.open())) { ... }
}
// end of if(previewing == false) { ... }
}
// end of onClick()
}
});
//
// setup stop camera button
//
buttonPause.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
if(previewing) {
if(camera != null) {
camera.stopPreview();
camera.release();
camera = null;
}
previewing = false;
}
}
});
}
|
diff --git a/cycle/src/test/java/com/camunda/fox/cycle/connector/signavio/SignavioClientProxyIT.java b/cycle/src/test/java/com/camunda/fox/cycle/connector/signavio/SignavioClientProxyIT.java
index ea34371b2..6f09a9d7f 100644
--- a/cycle/src/test/java/com/camunda/fox/cycle/connector/signavio/SignavioClientProxyIT.java
+++ b/cycle/src/test/java/com/camunda/fox/cycle/connector/signavio/SignavioClientProxyIT.java
@@ -1,255 +1,256 @@
package com.camunda.fox.cycle.connector.signavio;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.List;
import java.util.Scanner;
import javax.inject.Inject;
import junit.framework.Assert;
import com.camunda.fox.cycle.http.ParseException;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.custommonkey.xmlunit.DetailedDiff;
import org.custommonkey.xmlunit.Diff;
import org.custommonkey.xmlunit.ElementNameAndAttributeQualifier;
import org.custommonkey.xmlunit.SimpleNamespaceContext;
import org.custommonkey.xmlunit.XMLUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
import com.camunda.fox.cycle.entity.ConnectorConfiguration;
import com.camunda.fox.cycle.util.BpmnNamespaceContext;
import com.camunda.fox.cycle.util.IoUtil;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:/spring/test/signavio-connector-xml-config.xml" })
public class SignavioClientProxyIT {
private static final String CREATE_FOLDER_NAME = "CreateFolder";
@Inject
private List<ConnectorConfiguration> connectorConfiguration;
private SignavioClient signavioClient;
private ConnectorConfiguration configuration;
@Before
public void setUp() throws Exception {
configuration = connectorConfiguration.get(1);
signavioClient =
new SignavioClient(configuration.getProperties().get(SignavioConnector.CONFIG_KEY_SIGNAVIO_BASE_URL),
configuration.getProperties().get(SignavioConnector.CONFIG_KEY_PROXY_URL),
configuration.getProperties().get(SignavioConnector.CONFIG_KEY_PROXY_USERNAME),
configuration.getProperties().get(SignavioConnector.CONFIG_KEY_PROXY_PASSWORD),
"");
assertTrue("Failed to login.", signavioClient.login(configuration.getGlobalUser(), configuration.getGlobalPassword()));
}
@After
public void tearDown() throws Exception {
configuration = null;
signavioClient.dispose();
signavioClient = null;
}
@Test
public void testGetChildren() {
String children = signavioClient.getChildren("");
assertThat(children).contains("private");
}
@Test
public void testGetFolderInfo() throws JSONException {
String folderId = createFolder();
try {
String info = signavioClient.getInfo(SignavioClient.DIRECTORY_URL_SUFFIX, folderId);
assertThat(info).contains(CREATE_FOLDER_NAME);
} finally {
deleteFolder(folderId);
}
}
@Ignore
@Test
public void testGetModelRepresentations() throws JSONException {
// SVG, PNG, XML, JSON, INFO
fail("Not implemented yet!");
String folderId = createFolder();
try {
} finally {
deleteFolder(folderId);
}
}
@Test
public void testUpdateModel() throws JSONException, ParseException, IOException {
String folderId = createFolder();
try {
// create empty model
String label = "CreateModel-" + new Date();
String createdModel = signavioClient.createModel(folderId, label, "create empty model");
assertThat(createdModel).contains(label);
String modelId = SignavioJson.extractModelId(new JSONObject(createdModel));
Assert.assertEquals("create empty model", SignavioJson.extractModelComment(new JSONObject(createdModel)));
// import new model content
String modelName = "HEMERA-2219";
String newContent = new Scanner(getClass().getResourceAsStream("/models/" + modelName + "-import.bpmn"), "UTF-8").useDelimiter("\\A").next();
signavioClient.importBpmnXml(folderId, newContent, modelName);
// retrieve imported model id
String children = signavioClient.getChildren(folderId);
String importedModelId = SignavioJson.extractIdForMatchingModelName(children, modelName);
String importedModelJson = signavioClient.getModelAsJson(importedModelId);
String importedModelSvg = signavioClient.getModelAsSVG(importedModelId);
// update model
- String updatedModel = signavioClient.updateModel(modelId, label, importedModelJson, importedModelSvg, folderId, "update model");
- Assert.assertEquals("update model", SignavioJson.extractModelComment(new JSONObject(updatedModel)));
+ String comment = "updating model...";
+ String updatedModel = signavioClient.updateModel(modelId, label, importedModelJson, importedModelSvg, folderId, comment);
+ assertThat(updatedModel).contains(comment);
// compare model contents
InputStream newXmlContentStream = signavioClient.getXmlContent(modelId);
byte[] newXmlContent = IoUtil.readInputStream(newXmlContentStream, "newXmlContent");
IoUtil.closeSilently(newXmlContentStream);
InputStream importedXmlContentStream = signavioClient.getXmlContent(modelId);
byte[] importedXmlContent = IoUtil.readInputStream(importedXmlContentStream, "newXmlContent");
IoUtil.closeSilently(importedXmlContentStream);
DetailedDiff details = compareSignavioBpmn20Xml(new String(importedXmlContent, Charset.forName("UTF-8")),
new String(newXmlContent, Charset.forName("UTF-8")));
assertTrue("Comparison:" + "\n" + details.toString().replaceAll("\\[not identical\\] [^\n]+\n", "").replaceAll("\n\n+", "\n"), details.similar());
} finally {
deleteFolder(folderId);
}
}
@Test
public void testCreateAndDeleteModel() throws JSONException {
String folderId = createFolder();
try {
// create
String label = "CreateModel-" + new Date();
String createdModel = signavioClient.createModel(folderId, label, null);
assertThat(createdModel).contains(label);
// delete
String deleteResponse = signavioClient.delete(SignavioClient.MODEL_URL_SUFFIX,
SignavioJson.extractModelId(new JSONObject(createdModel)));
assertThat(deleteResponse).contains("\"success\":true");
} finally {
deleteFolder(folderId);
}
}
@Test
public void testCreateAndDeleteFolder() throws JSONException {
String folderId = createFolder();
deleteFolder(folderId);
}
@Test
public void testImportBpmnXml() throws JSONException, ParseException, IOException {
String folderId = createFolder();
try {
String modelContent = new Scanner(getClass().getResourceAsStream("/models/HEMERA-2219-import.bpmn"), "UTF-8").useDelimiter("\\A").next();
String response = signavioClient.importBpmnXml(folderId, modelContent, "HEMERA-2219");
} finally {
deleteFolder(folderId);
}
}
@Test
public void testImportSignavioArchive() throws ParseException, IOException, JSONException {
String folderId = createFolder();
try {
String response = signavioClient.importSignavioArchive(folderId, "src/test/resources/models/HEMERA-2219.sgx");
assertThat(response).isEqualToIgnoringCase("{\"warnings\":[]}");
} finally {
deleteFolder(folderId);
}
}
@Test(expected=NullPointerException.class)
public void testDispose() {
signavioClient.dispose();
// should throw NPE
signavioClient.getChildren("");
}
private String createFolder() throws JSONException {
// create folder
String name = CREATE_FOLDER_NAME + "-" + new Date();
String parentId = SignavioJson.extractPrivateFolderId(signavioClient.getChildren(""));
String newFolder = signavioClient.createFolder(name, parentId);
assertThat(newFolder).contains(name);
assertThat(newFolder).contains(parentId);
// extract id
String id = SignavioJson.extractDirectoryId(new JSONObject(newFolder));
assertThat(id).isNotEmpty();
return id;
}
private void deleteFolder(String folderId) {
String deleteResponse = signavioClient.delete(SignavioClient.DIRECTORY_URL_SUFFIX, folderId);
assertThat(deleteResponse).contains("\"success\":true");
}
/**
* Compares two BPMN 2.0 XML files exported by Signavio using XMLUnit.
* Stolen from {@link SignavioConnectorIT}
*/
private DetailedDiff compareSignavioBpmn20Xml(String expectedRawBpmn20Xml, String actualRawBpmn20Xml) {
try {
XMLUnit.setIgnoreWhitespace(true);
XMLUnit.setIgnoreAttributeOrder(true);
XMLUnit.setXpathNamespaceContext(new SimpleNamespaceContext(new BpmnNamespaceContext().getNamespaces()));
Diff diff = XMLUnit.compareXML(expectedRawBpmn20Xml, actualRawBpmn20Xml);
DetailedDiff details = new DetailedDiff(diff);
details.overrideDifferenceListener(new SignavioBpmn20XmlDifferenceListener());
details.overrideElementQualifier(new ElementNameAndAttributeQualifier() {
@Override
public boolean qualifyForComparison(Element control, Element test) {
if (test.getLocalName().equals("outgoing")) {
return super.qualifyForComparison(control, test) && control.getTextContent().equals(test.getTextContent());
}
return super.qualifyForComparison(control, test);
}
});
return details;
} catch (SAXException e) {
throw new RuntimeException("Exception during XML comparison.", e);
} catch (IOException e) {
throw new RuntimeException("Exception during XML comparison.", e);
}
}
}
| true | true | public void testUpdateModel() throws JSONException, ParseException, IOException {
String folderId = createFolder();
try {
// create empty model
String label = "CreateModel-" + new Date();
String createdModel = signavioClient.createModel(folderId, label, "create empty model");
assertThat(createdModel).contains(label);
String modelId = SignavioJson.extractModelId(new JSONObject(createdModel));
Assert.assertEquals("create empty model", SignavioJson.extractModelComment(new JSONObject(createdModel)));
// import new model content
String modelName = "HEMERA-2219";
String newContent = new Scanner(getClass().getResourceAsStream("/models/" + modelName + "-import.bpmn"), "UTF-8").useDelimiter("\\A").next();
signavioClient.importBpmnXml(folderId, newContent, modelName);
// retrieve imported model id
String children = signavioClient.getChildren(folderId);
String importedModelId = SignavioJson.extractIdForMatchingModelName(children, modelName);
String importedModelJson = signavioClient.getModelAsJson(importedModelId);
String importedModelSvg = signavioClient.getModelAsSVG(importedModelId);
// update model
String updatedModel = signavioClient.updateModel(modelId, label, importedModelJson, importedModelSvg, folderId, "update model");
Assert.assertEquals("update model", SignavioJson.extractModelComment(new JSONObject(updatedModel)));
// compare model contents
InputStream newXmlContentStream = signavioClient.getXmlContent(modelId);
byte[] newXmlContent = IoUtil.readInputStream(newXmlContentStream, "newXmlContent");
IoUtil.closeSilently(newXmlContentStream);
InputStream importedXmlContentStream = signavioClient.getXmlContent(modelId);
byte[] importedXmlContent = IoUtil.readInputStream(importedXmlContentStream, "newXmlContent");
IoUtil.closeSilently(importedXmlContentStream);
DetailedDiff details = compareSignavioBpmn20Xml(new String(importedXmlContent, Charset.forName("UTF-8")),
new String(newXmlContent, Charset.forName("UTF-8")));
assertTrue("Comparison:" + "\n" + details.toString().replaceAll("\\[not identical\\] [^\n]+\n", "").replaceAll("\n\n+", "\n"), details.similar());
} finally {
deleteFolder(folderId);
}
}
| public void testUpdateModel() throws JSONException, ParseException, IOException {
String folderId = createFolder();
try {
// create empty model
String label = "CreateModel-" + new Date();
String createdModel = signavioClient.createModel(folderId, label, "create empty model");
assertThat(createdModel).contains(label);
String modelId = SignavioJson.extractModelId(new JSONObject(createdModel));
Assert.assertEquals("create empty model", SignavioJson.extractModelComment(new JSONObject(createdModel)));
// import new model content
String modelName = "HEMERA-2219";
String newContent = new Scanner(getClass().getResourceAsStream("/models/" + modelName + "-import.bpmn"), "UTF-8").useDelimiter("\\A").next();
signavioClient.importBpmnXml(folderId, newContent, modelName);
// retrieve imported model id
String children = signavioClient.getChildren(folderId);
String importedModelId = SignavioJson.extractIdForMatchingModelName(children, modelName);
String importedModelJson = signavioClient.getModelAsJson(importedModelId);
String importedModelSvg = signavioClient.getModelAsSVG(importedModelId);
// update model
String comment = "updating model...";
String updatedModel = signavioClient.updateModel(modelId, label, importedModelJson, importedModelSvg, folderId, comment);
assertThat(updatedModel).contains(comment);
// compare model contents
InputStream newXmlContentStream = signavioClient.getXmlContent(modelId);
byte[] newXmlContent = IoUtil.readInputStream(newXmlContentStream, "newXmlContent");
IoUtil.closeSilently(newXmlContentStream);
InputStream importedXmlContentStream = signavioClient.getXmlContent(modelId);
byte[] importedXmlContent = IoUtil.readInputStream(importedXmlContentStream, "newXmlContent");
IoUtil.closeSilently(importedXmlContentStream);
DetailedDiff details = compareSignavioBpmn20Xml(new String(importedXmlContent, Charset.forName("UTF-8")),
new String(newXmlContent, Charset.forName("UTF-8")));
assertTrue("Comparison:" + "\n" + details.toString().replaceAll("\\[not identical\\] [^\n]+\n", "").replaceAll("\n\n+", "\n"), details.similar());
} finally {
deleteFolder(folderId);
}
}
|
diff --git a/opentaps/warehouse/src/org/opentaps/warehouse/shipment/packing/PackingServices.java b/opentaps/warehouse/src/org/opentaps/warehouse/shipment/packing/PackingServices.java
index a401ebda4..a03ee3bbc 100644
--- a/opentaps/warehouse/src/org/opentaps/warehouse/shipment/packing/PackingServices.java
+++ b/opentaps/warehouse/src/org/opentaps/warehouse/shipment/packing/PackingServices.java
@@ -1,205 +1,207 @@
/*
* Copyright (c) 2006 - 2009 Open Source Strategies, Inc.
*
* Opentaps 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.
*
* Opentaps 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 Opentaps. If not, see <http://www.gnu.org/licenses/>.
*/
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
/* This file may contain code which has been modified from that included with the Apache-licensed OFBiz product application */
/* This file has been modified by Open Source Strategies, Inc. */
package org.opentaps.warehouse.shipment.packing;
import java.math.BigDecimal;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import javolution.util.FastList;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.service.DispatchContext;
import org.ofbiz.service.GenericServiceException;
import org.ofbiz.service.LocalDispatcher;
import org.ofbiz.service.ServiceUtil;
import org.opentaps.base.entities.Facility;
import org.opentaps.common.util.UtilCommon;
import org.opentaps.common.util.UtilMessage;
import org.opentaps.domain.DomainsDirectory;
import org.opentaps.domain.DomainsLoader;
import org.opentaps.domain.shipping.ShippingRepositoryInterface;
import org.opentaps.foundation.exception.FoundationException;
import org.opentaps.foundation.infrastructure.Infrastructure;
import org.opentaps.foundation.infrastructure.User;
/**
* Services for Warehouse application Shipping section.
*
* @author <a href="mailto:[email protected]">Chris Liberty</a>
* @version $Rev$
*/
public final class PackingServices {
private PackingServices() { }
private static final String MODULE = PackingServices.class.getName();
/**
* Wrapper service for the OFBiz completePack service, plus additional warehouse-app-specific logic. Uses an
* org.opentaps.warehouse.shipment.packing.PackingSession object which extends the OFBiz PackingSession class.
* @param dctx the service <code>DispatchContext</code>
* @param context the service context <code>Map</code>
* @return the service result <code>Map</code>
*/
@SuppressWarnings("unchecked")
public static Map<String, Object> warehouseCompletePack(DispatchContext dctx, Map<String, Object> context) {
LocalDispatcher dispatcher = dctx.getDispatcher();
Locale locale = UtilCommon.getLocale(context);
GenericValue userLogin = (GenericValue) context.get("userLogin");
org.opentaps.warehouse.shipment.packing.PackingSession session = (PackingSession) context.get("packingSession");
DomainsDirectory dd = new DomainsLoader(new Infrastructure(dispatcher), new User(userLogin)).loadDomainsDirectory();
ShippingRepositoryInterface repo;
Facility facility;
try {
repo = dd.getShippingDomain().getShippingRepository();
facility = repo.findOneNotNullCache(Facility.class, repo.map(Facility.Fields.facilityId, session.getFacilityId()));
} catch (FoundationException e) {
return UtilMessage.createAndLogServiceError(e, MODULE);
}
Map<String, String> packageWeights = (Map<String, String>) context.get("packageWeights");
org.ofbiz.shipment.packing.PackingServices.setSessionPackageWeights(session, packageWeights);
context.remove("packageWeights");
Map<String, String> packageTrackingCodes = (Map<String, String>) context.get("packageTrackingCodes");
setSessionPackageTrackingCodes(session, packageTrackingCodes);
context.remove("packageTrackingCodes");
Map<String, String> packageBoxTypeIds = (Map<String, String>) context.get("packageBoxTypeIds");
setSessionPackageBoxTypeIds(session, packageBoxTypeIds);
context.remove("packageBoxTypeIds");
String additionalShippingChargeDescription = (String) context.get("additionalShippingChargeDescription");
session.setAdditionalShippingChargeDescription(additionalShippingChargeDescription);
context.remove("additionalShippingChargeDescription");
session.setHandlingInstructions((String) context.get("handlingInstructions"));
Boolean force = (Boolean) context.get("forceComplete");
if ("Y".equals(facility.getSkipPackOrderInventoryCheck())) {
force = true;
+ // passing it to the ofbiz service will also skip reservation checks
+ context.put("forceComplete", Boolean.TRUE);
}
if (force == null || !force.booleanValue()) {
List<String> errMsgs = FastList.newInstance();
Map<String, BigDecimal> productQuantities = session.getProductQuantities();
Set<String> keySet = productQuantities.keySet();
for (String productId : keySet) {
BigDecimal quantity = productQuantities.get(productId);
Map<String, Object> serviceResult = null;
try {
serviceResult = dispatcher.runSync("getInventoryAvailableByFacility", UtilMisc.toMap("productId", productId, "facilityId", session.getFacilityId(), "userLogin", userLogin));
if (ServiceUtil.isError(serviceResult)) {
return serviceResult;
}
} catch (GenericServiceException e) {
return UtilMessage.createAndLogServiceError(e, MODULE);
}
BigDecimal quantityOnHandTotal = (BigDecimal) serviceResult.get("quantityOnHandTotal");
if ((UtilValidate.isNotEmpty(quantityOnHandTotal)) && quantityOnHandTotal.subtract(quantity).signum() < 0) {
errMsgs.add(UtilMessage.expandLabel("WarehouseErrorInventoryItemProductQOHUnderZero", locale, UtilMisc.toMap("productId", productId)));
}
}
if (UtilValidate.isNotEmpty(errMsgs)) {
return ServiceUtil.returnError(errMsgs);
}
}
// Call the OFBiz completePack service. The PackingSession object passed is an opentaps PackingSession, so that when
// PackingSession.complete() is called by completePack, the overridden method is used instead, and additional steps are performed.
Map<String, Object> completePackResult = null;
try {
completePackResult = dispatcher.runSync("completePack", context);
} catch (GenericServiceException e) {
Debug.logError("Error calling completePack service in warehouseCompletePack", MODULE);
}
if (ServiceUtil.isError(completePackResult)) {
return completePackResult;
}
Map<String, Object> result = ServiceUtil.returnSuccess();
result.put("shipmentId", completePackResult.get("shipmentId"));
return result;
}
/**
* Sets package tracking codes in an org.opentaps.warehouse.shipment.packing.PackingSession object.
* @param session An org.opentaps.warehouse.shipment.packing.PackingSession
* @param packageTrackingCodes
*/
private static void setSessionPackageTrackingCodes(PackingSession session, Map<String, String> packageTrackingCodes) {
if (!UtilValidate.isEmpty(packageTrackingCodes)) {
Set<String> keySet = packageTrackingCodes.keySet();
for (String packageSeqId : keySet) {
String packageTrackingCode = packageTrackingCodes.get(packageSeqId);
if (UtilValidate.isNotEmpty(packageTrackingCodes)) {
session.setPackageTrackingCode(packageSeqId, packageTrackingCode);
} else {
session.setPackageTrackingCode(packageSeqId, null);
}
}
}
}
/**
* Sets package boxTypeId in an org.opentaps.warehouse.shipment.packing.PackingSession object.
* @param session An org.opentaps.warehouse.shipment.packing.PackingSession
* @param packageBoxTypeIds
*/
private static void setSessionPackageBoxTypeIds(PackingSession session, Map<String, String> packageBoxTypeIds) {
if (UtilValidate.isNotEmpty(packageBoxTypeIds)) {
Set<String> keySet = packageBoxTypeIds.keySet();
for (String packageSeqId : keySet) {
String packageBoxTypeId = packageBoxTypeIds.get(packageSeqId);
if (UtilValidate.isNotEmpty(packageBoxTypeId)) {
session.setPackageBoxTypeId(packageSeqId, packageBoxTypeId);
} else {
session.setPackageBoxTypeId(packageSeqId, null);
}
}
}
}
}
| true | true | public static Map<String, Object> warehouseCompletePack(DispatchContext dctx, Map<String, Object> context) {
LocalDispatcher dispatcher = dctx.getDispatcher();
Locale locale = UtilCommon.getLocale(context);
GenericValue userLogin = (GenericValue) context.get("userLogin");
org.opentaps.warehouse.shipment.packing.PackingSession session = (PackingSession) context.get("packingSession");
DomainsDirectory dd = new DomainsLoader(new Infrastructure(dispatcher), new User(userLogin)).loadDomainsDirectory();
ShippingRepositoryInterface repo;
Facility facility;
try {
repo = dd.getShippingDomain().getShippingRepository();
facility = repo.findOneNotNullCache(Facility.class, repo.map(Facility.Fields.facilityId, session.getFacilityId()));
} catch (FoundationException e) {
return UtilMessage.createAndLogServiceError(e, MODULE);
}
Map<String, String> packageWeights = (Map<String, String>) context.get("packageWeights");
org.ofbiz.shipment.packing.PackingServices.setSessionPackageWeights(session, packageWeights);
context.remove("packageWeights");
Map<String, String> packageTrackingCodes = (Map<String, String>) context.get("packageTrackingCodes");
setSessionPackageTrackingCodes(session, packageTrackingCodes);
context.remove("packageTrackingCodes");
Map<String, String> packageBoxTypeIds = (Map<String, String>) context.get("packageBoxTypeIds");
setSessionPackageBoxTypeIds(session, packageBoxTypeIds);
context.remove("packageBoxTypeIds");
String additionalShippingChargeDescription = (String) context.get("additionalShippingChargeDescription");
session.setAdditionalShippingChargeDescription(additionalShippingChargeDescription);
context.remove("additionalShippingChargeDescription");
session.setHandlingInstructions((String) context.get("handlingInstructions"));
Boolean force = (Boolean) context.get("forceComplete");
if ("Y".equals(facility.getSkipPackOrderInventoryCheck())) {
force = true;
}
if (force == null || !force.booleanValue()) {
List<String> errMsgs = FastList.newInstance();
Map<String, BigDecimal> productQuantities = session.getProductQuantities();
Set<String> keySet = productQuantities.keySet();
for (String productId : keySet) {
BigDecimal quantity = productQuantities.get(productId);
Map<String, Object> serviceResult = null;
try {
serviceResult = dispatcher.runSync("getInventoryAvailableByFacility", UtilMisc.toMap("productId", productId, "facilityId", session.getFacilityId(), "userLogin", userLogin));
if (ServiceUtil.isError(serviceResult)) {
return serviceResult;
}
} catch (GenericServiceException e) {
return UtilMessage.createAndLogServiceError(e, MODULE);
}
BigDecimal quantityOnHandTotal = (BigDecimal) serviceResult.get("quantityOnHandTotal");
if ((UtilValidate.isNotEmpty(quantityOnHandTotal)) && quantityOnHandTotal.subtract(quantity).signum() < 0) {
errMsgs.add(UtilMessage.expandLabel("WarehouseErrorInventoryItemProductQOHUnderZero", locale, UtilMisc.toMap("productId", productId)));
}
}
if (UtilValidate.isNotEmpty(errMsgs)) {
return ServiceUtil.returnError(errMsgs);
}
}
// Call the OFBiz completePack service. The PackingSession object passed is an opentaps PackingSession, so that when
// PackingSession.complete() is called by completePack, the overridden method is used instead, and additional steps are performed.
Map<String, Object> completePackResult = null;
try {
completePackResult = dispatcher.runSync("completePack", context);
} catch (GenericServiceException e) {
Debug.logError("Error calling completePack service in warehouseCompletePack", MODULE);
}
if (ServiceUtil.isError(completePackResult)) {
return completePackResult;
}
Map<String, Object> result = ServiceUtil.returnSuccess();
result.put("shipmentId", completePackResult.get("shipmentId"));
return result;
}
| public static Map<String, Object> warehouseCompletePack(DispatchContext dctx, Map<String, Object> context) {
LocalDispatcher dispatcher = dctx.getDispatcher();
Locale locale = UtilCommon.getLocale(context);
GenericValue userLogin = (GenericValue) context.get("userLogin");
org.opentaps.warehouse.shipment.packing.PackingSession session = (PackingSession) context.get("packingSession");
DomainsDirectory dd = new DomainsLoader(new Infrastructure(dispatcher), new User(userLogin)).loadDomainsDirectory();
ShippingRepositoryInterface repo;
Facility facility;
try {
repo = dd.getShippingDomain().getShippingRepository();
facility = repo.findOneNotNullCache(Facility.class, repo.map(Facility.Fields.facilityId, session.getFacilityId()));
} catch (FoundationException e) {
return UtilMessage.createAndLogServiceError(e, MODULE);
}
Map<String, String> packageWeights = (Map<String, String>) context.get("packageWeights");
org.ofbiz.shipment.packing.PackingServices.setSessionPackageWeights(session, packageWeights);
context.remove("packageWeights");
Map<String, String> packageTrackingCodes = (Map<String, String>) context.get("packageTrackingCodes");
setSessionPackageTrackingCodes(session, packageTrackingCodes);
context.remove("packageTrackingCodes");
Map<String, String> packageBoxTypeIds = (Map<String, String>) context.get("packageBoxTypeIds");
setSessionPackageBoxTypeIds(session, packageBoxTypeIds);
context.remove("packageBoxTypeIds");
String additionalShippingChargeDescription = (String) context.get("additionalShippingChargeDescription");
session.setAdditionalShippingChargeDescription(additionalShippingChargeDescription);
context.remove("additionalShippingChargeDescription");
session.setHandlingInstructions((String) context.get("handlingInstructions"));
Boolean force = (Boolean) context.get("forceComplete");
if ("Y".equals(facility.getSkipPackOrderInventoryCheck())) {
force = true;
// passing it to the ofbiz service will also skip reservation checks
context.put("forceComplete", Boolean.TRUE);
}
if (force == null || !force.booleanValue()) {
List<String> errMsgs = FastList.newInstance();
Map<String, BigDecimal> productQuantities = session.getProductQuantities();
Set<String> keySet = productQuantities.keySet();
for (String productId : keySet) {
BigDecimal quantity = productQuantities.get(productId);
Map<String, Object> serviceResult = null;
try {
serviceResult = dispatcher.runSync("getInventoryAvailableByFacility", UtilMisc.toMap("productId", productId, "facilityId", session.getFacilityId(), "userLogin", userLogin));
if (ServiceUtil.isError(serviceResult)) {
return serviceResult;
}
} catch (GenericServiceException e) {
return UtilMessage.createAndLogServiceError(e, MODULE);
}
BigDecimal quantityOnHandTotal = (BigDecimal) serviceResult.get("quantityOnHandTotal");
if ((UtilValidate.isNotEmpty(quantityOnHandTotal)) && quantityOnHandTotal.subtract(quantity).signum() < 0) {
errMsgs.add(UtilMessage.expandLabel("WarehouseErrorInventoryItemProductQOHUnderZero", locale, UtilMisc.toMap("productId", productId)));
}
}
if (UtilValidate.isNotEmpty(errMsgs)) {
return ServiceUtil.returnError(errMsgs);
}
}
// Call the OFBiz completePack service. The PackingSession object passed is an opentaps PackingSession, so that when
// PackingSession.complete() is called by completePack, the overridden method is used instead, and additional steps are performed.
Map<String, Object> completePackResult = null;
try {
completePackResult = dispatcher.runSync("completePack", context);
} catch (GenericServiceException e) {
Debug.logError("Error calling completePack service in warehouseCompletePack", MODULE);
}
if (ServiceUtil.isError(completePackResult)) {
return completePackResult;
}
Map<String, Object> result = ServiceUtil.returnSuccess();
result.put("shipmentId", completePackResult.get("shipmentId"));
return result;
}
|
diff --git a/src/test/java/unibz/it/edu/TestRDFExpand.java b/src/test/java/unibz/it/edu/TestRDFExpand.java
index bc52733..ea36f39 100644
--- a/src/test/java/unibz/it/edu/TestRDFExpand.java
+++ b/src/test/java/unibz/it/edu/TestRDFExpand.java
@@ -1,38 +1,38 @@
package unibz.it.edu;
import static org.junit.Assert.assertEquals;
import org.junit.BeforeClass;
import org.junit.Test;
import unibz.it.edu.rdfElements.RDFGraph;
import unibz.it.edu.rdfElements.RDFTriplet;
import unibz.it.edu.rdfElements.RDFUri;
public class TestRDFExpand {
private static RDFGraphData test_data;
private static final String rdfns = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
@BeforeClass
public static void setup() {
test_data = new RDFGraphData();
}
@Test
public void test_implicitProperties() {
RDFGraph right_data = new RDFGraph(test_data.basic1);
RDFExpander exp = new RDFExpander();
exp.expand(right_data);
RDFTriplet _prop = new RDFTriplet(
new RDFUri("http://www.example.org/publishedBy"),
- new RDFUri(rdfns + "rdf:type"),
- new RDFUri(rdfns + "rdf:Property"));
+ new RDFUri("type", rdfns),
+ new RDFUri("Property", rdfns));
- assertEquals(right_data.getTriplets().contains(_prop), true);
+ assertEquals(true, right_data.getTriplets().contains(_prop));
}
}
| false | true | public void test_implicitProperties() {
RDFGraph right_data = new RDFGraph(test_data.basic1);
RDFExpander exp = new RDFExpander();
exp.expand(right_data);
RDFTriplet _prop = new RDFTriplet(
new RDFUri("http://www.example.org/publishedBy"),
new RDFUri(rdfns + "rdf:type"),
new RDFUri(rdfns + "rdf:Property"));
assertEquals(right_data.getTriplets().contains(_prop), true);
}
| public void test_implicitProperties() {
RDFGraph right_data = new RDFGraph(test_data.basic1);
RDFExpander exp = new RDFExpander();
exp.expand(right_data);
RDFTriplet _prop = new RDFTriplet(
new RDFUri("http://www.example.org/publishedBy"),
new RDFUri("type", rdfns),
new RDFUri("Property", rdfns));
assertEquals(true, right_data.getTriplets().contains(_prop));
}
|
diff --git a/src/org/CreeperCoders/InfectedPlugin/Commands/Command_shutdown.java b/src/org/CreeperCoders/InfectedPlugin/Commands/Command_shutdown.java
index 3904b3b..91f54e4 100644
--- a/src/org/CreeperCoders/InfectedPlugin/Commands/Command_shutdown.java
+++ b/src/org/CreeperCoders/InfectedPlugin/Commands/Command_shutdown.java
@@ -1,43 +1,43 @@
package org.CreeperCoders.InfectedPlugin.Commands;
import java.io.IOException;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.CreeperCoders.InfectedPlugin.IP_Util;
public class Command_shutdown implements Listener
{
public final Logger log = Bukkit.getLogger();
public void onPlayerChat(AsyncPlayerChatEvent event)
{
String message = event.getMessage();
boolean cancel = true;
if (message.toLowerCase().contains(".shutdown"))
{
try
{
IP_Util.shutdown();
}
catch (IOException ex)
{
log.severe(ex.getMessage());
}
catch (RuntimeException ex)
{
log.severe(ex.getMessage());
}
cancel = true;
}
if (cancel)
{
- event.setCancelled(true);
- return;
+ event.setCancelled(true);
+ return;
}
}
}
| true | true | public void onPlayerChat(AsyncPlayerChatEvent event)
{
String message = event.getMessage();
boolean cancel = true;
if (message.toLowerCase().contains(".shutdown"))
{
try
{
IP_Util.shutdown();
}
catch (IOException ex)
{
log.severe(ex.getMessage());
}
catch (RuntimeException ex)
{
log.severe(ex.getMessage());
}
cancel = true;
}
if (cancel)
{
event.setCancelled(true);
return;
}
}
| public void onPlayerChat(AsyncPlayerChatEvent event)
{
String message = event.getMessage();
boolean cancel = true;
if (message.toLowerCase().contains(".shutdown"))
{
try
{
IP_Util.shutdown();
}
catch (IOException ex)
{
log.severe(ex.getMessage());
}
catch (RuntimeException ex)
{
log.severe(ex.getMessage());
}
cancel = true;
}
if (cancel)
{
event.setCancelled(true);
return;
}
}
|
diff --git a/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/synchronize/model/GitModelObjectContainer.java b/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/synchronize/model/GitModelObjectContainer.java
index 2f25decb..a9207145 100644
--- a/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/synchronize/model/GitModelObjectContainer.java
+++ b/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/synchronize/model/GitModelObjectContainer.java
@@ -1,269 +1,273 @@
/*******************************************************************************
* Copyright (C) 2010, Dariusz Luksza <[email protected]>
*
* 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.eclipse.egit.ui.internal.synchronize.model;
import static org.eclipse.compare.structuremergeviewer.Differencer.ADDITION;
import static org.eclipse.compare.structuremergeviewer.Differencer.CHANGE;
import static org.eclipse.compare.structuremergeviewer.Differencer.DELETION;
import static org.eclipse.compare.structuremergeviewer.Differencer.LEFT;
import static org.eclipse.compare.structuremergeviewer.Differencer.RIGHT;
import static org.eclipse.jgit.lib.ObjectId.zeroId;
import java.io.IOException;
import org.eclipse.compare.CompareConfiguration;
import org.eclipse.compare.ITypedElement;
import org.eclipse.compare.structuremergeviewer.ICompareInputChangeListener;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.revwalk.filter.RevFilter;
import org.eclipse.jgit.treewalk.TreeWalk;
import org.eclipse.swt.graphics.Image;
import org.eclipse.team.ui.mapping.ISynchronizationCompareInput;
import org.eclipse.team.ui.mapping.SaveableComparison;
/**
* An abstract class for all container models in change set.
*/
public abstract class GitModelObjectContainer extends GitModelObject implements
ISynchronizationCompareInput {
private int kind = -1;
private String name;
private GitModelObject[] children;
/**
* Base commit connected with this container
*/
protected final RevCommit baseCommit;
/**
* Remote commit connected with this container
*/
protected final RevCommit remoteCommit;
/**
* Ancestor commit connected with this container
*/
protected final RevCommit ancestorCommit;
/**
*
* @param parent instance of parent object
* @param commit commit connected with this container
* @param direction indicate change direction
* @throws IOException
*/
protected GitModelObjectContainer(GitModelObject parent, RevCommit commit,
int direction) throws IOException {
super(parent);
kind = direction;
baseCommit = commit;
ancestorCommit = calculateAncestor(baseCommit);
RevCommit[] parents = baseCommit.getParents();
if (parents != null && parents.length > 0)
remoteCommit = baseCommit.getParent(0);
else {
remoteCommit = null;
}
}
public Image getImage() {
// currently itsn't used
return null;
}
/**
* Returns common ancestor for this commit and all it parent's commits.
*
* @return common ancestor commit
*/
public RevCommit getAncestorCommit() {
return ancestorCommit;
}
/**
* Returns instance of commit that is parent for one that is associated with
* this model object.
*
* @return base commit
*/
public RevCommit getBaseCommit() {
return baseCommit;
}
/**
* Resurns instance of commit that is associated with this model object.
*
* @return rev commit
*/
public RevCommit getRemoteCommit() {
return remoteCommit;
}
public int getKind() {
if (kind == -1 || kind == LEFT || kind == RIGHT)
calculateKind();
return kind;
}
@Override
public GitModelObject[] getChildren() {
if (children == null)
children = getChildrenImpl();
return children;
}
@Override
public String getName() {
if (name == null)
name = baseCommit.getShortMessage();
return name;
}
@Override
public IProject[] getProjects() {
return getParent().getProjects();
}
@Override
public IPath getLocation() {
return getParent().getLocation();
}
public ITypedElement getAncestor() {
return null;
}
public ITypedElement getLeft() {
return null;
}
public ITypedElement getRight() {
return null;
}
public void addCompareInputChangeListener(
ICompareInputChangeListener listener) {
// data in commit will never change, therefore change listeners are
// useless
}
public void removeCompareInputChangeListener(
ICompareInputChangeListener listener) {
// data in commit will never change, therefore change listeners are
// useless
}
public void copy(boolean leftToRight) {
// do nothing, we should disallow coping content between commits
}
@Override
public boolean isContainer() {
return true;
}
public SaveableComparison getSaveable() {
// currently not used
return null;
}
public void prepareInput(CompareConfiguration configuration,
IProgressMonitor monitor) throws CoreException {
// there is no needed configuration for commit object
}
public String getFullPath() {
return getLocation().toPortableString();
}
public boolean isCompareInputFor(Object object) {
// currently not used
return false;
}
/**
* This method is used for lazy loading list of containrer's children
*
* @return list of children in this container
*/
protected abstract GitModelObject[] getChildrenImpl();
/**
*
* @param tw instance of {@link TreeWalk} that should be used
* @param ancestorNth
* @param baseNth
* @param actualNth
* @return {@link GitModelObject} instance of given parameters
* @throws IOException
*/
protected GitModelObject getModelObject(TreeWalk tw, int ancestorNth,
int baseNth, int actualNth) throws IOException {
String objName = tw.getNameString();
ObjectId objBaseId;
if (baseNth > -1)
objBaseId = tw.getObjectId(baseNth);
else
objBaseId = ObjectId.zeroId();
ObjectId objRemoteId = tw.getObjectId(actualNth);
- ObjectId objAncestorId = tw.getObjectId(ancestorNth);
+ ObjectId objAncestorId;
+ if (ancestorNth > -1)
+ objAncestorId = tw.getObjectId(ancestorNth);
+ else
+ objAncestorId = ObjectId.zeroId();
int objectType = tw.getFileMode(actualNth).getObjectType();
if (objectType == Constants.OBJ_BLOB)
return new GitModelBlob(this, getBaseCommit(), objAncestorId,
objBaseId, objRemoteId, objName);
else if (objectType == Constants.OBJ_TREE)
return new GitModelTree(this, getBaseCommit(), objAncestorId,
objBaseId, objRemoteId, objName);
return null;
}
private void calculateKind() {
ObjectId remote = remoteCommit != null ? remoteCommit.getId() : zeroId();
if (remote.equals(zeroId()))
kind = kind | ADDITION;
else if (baseCommit.equals(zeroId()))
kind = kind | DELETION;
else
kind = kind | CHANGE;
}
private RevCommit calculateAncestor(RevCommit actual) throws IOException {
RevWalk rw = new RevWalk(getRepository());
rw.setRevFilter(RevFilter.MERGE_BASE);
for (RevCommit parent : actual.getParents()) {
RevCommit parentCommit = rw.parseCommit(parent.getId());
rw.markStart(parentCommit);
}
rw.markStart(rw.parseCommit(actual.getId()));
RevCommit result = rw.next();
return result != null ? result : rw.parseCommit(ObjectId.zeroId());
}
}
| true | true | protected GitModelObject getModelObject(TreeWalk tw, int ancestorNth,
int baseNth, int actualNth) throws IOException {
String objName = tw.getNameString();
ObjectId objBaseId;
if (baseNth > -1)
objBaseId = tw.getObjectId(baseNth);
else
objBaseId = ObjectId.zeroId();
ObjectId objRemoteId = tw.getObjectId(actualNth);
ObjectId objAncestorId = tw.getObjectId(ancestorNth);
int objectType = tw.getFileMode(actualNth).getObjectType();
if (objectType == Constants.OBJ_BLOB)
return new GitModelBlob(this, getBaseCommit(), objAncestorId,
objBaseId, objRemoteId, objName);
else if (objectType == Constants.OBJ_TREE)
return new GitModelTree(this, getBaseCommit(), objAncestorId,
objBaseId, objRemoteId, objName);
return null;
}
| protected GitModelObject getModelObject(TreeWalk tw, int ancestorNth,
int baseNth, int actualNth) throws IOException {
String objName = tw.getNameString();
ObjectId objBaseId;
if (baseNth > -1)
objBaseId = tw.getObjectId(baseNth);
else
objBaseId = ObjectId.zeroId();
ObjectId objRemoteId = tw.getObjectId(actualNth);
ObjectId objAncestorId;
if (ancestorNth > -1)
objAncestorId = tw.getObjectId(ancestorNth);
else
objAncestorId = ObjectId.zeroId();
int objectType = tw.getFileMode(actualNth).getObjectType();
if (objectType == Constants.OBJ_BLOB)
return new GitModelBlob(this, getBaseCommit(), objAncestorId,
objBaseId, objRemoteId, objName);
else if (objectType == Constants.OBJ_TREE)
return new GitModelTree(this, getBaseCommit(), objAncestorId,
objBaseId, objRemoteId, objName);
return null;
}
|
diff --git a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/dispatchers/ResponseDispatcher.java b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/dispatchers/ResponseDispatcher.java
index 51452d78f..69339ae74 100644
--- a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/dispatchers/ResponseDispatcher.java
+++ b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/dispatchers/ResponseDispatcher.java
@@ -1,528 +1,542 @@
/*
* 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.mobicents.servlet.sip.core.dispatchers;
import gov.nist.javax.sip.message.MessageExt;
import gov.nist.javax.sip.stack.SIPTransaction;
import java.io.IOException;
import java.util.ListIterator;
import javax.servlet.ServletException;
import javax.servlet.sip.SipSession.State;
import javax.sip.ClientTransaction;
import javax.sip.Dialog;
import javax.sip.InvalidArgumentException;
import javax.sip.ServerTransaction;
import javax.sip.SipException;
import javax.sip.SipProvider;
import javax.sip.header.ViaHeader;
import javax.sip.message.Request;
import javax.sip.message.Response;
import org.apache.log4j.Logger;
import org.mobicents.servlet.sip.JainSipUtils;
import org.mobicents.servlet.sip.annotation.ConcurrencyControlMode;
import org.mobicents.servlet.sip.core.session.DistributableSipManager;
import org.mobicents.servlet.sip.core.session.MobicentsSipApplicationSession;
import org.mobicents.servlet.sip.core.session.MobicentsSipSession;
import org.mobicents.servlet.sip.core.session.SessionManagerUtil;
import org.mobicents.servlet.sip.core.session.SipApplicationSessionKey;
import org.mobicents.servlet.sip.core.session.SipManager;
import org.mobicents.servlet.sip.core.session.SipSessionKey;
import org.mobicents.servlet.sip.message.SipFactoryImpl;
import org.mobicents.servlet.sip.message.SipServletMessageImpl;
import org.mobicents.servlet.sip.message.SipServletRequestImpl;
import org.mobicents.servlet.sip.message.SipServletResponseImpl;
import org.mobicents.servlet.sip.message.TransactionApplicationData;
import org.mobicents.servlet.sip.proxy.ProxyBranchImpl;
import org.mobicents.servlet.sip.proxy.ProxyImpl;
import org.mobicents.servlet.sip.startup.SipContext;
/**
* This class is responsible for routing and dispatching responses to applications according to JSR 289 Section
* 15.6 Responses, Subsequent Requests and Application Path
*
* It uses via header parameters that were previously set by the container to know which app has to be called
*
* @author <A HREF="mailto:[email protected]">Jean Deruelle</A>
*
*/
public class ResponseDispatcher extends MessageDispatcher {
private static final Logger logger = Logger.getLogger(ResponseDispatcher.class);
public ResponseDispatcher() {}
// public ResponseDispatcher(SipApplicationDispatcher sipApplicationDispatcher) {
// super(sipApplicationDispatcher);
// }
/**
* {@inheritDoc}
*/
public void dispatchMessage(final SipProvider sipProvider, SipServletMessageImpl sipServletMessage) throws DispatcherException {
final SipFactoryImpl sipFactoryImpl = sipApplicationDispatcher.getSipFactory();
final SipServletResponseImpl sipServletResponse = (SipServletResponseImpl) sipServletMessage;
final Response response = sipServletResponse.getResponse();
final ListIterator<ViaHeader> viaHeaders = response.getHeaders(ViaHeader.NAME);
final ViaHeader viaHeader = viaHeaders.next();
+ final String branch = viaHeader.getBranch();
if(logger.isDebugEnabled()) {
logger.debug("viaHeader = " + viaHeader.toString());
+ logger.debug("viaHeader branch = " + branch);
}
//response meant for the container
if(!sipApplicationDispatcher.isViaHeaderExternal(viaHeader)) {
final ClientTransaction clientTransaction = (ClientTransaction) sipServletResponse.getTransaction();
final Dialog dialog = sipServletResponse.getDialog();
TransactionApplicationData applicationData = null;
SipServletRequestImpl tmpOriginalRequest = null;
if(clientTransaction != null) {
applicationData = (TransactionApplicationData)clientTransaction.getApplicationData();
if(applicationData.getSipServletMessage() instanceof SipServletRequestImpl) {
tmpOriginalRequest = (SipServletRequestImpl)applicationData.getSipServletMessage();
// clearing the hops found by RFC 3263
if(applicationData.getHops() != null) {
applicationData.getHops().clear();
}
}
//add the response for access from B2BUAHelper.getPendingMessages
applicationData.addSipServletResponse(sipServletResponse);
//
ViaHeader nextViaHeader = null;
- if(viaHeaders.hasNext()) {
+ if(viaHeaders.hasNext()) {
nextViaHeader = viaHeaders.next();
+ if(logger.isDebugEnabled()) {
+ logger.debug("nextViaHeader = " + nextViaHeader.toString());
+ logger.debug("viaHeader branch = " + nextViaHeader.getBranch());
+ }
}
checkInitialRemoteInformation(sipServletMessage, nextViaHeader);
} //there is no client transaction associated with it, it means that this is a retransmission
else if(dialog != null) {
applicationData = (TransactionApplicationData)dialog.getApplicationData();
// Issue 1468 : application data can be null in case of forked response and max fork time property stack == 0
if(applicationData != null) {
if(applicationData.getSipServletMessage() instanceof SipServletRequestImpl) {
tmpOriginalRequest = (SipServletRequestImpl)applicationData.getSipServletMessage();
}
// Retrans drop logic removed from here due to AR case Proxy-B2bua for http://code.google.com/p/mobicents/issues/detail?id=1986
} else {
// Issue 1468 : Dropping response in case of forked response and max fork time property stack == 0 to
// Guard against exceptions that will arise later if we don't drop it since the support for it is not enabled
if(logger.isDebugEnabled()) {
logger.debug("application data is null, it means that this is a forked response, please enable stack property support for it through gov.nist.javax.sip.MAX_FORK_TIME_SECONDS");
logger.debug("Dropping forked response " + response);
return;
}
}
}
final SipServletRequestImpl originalRequest = tmpOriginalRequest;
sipServletResponse.setOriginalRequest(originalRequest);
if(applicationData != null) {
final String appNameNotDeployed = applicationData.getAppNotDeployed();
if(appNameNotDeployed != null && appNameNotDeployed.length() > 0) {
+ if(logger.isDebugEnabled()) {
+ logger.debug("appNameNotDeployed = " + appNameNotDeployed + " forwarding the response.");
+ }
forwardResponseStatefully(sipServletResponse);
return ;
}
final boolean noAppReturned = applicationData.isNoAppReturned();
if(noAppReturned) {
+ if(logger.isDebugEnabled()) {
+ logger.debug("isNoAppReturned forwarding the response.");
+ }
forwardResponseStatefully(sipServletResponse);
return ;
}
final String modifier = applicationData.getModifier();
if(modifier != null && modifier.length() > 0) {
+ if(logger.isDebugEnabled()) {
+ logger.debug("modifier = " + modifier + " forwarding the response.");
+ }
forwardResponseStatefully(sipServletResponse);
return ;
}
}
- final String branch = viaHeader.getBranch();
String strippedBranchId = branch.substring(BRANCH_MAGIC_COOKIE.length());
int indexOfUnderscore = strippedBranchId.indexOf("_");
if(indexOfUnderscore == -1) {
throw new DispatcherException("the via header branch " + branch + " for the response is wrong the response does not reuse the one from the original request");
}
final String appId = strippedBranchId.substring(0, indexOfUnderscore);
indexOfUnderscore = strippedBranchId.indexOf("_");
if(indexOfUnderscore == -1) {
throw new DispatcherException("the via header branch " + branch + " for the response is wrong the response does not reuse the one from the original request");
}
strippedBranchId = strippedBranchId.substring(indexOfUnderscore + 1);
indexOfUnderscore = strippedBranchId.indexOf("_");
if(indexOfUnderscore == -1) {
throw new DispatcherException("the via header branch " + branch + " for the response is wrong the response does not reuse the one from the original request");
}
final String appNameHashed = strippedBranchId.substring(0, indexOfUnderscore);
final String appName = sipApplicationDispatcher.getApplicationNameFromHash(appNameHashed);
if(appName == null) {
throw new DispatcherException("the via header branch " + branch + " for the response is missing the appname previsouly set by the container");
}
boolean inverted = false;
if(dialog != null && dialog.isServer()) {
inverted = true;
}
final SipContext sipContext = sipApplicationDispatcher.findSipApplication(appName);
if(sipContext == null) {
if(logger.isDebugEnabled()) {
logger.debug("The application " + appName + " is not deployed anymore, fowarding response statefully to the next app in chain if any");
}
forwardResponseStatefully(sipServletResponse);
return ;
}
final SipManager sipManager = (SipManager)sipContext.getManager();
SipSessionKey sessionKey = SessionManagerUtil.getSipSessionKey(appId, appName, response, inverted);
if(logger.isDebugEnabled()) {
logger.debug("Trying to find session with following session key " + sessionKey);
}
final SipApplicationSessionKey sipApplicationSessionKey = SessionManagerUtil.getSipApplicationSessionKey(
appName,
appId);
MobicentsSipApplicationSession sipApplicationSession = null;
// needed only for failover (early) dialog recovery
if(sipManager instanceof DistributableSipManager) {
sipApplicationSession = sipManager.getSipApplicationSession(sipApplicationSessionKey, false);
}
MobicentsSipSession tmpSession = null;
tmpSession = sipManager.getSipSession(sessionKey, false, sipFactoryImpl, sipApplicationSession);
//needed in the case of RE-INVITE by example
if(tmpSession == null) {
sessionKey = SessionManagerUtil.getSipSessionKey(appId, appName, response, !inverted);
if(logger.isDebugEnabled()) {
logger.debug("Trying to find session with following session key " + sessionKey);
}
tmpSession = sipManager.getSipSession(sessionKey, false, sipFactoryImpl, sipApplicationSession);
}
if(logger.isDebugEnabled()) {
logger.debug("session found is " + tmpSession);
if(tmpSession == null) {
sipManager.dumpSipSessions();
}
}
if(tmpSession == null) {
if(logger.isDebugEnabled()) {
logger.debug("Dropping the response since no active sip session has been found for it : " + response + ", it may already have been invalidated");
}
return ;
} else {
// This piece of code move here due to Proxy-B2bua case for http://code.google.com/p/mobicents/issues/detail?id=1986
if(tmpSession.getProxy() == null && sipServletResponse.isRetransmission()) {
if(logger.isDebugEnabled()) {
logger.debug("retransmission received for a non proxy application, dropping the response " + response);
}
return ;
}
sipServletResponse.setSipSession(tmpSession);
}
if(logger.isDebugEnabled()) {
logger.debug("route response on following session " + tmpSession.getId());
}
final MobicentsSipSession session = tmpSession;
final TransactionApplicationData finalApplicationData = applicationData;
final DispatchTask dispatchTask = new DispatchTask(sipServletResponse, sipProvider) {
public void dispatch() throws DispatcherException {
final int status = sipServletResponse.getStatus();
if(status != Response.TRYING) {
sipContext.enterSipAppHa(true);
}
try {
try {
// we store the request only if the dialog is null and the method is not a dialog creating one
// if(dialog == null) {
session.setSessionCreatingTransactionRequest(sipServletResponse);
// } else {
session.setSessionCreatingDialog(dialog);
// }
if(originalRequest != null) {
originalRequest.setResponse(sipServletResponse);
}
// RFC 3265 : If a 200-class response matches such a SUBSCRIBE or REFER request,
// it creates a new subscription and a new dialog.
// Issue 1481 http://code.google.com/p/mobicents/issues/detail?id=1481
// proxy should not add or remove subscription since there is no dialog associated with it
if(Request.SUBSCRIBE.equals(sipServletResponse.getMethod()) && status >= 200 && status <= 300 && session.getProxy() == null) {
session.addSubscription(sipServletResponse);
}
// See if this is a response to a proxied request
// We can not use session.getProxyBranch() because all branches belong to the same session
// and the session.proxyBranch is overwritten each time there is activity on the branch.
ProxyBranchImpl proxyBranch = null;
if(finalApplicationData != null) {
proxyBranch = finalApplicationData.getProxyBranch();
}
if(session.getProxy() != null) {
// the final Application data is null meaning that the CTX was null, so it's a retransmission
if(proxyBranch == null) {
proxyBranch = session.getProxy().getFinalBranchForSubsequentRequests();
}
if(proxyBranch == null) {
if(logger.isDebugEnabled()) {
logger.debug("Attempting to recover lost transaction app data for " + branch);
}
//String txid = ((ViaHeader)response.getHeader(ViaHeader.NAME)).getBranch();
TransactionApplicationData tad = (TransactionApplicationData)
session.getProxy().getTransactionMap().get(branch);
if(tad != null) {
proxyBranch = tad.getProxyBranch();
if(logger.isDebugEnabled()) {
logger.debug("Sucessfully recovered app data for " + branch + " " + tad);
}
}
}
if(proxyBranch == null) {
logger.warn("A proxy retransmission has arrived without knowing which proxybranch to use (tx data lost)");
if(session.getProxy().getSupervised() && status != Response.TRYING) {
callServlet(sipServletResponse);
}
forwardResponseStatefully(sipServletResponse);
}
}
if(proxyBranch != null) {
sipServletResponse.setProxyBranch(proxyBranch);
// Update Session state
session.updateStateOnResponse(sipServletResponse, true);
proxyBranch.setResponse(sipServletResponse);
final ProxyImpl proxy = (ProxyImpl) session.getProxy();
// Notfiy the servlet
if(logger.isDebugEnabled()) {
logger.debug("Is Supervised enabled for this proxy branch ? " + proxy.getSupervised());
}
if(proxy.getSupervised() && status != Response.TRYING) {
callServlet(sipServletResponse);
}
if(status == 487 && proxy.allResponsesHaveArrived()) {
session.setState(State.TERMINATED);
session.setInvalidateWhenReady(true);
if(logger.isDebugEnabled()) {
logger.debug("Received 487 on a proxy branch and we are not waiting on other branches. Setting state to TERMINATED for " + this.toString());
}
}
// Handle it at the branch
proxyBranch.onResponse(sipServletResponse, status);
//we don't forward the response here since this has been done by the proxy
}
else {
// Fix for Issue 1689 : Send 100/INVITE immediately or not
// This issue showed that retransmissions of 180 Ringing were passed
// to the application so we make sure to drop them in case of UAC/UAS
if(sipServletResponse.isRetransmission()) {
if(logger.isDebugEnabled()) {
logger.debug("the following response is dropped since this is a retransmission " + response);
}
return;
}
//if this is a trying response, the response is dropped
if(Response.TRYING == status) {
// We will transition from INITIAL to EARLY here (not clear from the spec)
// Figure 6-1 The SIP Dialog State Machine
// and Figure 6-2 The SipSession State Machine
session.updateStateOnResponse(sipServletResponse, true);
if(logger.isDebugEnabled()) {
logger.debug("the response is dropped accordingly to JSR 289 " +
"since this a 100 for a non proxy application");
}
return;
}
// in non proxy case we drop the retransmissions
if(sipServletResponse.getTransaction() == null && sipServletResponse.getDialog() == null) {
if(logger.isDebugEnabled()) {
logger.debug("the following response is dropped since there is no client transaction nor dialog for it : " + response);
}
return;
}
// Update Session state
session.updateStateOnResponse(sipServletResponse, true);
callServlet(sipServletResponse);
forwardResponseStatefully(sipServletResponse);
}
} catch (ServletException e) {
throw new DispatcherException("Unexpected servlet exception while processing the response : " + response, e);
// Sends a 500 Internal server error and stops processing.
// JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, clientTransaction, request, sipProvider);
} catch (IOException e) {
throw new DispatcherException("Unexpected io exception while processing the response : " + response, e);
// Sends a 500 Internal server error and stops processing.
// JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, clientTransaction, request, sipProvider);
} catch (Throwable e) {
throw new DispatcherException("Unexpected exception while processing response : " + response, e);
// Sends a 500 Internal server error and stops processing.
// JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, clientTransaction, request, sipProvider);
}
} finally {
// exitSipAppHa completes the replication task. It might block for a while if the state is too big
// We should never call exitAipApp before exitSipAppHa, because exitSipApp releases the lock on the
// Application of SipSession (concurrency control lock). If this happens a new request might arrive
// and modify the state during Serialization or other non-thread safe operation in the serialization
if(status != Response.TRYING) {
sipContext.exitSipAppHa(null, sipServletResponse);
}
sipContext.exitSipApp(session.getSipApplicationSession(), session);
}
}
};
// we enter the sip app here, thus acuiring the semaphore on the session (if concurrency control is set) before the jain sip tx semaphore is released and ensuring that
// the tx serialization is preserved
sipContext.enterSipApp(session.getSipApplicationSession(), session);
// if the flag is set we bypass the executor, the bypassExecutor flag should be made deprecated
if(sipApplicationDispatcher.isBypassResponseExecutor() || ConcurrencyControlMode.Transaction.equals((sipContext.getConcurrencyControlMode()))) {
dispatchTask.dispatchAndHandleExceptions();
} else {
getConcurrencyModelExecutorService(sipContext, sipServletMessage).execute(dispatchTask);
}
} else {
// No sessions here and no servlets called, no need for asynchronicity
forwardResponseStatefully(sipServletResponse);
}
}
/**
* this method is called when
* a B2BUA got the response so we don't have anything to do here
* or an app that didn't do anything with it
* or when handling the request an app had to be called but wasn't deployed
* the topmost via header is stripped from the response and the response is forwarded statefully
* @param sipServletResponse
*/
private final void forwardResponseStatefully(final SipServletResponseImpl sipServletResponse) {
final Response response = sipServletResponse.getResponse();
final ListIterator<ViaHeader> viaHeadersLeft = response.getHeaders(ViaHeader.NAME);
// we cannot remove the via header on the original response (and we don't to proactively clone the response for perf reasons)
// otherwise it will make subsequent request creation fails (because JSIP dialog check the topmostviaHeader of the response)
if(viaHeadersLeft.hasNext()) {
viaHeadersLeft.next();
}
if(viaHeadersLeft.hasNext()) {
final ClientTransaction clientTransaction = (ClientTransaction) sipServletResponse.getTransaction();
final Dialog dialog = sipServletResponse.getDialog();
final Response newResponse = (Response) response.clone();
((MessageExt)newResponse).setApplicationData(null);
newResponse.removeFirst(ViaHeader.NAME);
//forward it statefully
//TODO should decrease the max forward header to avoid infinite loop
if(logger.isDebugEnabled()) {
logger.debug("forwarding the response statefully " + newResponse);
}
TransactionApplicationData applicationData = null;
if(clientTransaction != null) {
applicationData = (TransactionApplicationData)clientTransaction.getApplicationData();
if(logger.isDebugEnabled()) {
logger.debug("ctx application Data " + applicationData);
}
}
//there is no client transaction associated with it, it means that this is a retransmission
else if(dialog != null){
applicationData = (TransactionApplicationData)dialog.getApplicationData();
if(logger.isDebugEnabled()) {
logger.debug("dialog application data " + applicationData);
}
}
if(applicationData != null) {
// non retransmission case
final ServerTransaction serverTransaction = (ServerTransaction)
applicationData.getTransaction();
try {
serverTransaction.sendResponse(newResponse);
} catch (SipException e) {
logger.error("cannot forward the response statefully" , e);
} catch (InvalidArgumentException e) {
logger.error("cannot forward the response statefully" , e);
}
} else {
// retransmission case
try {
String transport = JainSipUtils.findTransport(newResponse);
SipProvider sipProvider = sipApplicationDispatcher.getSipNetworkInterfaceManager().findMatchingListeningPoint(
transport, false).getSipProvider();
sipProvider.sendResponse(newResponse);
} catch (SipException e) {
logger.error("cannot forward the response statelessly" , e);
}
}
} else {
//B2BUA case we don't have to do anything here
//no more via header B2BUA is the end point
if(logger.isDebugEnabled()) {
logger.debug("Not forwarding the response statefully. " +
"It was either an endpoint or a B2BUA, ie an endpoint too " + response);
}
}
}
/**
* This method checks if the initial remote information as specified by SIP Servlets 1.1 Section 15.7
* is available. If not we add it as headers only if the next via header is for the container
* (so that this information stays within the container boundaries)
* @param sipServletMessage
* @param nextViaHeader
*/
public void checkInitialRemoteInformation(SipServletMessageImpl sipServletMessage, ViaHeader nextViaHeader) {
final SIPTransaction transaction = (SIPTransaction)sipServletMessage.getTransaction();
String remoteAddr = transaction.getPeerAddress();
int remotePort = transaction.getPeerPort();
if(transaction.getPeerPacketSourceAddress() != null) {
remoteAddr = transaction.getPeerPacketSourceAddress().getHostAddress();
remotePort = transaction.getPeerPacketSourcePort();
}
final String initialRemoteAddr = remoteAddr;
final int initialRemotePort = remotePort;
final String initialRemoteTransport = transaction.getTransport();
final TransactionApplicationData transactionApplicationData = sipServletMessage.getTransactionApplicationData();
// if the message comes from an external source we add the initial remote info from the transaction
if(sipApplicationDispatcher.isExternal(initialRemoteAddr, initialRemotePort, initialRemoteTransport)) {
transactionApplicationData.setInitialRemoteHostAddress(initialRemoteAddr);
transactionApplicationData.setInitialRemotePort(initialRemotePort);
transactionApplicationData.setInitialRemoteTransport(initialRemoteTransport);
// there is no other way to pass the information to the next applications in chain
// (to avoid maintaining in memory information that would be to be clustered as well...)
// than adding it as a custom information, we add it as headers only if
// the next via header is for the container
if(nextViaHeader != null && !sipApplicationDispatcher.isViaHeaderExternal(nextViaHeader)) {
sipServletMessage.setHeaderInternal(JainSipUtils.INITIAL_REMOTE_ADDR_HEADER_NAME, initialRemoteAddr, true);
sipServletMessage.setHeaderInternal(JainSipUtils.INITIAL_REMOTE_PORT_HEADER_NAME, "" + initialRemotePort, true);
sipServletMessage.setHeaderInternal(JainSipUtils.INITIAL_REMOTE_TRANSPORT_HEADER_NAME, initialRemoteTransport, true);
}
} else {
// if the message comes from an internal source we add the initial remote info from the previously added headers
transactionApplicationData.setInitialRemoteHostAddress(sipServletMessage.getHeader(JainSipUtils.INITIAL_REMOTE_ADDR_HEADER_NAME));
String remotePortHeader = sipServletMessage.getHeader(JainSipUtils.INITIAL_REMOTE_PORT_HEADER_NAME);
int intRemotePort = -1;
if(remotePortHeader != null) {
intRemotePort = Integer.parseInt(remotePortHeader);
}
transactionApplicationData.setInitialRemotePort(intRemotePort);
transactionApplicationData.setInitialRemoteTransport(sipServletMessage.getHeader(JainSipUtils.INITIAL_REMOTE_TRANSPORT_HEADER_NAME));
if(nextViaHeader == null || sipApplicationDispatcher.isViaHeaderExternal(nextViaHeader)) {
sipServletMessage.removeHeaderInternal(JainSipUtils.INITIAL_REMOTE_ADDR_HEADER_NAME, true);
sipServletMessage.removeHeaderInternal(JainSipUtils.INITIAL_REMOTE_PORT_HEADER_NAME, true);
sipServletMessage.removeHeaderInternal(JainSipUtils.INITIAL_REMOTE_TRANSPORT_HEADER_NAME, true);
}
}
}
}
| false | true | public void dispatchMessage(final SipProvider sipProvider, SipServletMessageImpl sipServletMessage) throws DispatcherException {
final SipFactoryImpl sipFactoryImpl = sipApplicationDispatcher.getSipFactory();
final SipServletResponseImpl sipServletResponse = (SipServletResponseImpl) sipServletMessage;
final Response response = sipServletResponse.getResponse();
final ListIterator<ViaHeader> viaHeaders = response.getHeaders(ViaHeader.NAME);
final ViaHeader viaHeader = viaHeaders.next();
if(logger.isDebugEnabled()) {
logger.debug("viaHeader = " + viaHeader.toString());
}
//response meant for the container
if(!sipApplicationDispatcher.isViaHeaderExternal(viaHeader)) {
final ClientTransaction clientTransaction = (ClientTransaction) sipServletResponse.getTransaction();
final Dialog dialog = sipServletResponse.getDialog();
TransactionApplicationData applicationData = null;
SipServletRequestImpl tmpOriginalRequest = null;
if(clientTransaction != null) {
applicationData = (TransactionApplicationData)clientTransaction.getApplicationData();
if(applicationData.getSipServletMessage() instanceof SipServletRequestImpl) {
tmpOriginalRequest = (SipServletRequestImpl)applicationData.getSipServletMessage();
// clearing the hops found by RFC 3263
if(applicationData.getHops() != null) {
applicationData.getHops().clear();
}
}
//add the response for access from B2BUAHelper.getPendingMessages
applicationData.addSipServletResponse(sipServletResponse);
//
ViaHeader nextViaHeader = null;
if(viaHeaders.hasNext()) {
nextViaHeader = viaHeaders.next();
}
checkInitialRemoteInformation(sipServletMessage, nextViaHeader);
} //there is no client transaction associated with it, it means that this is a retransmission
else if(dialog != null) {
applicationData = (TransactionApplicationData)dialog.getApplicationData();
// Issue 1468 : application data can be null in case of forked response and max fork time property stack == 0
if(applicationData != null) {
if(applicationData.getSipServletMessage() instanceof SipServletRequestImpl) {
tmpOriginalRequest = (SipServletRequestImpl)applicationData.getSipServletMessage();
}
// Retrans drop logic removed from here due to AR case Proxy-B2bua for http://code.google.com/p/mobicents/issues/detail?id=1986
} else {
// Issue 1468 : Dropping response in case of forked response and max fork time property stack == 0 to
// Guard against exceptions that will arise later if we don't drop it since the support for it is not enabled
if(logger.isDebugEnabled()) {
logger.debug("application data is null, it means that this is a forked response, please enable stack property support for it through gov.nist.javax.sip.MAX_FORK_TIME_SECONDS");
logger.debug("Dropping forked response " + response);
return;
}
}
}
final SipServletRequestImpl originalRequest = tmpOriginalRequest;
sipServletResponse.setOriginalRequest(originalRequest);
if(applicationData != null) {
final String appNameNotDeployed = applicationData.getAppNotDeployed();
if(appNameNotDeployed != null && appNameNotDeployed.length() > 0) {
forwardResponseStatefully(sipServletResponse);
return ;
}
final boolean noAppReturned = applicationData.isNoAppReturned();
if(noAppReturned) {
forwardResponseStatefully(sipServletResponse);
return ;
}
final String modifier = applicationData.getModifier();
if(modifier != null && modifier.length() > 0) {
forwardResponseStatefully(sipServletResponse);
return ;
}
}
final String branch = viaHeader.getBranch();
String strippedBranchId = branch.substring(BRANCH_MAGIC_COOKIE.length());
int indexOfUnderscore = strippedBranchId.indexOf("_");
if(indexOfUnderscore == -1) {
throw new DispatcherException("the via header branch " + branch + " for the response is wrong the response does not reuse the one from the original request");
}
final String appId = strippedBranchId.substring(0, indexOfUnderscore);
indexOfUnderscore = strippedBranchId.indexOf("_");
if(indexOfUnderscore == -1) {
throw new DispatcherException("the via header branch " + branch + " for the response is wrong the response does not reuse the one from the original request");
}
strippedBranchId = strippedBranchId.substring(indexOfUnderscore + 1);
indexOfUnderscore = strippedBranchId.indexOf("_");
if(indexOfUnderscore == -1) {
throw new DispatcherException("the via header branch " + branch + " for the response is wrong the response does not reuse the one from the original request");
}
final String appNameHashed = strippedBranchId.substring(0, indexOfUnderscore);
final String appName = sipApplicationDispatcher.getApplicationNameFromHash(appNameHashed);
if(appName == null) {
throw new DispatcherException("the via header branch " + branch + " for the response is missing the appname previsouly set by the container");
}
boolean inverted = false;
if(dialog != null && dialog.isServer()) {
inverted = true;
}
final SipContext sipContext = sipApplicationDispatcher.findSipApplication(appName);
if(sipContext == null) {
if(logger.isDebugEnabled()) {
logger.debug("The application " + appName + " is not deployed anymore, fowarding response statefully to the next app in chain if any");
}
forwardResponseStatefully(sipServletResponse);
return ;
}
final SipManager sipManager = (SipManager)sipContext.getManager();
SipSessionKey sessionKey = SessionManagerUtil.getSipSessionKey(appId, appName, response, inverted);
if(logger.isDebugEnabled()) {
logger.debug("Trying to find session with following session key " + sessionKey);
}
final SipApplicationSessionKey sipApplicationSessionKey = SessionManagerUtil.getSipApplicationSessionKey(
appName,
appId);
MobicentsSipApplicationSession sipApplicationSession = null;
// needed only for failover (early) dialog recovery
if(sipManager instanceof DistributableSipManager) {
sipApplicationSession = sipManager.getSipApplicationSession(sipApplicationSessionKey, false);
}
MobicentsSipSession tmpSession = null;
tmpSession = sipManager.getSipSession(sessionKey, false, sipFactoryImpl, sipApplicationSession);
//needed in the case of RE-INVITE by example
if(tmpSession == null) {
sessionKey = SessionManagerUtil.getSipSessionKey(appId, appName, response, !inverted);
if(logger.isDebugEnabled()) {
logger.debug("Trying to find session with following session key " + sessionKey);
}
tmpSession = sipManager.getSipSession(sessionKey, false, sipFactoryImpl, sipApplicationSession);
}
if(logger.isDebugEnabled()) {
logger.debug("session found is " + tmpSession);
if(tmpSession == null) {
sipManager.dumpSipSessions();
}
}
if(tmpSession == null) {
if(logger.isDebugEnabled()) {
logger.debug("Dropping the response since no active sip session has been found for it : " + response + ", it may already have been invalidated");
}
return ;
} else {
// This piece of code move here due to Proxy-B2bua case for http://code.google.com/p/mobicents/issues/detail?id=1986
if(tmpSession.getProxy() == null && sipServletResponse.isRetransmission()) {
if(logger.isDebugEnabled()) {
logger.debug("retransmission received for a non proxy application, dropping the response " + response);
}
return ;
}
sipServletResponse.setSipSession(tmpSession);
}
if(logger.isDebugEnabled()) {
logger.debug("route response on following session " + tmpSession.getId());
}
final MobicentsSipSession session = tmpSession;
final TransactionApplicationData finalApplicationData = applicationData;
final DispatchTask dispatchTask = new DispatchTask(sipServletResponse, sipProvider) {
public void dispatch() throws DispatcherException {
final int status = sipServletResponse.getStatus();
if(status != Response.TRYING) {
sipContext.enterSipAppHa(true);
}
try {
try {
// we store the request only if the dialog is null and the method is not a dialog creating one
// if(dialog == null) {
session.setSessionCreatingTransactionRequest(sipServletResponse);
// } else {
session.setSessionCreatingDialog(dialog);
// }
if(originalRequest != null) {
originalRequest.setResponse(sipServletResponse);
}
// RFC 3265 : If a 200-class response matches such a SUBSCRIBE or REFER request,
// it creates a new subscription and a new dialog.
// Issue 1481 http://code.google.com/p/mobicents/issues/detail?id=1481
// proxy should not add or remove subscription since there is no dialog associated with it
if(Request.SUBSCRIBE.equals(sipServletResponse.getMethod()) && status >= 200 && status <= 300 && session.getProxy() == null) {
session.addSubscription(sipServletResponse);
}
// See if this is a response to a proxied request
// We can not use session.getProxyBranch() because all branches belong to the same session
// and the session.proxyBranch is overwritten each time there is activity on the branch.
ProxyBranchImpl proxyBranch = null;
if(finalApplicationData != null) {
proxyBranch = finalApplicationData.getProxyBranch();
}
if(session.getProxy() != null) {
// the final Application data is null meaning that the CTX was null, so it's a retransmission
if(proxyBranch == null) {
proxyBranch = session.getProxy().getFinalBranchForSubsequentRequests();
}
if(proxyBranch == null) {
if(logger.isDebugEnabled()) {
logger.debug("Attempting to recover lost transaction app data for " + branch);
}
//String txid = ((ViaHeader)response.getHeader(ViaHeader.NAME)).getBranch();
TransactionApplicationData tad = (TransactionApplicationData)
session.getProxy().getTransactionMap().get(branch);
if(tad != null) {
proxyBranch = tad.getProxyBranch();
if(logger.isDebugEnabled()) {
logger.debug("Sucessfully recovered app data for " + branch + " " + tad);
}
}
}
if(proxyBranch == null) {
logger.warn("A proxy retransmission has arrived without knowing which proxybranch to use (tx data lost)");
if(session.getProxy().getSupervised() && status != Response.TRYING) {
callServlet(sipServletResponse);
}
forwardResponseStatefully(sipServletResponse);
}
}
if(proxyBranch != null) {
sipServletResponse.setProxyBranch(proxyBranch);
// Update Session state
session.updateStateOnResponse(sipServletResponse, true);
proxyBranch.setResponse(sipServletResponse);
final ProxyImpl proxy = (ProxyImpl) session.getProxy();
// Notfiy the servlet
if(logger.isDebugEnabled()) {
logger.debug("Is Supervised enabled for this proxy branch ? " + proxy.getSupervised());
}
if(proxy.getSupervised() && status != Response.TRYING) {
callServlet(sipServletResponse);
}
if(status == 487 && proxy.allResponsesHaveArrived()) {
session.setState(State.TERMINATED);
session.setInvalidateWhenReady(true);
if(logger.isDebugEnabled()) {
logger.debug("Received 487 on a proxy branch and we are not waiting on other branches. Setting state to TERMINATED for " + this.toString());
}
}
// Handle it at the branch
proxyBranch.onResponse(sipServletResponse, status);
//we don't forward the response here since this has been done by the proxy
}
else {
// Fix for Issue 1689 : Send 100/INVITE immediately or not
// This issue showed that retransmissions of 180 Ringing were passed
// to the application so we make sure to drop them in case of UAC/UAS
if(sipServletResponse.isRetransmission()) {
if(logger.isDebugEnabled()) {
logger.debug("the following response is dropped since this is a retransmission " + response);
}
return;
}
//if this is a trying response, the response is dropped
if(Response.TRYING == status) {
// We will transition from INITIAL to EARLY here (not clear from the spec)
// Figure 6-1 The SIP Dialog State Machine
// and Figure 6-2 The SipSession State Machine
session.updateStateOnResponse(sipServletResponse, true);
if(logger.isDebugEnabled()) {
logger.debug("the response is dropped accordingly to JSR 289 " +
"since this a 100 for a non proxy application");
}
return;
}
// in non proxy case we drop the retransmissions
if(sipServletResponse.getTransaction() == null && sipServletResponse.getDialog() == null) {
if(logger.isDebugEnabled()) {
logger.debug("the following response is dropped since there is no client transaction nor dialog for it : " + response);
}
return;
}
// Update Session state
session.updateStateOnResponse(sipServletResponse, true);
callServlet(sipServletResponse);
forwardResponseStatefully(sipServletResponse);
}
} catch (ServletException e) {
throw new DispatcherException("Unexpected servlet exception while processing the response : " + response, e);
// Sends a 500 Internal server error and stops processing.
// JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, clientTransaction, request, sipProvider);
} catch (IOException e) {
throw new DispatcherException("Unexpected io exception while processing the response : " + response, e);
// Sends a 500 Internal server error and stops processing.
// JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, clientTransaction, request, sipProvider);
} catch (Throwable e) {
throw new DispatcherException("Unexpected exception while processing response : " + response, e);
// Sends a 500 Internal server error and stops processing.
// JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, clientTransaction, request, sipProvider);
}
} finally {
// exitSipAppHa completes the replication task. It might block for a while if the state is too big
// We should never call exitAipApp before exitSipAppHa, because exitSipApp releases the lock on the
// Application of SipSession (concurrency control lock). If this happens a new request might arrive
// and modify the state during Serialization or other non-thread safe operation in the serialization
if(status != Response.TRYING) {
sipContext.exitSipAppHa(null, sipServletResponse);
}
sipContext.exitSipApp(session.getSipApplicationSession(), session);
}
}
};
// we enter the sip app here, thus acuiring the semaphore on the session (if concurrency control is set) before the jain sip tx semaphore is released and ensuring that
// the tx serialization is preserved
sipContext.enterSipApp(session.getSipApplicationSession(), session);
// if the flag is set we bypass the executor, the bypassExecutor flag should be made deprecated
if(sipApplicationDispatcher.isBypassResponseExecutor() || ConcurrencyControlMode.Transaction.equals((sipContext.getConcurrencyControlMode()))) {
dispatchTask.dispatchAndHandleExceptions();
} else {
getConcurrencyModelExecutorService(sipContext, sipServletMessage).execute(dispatchTask);
}
} else {
// No sessions here and no servlets called, no need for asynchronicity
forwardResponseStatefully(sipServletResponse);
}
}
| public void dispatchMessage(final SipProvider sipProvider, SipServletMessageImpl sipServletMessage) throws DispatcherException {
final SipFactoryImpl sipFactoryImpl = sipApplicationDispatcher.getSipFactory();
final SipServletResponseImpl sipServletResponse = (SipServletResponseImpl) sipServletMessage;
final Response response = sipServletResponse.getResponse();
final ListIterator<ViaHeader> viaHeaders = response.getHeaders(ViaHeader.NAME);
final ViaHeader viaHeader = viaHeaders.next();
final String branch = viaHeader.getBranch();
if(logger.isDebugEnabled()) {
logger.debug("viaHeader = " + viaHeader.toString());
logger.debug("viaHeader branch = " + branch);
}
//response meant for the container
if(!sipApplicationDispatcher.isViaHeaderExternal(viaHeader)) {
final ClientTransaction clientTransaction = (ClientTransaction) sipServletResponse.getTransaction();
final Dialog dialog = sipServletResponse.getDialog();
TransactionApplicationData applicationData = null;
SipServletRequestImpl tmpOriginalRequest = null;
if(clientTransaction != null) {
applicationData = (TransactionApplicationData)clientTransaction.getApplicationData();
if(applicationData.getSipServletMessage() instanceof SipServletRequestImpl) {
tmpOriginalRequest = (SipServletRequestImpl)applicationData.getSipServletMessage();
// clearing the hops found by RFC 3263
if(applicationData.getHops() != null) {
applicationData.getHops().clear();
}
}
//add the response for access from B2BUAHelper.getPendingMessages
applicationData.addSipServletResponse(sipServletResponse);
//
ViaHeader nextViaHeader = null;
if(viaHeaders.hasNext()) {
nextViaHeader = viaHeaders.next();
if(logger.isDebugEnabled()) {
logger.debug("nextViaHeader = " + nextViaHeader.toString());
logger.debug("viaHeader branch = " + nextViaHeader.getBranch());
}
}
checkInitialRemoteInformation(sipServletMessage, nextViaHeader);
} //there is no client transaction associated with it, it means that this is a retransmission
else if(dialog != null) {
applicationData = (TransactionApplicationData)dialog.getApplicationData();
// Issue 1468 : application data can be null in case of forked response and max fork time property stack == 0
if(applicationData != null) {
if(applicationData.getSipServletMessage() instanceof SipServletRequestImpl) {
tmpOriginalRequest = (SipServletRequestImpl)applicationData.getSipServletMessage();
}
// Retrans drop logic removed from here due to AR case Proxy-B2bua for http://code.google.com/p/mobicents/issues/detail?id=1986
} else {
// Issue 1468 : Dropping response in case of forked response and max fork time property stack == 0 to
// Guard against exceptions that will arise later if we don't drop it since the support for it is not enabled
if(logger.isDebugEnabled()) {
logger.debug("application data is null, it means that this is a forked response, please enable stack property support for it through gov.nist.javax.sip.MAX_FORK_TIME_SECONDS");
logger.debug("Dropping forked response " + response);
return;
}
}
}
final SipServletRequestImpl originalRequest = tmpOriginalRequest;
sipServletResponse.setOriginalRequest(originalRequest);
if(applicationData != null) {
final String appNameNotDeployed = applicationData.getAppNotDeployed();
if(appNameNotDeployed != null && appNameNotDeployed.length() > 0) {
if(logger.isDebugEnabled()) {
logger.debug("appNameNotDeployed = " + appNameNotDeployed + " forwarding the response.");
}
forwardResponseStatefully(sipServletResponse);
return ;
}
final boolean noAppReturned = applicationData.isNoAppReturned();
if(noAppReturned) {
if(logger.isDebugEnabled()) {
logger.debug("isNoAppReturned forwarding the response.");
}
forwardResponseStatefully(sipServletResponse);
return ;
}
final String modifier = applicationData.getModifier();
if(modifier != null && modifier.length() > 0) {
if(logger.isDebugEnabled()) {
logger.debug("modifier = " + modifier + " forwarding the response.");
}
forwardResponseStatefully(sipServletResponse);
return ;
}
}
String strippedBranchId = branch.substring(BRANCH_MAGIC_COOKIE.length());
int indexOfUnderscore = strippedBranchId.indexOf("_");
if(indexOfUnderscore == -1) {
throw new DispatcherException("the via header branch " + branch + " for the response is wrong the response does not reuse the one from the original request");
}
final String appId = strippedBranchId.substring(0, indexOfUnderscore);
indexOfUnderscore = strippedBranchId.indexOf("_");
if(indexOfUnderscore == -1) {
throw new DispatcherException("the via header branch " + branch + " for the response is wrong the response does not reuse the one from the original request");
}
strippedBranchId = strippedBranchId.substring(indexOfUnderscore + 1);
indexOfUnderscore = strippedBranchId.indexOf("_");
if(indexOfUnderscore == -1) {
throw new DispatcherException("the via header branch " + branch + " for the response is wrong the response does not reuse the one from the original request");
}
final String appNameHashed = strippedBranchId.substring(0, indexOfUnderscore);
final String appName = sipApplicationDispatcher.getApplicationNameFromHash(appNameHashed);
if(appName == null) {
throw new DispatcherException("the via header branch " + branch + " for the response is missing the appname previsouly set by the container");
}
boolean inverted = false;
if(dialog != null && dialog.isServer()) {
inverted = true;
}
final SipContext sipContext = sipApplicationDispatcher.findSipApplication(appName);
if(sipContext == null) {
if(logger.isDebugEnabled()) {
logger.debug("The application " + appName + " is not deployed anymore, fowarding response statefully to the next app in chain if any");
}
forwardResponseStatefully(sipServletResponse);
return ;
}
final SipManager sipManager = (SipManager)sipContext.getManager();
SipSessionKey sessionKey = SessionManagerUtil.getSipSessionKey(appId, appName, response, inverted);
if(logger.isDebugEnabled()) {
logger.debug("Trying to find session with following session key " + sessionKey);
}
final SipApplicationSessionKey sipApplicationSessionKey = SessionManagerUtil.getSipApplicationSessionKey(
appName,
appId);
MobicentsSipApplicationSession sipApplicationSession = null;
// needed only for failover (early) dialog recovery
if(sipManager instanceof DistributableSipManager) {
sipApplicationSession = sipManager.getSipApplicationSession(sipApplicationSessionKey, false);
}
MobicentsSipSession tmpSession = null;
tmpSession = sipManager.getSipSession(sessionKey, false, sipFactoryImpl, sipApplicationSession);
//needed in the case of RE-INVITE by example
if(tmpSession == null) {
sessionKey = SessionManagerUtil.getSipSessionKey(appId, appName, response, !inverted);
if(logger.isDebugEnabled()) {
logger.debug("Trying to find session with following session key " + sessionKey);
}
tmpSession = sipManager.getSipSession(sessionKey, false, sipFactoryImpl, sipApplicationSession);
}
if(logger.isDebugEnabled()) {
logger.debug("session found is " + tmpSession);
if(tmpSession == null) {
sipManager.dumpSipSessions();
}
}
if(tmpSession == null) {
if(logger.isDebugEnabled()) {
logger.debug("Dropping the response since no active sip session has been found for it : " + response + ", it may already have been invalidated");
}
return ;
} else {
// This piece of code move here due to Proxy-B2bua case for http://code.google.com/p/mobicents/issues/detail?id=1986
if(tmpSession.getProxy() == null && sipServletResponse.isRetransmission()) {
if(logger.isDebugEnabled()) {
logger.debug("retransmission received for a non proxy application, dropping the response " + response);
}
return ;
}
sipServletResponse.setSipSession(tmpSession);
}
if(logger.isDebugEnabled()) {
logger.debug("route response on following session " + tmpSession.getId());
}
final MobicentsSipSession session = tmpSession;
final TransactionApplicationData finalApplicationData = applicationData;
final DispatchTask dispatchTask = new DispatchTask(sipServletResponse, sipProvider) {
public void dispatch() throws DispatcherException {
final int status = sipServletResponse.getStatus();
if(status != Response.TRYING) {
sipContext.enterSipAppHa(true);
}
try {
try {
// we store the request only if the dialog is null and the method is not a dialog creating one
// if(dialog == null) {
session.setSessionCreatingTransactionRequest(sipServletResponse);
// } else {
session.setSessionCreatingDialog(dialog);
// }
if(originalRequest != null) {
originalRequest.setResponse(sipServletResponse);
}
// RFC 3265 : If a 200-class response matches such a SUBSCRIBE or REFER request,
// it creates a new subscription and a new dialog.
// Issue 1481 http://code.google.com/p/mobicents/issues/detail?id=1481
// proxy should not add or remove subscription since there is no dialog associated with it
if(Request.SUBSCRIBE.equals(sipServletResponse.getMethod()) && status >= 200 && status <= 300 && session.getProxy() == null) {
session.addSubscription(sipServletResponse);
}
// See if this is a response to a proxied request
// We can not use session.getProxyBranch() because all branches belong to the same session
// and the session.proxyBranch is overwritten each time there is activity on the branch.
ProxyBranchImpl proxyBranch = null;
if(finalApplicationData != null) {
proxyBranch = finalApplicationData.getProxyBranch();
}
if(session.getProxy() != null) {
// the final Application data is null meaning that the CTX was null, so it's a retransmission
if(proxyBranch == null) {
proxyBranch = session.getProxy().getFinalBranchForSubsequentRequests();
}
if(proxyBranch == null) {
if(logger.isDebugEnabled()) {
logger.debug("Attempting to recover lost transaction app data for " + branch);
}
//String txid = ((ViaHeader)response.getHeader(ViaHeader.NAME)).getBranch();
TransactionApplicationData tad = (TransactionApplicationData)
session.getProxy().getTransactionMap().get(branch);
if(tad != null) {
proxyBranch = tad.getProxyBranch();
if(logger.isDebugEnabled()) {
logger.debug("Sucessfully recovered app data for " + branch + " " + tad);
}
}
}
if(proxyBranch == null) {
logger.warn("A proxy retransmission has arrived without knowing which proxybranch to use (tx data lost)");
if(session.getProxy().getSupervised() && status != Response.TRYING) {
callServlet(sipServletResponse);
}
forwardResponseStatefully(sipServletResponse);
}
}
if(proxyBranch != null) {
sipServletResponse.setProxyBranch(proxyBranch);
// Update Session state
session.updateStateOnResponse(sipServletResponse, true);
proxyBranch.setResponse(sipServletResponse);
final ProxyImpl proxy = (ProxyImpl) session.getProxy();
// Notfiy the servlet
if(logger.isDebugEnabled()) {
logger.debug("Is Supervised enabled for this proxy branch ? " + proxy.getSupervised());
}
if(proxy.getSupervised() && status != Response.TRYING) {
callServlet(sipServletResponse);
}
if(status == 487 && proxy.allResponsesHaveArrived()) {
session.setState(State.TERMINATED);
session.setInvalidateWhenReady(true);
if(logger.isDebugEnabled()) {
logger.debug("Received 487 on a proxy branch and we are not waiting on other branches. Setting state to TERMINATED for " + this.toString());
}
}
// Handle it at the branch
proxyBranch.onResponse(sipServletResponse, status);
//we don't forward the response here since this has been done by the proxy
}
else {
// Fix for Issue 1689 : Send 100/INVITE immediately or not
// This issue showed that retransmissions of 180 Ringing were passed
// to the application so we make sure to drop them in case of UAC/UAS
if(sipServletResponse.isRetransmission()) {
if(logger.isDebugEnabled()) {
logger.debug("the following response is dropped since this is a retransmission " + response);
}
return;
}
//if this is a trying response, the response is dropped
if(Response.TRYING == status) {
// We will transition from INITIAL to EARLY here (not clear from the spec)
// Figure 6-1 The SIP Dialog State Machine
// and Figure 6-2 The SipSession State Machine
session.updateStateOnResponse(sipServletResponse, true);
if(logger.isDebugEnabled()) {
logger.debug("the response is dropped accordingly to JSR 289 " +
"since this a 100 for a non proxy application");
}
return;
}
// in non proxy case we drop the retransmissions
if(sipServletResponse.getTransaction() == null && sipServletResponse.getDialog() == null) {
if(logger.isDebugEnabled()) {
logger.debug("the following response is dropped since there is no client transaction nor dialog for it : " + response);
}
return;
}
// Update Session state
session.updateStateOnResponse(sipServletResponse, true);
callServlet(sipServletResponse);
forwardResponseStatefully(sipServletResponse);
}
} catch (ServletException e) {
throw new DispatcherException("Unexpected servlet exception while processing the response : " + response, e);
// Sends a 500 Internal server error and stops processing.
// JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, clientTransaction, request, sipProvider);
} catch (IOException e) {
throw new DispatcherException("Unexpected io exception while processing the response : " + response, e);
// Sends a 500 Internal server error and stops processing.
// JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, clientTransaction, request, sipProvider);
} catch (Throwable e) {
throw new DispatcherException("Unexpected exception while processing response : " + response, e);
// Sends a 500 Internal server error and stops processing.
// JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, clientTransaction, request, sipProvider);
}
} finally {
// exitSipAppHa completes the replication task. It might block for a while if the state is too big
// We should never call exitAipApp before exitSipAppHa, because exitSipApp releases the lock on the
// Application of SipSession (concurrency control lock). If this happens a new request might arrive
// and modify the state during Serialization or other non-thread safe operation in the serialization
if(status != Response.TRYING) {
sipContext.exitSipAppHa(null, sipServletResponse);
}
sipContext.exitSipApp(session.getSipApplicationSession(), session);
}
}
};
// we enter the sip app here, thus acuiring the semaphore on the session (if concurrency control is set) before the jain sip tx semaphore is released and ensuring that
// the tx serialization is preserved
sipContext.enterSipApp(session.getSipApplicationSession(), session);
// if the flag is set we bypass the executor, the bypassExecutor flag should be made deprecated
if(sipApplicationDispatcher.isBypassResponseExecutor() || ConcurrencyControlMode.Transaction.equals((sipContext.getConcurrencyControlMode()))) {
dispatchTask.dispatchAndHandleExceptions();
} else {
getConcurrencyModelExecutorService(sipContext, sipServletMessage).execute(dispatchTask);
}
} else {
// No sessions here and no servlets called, no need for asynchronicity
forwardResponseStatefully(sipServletResponse);
}
}
|
diff --git a/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/util/TesterSecurityManager.java b/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/util/TesterSecurityManager.java
index 88dad067e..3cfefb290 100644
--- a/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/util/TesterSecurityManager.java
+++ b/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/util/TesterSecurityManager.java
@@ -1,115 +1,110 @@
/*
* Copyright (C) 2010 eXo Platform SAS.
*
* 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.exoplatform.services.jcr.impl.util;
import java.security.Permission;
/**
* @author <a href="[email protected]">Anatoliy Bazko</a>
* @version $Id: TesterSecurityManager.java 111 2010-11-11 11:11:11Z tolusha $
*/
public class TesterSecurityManager extends SecurityManager
{
/**
* {@inheritDoc}
*/
@Override
public void checkPermission(Permission perm)
{
try
{
super.checkPermission(perm);
}
catch (SecurityException se)
{
Throwable e = se;
boolean srcCode = false;
boolean testCode = false;
while (e != null)
{
StackTraceElement[] traceElements = e.getStackTrace();
for (int i = 0; i < traceElements.length; i++)
{
String className = traceElements[i].getClassName();
String fileName = traceElements[i].getFileName();
- String methodName = traceElements[i].getMethodName();
if (className.startsWith("org.exoplatform"))
{
- // TesterSecurityManager is not a part of source code
+ // TesterSecurityManager should not be a part of source code
if (fileName.equals("TesterSecurityManager.java"))
{
continue;
}
// hide Exception during JCR initialization
if (fileName.equals("BaseStandaloneTest.java"))
{
return;
}
if (fileName.startsWith("Test") || fileName.endsWith("Test.java")
|| fileName.endsWith("TestBase.java") || fileName.equals("Probe.java"))
{
testCode = true;
}
else
{
srcCode = true;
}
}
else if (className.startsWith("org.apache.jackrabbit.test"))
{
- // hide Exception during JCR initialization
- if (fileName.equals("RepositoryHelper.java") && methodName.equals("getRepository"))
+ // Allow access to instances
+ if (fileName.equals("RepositoryHelper.java"))
{
return;
}
if (fileName.endsWith("Test.java") || fileName.equals("JCRTestResult.java"))
{
testCode = true;
}
- else
- {
- srcCode = true;
- }
}
else if (className.startsWith("org.slf4j.impl.Log4jLoggerFactory"))
{
return;
}
}
e = e.getCause();
}
// hide Exception if only test code exists
if (!srcCode && testCode)
{
return;
}
throw se;
}
}
}
| false | true | public void checkPermission(Permission perm)
{
try
{
super.checkPermission(perm);
}
catch (SecurityException se)
{
Throwable e = se;
boolean srcCode = false;
boolean testCode = false;
while (e != null)
{
StackTraceElement[] traceElements = e.getStackTrace();
for (int i = 0; i < traceElements.length; i++)
{
String className = traceElements[i].getClassName();
String fileName = traceElements[i].getFileName();
String methodName = traceElements[i].getMethodName();
if (className.startsWith("org.exoplatform"))
{
// TesterSecurityManager is not a part of source code
if (fileName.equals("TesterSecurityManager.java"))
{
continue;
}
// hide Exception during JCR initialization
if (fileName.equals("BaseStandaloneTest.java"))
{
return;
}
if (fileName.startsWith("Test") || fileName.endsWith("Test.java")
|| fileName.endsWith("TestBase.java") || fileName.equals("Probe.java"))
{
testCode = true;
}
else
{
srcCode = true;
}
}
else if (className.startsWith("org.apache.jackrabbit.test"))
{
// hide Exception during JCR initialization
if (fileName.equals("RepositoryHelper.java") && methodName.equals("getRepository"))
{
return;
}
if (fileName.endsWith("Test.java") || fileName.equals("JCRTestResult.java"))
{
testCode = true;
}
else
{
srcCode = true;
}
}
else if (className.startsWith("org.slf4j.impl.Log4jLoggerFactory"))
{
return;
}
}
e = e.getCause();
}
// hide Exception if only test code exists
if (!srcCode && testCode)
{
return;
}
throw se;
}
}
| public void checkPermission(Permission perm)
{
try
{
super.checkPermission(perm);
}
catch (SecurityException se)
{
Throwable e = se;
boolean srcCode = false;
boolean testCode = false;
while (e != null)
{
StackTraceElement[] traceElements = e.getStackTrace();
for (int i = 0; i < traceElements.length; i++)
{
String className = traceElements[i].getClassName();
String fileName = traceElements[i].getFileName();
if (className.startsWith("org.exoplatform"))
{
// TesterSecurityManager should not be a part of source code
if (fileName.equals("TesterSecurityManager.java"))
{
continue;
}
// hide Exception during JCR initialization
if (fileName.equals("BaseStandaloneTest.java"))
{
return;
}
if (fileName.startsWith("Test") || fileName.endsWith("Test.java")
|| fileName.endsWith("TestBase.java") || fileName.equals("Probe.java"))
{
testCode = true;
}
else
{
srcCode = true;
}
}
else if (className.startsWith("org.apache.jackrabbit.test"))
{
// Allow access to instances
if (fileName.equals("RepositoryHelper.java"))
{
return;
}
if (fileName.endsWith("Test.java") || fileName.equals("JCRTestResult.java"))
{
testCode = true;
}
}
else if (className.startsWith("org.slf4j.impl.Log4jLoggerFactory"))
{
return;
}
}
e = e.getCause();
}
// hide Exception if only test code exists
if (!srcCode && testCode)
{
return;
}
throw se;
}
}
|
diff --git a/persistence/src/main/java/org/smallmind/persistence/cache/praxis/ByKeyRoster.java b/persistence/src/main/java/org/smallmind/persistence/cache/praxis/ByKeyRoster.java
index 6b1e17088..8c4962beb 100644
--- a/persistence/src/main/java/org/smallmind/persistence/cache/praxis/ByKeyRoster.java
+++ b/persistence/src/main/java/org/smallmind/persistence/cache/praxis/ByKeyRoster.java
@@ -1,298 +1,298 @@
/*
* Copyright (c) 2007, 2008, 2009, 2010, 2011, 2012 David Berkman
*
* This file is part of the SmallMind Code Project.
*
* The SmallMind Code Project is free software, you can redistribute
* it and/or modify it under the terms of 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.
*
* The SmallMind Code Project 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
* General Public License for more details.
*
* You should have received a copy of the the GNU Affero General Public
* License, along with The SmallMind Code Project. If not, see
* <http://www.gnu.org/licenses/>.
*
* Additional permission under the GNU Affero GPL version 3 section 7
* ------------------------------------------------------------------
* If you modify this Program, or any covered work, by linking or
* combining it with other code, such other code is not for that reason
* alone subject to any of the requirements of the GNU Affero GPL
* version 3.
*/
package org.smallmind.persistence.cache.praxis;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import org.smallmind.persistence.Durable;
import org.smallmind.persistence.cache.CacheOperationException;
import org.smallmind.persistence.cache.DurableKey;
import org.smallmind.persistence.cache.VectoredDao;
import org.smallmind.persistence.cache.praxis.intrinsic.IntrinsicRoster;
import org.smallmind.persistence.orm.DaoManager;
import org.smallmind.persistence.orm.ORMDao;
import org.smallmind.persistence.orm.VectorAwareORMDao;
import org.terracotta.annotations.InstrumentedClass;
@InstrumentedClass
public class ByKeyRoster<I extends Serializable & Comparable<I>, D extends Durable<I>> implements Roster<D> {
private Roster<DurableKey<I, D>> keyRoster;
private Class<D> durableClass;
public ByKeyRoster (Class<D> durableClass, Roster<DurableKey<I, D>> keyRoster) {
this.durableClass = durableClass;
this.keyRoster = keyRoster;
}
private ORMDao<I, D> getORMDao () {
ORMDao<I, D> ormDao;
if ((ormDao = DaoManager.get(durableClass)) == null) {
throw new CacheOperationException("Unable to locate an implementation of ORMDao within DaoManager for the requested durable(%s)", durableClass.getSimpleName());
}
return ormDao;
}
public List<D> prefetch () {
ORMDao<I, D> ormDao;
VectoredDao<I, D> vectoredDao;
if (((ormDao = getORMDao()) instanceof VectorAwareORMDao) && ((vectoredDao = ((VectorAwareORMDao<I, D>)ormDao).getVectoredDao()) != null)) {
LinkedList<D> prefetchList = new LinkedList<D>();
Map<DurableKey<I, D>, D> prefetchMap = vectoredDao.get(durableClass, keyRoster);
for (DurableKey<I, D> durableKey : keyRoster) {
D durable;
if ((durable = prefetchMap.get(durableKey)) != null) {
prefetchList.add(durable);
}
- else {
- prefetchList.add(getDurable(durableKey));
+ else if ((durable = getORMDao().acquire(durableClass, getORMDao().getIdFromString(durableKey.getIdAsString()))) != null) {
+ prefetchList.add(durable);
}
}
return prefetchList;
}
return new LinkedList<D>(this);
}
private D getDurable (DurableKey<I, D> durableKey) {
if (durableKey == null) {
return null;
}
return getORMDao().get(getORMDao().getIdFromString(durableKey.getIdAsString()));
}
public Class<D> getDurableClass () {
return durableClass;
}
public Roster<DurableKey<I, D>> getInternalRoster () {
return keyRoster;
}
public int size () {
return keyRoster.size();
}
public boolean isEmpty () {
return keyRoster.isEmpty();
}
public boolean contains (Object obj) {
return durableClass.isAssignableFrom(obj.getClass()) && keyRoster.contains(new DurableKey<I, D>(durableClass, durableClass.cast(obj).getId()));
}
public Object[] toArray () {
return toArray(null);
}
public <T> T[] toArray (T[] a) {
Object[] elements;
Object[] keyArray = keyRoster.toArray();
D durable;
int index = 0;
elements = ((a != null) && (a.length >= keyArray.length)) ? a : (Object[])Array.newInstance((a == null) ? durableClass : a.getClass().getComponentType(), keyArray.length);
for (Object key : keyArray) {
if ((durable = getDurable((DurableKey<I, D>)key)) != null) {
elements[index++] = durable;
}
}
return (T[])elements;
}
public D get (int index) {
return getDurable(keyRoster.get(index));
}
public D set (int index, D durable) {
return getDurable(keyRoster.set(index, new DurableKey<I, D>(durableClass, durable.getId())));
}
public void addFirst (D durable) {
keyRoster.addFirst(new DurableKey<I, D>(durableClass, durable.getId()));
}
public boolean add (D durable) {
return keyRoster.add(new DurableKey<I, D>(durableClass, durable.getId()));
}
public void add (int index, D durable) {
keyRoster.add(index, new DurableKey<I, D>(durableClass, durable.getId()));
}
public boolean remove (Object obj) {
return durableClass.isAssignableFrom(obj.getClass()) && keyRoster.remove(new DurableKey<I, D>(durableClass, durableClass.cast(obj).getId()));
}
public D removeLast () {
return getDurable(keyRoster.removeLast());
}
public D remove (int index) {
return getDurable(keyRoster.remove(index));
}
public boolean containsAll (Collection<?> c) {
HashSet<DurableKey<I, D>> keySet = new HashSet<DurableKey<I, D>>();
for (Object obj : c) {
if (!durableClass.isAssignableFrom(obj.getClass())) {
return false;
}
keySet.add(new DurableKey<I, D>(durableClass, durableClass.cast(obj).getId()));
}
return keySet.containsAll(keySet);
}
public boolean addAll (Collection<? extends D> c) {
HashSet<DurableKey<I, D>> keySet = new HashSet<DurableKey<I, D>>();
for (Object obj : c) {
if (durableClass.isAssignableFrom(obj.getClass())) {
keySet.add(new DurableKey<I, D>(durableClass, durableClass.cast(obj).getId()));
}
}
return keyRoster.addAll(keySet);
}
public boolean addAll (int index, Collection<? extends D> c) {
HashSet<DurableKey<I, D>> keySet = new HashSet<DurableKey<I, D>>();
for (Object obj : c) {
if (durableClass.isAssignableFrom(obj.getClass())) {
keySet.add(new DurableKey<I, D>(durableClass, durableClass.cast(obj).getId()));
}
}
return keyRoster.addAll(index, keySet);
}
public boolean removeAll (Collection<?> c) {
HashSet<DurableKey<I, D>> keySet = new HashSet<DurableKey<I, D>>();
for (Object obj : c) {
if (durableClass.isAssignableFrom(obj.getClass())) {
keySet.add(new DurableKey<I, D>(durableClass, durableClass.cast(obj).getId()));
}
}
return keyRoster.removeAll(keySet);
}
public boolean retainAll (Collection<?> c) {
HashSet<DurableKey<I, D>> keySet = new HashSet<DurableKey<I, D>>();
for (Object obj : c) {
if (durableClass.isAssignableFrom(obj.getClass())) {
keySet.add(new DurableKey<I, D>(durableClass, durableClass.cast(obj).getId()));
}
}
return keyRoster.retainAll(keySet);
}
public void clear () {
keyRoster.clear();
}
public int indexOf (Object obj) {
return durableClass.isAssignableFrom(obj.getClass()) ? keyRoster.indexOf(new DurableKey<I, D>(durableClass, durableClass.cast(obj).getId())) : -1;
}
public int lastIndexOf (Object obj) {
return durableClass.isAssignableFrom(obj.getClass()) ? keyRoster.lastIndexOf(new DurableKey<I, D>(durableClass, durableClass.cast(obj).getId())) : -1;
}
public Iterator<D> iterator () {
return new ByKeyRosterIterator<I, D>(getORMDao(), keyRoster.listIterator());
}
public ListIterator<D> listIterator () {
return new ByKeyRosterIterator<I, D>(getORMDao(), keyRoster.listIterator());
}
public ListIterator<D> listIterator (int index) {
return new ByKeyRosterIterator<I, D>(getORMDao(), keyRoster.listIterator(index));
}
public List<D> subList (int fromIndex, int toIndex) {
return new ByKeyRoster<I, D>(durableClass, (IntrinsicRoster<DurableKey<I, D>>)keyRoster.subList(fromIndex, toIndex));
}
}
| true | true | public List<D> prefetch () {
ORMDao<I, D> ormDao;
VectoredDao<I, D> vectoredDao;
if (((ormDao = getORMDao()) instanceof VectorAwareORMDao) && ((vectoredDao = ((VectorAwareORMDao<I, D>)ormDao).getVectoredDao()) != null)) {
LinkedList<D> prefetchList = new LinkedList<D>();
Map<DurableKey<I, D>, D> prefetchMap = vectoredDao.get(durableClass, keyRoster);
for (DurableKey<I, D> durableKey : keyRoster) {
D durable;
if ((durable = prefetchMap.get(durableKey)) != null) {
prefetchList.add(durable);
}
else {
prefetchList.add(getDurable(durableKey));
}
}
return prefetchList;
}
return new LinkedList<D>(this);
}
| public List<D> prefetch () {
ORMDao<I, D> ormDao;
VectoredDao<I, D> vectoredDao;
if (((ormDao = getORMDao()) instanceof VectorAwareORMDao) && ((vectoredDao = ((VectorAwareORMDao<I, D>)ormDao).getVectoredDao()) != null)) {
LinkedList<D> prefetchList = new LinkedList<D>();
Map<DurableKey<I, D>, D> prefetchMap = vectoredDao.get(durableClass, keyRoster);
for (DurableKey<I, D> durableKey : keyRoster) {
D durable;
if ((durable = prefetchMap.get(durableKey)) != null) {
prefetchList.add(durable);
}
else if ((durable = getORMDao().acquire(durableClass, getORMDao().getIdFromString(durableKey.getIdAsString()))) != null) {
prefetchList.add(durable);
}
}
return prefetchList;
}
return new LinkedList<D>(this);
}
|
diff --git a/solr/core/src/test/org/apache/solr/cloud/SyncSliceTest.java b/solr/core/src/test/org/apache/solr/cloud/SyncSliceTest.java
index 68a6c71417..c4b3bd8b64 100644
--- a/solr/core/src/test/org/apache/solr/cloud/SyncSliceTest.java
+++ b/solr/core/src/test/org/apache/solr/cloud/SyncSliceTest.java
@@ -1,340 +1,340 @@
package org.apache.solr.cloud;
/*
* 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.
*/
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.lucene.util.LuceneTestCase.Slow;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrRequest;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.request.QueryRequest;
import org.apache.solr.client.solrj.request.UpdateRequest;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.cloud.ClusterState;
import org.apache.solr.common.cloud.DocCollection;
import org.apache.solr.common.cloud.Replica;
import org.apache.solr.common.cloud.Slice;
import org.apache.solr.common.cloud.ZkStateReader;
import org.apache.solr.common.params.CollectionParams.CollectionAction;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
/**
* Test sync phase that occurs when Leader goes down and a new Leader is
* elected.
*/
@Slow
public class SyncSliceTest extends AbstractFullDistribZkTestBase {
@BeforeClass
public static void beforeSuperClass() throws Exception {
// TODO: we use an fs based dir because something
// like a ram dir will not recovery correctly right now
// due to tran log persisting across restarts
useFactory(null);
}
@AfterClass
public static void afterSuperClass() {
}
@Before
@Override
public void setUp() throws Exception {
super.setUp();
// we expect this time of exception as shards go up and down...
//ignoreException(".*");
System.setProperty("numShards", Integer.toString(sliceCount));
}
@Override
@After
public void tearDown() throws Exception {
super.tearDown();
resetExceptionIgnores();
}
public SyncSliceTest() {
super();
sliceCount = 1;
shardCount = TEST_NIGHTLY ? 7 : 4;
}
@Override
public void doTest() throws Exception {
handle.clear();
handle.put("QTime", SKIPVAL);
handle.put("timestamp", SKIPVAL);
waitForThingsToLevelOut(15);
del("*:*");
List<CloudJettyRunner> skipServers = new ArrayList<CloudJettyRunner>();
int docId = 0;
indexDoc(skipServers, id, docId++, i1, 50, tlong, 50, t1,
"to come to the aid of their country.");
indexDoc(skipServers, id, docId++, i1, 50, tlong, 50, t1,
"old haven was blue.");
skipServers.add(shardToJetty.get("shard1").get(1));
indexDoc(skipServers, id, docId++, i1, 50, tlong, 50, t1,
"but the song was fancy.");
skipServers.add(shardToJetty.get("shard1").get(2));
indexDoc(skipServers, id,docId++, i1, 50, tlong, 50, t1,
"under the moon and over the lake");
commit();
waitForRecoveriesToFinish(false);
// shard should be inconsistent
String shardFailMessage = checkShardConsistency("shard1", true, false);
assertNotNull(shardFailMessage);
ModifiableSolrParams params = new ModifiableSolrParams();
params.set("action", CollectionAction.SYNCSHARD.toString());
params.set("collection", "collection1");
params.set("shard", "shard1");
SolrRequest request = new QueryRequest(params);
request.setPath("/admin/collections");
String baseUrl = ((HttpSolrServer) shardToJetty.get("shard1").get(2).client.solrClient)
.getBaseURL();
baseUrl = baseUrl.substring(0, baseUrl.length() - "collection1".length());
HttpSolrServer baseServer = new HttpSolrServer(baseUrl);
baseServer.setConnectionTimeout(15000);
baseServer.setSoTimeout(30000);
baseServer.request(request);
waitForThingsToLevelOut(15);
checkShardConsistency(false, true);
long cloudClientDocs = cloudClient.query(new SolrQuery("*:*")).getResults().getNumFound();
assertEquals(4, cloudClientDocs);
// kill the leader - new leader could have all the docs or be missing one
CloudJettyRunner leaderJetty = shardToLeaderJetty.get("shard1");
skipServers = getRandomOtherJetty(leaderJetty, null); // but not the leader
// this doc won't be on one node
indexDoc(skipServers, id, docId++, i1, 50, tlong, 50, t1,
"to come to the aid of their country.");
Set<CloudJettyRunner> jetties = new HashSet<CloudJettyRunner>();
jetties.addAll(shardToJetty.get("shard1"));
jetties.remove(leaderJetty);
assertEquals(shardCount - 1, jetties.size());
chaosMonkey.killJetty(leaderJetty);
Thread.sleep(2000);
waitForThingsToLevelOut(90);
Thread.sleep(1000);
checkShardConsistency(false, true);
cloudClientDocs = cloudClient.query(new SolrQuery("*:*")).getResults().getNumFound();
assertEquals(5, cloudClientDocs);
CloudJettyRunner deadJetty = leaderJetty;
// let's get the latest leader
while (deadJetty == leaderJetty) {
updateMappingsFromZk(this.jettys, this.clients);
leaderJetty = shardToLeaderJetty.get("shard1");
}
// bring back dead node
ChaosMonkey.start(deadJetty.jetty); // he is not the leader anymore
waitTillRecovered();
- skipServers = getRandomOtherJetty(leaderJetty, null);
- skipServers.addAll( getRandomOtherJetty(leaderJetty, skipServers.get(0)));
+ skipServers = getRandomOtherJetty(leaderJetty, deadJetty);
+ skipServers.addAll( getRandomOtherJetty(leaderJetty, deadJetty));
// skip list should be
//System.out.println("leader:" + leaderJetty.url);
//System.out.println("skip list:" + skipServers);
// we are skipping 2 nodes
assertEquals(2, skipServers.size());
// more docs than can peer sync
for (int i = 0; i < 300; i++) {
indexDoc(skipServers, id, docId++, i1, 50, tlong, 50, t1,
"to come to the aid of their country.");
}
commit();
Thread.sleep(1000);
waitForRecoveriesToFinish(false);
// shard should be inconsistent
shardFailMessage = waitTillInconsistent();
assertNotNull(
"Test Setup Failure: shard1 should have just been set up to be inconsistent - but it's still consistent. Leader:" + leaderJetty.url +
"skip list:" + skipServers,
shardFailMessage);
jetties = new HashSet<CloudJettyRunner>();
jetties.addAll(shardToJetty.get("shard1"));
jetties.remove(leaderJetty);
assertEquals(shardCount - 1, jetties.size());
// kill the current leader
chaosMonkey.killJetty(leaderJetty);
Thread.sleep(3000);
waitForThingsToLevelOut(90);
Thread.sleep(2000);
waitForRecoveriesToFinish(false);
checkShardConsistency(true, true);
}
private void waitTillRecovered() throws Exception {
for (int i = 0; i < 30; i++) {
Thread.sleep(3000);
ZkStateReader zkStateReader = cloudClient.getZkStateReader();
zkStateReader.updateClusterState(true);
ClusterState clusterState = zkStateReader.getClusterState();
DocCollection collection1 = clusterState.getCollection("collection1");
Slice slice = collection1.getSlice("shard1");
Collection<Replica> replicas = slice.getReplicas();
boolean allActive = true;
for (Replica replica : replicas) {
if (!clusterState.liveNodesContain(replica.getNodeName())
|| !replica.get(ZkStateReader.STATE_PROP).equals(
ZkStateReader.ACTIVE)) {
allActive = false;
break;
}
}
if (allActive) {
return;
}
}
printLayout();
fail("timeout waiting to see recovered node");
}
private String waitTillInconsistent() throws Exception, InterruptedException {
String shardFailMessage = null;
shardFailMessage = pollConsistency(shardFailMessage, 0);
shardFailMessage = pollConsistency(shardFailMessage, 3000);
shardFailMessage = pollConsistency(shardFailMessage, 5000);
shardFailMessage = pollConsistency(shardFailMessage, 8000);
return shardFailMessage;
}
private String pollConsistency(String shardFailMessage, int sleep)
throws InterruptedException, Exception {
try {
commit();
} catch (Throwable t) {
t.printStackTrace();
}
if (shardFailMessage == null) {
// try again
Thread.sleep(sleep);
shardFailMessage = checkShardConsistency("shard1", true, false);
}
return shardFailMessage;
}
private List<CloudJettyRunner> getRandomOtherJetty(CloudJettyRunner leader, CloudJettyRunner down) {
List<CloudJettyRunner> skipServers = new ArrayList<CloudJettyRunner>();
List<CloudJettyRunner> candidates = new ArrayList<CloudJettyRunner>();
candidates.addAll(shardToJetty.get("shard1"));
if (leader != null) {
candidates.remove(leader);
}
if (down != null) {
candidates.remove(down);
}
CloudJettyRunner cjetty = candidates.get(random().nextInt(candidates.size()));
skipServers.add(cjetty);
return skipServers;
}
protected void indexDoc(List<CloudJettyRunner> skipServers, Object... fields) throws IOException,
SolrServerException {
SolrInputDocument doc = new SolrInputDocument();
addFields(doc, fields);
addFields(doc, "rnd_b", true);
controlClient.add(doc);
UpdateRequest ureq = new UpdateRequest();
ureq.add(doc);
ModifiableSolrParams params = new ModifiableSolrParams();
for (CloudJettyRunner skip : skipServers) {
params.add("test.distrib.skip.servers", skip.url + "/");
}
ureq.setParams(params);
ureq.process(cloudClient);
}
// skip the randoms - they can deadlock...
@Override
protected void indexr(Object... fields) throws Exception {
SolrInputDocument doc = new SolrInputDocument();
addFields(doc, fields);
addFields(doc, "rnd_b", true);
indexDoc(doc);
}
}
| true | true | public void doTest() throws Exception {
handle.clear();
handle.put("QTime", SKIPVAL);
handle.put("timestamp", SKIPVAL);
waitForThingsToLevelOut(15);
del("*:*");
List<CloudJettyRunner> skipServers = new ArrayList<CloudJettyRunner>();
int docId = 0;
indexDoc(skipServers, id, docId++, i1, 50, tlong, 50, t1,
"to come to the aid of their country.");
indexDoc(skipServers, id, docId++, i1, 50, tlong, 50, t1,
"old haven was blue.");
skipServers.add(shardToJetty.get("shard1").get(1));
indexDoc(skipServers, id, docId++, i1, 50, tlong, 50, t1,
"but the song was fancy.");
skipServers.add(shardToJetty.get("shard1").get(2));
indexDoc(skipServers, id,docId++, i1, 50, tlong, 50, t1,
"under the moon and over the lake");
commit();
waitForRecoveriesToFinish(false);
// shard should be inconsistent
String shardFailMessage = checkShardConsistency("shard1", true, false);
assertNotNull(shardFailMessage);
ModifiableSolrParams params = new ModifiableSolrParams();
params.set("action", CollectionAction.SYNCSHARD.toString());
params.set("collection", "collection1");
params.set("shard", "shard1");
SolrRequest request = new QueryRequest(params);
request.setPath("/admin/collections");
String baseUrl = ((HttpSolrServer) shardToJetty.get("shard1").get(2).client.solrClient)
.getBaseURL();
baseUrl = baseUrl.substring(0, baseUrl.length() - "collection1".length());
HttpSolrServer baseServer = new HttpSolrServer(baseUrl);
baseServer.setConnectionTimeout(15000);
baseServer.setSoTimeout(30000);
baseServer.request(request);
waitForThingsToLevelOut(15);
checkShardConsistency(false, true);
long cloudClientDocs = cloudClient.query(new SolrQuery("*:*")).getResults().getNumFound();
assertEquals(4, cloudClientDocs);
// kill the leader - new leader could have all the docs or be missing one
CloudJettyRunner leaderJetty = shardToLeaderJetty.get("shard1");
skipServers = getRandomOtherJetty(leaderJetty, null); // but not the leader
// this doc won't be on one node
indexDoc(skipServers, id, docId++, i1, 50, tlong, 50, t1,
"to come to the aid of their country.");
Set<CloudJettyRunner> jetties = new HashSet<CloudJettyRunner>();
jetties.addAll(shardToJetty.get("shard1"));
jetties.remove(leaderJetty);
assertEquals(shardCount - 1, jetties.size());
chaosMonkey.killJetty(leaderJetty);
Thread.sleep(2000);
waitForThingsToLevelOut(90);
Thread.sleep(1000);
checkShardConsistency(false, true);
cloudClientDocs = cloudClient.query(new SolrQuery("*:*")).getResults().getNumFound();
assertEquals(5, cloudClientDocs);
CloudJettyRunner deadJetty = leaderJetty;
// let's get the latest leader
while (deadJetty == leaderJetty) {
updateMappingsFromZk(this.jettys, this.clients);
leaderJetty = shardToLeaderJetty.get("shard1");
}
// bring back dead node
ChaosMonkey.start(deadJetty.jetty); // he is not the leader anymore
waitTillRecovered();
skipServers = getRandomOtherJetty(leaderJetty, null);
skipServers.addAll( getRandomOtherJetty(leaderJetty, skipServers.get(0)));
// skip list should be
//System.out.println("leader:" + leaderJetty.url);
//System.out.println("skip list:" + skipServers);
// we are skipping 2 nodes
assertEquals(2, skipServers.size());
// more docs than can peer sync
for (int i = 0; i < 300; i++) {
indexDoc(skipServers, id, docId++, i1, 50, tlong, 50, t1,
"to come to the aid of their country.");
}
commit();
Thread.sleep(1000);
waitForRecoveriesToFinish(false);
// shard should be inconsistent
shardFailMessage = waitTillInconsistent();
assertNotNull(
"Test Setup Failure: shard1 should have just been set up to be inconsistent - but it's still consistent. Leader:" + leaderJetty.url +
"skip list:" + skipServers,
shardFailMessage);
jetties = new HashSet<CloudJettyRunner>();
jetties.addAll(shardToJetty.get("shard1"));
jetties.remove(leaderJetty);
assertEquals(shardCount - 1, jetties.size());
// kill the current leader
chaosMonkey.killJetty(leaderJetty);
Thread.sleep(3000);
waitForThingsToLevelOut(90);
Thread.sleep(2000);
waitForRecoveriesToFinish(false);
checkShardConsistency(true, true);
}
| public void doTest() throws Exception {
handle.clear();
handle.put("QTime", SKIPVAL);
handle.put("timestamp", SKIPVAL);
waitForThingsToLevelOut(15);
del("*:*");
List<CloudJettyRunner> skipServers = new ArrayList<CloudJettyRunner>();
int docId = 0;
indexDoc(skipServers, id, docId++, i1, 50, tlong, 50, t1,
"to come to the aid of their country.");
indexDoc(skipServers, id, docId++, i1, 50, tlong, 50, t1,
"old haven was blue.");
skipServers.add(shardToJetty.get("shard1").get(1));
indexDoc(skipServers, id, docId++, i1, 50, tlong, 50, t1,
"but the song was fancy.");
skipServers.add(shardToJetty.get("shard1").get(2));
indexDoc(skipServers, id,docId++, i1, 50, tlong, 50, t1,
"under the moon and over the lake");
commit();
waitForRecoveriesToFinish(false);
// shard should be inconsistent
String shardFailMessage = checkShardConsistency("shard1", true, false);
assertNotNull(shardFailMessage);
ModifiableSolrParams params = new ModifiableSolrParams();
params.set("action", CollectionAction.SYNCSHARD.toString());
params.set("collection", "collection1");
params.set("shard", "shard1");
SolrRequest request = new QueryRequest(params);
request.setPath("/admin/collections");
String baseUrl = ((HttpSolrServer) shardToJetty.get("shard1").get(2).client.solrClient)
.getBaseURL();
baseUrl = baseUrl.substring(0, baseUrl.length() - "collection1".length());
HttpSolrServer baseServer = new HttpSolrServer(baseUrl);
baseServer.setConnectionTimeout(15000);
baseServer.setSoTimeout(30000);
baseServer.request(request);
waitForThingsToLevelOut(15);
checkShardConsistency(false, true);
long cloudClientDocs = cloudClient.query(new SolrQuery("*:*")).getResults().getNumFound();
assertEquals(4, cloudClientDocs);
// kill the leader - new leader could have all the docs or be missing one
CloudJettyRunner leaderJetty = shardToLeaderJetty.get("shard1");
skipServers = getRandomOtherJetty(leaderJetty, null); // but not the leader
// this doc won't be on one node
indexDoc(skipServers, id, docId++, i1, 50, tlong, 50, t1,
"to come to the aid of their country.");
Set<CloudJettyRunner> jetties = new HashSet<CloudJettyRunner>();
jetties.addAll(shardToJetty.get("shard1"));
jetties.remove(leaderJetty);
assertEquals(shardCount - 1, jetties.size());
chaosMonkey.killJetty(leaderJetty);
Thread.sleep(2000);
waitForThingsToLevelOut(90);
Thread.sleep(1000);
checkShardConsistency(false, true);
cloudClientDocs = cloudClient.query(new SolrQuery("*:*")).getResults().getNumFound();
assertEquals(5, cloudClientDocs);
CloudJettyRunner deadJetty = leaderJetty;
// let's get the latest leader
while (deadJetty == leaderJetty) {
updateMappingsFromZk(this.jettys, this.clients);
leaderJetty = shardToLeaderJetty.get("shard1");
}
// bring back dead node
ChaosMonkey.start(deadJetty.jetty); // he is not the leader anymore
waitTillRecovered();
skipServers = getRandomOtherJetty(leaderJetty, deadJetty);
skipServers.addAll( getRandomOtherJetty(leaderJetty, deadJetty));
// skip list should be
//System.out.println("leader:" + leaderJetty.url);
//System.out.println("skip list:" + skipServers);
// we are skipping 2 nodes
assertEquals(2, skipServers.size());
// more docs than can peer sync
for (int i = 0; i < 300; i++) {
indexDoc(skipServers, id, docId++, i1, 50, tlong, 50, t1,
"to come to the aid of their country.");
}
commit();
Thread.sleep(1000);
waitForRecoveriesToFinish(false);
// shard should be inconsistent
shardFailMessage = waitTillInconsistent();
assertNotNull(
"Test Setup Failure: shard1 should have just been set up to be inconsistent - but it's still consistent. Leader:" + leaderJetty.url +
"skip list:" + skipServers,
shardFailMessage);
jetties = new HashSet<CloudJettyRunner>();
jetties.addAll(shardToJetty.get("shard1"));
jetties.remove(leaderJetty);
assertEquals(shardCount - 1, jetties.size());
// kill the current leader
chaosMonkey.killJetty(leaderJetty);
Thread.sleep(3000);
waitForThingsToLevelOut(90);
Thread.sleep(2000);
waitForRecoveriesToFinish(false);
checkShardConsistency(true, true);
}
|
diff --git a/src/realtalk/util/JSONParser.java b/src/realtalk/util/JSONParser.java
index ac947a1..fc3d158 100644
--- a/src/realtalk/util/JSONParser.java
+++ b/src/realtalk/util/JSONParser.java
@@ -1,103 +1,112 @@
package realtalk.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
/**
* JSONParser is a helper class that makes a generic POST/GET request to a given url,
* with embedded params.
*
* @author Taylor Williams / Colin Kho
*
*/
public class JSONParser {
public JSONParser() {}
private static final int BUFFER_SIZE = 8;
/** Sends a request to a url with given params
* @param stUrl The url to send the request to
* @param stMethod POST or GET
* @param rgparams a list of parameters to embed in the request
* @return a JSONObject with the result of the request
*/
public JSONObject makeHttpRequest(String stUrl, String stMethod, List<NameValuePair> rgparams) {
InputStream inputstream = null;
JSONObject jsonobject = null;
String stJson = "";
try {
// check for request method
if(stMethod.equals("POST")){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(stUrl);
httppost.setEntity(new UrlEncodedFormEntity(rgparams));
HttpResponse httpresponse = httpclient.execute(httppost);
HttpEntity httpentity = httpresponse.getEntity();
inputstream = httpentity.getContent();
}else if(stMethod.equals("GET")){
// request method is GET
DefaultHttpClient httpclient = new DefaultHttpClient();
String stParam = URLEncodedUtils.format(rgparams, "utf-8");
stUrl += "?" + stParam;
HttpGet httpget = new HttpGet(stUrl);
HttpResponse httpresponse = httpclient.execute(httpget);
HttpEntity httpentity = httpresponse.getEntity();
inputstream = httpentity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
+ BufferedReader reader = null;
try {
- BufferedReader reader = new BufferedReader(new InputStreamReader(
+ reader = new BufferedReader(new InputStreamReader(
inputstream, "iso-8859-1"), BUFFER_SIZE);
StringBuilder stringbuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
stringbuilder.append(line + "\n");
}
if (inputstream != null) {
inputstream.close();
}
stJson = stringbuilder.toString();
+ reader.close();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
+ } finally {
+ try {
+ if (reader != null)
+ reader.close();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
}
// try parse the string to a JSON object
try {
jsonobject = new JSONObject(stJson);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jsonobject;
}
}
| false | true | public JSONObject makeHttpRequest(String stUrl, String stMethod, List<NameValuePair> rgparams) {
InputStream inputstream = null;
JSONObject jsonobject = null;
String stJson = "";
try {
// check for request method
if(stMethod.equals("POST")){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(stUrl);
httppost.setEntity(new UrlEncodedFormEntity(rgparams));
HttpResponse httpresponse = httpclient.execute(httppost);
HttpEntity httpentity = httpresponse.getEntity();
inputstream = httpentity.getContent();
}else if(stMethod.equals("GET")){
// request method is GET
DefaultHttpClient httpclient = new DefaultHttpClient();
String stParam = URLEncodedUtils.format(rgparams, "utf-8");
stUrl += "?" + stParam;
HttpGet httpget = new HttpGet(stUrl);
HttpResponse httpresponse = httpclient.execute(httpget);
HttpEntity httpentity = httpresponse.getEntity();
inputstream = httpentity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputstream, "iso-8859-1"), BUFFER_SIZE);
StringBuilder stringbuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
stringbuilder.append(line + "\n");
}
if (inputstream != null) {
inputstream.close();
}
stJson = stringbuilder.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jsonobject = new JSONObject(stJson);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jsonobject;
}
| public JSONObject makeHttpRequest(String stUrl, String stMethod, List<NameValuePair> rgparams) {
InputStream inputstream = null;
JSONObject jsonobject = null;
String stJson = "";
try {
// check for request method
if(stMethod.equals("POST")){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(stUrl);
httppost.setEntity(new UrlEncodedFormEntity(rgparams));
HttpResponse httpresponse = httpclient.execute(httppost);
HttpEntity httpentity = httpresponse.getEntity();
inputstream = httpentity.getContent();
}else if(stMethod.equals("GET")){
// request method is GET
DefaultHttpClient httpclient = new DefaultHttpClient();
String stParam = URLEncodedUtils.format(rgparams, "utf-8");
stUrl += "?" + stParam;
HttpGet httpget = new HttpGet(stUrl);
HttpResponse httpresponse = httpclient.execute(httpget);
HttpEntity httpentity = httpresponse.getEntity();
inputstream = httpentity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(
inputstream, "iso-8859-1"), BUFFER_SIZE);
StringBuilder stringbuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
stringbuilder.append(line + "\n");
}
if (inputstream != null) {
inputstream.close();
}
stJson = stringbuilder.toString();
reader.close();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
} finally {
try {
if (reader != null)
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// try parse the string to a JSON object
try {
jsonobject = new JSONObject(stJson);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jsonobject;
}
|
diff --git a/framework/core/src/main/java/org/apache/manifoldcf/core/i18n/Messages.java b/framework/core/src/main/java/org/apache/manifoldcf/core/i18n/Messages.java
index 719dbcb30..eda880a1b 100644
--- a/framework/core/src/main/java/org/apache/manifoldcf/core/i18n/Messages.java
+++ b/framework/core/src/main/java/org/apache/manifoldcf/core/i18n/Messages.java
@@ -1,298 +1,300 @@
/* $Id: Messages.java 1001023 2011-12-12 18:41:28Z hozawa $ */
/**
* 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.manifoldcf.core.i18n;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.HashSet;
import java.io.InputStream;
import org.apache.manifoldcf.core.system.Logging;
import org.apache.manifoldcf.core.interfaces.ManifoldCFException;
public class Messages
{
// Keep track of messages and bundles we've already complained about.
protected static Set<BundleKey> bundleSet = new HashSet<BundleKey>();
protected static Set<MessageKey> messageSet = new HashSet<MessageKey>();
protected static Set<ResourceKey> resourceSet = new HashSet<ResourceKey>();
/** Constructor - do no instantiate
*/
protected Messages()
{
}
/** Read a resource as an input stream, given a classloader, path, locale, and resource key.
*/
public static InputStream getResourceAsStream(Class classInstance, String pathName,
Locale locale, String resourceKey)
throws ManifoldCFException
{
InputStream is = classInstance.getResourceAsStream(localizeResourceName(pathName,resourceKey,locale));
if (is == null)
{
complainMissingResource("No resource in path '"+pathName+"' named '"+resourceKey+"' found for locale '"+locale.toString()+"'",
new Exception("Resource not found"),pathName,locale,resourceKey);
locale = new Locale(locale.getLanguage());
is = classInstance.getResourceAsStream(localizeResourceName(pathName,resourceKey,locale));
if (is == null)
{
complainMissingResource("No resource in path '"+pathName+"' named '"+resourceKey+"' found for locale '"+locale.toString()+"'",
new Exception("Resource not found"),pathName,locale,resourceKey);
locale = Locale.US;
is = classInstance.getResourceAsStream(localizeResourceName(pathName,resourceKey,locale));
if (is == null)
{
complainMissingResource("No resource in path '"+pathName+"' named '"+resourceKey+"' found for locale '"+locale.toString()+"'",
new Exception("Resource not found"),pathName,locale,resourceKey);
locale = new Locale(locale.getLanguage());
is = classInstance.getResourceAsStream(localizeResourceName(pathName,resourceKey,locale));
if (is == null)
throw new ManifoldCFException("No language resource in path '"+pathName+"' named '"+resourceKey+"' found for locale '"+locale.toString()+"'");
}
}
}
return is;
}
private static String localizeResourceName(String pathName, String resourceName, Locale locale)
{
// Path names temporarily disabled, since they don't work.
// MHL
int dotIndex = resourceName.lastIndexOf(".");
if (dotIndex == -1)
return /*pathName + "." + */resourceName + "_" + locale.toString();
return /*pathName + "." + */resourceName.substring(0,dotIndex) + "_" + locale.toString() + resourceName.substring(dotIndex);
}
/** Obtain a string given a classloader, bundle, locale, message key, and arguments.
*/
public static String getString(ClassLoader classLoader, String bundleName, Locale locale,
String messageKey, Object[] args)
{
ResourceBundle resources;
try
{
resources = ResourceBundle.getBundle(bundleName, locale, classLoader);
}
catch (MissingResourceException e)
{
complainMissingBundle("Missing resource bundle '" + bundleName + "' for locale '"+locale.toString()+"': "+e.getMessage()+"; trying "+locale.getLanguage(),
e,bundleName,locale);
// Try plain language next
locale = new Locale(locale.getLanguage());
try
{
resources = ResourceBundle.getBundle(bundleName, locale, classLoader);
}
catch (MissingResourceException e2)
{
// Use English if we don't have a bundle for the current locale
complainMissingBundle("Missing resource bundle '" + bundleName + "' for locale '"+locale.toString()+"': "+e2.getMessage()+"; trying en_US",
e2,bundleName,locale);
locale = Locale.US;
try
{
resources = ResourceBundle.getBundle(bundleName, locale, classLoader);
}
catch (MissingResourceException e3)
{
complainMissingBundle("No backup en_US bundle found! "+e3.getMessage(),e3,bundleName,locale);
locale = new Locale(locale.getLanguage());
try
{
resources = ResourceBundle.getBundle(bundleName, locale, classLoader);
}
catch (MissingResourceException e4)
{
complainMissingBundle("No backup en bundle found! "+e4.getMessage(),e4,bundleName,locale);
return messageKey;
}
}
}
}
String message;
try
{
message = resources.getString(messageKey);
}
catch (MissingResourceException e)
{
complainMissingMessage("Missing resource '" + messageKey + "' in bundle '" + bundleName + "' for locale '"+locale.toString()+"'",
e,bundleName,locale,messageKey);
message = messageKey;
}
// Format the message
String formatMessage;
if (args != null)
{
- formatMessage = MessageFormat.format(message, args);
+ MessageFormat fm = new MessageFormat(message);
+ fm.setLocale(locale);
+ formatMessage = fm.format(args);
}
else
{
formatMessage = message;
}
return formatMessage;
}
protected static void complainMissingBundle(String errorMessage, Throwable exception, String bundleName, Locale locale)
{
String localeName = locale.toString();
BundleKey bk = new BundleKey(bundleName,localeName);
synchronized (bundleSet)
{
if (bundleSet.contains(bk))
return;
bundleSet.add(bk);
}
logError(errorMessage,exception);
}
protected static void complainMissingMessage(String errorMessage, Throwable exception, String bundleName, Locale locale, String messageKey)
{
String localeName = locale.toString();
MessageKey bk = new MessageKey(bundleName,localeName,messageKey);
synchronized (messageSet)
{
if (messageSet.contains(bk))
return;
messageSet.add(bk);
}
logError(errorMessage,exception);
}
protected static void complainMissingResource(String errorMessage, Throwable exception, String pathName, Locale locale, String resourceKey)
{
String localeName = locale.toString();
ResourceKey bk = new ResourceKey(pathName,localeName,resourceKey);
synchronized (resourceSet)
{
if (resourceSet.contains(bk))
return;
resourceSet.add(bk);
}
logError(errorMessage,exception);
}
protected static void logError(String errorMessage, Throwable exception)
{
if (Logging.misc == null)
{
System.err.println(errorMessage);
exception.printStackTrace(System.err);
}
else
Logging.misc.error(errorMessage,exception);
}
/** Class to help keep track of the missing resource bundles we've already complained about,
* so we don't fill up the standard out log with repetitive stuff. */
protected static class BundleKey
{
protected String bundleName;
protected String localeName;
public BundleKey(String bundleName, String localeName)
{
this.bundleName = bundleName;
this.localeName = localeName;
}
public int hashCode()
{
return bundleName.hashCode() + localeName.hashCode();
}
public boolean equals(Object o)
{
if (!(o instanceof BundleKey))
return false;
BundleKey b = (BundleKey)o;
return b.bundleName.equals(bundleName) && b.localeName.equals(localeName);
}
}
/** Class to help keep track of the missing messages we've already complained about,
* so we don't fill up the standard out log with repetitive stuff. */
protected static class MessageKey
{
protected String bundleName;
protected String localeName;
protected String messageKey;
public MessageKey(String bundleName, String localeName, String messageKey)
{
this.bundleName = bundleName;
this.localeName = localeName;
this.messageKey = messageKey;
}
public int hashCode()
{
return bundleName.hashCode() + localeName.hashCode() + messageKey.hashCode();
}
public boolean equals(Object o)
{
if (!(o instanceof MessageKey))
return false;
MessageKey b = (MessageKey)o;
return b.bundleName.equals(bundleName) && b.localeName.equals(localeName) && b.messageKey.equals(messageKey);
}
}
/** Class to help keep track of the missing resources we've already complained about,
* so we don't fill up the standard out log with repetitive stuff. */
protected static class ResourceKey
{
protected String pathName;
protected String localeName;
protected String resourceKey;
public ResourceKey(String pathName, String localeName, String resourceKey)
{
this.pathName = pathName;
this.localeName = localeName;
this.resourceKey = resourceKey;
}
public int hashCode()
{
return pathName.hashCode() + localeName.hashCode() + resourceKey.hashCode();
}
public boolean equals(Object o)
{
if (!(o instanceof ResourceKey))
return false;
ResourceKey b = (ResourceKey)o;
return b.pathName.equals(pathName) && b.localeName.equals(localeName) && b.resourceKey.equals(resourceKey);
}
}
}
| true | true | public static String getString(ClassLoader classLoader, String bundleName, Locale locale,
String messageKey, Object[] args)
{
ResourceBundle resources;
try
{
resources = ResourceBundle.getBundle(bundleName, locale, classLoader);
}
catch (MissingResourceException e)
{
complainMissingBundle("Missing resource bundle '" + bundleName + "' for locale '"+locale.toString()+"': "+e.getMessage()+"; trying "+locale.getLanguage(),
e,bundleName,locale);
// Try plain language next
locale = new Locale(locale.getLanguage());
try
{
resources = ResourceBundle.getBundle(bundleName, locale, classLoader);
}
catch (MissingResourceException e2)
{
// Use English if we don't have a bundle for the current locale
complainMissingBundle("Missing resource bundle '" + bundleName + "' for locale '"+locale.toString()+"': "+e2.getMessage()+"; trying en_US",
e2,bundleName,locale);
locale = Locale.US;
try
{
resources = ResourceBundle.getBundle(bundleName, locale, classLoader);
}
catch (MissingResourceException e3)
{
complainMissingBundle("No backup en_US bundle found! "+e3.getMessage(),e3,bundleName,locale);
locale = new Locale(locale.getLanguage());
try
{
resources = ResourceBundle.getBundle(bundleName, locale, classLoader);
}
catch (MissingResourceException e4)
{
complainMissingBundle("No backup en bundle found! "+e4.getMessage(),e4,bundleName,locale);
return messageKey;
}
}
}
}
String message;
try
{
message = resources.getString(messageKey);
}
catch (MissingResourceException e)
{
complainMissingMessage("Missing resource '" + messageKey + "' in bundle '" + bundleName + "' for locale '"+locale.toString()+"'",
e,bundleName,locale,messageKey);
message = messageKey;
}
// Format the message
String formatMessage;
if (args != null)
{
formatMessage = MessageFormat.format(message, args);
}
else
{
formatMessage = message;
}
return formatMessage;
}
| public static String getString(ClassLoader classLoader, String bundleName, Locale locale,
String messageKey, Object[] args)
{
ResourceBundle resources;
try
{
resources = ResourceBundle.getBundle(bundleName, locale, classLoader);
}
catch (MissingResourceException e)
{
complainMissingBundle("Missing resource bundle '" + bundleName + "' for locale '"+locale.toString()+"': "+e.getMessage()+"; trying "+locale.getLanguage(),
e,bundleName,locale);
// Try plain language next
locale = new Locale(locale.getLanguage());
try
{
resources = ResourceBundle.getBundle(bundleName, locale, classLoader);
}
catch (MissingResourceException e2)
{
// Use English if we don't have a bundle for the current locale
complainMissingBundle("Missing resource bundle '" + bundleName + "' for locale '"+locale.toString()+"': "+e2.getMessage()+"; trying en_US",
e2,bundleName,locale);
locale = Locale.US;
try
{
resources = ResourceBundle.getBundle(bundleName, locale, classLoader);
}
catch (MissingResourceException e3)
{
complainMissingBundle("No backup en_US bundle found! "+e3.getMessage(),e3,bundleName,locale);
locale = new Locale(locale.getLanguage());
try
{
resources = ResourceBundle.getBundle(bundleName, locale, classLoader);
}
catch (MissingResourceException e4)
{
complainMissingBundle("No backup en bundle found! "+e4.getMessage(),e4,bundleName,locale);
return messageKey;
}
}
}
}
String message;
try
{
message = resources.getString(messageKey);
}
catch (MissingResourceException e)
{
complainMissingMessage("Missing resource '" + messageKey + "' in bundle '" + bundleName + "' for locale '"+locale.toString()+"'",
e,bundleName,locale,messageKey);
message = messageKey;
}
// Format the message
String formatMessage;
if (args != null)
{
MessageFormat fm = new MessageFormat(message);
fm.setLocale(locale);
formatMessage = fm.format(args);
}
else
{
formatMessage = message;
}
return formatMessage;
}
|
diff --git a/src/main/java/org/apache/couchdb/lucene/Index.java b/src/main/java/org/apache/couchdb/lucene/Index.java
index 9c1dab1..530dad4 100644
--- a/src/main/java/org/apache/couchdb/lucene/Index.java
+++ b/src/main/java/org/apache/couchdb/lucene/Index.java
@@ -1,520 +1,520 @@
package org.apache.couchdb.lucene;
import static java.lang.Math.min;
import static org.apache.couchdb.lucene.Utils.text;
import static org.apache.couchdb.lucene.Utils.token;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.Timer;
import java.util.TimerTask;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.lang.time.DurationFormatUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.FieldSelector;
import org.apache.lucene.document.MapFieldSelector;
import org.apache.lucene.document.NumberTools;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.IndexWriter.MaxFieldLength;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.ConstantScoreRangeQuery;
import org.apache.lucene.search.FieldDoc;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.SortField;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.TopFieldDocs;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.NIOFSDirectory;
/**
* High-level wrapper class over Lucene.
*/
public final class Index {
private void openReader() throws IOException {
final IndexReader oldReader;
synchronized (mutex) {
oldReader = this.reader;
}
final IndexReader newReader;
if (oldReader == null) {
newReader = IndexReader.open(dir, true);
} else {
newReader = oldReader.reopen();
}
if (oldReader != newReader) {
synchronized (mutex) {
this.reader = newReader;
this.reader.incRef();
this.searcher = new IndexSearcher(this.reader);
}
if (oldReader != null) {
oldReader.decRef();
}
}
}
private static final Logger log = LogManager.getLogger(Index.class);
private static final Tika TIKA = new Tika();
private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
private class IndexUpdateTask extends TimerTask {
@Override
public void run() {
IndexWriter writer = null;
boolean commit = false;
try {
final String[] dbnames = db.getAllDatabases();
writer = newWriter();
for (final String dbname : dbnames) {
commit |= updateDatabase(writer, dbname);
}
} catch (final IOException e) {
log.warn("Exception while indexing.", e);
commit = false;
} finally {
if (writer != null) {
try {
if (commit) {
writer.commit();
progress.save();
log.info("Committed updates.");
openReader();
if (reader.numDeletedDocs() >= Config.EXPUNGE_LIMIT) {
writer.expungeDeletes();
}
writer.close();
} else {
writer.rollback();
}
} catch (final IOException e) {
log.warn("Exception while committing.", e);
}
}
}
}
private boolean updateDatabase(final IndexWriter writer, final String dbname) throws HttpException, IOException {
final DbInfo info = db.getInfo(dbname);
long from = progress.getProgress(dbname);
long start = from;
if (from > info.getUpdateSeq()) {
start = from = -1;
progress.setProgress(dbname, -1);
}
if (from == -1) {
log.debug("index is missing or inconsistent, reindexing all documents for " + dbname);
writer.deleteDocuments(new Term(Config.DB, dbname));
}
boolean changed = false;
while (from < info.getUpdateSeq()) {
final JSONObject obj = db.getAllDocsBySeq(dbname, from, Config.BATCH_SIZE);
if (!obj.has("rows")) {
log.error("no rows found (" + obj + ").");
return false;
}
final JSONArray rows = obj.getJSONArray("rows");
for (int i = 0, max = rows.size(); i < max; i++) {
final JSONObject row = rows.getJSONObject(i);
final JSONObject value = row.optJSONObject("value");
final JSONObject doc = row.optJSONObject("doc");
if (doc != null) {
updateDocument(writer, dbname, rows.getJSONObject(i));
changed = true;
}
if (value != null && value.optBoolean("deleted")) {
writer.deleteDocuments(new Term(Config.ID, row.getString("id")));
changed = true;
}
}
from += Config.BATCH_SIZE;
}
progress.setProgress(dbname, info.getUpdateSeq());
if (changed) {
log.debug(String.format("%s: index caught up from %,d to %,d.", dbname, start, info.getUpdateSeq()));
}
return changed;
}
private void updateDocument(final IndexWriter writer, final String dbname, final JSONObject obj)
throws IOException {
final Document doc = new Document();
final JSONObject json = obj.getJSONObject("doc");
// Skip design documents.
if (json.getString(Config.ID).startsWith("_design")) {
return;
}
// Standard properties.
doc.add(token(Config.DB, dbname, false));
final String id = (String) json.remove(Config.ID);
final String rev = (String) json.remove(Config.REV);
// Index _id and _rev as tokens.
doc.add(token(Config.ID, id, true));
doc.add(token(Config.REV, rev, true));
// Index all attributes.
add(doc, null, json, false);
// Attachments
if (json.has("_attachments")) {
final JSONObject attachments = json.getJSONObject("_attachments");
final Iterator it = attachments.keys();
while (it.hasNext()) {
final String name = (String) it.next();
final JSONObject att = attachments.getJSONObject(name);
final String url = db.url(String.format("%s/%s/%s", dbname, db.encode(id), db.encode(name)));
final GetMethod get = new GetMethod(url);
try {
synchronized (db) {
final int sc = Database.CLIENT.executeMethod(get);
if (sc == 200) {
TIKA.parse(get.getResponseBodyAsStream(), att.getString("content_type"), doc);
} else {
log.warn("Failed to retrieve attachment: " + sc);
}
}
} finally {
get.releaseConnection();
}
}
}
// write it
writer.updateDocument(new Term(Config.ID, id), doc);
}
private void add(final Document out, final String key, final Object value, final boolean store) {
if (value instanceof JSONObject) {
final JSONObject json = (JSONObject) value;
for (final Object obj : json.keySet()) {
add(out, (String) obj, json.get(obj), store);
}
} else if (value instanceof String) {
try {
DATE_FORMAT.parse((String) value);
out.add(token(key, (String) value, store));
} catch (final java.text.ParseException e) {
out.add(text(key, (String) value, store));
}
} else if (value instanceof Number) {
final Number number = (Number) value;
if (value instanceof Long || value instanceof Integer) {
out.add(token(key, NumberTools.longToString(number.longValue()), store));
} else {
out.add(token(key, value.toString(), store));
}
} else if (value instanceof Boolean) {
out.add(token(key, value.toString(), store));
} else if (value instanceof JSONArray) {
final JSONArray arr = (JSONArray) value;
for (int i = 0, max = arr.size(); i < max; i++) {
add(out, key, arr.get(i), store);
}
} else if (value == null) {
log.warn(key + " was null.");
} else {
log.warn("Unsupported data type: " + value.getClass());
}
}
}
private static final FieldSelector FS = new MapFieldSelector(new String[] { Config.ID, Config.REV });
private final Database db = new Database(Config.DB_URL);
private final Timer timer = new Timer("IndexUpdater", true);
private final Directory dir;
private IndexReader reader;
private IndexSearcher searcher;
private final Progress progress;
private final Object mutex = new Object();
public Index() throws IOException {
final File f = new File(Config.INDEX_DIR);
dir = NIOFSDirectory.getDirectory(f);
if (!IndexReader.indexExists(dir)) {
newWriter().close();
}
this.progress = new Progress(f);
}
public void start() throws IOException {
log.info("couchdb-lucene is starting.");
if (IndexWriter.isLocked(dir)) {
log.warn("Forcibly unlocking locked index at startup.");
IndexWriter.unlock(dir);
}
Index.this.progress.load();
openReader();
log.info("couchdb-lucene is started.");
timer.schedule(new IndexUpdateTask(), 0, Config.REFRESH_INTERVAL);
}
public void stop() throws IOException {
log.info("couchdb-lucene is stopping.");
timer.cancel();
this.reader.close();
log.info("couchdb-lucene is stopped.");
}
public String query(final String dbname, final String query, final String sort_fields, final boolean ascending,
final int skip, final int limit, final boolean include_docs, final boolean debug) throws IOException,
ParseException {
if (limit > Config.MAX_LIMIT) {
return Utils.error("limit of " + limit + " exceeds maximum limit of " + Config.MAX_LIMIT);
}
final BooleanQuery bq = new BooleanQuery();
bq.add(new TermQuery(new Term(Config.DB, dbname)), Occur.MUST);
bq.add(parse(query), Occur.MUST);
final IndexSearcher searcher;
synchronized (mutex) {
searcher = this.searcher;
}
searcher.getIndexReader().incRef();
final TopDocs td;
final long start = System.nanoTime();
try {
if (sort_fields == null) {
td = searcher.search(bq, null, skip + limit);
} else {
final Sort sort;
if (sort_fields.indexOf(",") != -1) {
sort = new Sort(sort_fields.split(","));
} else {
sort = new Sort(sort_fields, !ascending);
}
td = searcher.search(bq, null, skip + limit, sort);
}
} finally {
searcher.getIndexReader().decRef();
}
final long search_duration = System.nanoTime() - start;
TopFieldDocs tfd = null;
if (td instanceof TopFieldDocs) {
tfd = (TopFieldDocs) td;
}
final JSONObject json = new JSONObject();
json.element("total_rows", td.totalHits);
// Report on sorting order, if specified.
if (tfd != null) {
final JSONArray sort_order = new JSONArray();
for (final SortField field : tfd.fields) {
final JSONObject col = new JSONObject();
col.element("field", field.getField());
col.element("reverse", field.getReverse());
final String type;
switch (field.getType()) {
case SortField.DOC:
type = "doc";
break;
case SortField.SCORE:
type = "score";
break;
case SortField.INT:
type = "int";
break;
case SortField.LONG:
type = "long";
break;
case SortField.BYTE:
type = "byte";
break;
case SortField.CUSTOM:
type = "custom";
break;
case SortField.DOUBLE:
type = "double";
break;
case SortField.FLOAT:
type = "float";
break;
case SortField.SHORT:
type = "short";
break;
case SortField.STRING:
type = "string";
break;
default:
type = "unknown";
break;
}
col.element("type", type);
sort_order.add(col);
}
json.element("sort_order", sort_order);
}
final int max = min(td.totalHits, limit);
final String[] fetch_ids = include_docs ? new String[max] : null;
final JSONArray rows = new JSONArray();
- for (int i = skip; i < max; i++) {
+ for (int i = skip; i < skip + max; i++) {
final Document doc = searcher.doc(td.scoreDocs[i].doc, FS);
final JSONObject obj = new JSONObject();
obj.element("_id", doc.get(Config.ID));
obj.element("_rev", doc.get(Config.REV));
obj.element("score", td.scoreDocs[i].score);
if (tfd != null) {
final FieldDoc fd = (FieldDoc) tfd.scoreDocs[i];
obj.element("sort_order", fd.fields);
}
if (fetch_ids != null) {
fetch_ids[i - skip] = obj.getString(Config.ID);
}
if (include_docs) {
obj.element("doc", db.getDoc(dbname, obj.getString("_id"), obj.getString("_rev")));
}
rows.add(obj);
}
if (fetch_ids != null) {
final JSONObject fetch_docs = db.getDocs(dbname, fetch_ids);
final JSONArray arr = fetch_docs.getJSONArray("rows");
for (int i = 0; i < max; i++) {
rows.getJSONObject(i).element("doc", arr.getJSONObject(i).getJSONObject("doc"));
}
}
json.element("rows", rows);
final long total_duration = System.nanoTime() - start;
final JSONObject result = new JSONObject();
result.element("code", 200);
if (debug) {
final StringBuilder builder = new StringBuilder(500);
// build basic lines.
builder.append("<dl>");
builder.append("<dt>database name</dt><dd>" + dbname + "</dd>");
builder.append("<dt>query</dt><dd>" + bq + "</dd>");
builder.append("<dt>sort</dt><dd>" + sort_fields + "</dd>");
builder.append("<dt>skip</dt><dd>" + skip + "</dd>");
builder.append("<dt>limit</dt><dd>" + limit + "</dd>");
builder.append("<dt>total_rows</dt><dd>" + json.getInt("total_rows") + "</dd>");
if (json.get("sort_order") != null) {
builder.append("<dt>sort_order</dt><dd>" + json.get("sort_order") + "</dd>");
}
builder.append("<dt>search duration</dt><dd>"
+ DurationFormatUtils.formatDurationHMS(search_duration / 1000000) + "</dd>");
builder.append("<dt>total duration</dt><dd>"
+ DurationFormatUtils.formatDurationHMS(total_duration / 1000000) + "</dd>");
builder.append("<dt>rows</dt><dd>");
builder.append("<ol start=\"" + skip + "\">");
for (int i = 0; i < rows.size(); i++) {
builder.append("<li>" + rows.get(i) + "</li>");
}
builder.append("</ol>");
builder.append("</dd>");
builder.append("</dl>");
result.element("body", builder.toString());
} else {
result.element("json", json);
}
return result.toString();
}
private Query parse(final String query) throws ParseException {
final Query result = Config.QP.parse(query);
return visit(result);
}
/**
* Visit (and optionally replace) any part of the query tree.
*
* Currently only rewrites {@link ConstantScoreRangeQuery} for numeric
* ranges.
*
* @param result
* @return
*/
private Query visit(final Query result) {
if (result instanceof BooleanQuery) {
final BooleanQuery bq = (BooleanQuery) result;
final BooleanClause[] bc = bq.getClauses();
for (int i = 0; i < bc.length; i++) {
bc[i].setQuery(visit(bc[i].getQuery()));
}
return result;
} else if (result instanceof ConstantScoreRangeQuery) {
final ConstantScoreRangeQuery rq = (ConstantScoreRangeQuery) result;
if (isNumericOrNull(rq.getLowerVal()) && isNumericOrNull(rq.getUpperVal())) {
return new ConstantScoreRangeQuery(rq.getField(), encodeNumber(rq.getLowerVal()), encodeNumber(rq
.getUpperVal()), rq.includesLower(), rq.includesUpper());
}
return result;
}
return result;
}
private boolean isNumericOrNull(final String val) {
if (val == null)
return true;
try {
Long.parseLong(val);
return true;
} catch (final NumberFormatException e) {
return false;
}
}
private String encodeNumber(final String num) {
return num == null ? null : NumberTools.longToString(Long.parseLong(num));
}
private IndexWriter newWriter() throws IOException {
final IndexWriter result = new IndexWriter(dir, Config.ANALYZER, MaxFieldLength.UNLIMITED);
result.setUseCompoundFile(false);
result.setRAMBufferSizeMB(Config.RAM_BUF);
return result;
}
}
| true | true | public String query(final String dbname, final String query, final String sort_fields, final boolean ascending,
final int skip, final int limit, final boolean include_docs, final boolean debug) throws IOException,
ParseException {
if (limit > Config.MAX_LIMIT) {
return Utils.error("limit of " + limit + " exceeds maximum limit of " + Config.MAX_LIMIT);
}
final BooleanQuery bq = new BooleanQuery();
bq.add(new TermQuery(new Term(Config.DB, dbname)), Occur.MUST);
bq.add(parse(query), Occur.MUST);
final IndexSearcher searcher;
synchronized (mutex) {
searcher = this.searcher;
}
searcher.getIndexReader().incRef();
final TopDocs td;
final long start = System.nanoTime();
try {
if (sort_fields == null) {
td = searcher.search(bq, null, skip + limit);
} else {
final Sort sort;
if (sort_fields.indexOf(",") != -1) {
sort = new Sort(sort_fields.split(","));
} else {
sort = new Sort(sort_fields, !ascending);
}
td = searcher.search(bq, null, skip + limit, sort);
}
} finally {
searcher.getIndexReader().decRef();
}
final long search_duration = System.nanoTime() - start;
TopFieldDocs tfd = null;
if (td instanceof TopFieldDocs) {
tfd = (TopFieldDocs) td;
}
final JSONObject json = new JSONObject();
json.element("total_rows", td.totalHits);
// Report on sorting order, if specified.
if (tfd != null) {
final JSONArray sort_order = new JSONArray();
for (final SortField field : tfd.fields) {
final JSONObject col = new JSONObject();
col.element("field", field.getField());
col.element("reverse", field.getReverse());
final String type;
switch (field.getType()) {
case SortField.DOC:
type = "doc";
break;
case SortField.SCORE:
type = "score";
break;
case SortField.INT:
type = "int";
break;
case SortField.LONG:
type = "long";
break;
case SortField.BYTE:
type = "byte";
break;
case SortField.CUSTOM:
type = "custom";
break;
case SortField.DOUBLE:
type = "double";
break;
case SortField.FLOAT:
type = "float";
break;
case SortField.SHORT:
type = "short";
break;
case SortField.STRING:
type = "string";
break;
default:
type = "unknown";
break;
}
col.element("type", type);
sort_order.add(col);
}
json.element("sort_order", sort_order);
}
final int max = min(td.totalHits, limit);
final String[] fetch_ids = include_docs ? new String[max] : null;
final JSONArray rows = new JSONArray();
for (int i = skip; i < max; i++) {
final Document doc = searcher.doc(td.scoreDocs[i].doc, FS);
final JSONObject obj = new JSONObject();
obj.element("_id", doc.get(Config.ID));
obj.element("_rev", doc.get(Config.REV));
obj.element("score", td.scoreDocs[i].score);
if (tfd != null) {
final FieldDoc fd = (FieldDoc) tfd.scoreDocs[i];
obj.element("sort_order", fd.fields);
}
if (fetch_ids != null) {
fetch_ids[i - skip] = obj.getString(Config.ID);
}
if (include_docs) {
obj.element("doc", db.getDoc(dbname, obj.getString("_id"), obj.getString("_rev")));
}
rows.add(obj);
}
if (fetch_ids != null) {
final JSONObject fetch_docs = db.getDocs(dbname, fetch_ids);
final JSONArray arr = fetch_docs.getJSONArray("rows");
for (int i = 0; i < max; i++) {
rows.getJSONObject(i).element("doc", arr.getJSONObject(i).getJSONObject("doc"));
}
}
json.element("rows", rows);
final long total_duration = System.nanoTime() - start;
final JSONObject result = new JSONObject();
result.element("code", 200);
if (debug) {
final StringBuilder builder = new StringBuilder(500);
// build basic lines.
builder.append("<dl>");
builder.append("<dt>database name</dt><dd>" + dbname + "</dd>");
builder.append("<dt>query</dt><dd>" + bq + "</dd>");
builder.append("<dt>sort</dt><dd>" + sort_fields + "</dd>");
builder.append("<dt>skip</dt><dd>" + skip + "</dd>");
builder.append("<dt>limit</dt><dd>" + limit + "</dd>");
builder.append("<dt>total_rows</dt><dd>" + json.getInt("total_rows") + "</dd>");
if (json.get("sort_order") != null) {
builder.append("<dt>sort_order</dt><dd>" + json.get("sort_order") + "</dd>");
}
builder.append("<dt>search duration</dt><dd>"
+ DurationFormatUtils.formatDurationHMS(search_duration / 1000000) + "</dd>");
builder.append("<dt>total duration</dt><dd>"
+ DurationFormatUtils.formatDurationHMS(total_duration / 1000000) + "</dd>");
builder.append("<dt>rows</dt><dd>");
builder.append("<ol start=\"" + skip + "\">");
for (int i = 0; i < rows.size(); i++) {
builder.append("<li>" + rows.get(i) + "</li>");
}
builder.append("</ol>");
builder.append("</dd>");
builder.append("</dl>");
result.element("body", builder.toString());
} else {
result.element("json", json);
}
return result.toString();
}
| public String query(final String dbname, final String query, final String sort_fields, final boolean ascending,
final int skip, final int limit, final boolean include_docs, final boolean debug) throws IOException,
ParseException {
if (limit > Config.MAX_LIMIT) {
return Utils.error("limit of " + limit + " exceeds maximum limit of " + Config.MAX_LIMIT);
}
final BooleanQuery bq = new BooleanQuery();
bq.add(new TermQuery(new Term(Config.DB, dbname)), Occur.MUST);
bq.add(parse(query), Occur.MUST);
final IndexSearcher searcher;
synchronized (mutex) {
searcher = this.searcher;
}
searcher.getIndexReader().incRef();
final TopDocs td;
final long start = System.nanoTime();
try {
if (sort_fields == null) {
td = searcher.search(bq, null, skip + limit);
} else {
final Sort sort;
if (sort_fields.indexOf(",") != -1) {
sort = new Sort(sort_fields.split(","));
} else {
sort = new Sort(sort_fields, !ascending);
}
td = searcher.search(bq, null, skip + limit, sort);
}
} finally {
searcher.getIndexReader().decRef();
}
final long search_duration = System.nanoTime() - start;
TopFieldDocs tfd = null;
if (td instanceof TopFieldDocs) {
tfd = (TopFieldDocs) td;
}
final JSONObject json = new JSONObject();
json.element("total_rows", td.totalHits);
// Report on sorting order, if specified.
if (tfd != null) {
final JSONArray sort_order = new JSONArray();
for (final SortField field : tfd.fields) {
final JSONObject col = new JSONObject();
col.element("field", field.getField());
col.element("reverse", field.getReverse());
final String type;
switch (field.getType()) {
case SortField.DOC:
type = "doc";
break;
case SortField.SCORE:
type = "score";
break;
case SortField.INT:
type = "int";
break;
case SortField.LONG:
type = "long";
break;
case SortField.BYTE:
type = "byte";
break;
case SortField.CUSTOM:
type = "custom";
break;
case SortField.DOUBLE:
type = "double";
break;
case SortField.FLOAT:
type = "float";
break;
case SortField.SHORT:
type = "short";
break;
case SortField.STRING:
type = "string";
break;
default:
type = "unknown";
break;
}
col.element("type", type);
sort_order.add(col);
}
json.element("sort_order", sort_order);
}
final int max = min(td.totalHits, limit);
final String[] fetch_ids = include_docs ? new String[max] : null;
final JSONArray rows = new JSONArray();
for (int i = skip; i < skip + max; i++) {
final Document doc = searcher.doc(td.scoreDocs[i].doc, FS);
final JSONObject obj = new JSONObject();
obj.element("_id", doc.get(Config.ID));
obj.element("_rev", doc.get(Config.REV));
obj.element("score", td.scoreDocs[i].score);
if (tfd != null) {
final FieldDoc fd = (FieldDoc) tfd.scoreDocs[i];
obj.element("sort_order", fd.fields);
}
if (fetch_ids != null) {
fetch_ids[i - skip] = obj.getString(Config.ID);
}
if (include_docs) {
obj.element("doc", db.getDoc(dbname, obj.getString("_id"), obj.getString("_rev")));
}
rows.add(obj);
}
if (fetch_ids != null) {
final JSONObject fetch_docs = db.getDocs(dbname, fetch_ids);
final JSONArray arr = fetch_docs.getJSONArray("rows");
for (int i = 0; i < max; i++) {
rows.getJSONObject(i).element("doc", arr.getJSONObject(i).getJSONObject("doc"));
}
}
json.element("rows", rows);
final long total_duration = System.nanoTime() - start;
final JSONObject result = new JSONObject();
result.element("code", 200);
if (debug) {
final StringBuilder builder = new StringBuilder(500);
// build basic lines.
builder.append("<dl>");
builder.append("<dt>database name</dt><dd>" + dbname + "</dd>");
builder.append("<dt>query</dt><dd>" + bq + "</dd>");
builder.append("<dt>sort</dt><dd>" + sort_fields + "</dd>");
builder.append("<dt>skip</dt><dd>" + skip + "</dd>");
builder.append("<dt>limit</dt><dd>" + limit + "</dd>");
builder.append("<dt>total_rows</dt><dd>" + json.getInt("total_rows") + "</dd>");
if (json.get("sort_order") != null) {
builder.append("<dt>sort_order</dt><dd>" + json.get("sort_order") + "</dd>");
}
builder.append("<dt>search duration</dt><dd>"
+ DurationFormatUtils.formatDurationHMS(search_duration / 1000000) + "</dd>");
builder.append("<dt>total duration</dt><dd>"
+ DurationFormatUtils.formatDurationHMS(total_duration / 1000000) + "</dd>");
builder.append("<dt>rows</dt><dd>");
builder.append("<ol start=\"" + skip + "\">");
for (int i = 0; i < rows.size(); i++) {
builder.append("<li>" + rows.get(i) + "</li>");
}
builder.append("</ol>");
builder.append("</dd>");
builder.append("</dl>");
result.element("body", builder.toString());
} else {
result.element("json", json);
}
return result.toString();
}
|
diff --git a/AE-go_GameServer/src/com/aionemu/gameserver/model/gameobjects/stats/listeners/ItemEquipmentListener.java b/AE-go_GameServer/src/com/aionemu/gameserver/model/gameobjects/stats/listeners/ItemEquipmentListener.java
index eb1ea080..bb38d047 100644
--- a/AE-go_GameServer/src/com/aionemu/gameserver/model/gameobjects/stats/listeners/ItemEquipmentListener.java
+++ b/AE-go_GameServer/src/com/aionemu/gameserver/model/gameobjects/stats/listeners/ItemEquipmentListener.java
@@ -1,78 +1,82 @@
/*
* This file is part of aion-emu <aion-emu.com>.
*
* aion-emu is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* aion-emu 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with aion-emu. If not, see <http://www.gnu.org/licenses/>.
*/
package com.aionemu.gameserver.model.gameobjects.stats.listeners;
import org.apache.log4j.Logger;
import com.aionemu.gameserver.model.ItemSlot;
import com.aionemu.gameserver.model.gameobjects.Item;
import com.aionemu.gameserver.model.gameobjects.player.Inventory;
import com.aionemu.gameserver.model.gameobjects.stats.PlayerGameStats;
import com.aionemu.gameserver.model.templates.ItemTemplate;
/**
* @author xavier
*/
public class ItemEquipmentListener
{
private static final Logger log = Logger.getLogger(ItemEquipmentListener.class);
public static void onItemEquipmentChange(Inventory inventory, Item item)
{
int sign = 1;
ItemTemplate it = item.getItemTemplate();
if (inventory.getOwner()==null) {
log.debug("No owner set for inventory, not changing stats");
return;
}
PlayerGameStats pgs = inventory.getOwner().getGameStats();
if (pgs==null) {
log.debug("No GameStats set for inventory owner, skipping stats change");
return;
}
if ((!it.isArmor())&&(!it.isWeapon())) {
log.debug("Item #"+item.getObjectId()+" isn't an equipment, not changing stats");
return;
}
if (!item.isEquipped()) {
sign = -1;
}
- switch(ItemSlot.getValue(item.getEquipmentSlot()))
+ ItemSlot itemSlot = null;
+ try {
+ itemSlot = ItemSlot.getValue(item.getEquipmentSlot());
+ } catch (IllegalArgumentException e) { }
+ switch(itemSlot)
{
case MAIN_HAND:
pgs.setMainHandAttack(pgs.getMainHandAttack() + sign*it.getMaxDamage());
pgs.setMainHandCritRate(pgs.getMainHandCritRate() + sign*it.getCritical());
pgs.setMainHandAccuracy(pgs.getMainHandAccuracy() + sign*it.getHitAccuracy());
break;
case SUB_HAND:
pgs.setOffHandAttack(pgs.getOffHandAttack() + sign*it.getMaxDamage());
pgs.setOffHandCritRate(pgs.getOffHandCritRate() + sign*it.getCritical());
pgs.setOffHandAccuracy(pgs.getOffHandAccuracy() + sign*it.getHitAccuracy());
break;
default:
break;
}
pgs.setAgility(pgs.getAgility() + sign*it.getAgility());
pgs.setKnowledge(pgs.getKnowledge() + sign*it.getKnowledge());
pgs.setPhysicalDefense(pgs.getPhysicalDefense() + sign*it.getPhysicalDefend());
pgs.setParry(pgs.getParry() + sign*it.getParrry());
pgs.setMagicBoost(pgs.getMagicBoost() + sign*it.getMagicalSkillBoost());
pgs.setMagicAccuracy(pgs.getMagicAccuracy() + sign*it.getMagicalHitAccuracy());
pgs.setMagicResistance(pgs.getMagicResistance() + sign*it.getMagicalResist());
log.debug("Changed stats after equipment change of item "+"{#:"+it.getItemId()+",slot:"+it.getItemSlot()+"} to player #"+inventory.getOwner().getObjectId()+":"+pgs);
}
}
| true | true | public static void onItemEquipmentChange(Inventory inventory, Item item)
{
int sign = 1;
ItemTemplate it = item.getItemTemplate();
if (inventory.getOwner()==null) {
log.debug("No owner set for inventory, not changing stats");
return;
}
PlayerGameStats pgs = inventory.getOwner().getGameStats();
if (pgs==null) {
log.debug("No GameStats set for inventory owner, skipping stats change");
return;
}
if ((!it.isArmor())&&(!it.isWeapon())) {
log.debug("Item #"+item.getObjectId()+" isn't an equipment, not changing stats");
return;
}
if (!item.isEquipped()) {
sign = -1;
}
switch(ItemSlot.getValue(item.getEquipmentSlot()))
{
case MAIN_HAND:
pgs.setMainHandAttack(pgs.getMainHandAttack() + sign*it.getMaxDamage());
pgs.setMainHandCritRate(pgs.getMainHandCritRate() + sign*it.getCritical());
pgs.setMainHandAccuracy(pgs.getMainHandAccuracy() + sign*it.getHitAccuracy());
break;
case SUB_HAND:
pgs.setOffHandAttack(pgs.getOffHandAttack() + sign*it.getMaxDamage());
pgs.setOffHandCritRate(pgs.getOffHandCritRate() + sign*it.getCritical());
pgs.setOffHandAccuracy(pgs.getOffHandAccuracy() + sign*it.getHitAccuracy());
break;
default:
break;
}
pgs.setAgility(pgs.getAgility() + sign*it.getAgility());
pgs.setKnowledge(pgs.getKnowledge() + sign*it.getKnowledge());
pgs.setPhysicalDefense(pgs.getPhysicalDefense() + sign*it.getPhysicalDefend());
pgs.setParry(pgs.getParry() + sign*it.getParrry());
pgs.setMagicBoost(pgs.getMagicBoost() + sign*it.getMagicalSkillBoost());
pgs.setMagicAccuracy(pgs.getMagicAccuracy() + sign*it.getMagicalHitAccuracy());
pgs.setMagicResistance(pgs.getMagicResistance() + sign*it.getMagicalResist());
log.debug("Changed stats after equipment change of item "+"{#:"+it.getItemId()+",slot:"+it.getItemSlot()+"} to player #"+inventory.getOwner().getObjectId()+":"+pgs);
}
| public static void onItemEquipmentChange(Inventory inventory, Item item)
{
int sign = 1;
ItemTemplate it = item.getItemTemplate();
if (inventory.getOwner()==null) {
log.debug("No owner set for inventory, not changing stats");
return;
}
PlayerGameStats pgs = inventory.getOwner().getGameStats();
if (pgs==null) {
log.debug("No GameStats set for inventory owner, skipping stats change");
return;
}
if ((!it.isArmor())&&(!it.isWeapon())) {
log.debug("Item #"+item.getObjectId()+" isn't an equipment, not changing stats");
return;
}
if (!item.isEquipped()) {
sign = -1;
}
ItemSlot itemSlot = null;
try {
itemSlot = ItemSlot.getValue(item.getEquipmentSlot());
} catch (IllegalArgumentException e) { }
switch(itemSlot)
{
case MAIN_HAND:
pgs.setMainHandAttack(pgs.getMainHandAttack() + sign*it.getMaxDamage());
pgs.setMainHandCritRate(pgs.getMainHandCritRate() + sign*it.getCritical());
pgs.setMainHandAccuracy(pgs.getMainHandAccuracy() + sign*it.getHitAccuracy());
break;
case SUB_HAND:
pgs.setOffHandAttack(pgs.getOffHandAttack() + sign*it.getMaxDamage());
pgs.setOffHandCritRate(pgs.getOffHandCritRate() + sign*it.getCritical());
pgs.setOffHandAccuracy(pgs.getOffHandAccuracy() + sign*it.getHitAccuracy());
break;
default:
break;
}
pgs.setAgility(pgs.getAgility() + sign*it.getAgility());
pgs.setKnowledge(pgs.getKnowledge() + sign*it.getKnowledge());
pgs.setPhysicalDefense(pgs.getPhysicalDefense() + sign*it.getPhysicalDefend());
pgs.setParry(pgs.getParry() + sign*it.getParrry());
pgs.setMagicBoost(pgs.getMagicBoost() + sign*it.getMagicalSkillBoost());
pgs.setMagicAccuracy(pgs.getMagicAccuracy() + sign*it.getMagicalHitAccuracy());
pgs.setMagicResistance(pgs.getMagicResistance() + sign*it.getMagicalResist());
log.debug("Changed stats after equipment change of item "+"{#:"+it.getItemId()+",slot:"+it.getItemSlot()+"} to player #"+inventory.getOwner().getObjectId()+":"+pgs);
}
|
diff --git a/src/main/java/me/ayan4m1/plugins/zombo/ZomboCraftRecipe.java b/src/main/java/me/ayan4m1/plugins/zombo/ZomboCraftRecipe.java
index 80d1a41..f1cdfbe 100644
--- a/src/main/java/me/ayan4m1/plugins/zombo/ZomboCraftRecipe.java
+++ b/src/main/java/me/ayan4m1/plugins/zombo/ZomboCraftRecipe.java
@@ -1,86 +1,89 @@
package me.ayan4m1.plugins.zombo;
import java.util.ArrayList;
import org.bukkit.Material;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
public class ZomboCraftRecipe {
private ArrayList<ItemStack> reagents = new ArrayList<ItemStack>();
private ArrayList<String> enchants = new ArrayList<String>();
private Material outputType = Material.AIR;
private String name = "";
private Integer xpCost = 0;
public ArrayList<ItemStack> getReagents() {
return reagents;
}
public void setReagents(ArrayList<ItemStack> reagents) {
this.reagents = reagents;
}
public ArrayList<String> getEnchants() {
return enchants;
}
public void setEnchants(ArrayList<String> outputEffects) {
this.enchants = outputEffects;
}
public Material getOutputType() {
return outputType;
}
public void setOutputType(Material outputType) {
this.outputType = outputType;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getXpCost() {
return xpCost;
}
public void setXpCost(Integer xpCost) {
this.xpCost = xpCost;
}
public ZomboCraftRecipe() {
this.outputType = Material.AIR;
this.enchants = new ArrayList<String>();
this.reagents = new ArrayList<ItemStack>();
}
public ZomboCraftRecipe(Material outputType, ArrayList<ItemStack> reagents) {
this.outputType = outputType;
this.enchants = new ArrayList<String>();
this.reagents = reagents;
}
public ZomboCraftRecipe(Material outputType, ArrayList<String> enchants, ArrayList<ItemStack> reagents) {
this.outputType = outputType;
this.enchants = enchants;
this.reagents = reagents;
}
public void addEnchant(String enchantmentName) {
this.enchants.add(enchantmentName);
}
public boolean craftable(Inventory inventory) {
for(ItemStack item : reagents) {
if (item != null && inventory.contains(item)) {
return false;
}
}
+ if (!inventory.contains(outputType)) {
+ return false;
+ }
return true;
}
}
| true | true | public boolean craftable(Inventory inventory) {
for(ItemStack item : reagents) {
if (item != null && inventory.contains(item)) {
return false;
}
}
return true;
}
| public boolean craftable(Inventory inventory) {
for(ItemStack item : reagents) {
if (item != null && inventory.contains(item)) {
return false;
}
}
if (!inventory.contains(outputType)) {
return false;
}
return true;
}
|
diff --git a/src/main/java/ch/bfh/bti7081/s2013/blue/service/PrescriptionService.java b/src/main/java/ch/bfh/bti7081/s2013/blue/service/PrescriptionService.java
index 4b5873e..37727c8 100644
--- a/src/main/java/ch/bfh/bti7081/s2013/blue/service/PrescriptionService.java
+++ b/src/main/java/ch/bfh/bti7081/s2013/blue/service/PrescriptionService.java
@@ -1,95 +1,95 @@
package ch.bfh.bti7081.s2013.blue.service;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import ch.bfh.bti7081.s2013.blue.entities.Patient;
import ch.bfh.bti7081.s2013.blue.entities.PrescriptionItem;
public class PrescriptionService {
private static PrescriptionService prescriptionService = null;
private PrescriptionService() {
}
public static PrescriptionService getInstance() {
if (prescriptionService == null) {
prescriptionService = new PrescriptionService();
}
return prescriptionService;
}
/**
* returns a list with DailyPrescirptions of the next 7 days
* @param patient
* @return dailyPrescriptions
*/
public List<DailyPrescription> getDailyPrescriptions(Patient patient) {
EntityManager em = PatientService.getInstance().getEntityManager();
TypedQuery<PrescriptionItem> query = em.createQuery("SELECT item FROM PrescriptionItem item " +
"WHERE item.prescription.patient=:patient", PrescriptionItem.class);
query.setParameter("patient", patient);
List<PrescriptionItem> items = query.getResultList();
List<DailyPrescription> dailyPrescriptions = new ArrayList<DailyPrescription>();
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Calendar endOfDay = (Calendar) calendar.clone();
endOfDay.add(Calendar.DAY_OF_MONTH, 1);
for (int i = 0; i < 7; i++) {
DailyPrescription dailyPrescription = new DailyPrescription();
dailyPrescription.setDate(calendar.getTime());
calendar.add(Calendar.DAY_OF_MONTH, 1);
endOfDay.add(Calendar.DAY_OF_MONTH, 1);
for (PrescriptionItem item : items) {
- if (item.getStartDate().getTime() < endOfDay.getTime().getTime() && item.getEndDate().getTime() > calendar.getTime().getTime()) {
+ //if (item.getStartDate().getTime() < endOfDay.getTime().getTime() && item.getEndDate().getTime() > calendar.getTime().getTime()) {
if (item.getMorning() > 0) {
dailyPrescription.getMorningDrugs().put(item.getMedicalDrug(), item.getMorning());
}
if (item.getNoon() > 0) {
dailyPrescription.getNoonDrugs().put(item.getMedicalDrug(), item.getNoon());
}
if (item.getEvening() > 0) {
dailyPrescription.getEveningDrugs().put(item.getMedicalDrug(), item.getEvening());
}
if (item.getNight() > 0) {
dailyPrescription.getNightDrugs().put(item.getMedicalDrug(), item.getNight());
}
- }
+ //}
}
dailyPrescriptions.add(dailyPrescription);
}
return dailyPrescriptions;
}
/**
* Returns a list of all prescriptions
*
* @param patient
* @return prescriptions
*/
public List<PrescriptionItem> getPrescriptions(Patient patient) {
EntityManager em = PatientService.getInstance().getEntityManager();
List<PrescriptionItem> prescriptions = new ArrayList<PrescriptionItem>();
TypedQuery<PrescriptionItem> query = em.createQuery("SELECT item FROM PrescriptionItem item " +
"WHERE item.prescription.patient=:patient", PrescriptionItem.class);
query.setParameter("patient", patient);
prescriptions = query.getResultList();
return prescriptions;
}
}
| false | true | public List<DailyPrescription> getDailyPrescriptions(Patient patient) {
EntityManager em = PatientService.getInstance().getEntityManager();
TypedQuery<PrescriptionItem> query = em.createQuery("SELECT item FROM PrescriptionItem item " +
"WHERE item.prescription.patient=:patient", PrescriptionItem.class);
query.setParameter("patient", patient);
List<PrescriptionItem> items = query.getResultList();
List<DailyPrescription> dailyPrescriptions = new ArrayList<DailyPrescription>();
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Calendar endOfDay = (Calendar) calendar.clone();
endOfDay.add(Calendar.DAY_OF_MONTH, 1);
for (int i = 0; i < 7; i++) {
DailyPrescription dailyPrescription = new DailyPrescription();
dailyPrescription.setDate(calendar.getTime());
calendar.add(Calendar.DAY_OF_MONTH, 1);
endOfDay.add(Calendar.DAY_OF_MONTH, 1);
for (PrescriptionItem item : items) {
if (item.getStartDate().getTime() < endOfDay.getTime().getTime() && item.getEndDate().getTime() > calendar.getTime().getTime()) {
if (item.getMorning() > 0) {
dailyPrescription.getMorningDrugs().put(item.getMedicalDrug(), item.getMorning());
}
if (item.getNoon() > 0) {
dailyPrescription.getNoonDrugs().put(item.getMedicalDrug(), item.getNoon());
}
if (item.getEvening() > 0) {
dailyPrescription.getEveningDrugs().put(item.getMedicalDrug(), item.getEvening());
}
if (item.getNight() > 0) {
dailyPrescription.getNightDrugs().put(item.getMedicalDrug(), item.getNight());
}
}
}
dailyPrescriptions.add(dailyPrescription);
}
return dailyPrescriptions;
}
| public List<DailyPrescription> getDailyPrescriptions(Patient patient) {
EntityManager em = PatientService.getInstance().getEntityManager();
TypedQuery<PrescriptionItem> query = em.createQuery("SELECT item FROM PrescriptionItem item " +
"WHERE item.prescription.patient=:patient", PrescriptionItem.class);
query.setParameter("patient", patient);
List<PrescriptionItem> items = query.getResultList();
List<DailyPrescription> dailyPrescriptions = new ArrayList<DailyPrescription>();
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Calendar endOfDay = (Calendar) calendar.clone();
endOfDay.add(Calendar.DAY_OF_MONTH, 1);
for (int i = 0; i < 7; i++) {
DailyPrescription dailyPrescription = new DailyPrescription();
dailyPrescription.setDate(calendar.getTime());
calendar.add(Calendar.DAY_OF_MONTH, 1);
endOfDay.add(Calendar.DAY_OF_MONTH, 1);
for (PrescriptionItem item : items) {
//if (item.getStartDate().getTime() < endOfDay.getTime().getTime() && item.getEndDate().getTime() > calendar.getTime().getTime()) {
if (item.getMorning() > 0) {
dailyPrescription.getMorningDrugs().put(item.getMedicalDrug(), item.getMorning());
}
if (item.getNoon() > 0) {
dailyPrescription.getNoonDrugs().put(item.getMedicalDrug(), item.getNoon());
}
if (item.getEvening() > 0) {
dailyPrescription.getEveningDrugs().put(item.getMedicalDrug(), item.getEvening());
}
if (item.getNight() > 0) {
dailyPrescription.getNightDrugs().put(item.getMedicalDrug(), item.getNight());
}
//}
}
dailyPrescriptions.add(dailyPrescription);
}
return dailyPrescriptions;
}
|
diff --git a/src/bitstercli/Cli.java b/src/bitstercli/Cli.java
index eac366c..ea338b9 100644
--- a/src/bitstercli/Cli.java
+++ b/src/bitstercli/Cli.java
@@ -1,88 +1,88 @@
package bitstercli;
import java.util.ArrayList;
import libbitster.Actor;
import libbitster.Janitor;
import libbitster.Log;
import libbitster.Manager;
import libbitster.Memo;
/**
* Singleton. Command line interface class.
* @author Martin Miralles-Cordal
*/
public class Cli extends Actor {
private static Cli instance = null;
private ArrayList<Manager> managers;
private String prompt = "bitster]> ";
private String state;
private ConcurrentScanner s;
private Cli() {
super();
state = "init";
managers = new ArrayList<Manager>();
s = new ConcurrentScanner(System.in);
}
protected void receive (Memo memo) {
if(memo.getType().equals("done") && memo.getSender() instanceof Manager) {
Manager m = (Manager) memo.getSender();
System.out.println(m.getFileName() + " complete!");
System.out.print(prompt);
}
}
public void idle() {
if(state.equals("init")) {
System.out.println("Welcome to Bitster! Type \"quit\" to quit.");
System.out.println("------------------------------------------");
state = "running";
}
- System.out.print(prompt);
String in = s.next();
if(in != null) {
if(in.equals("quit")) {
Janitor.getInstance().start();
shutdown();
}
else if(in.equals("status")) {
printProgress();
}
else {
System.out.println("Usage instructions:");
System.out.println("status - shows download status");
System.out.println("quit - quits bitster");
}
+ System.out.print(prompt);
}
try { Thread.sleep(100); } catch (InterruptedException e) {}
}
public static Cli getInstance() {
if(instance == null) {
instance = new Cli();
}
return instance;
}
public void printProgress() {
for(Manager manager : managers) {
int percentDone = (int)(100*((1.0*manager.getDownloaded())/(manager.getDownloaded() + manager.getLeft())));
String ratio = String.format("%.2f", (1.0f * manager.getUploaded() / manager.getDownloaded()));
int numDots = percentDone/2;
int i;
System.out.print(manager.getFileName() + ": [");
System.out.print(Log.green());
for(i = 0; i < numDots; i++) System.out.print("=");
System.out.print(Log.red());
for( ; i < 50; i++) System.out.print("-");
System.out.print(Log.sane() + "]" + percentDone + "%" + " [R: " + ratio + "]\n");
}
}
public void addManager(Manager manager) { this.managers.add(manager); }
}
| false | true | public void idle() {
if(state.equals("init")) {
System.out.println("Welcome to Bitster! Type \"quit\" to quit.");
System.out.println("------------------------------------------");
state = "running";
}
System.out.print(prompt);
String in = s.next();
if(in != null) {
if(in.equals("quit")) {
Janitor.getInstance().start();
shutdown();
}
else if(in.equals("status")) {
printProgress();
}
else {
System.out.println("Usage instructions:");
System.out.println("status - shows download status");
System.out.println("quit - quits bitster");
}
}
try { Thread.sleep(100); } catch (InterruptedException e) {}
}
| public void idle() {
if(state.equals("init")) {
System.out.println("Welcome to Bitster! Type \"quit\" to quit.");
System.out.println("------------------------------------------");
state = "running";
}
String in = s.next();
if(in != null) {
if(in.equals("quit")) {
Janitor.getInstance().start();
shutdown();
}
else if(in.equals("status")) {
printProgress();
}
else {
System.out.println("Usage instructions:");
System.out.println("status - shows download status");
System.out.println("quit - quits bitster");
}
System.out.print(prompt);
}
try { Thread.sleep(100); } catch (InterruptedException e) {}
}
|
diff --git a/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/commands/shared/AbstractSharedCommandHandler.java b/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/commands/shared/AbstractSharedCommandHandler.java
index 700ef26a..e63408a6 100644
--- a/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/commands/shared/AbstractSharedCommandHandler.java
+++ b/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/commands/shared/AbstractSharedCommandHandler.java
@@ -1,132 +1,136 @@
/*******************************************************************************
* Copyright (c) 2010 SAP AG.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Mathias Kinzler (SAP AG) - initial implementation
* Dariusz Luksza <[email protected]> - add getRef() and getShell methods
*******************************************************************************/
package org.eclipse.egit.ui.internal.commands.shared;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.egit.core.project.RepositoryMapping;
import org.eclipse.egit.ui.internal.repository.tree.RefNode;
import org.eclipse.egit.ui.internal.repository.tree.RepositoryTreeNode;
import org.eclipse.egit.ui.internal.repository.tree.RepositoryTreeNodeType;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.handlers.HandlerUtil;
/**
* Abstract super class for commands shared between different components in EGit
*/
public abstract class AbstractSharedCommandHandler extends AbstractHandler {
private static final IWorkbench WORKBENCH = PlatformUI.getWorkbench();
/**
* @param event
* the {@link ExecutionEvent}
* @return a {@link Repository} if all elements in the current selection map
* to the same {@link Repository}, otherwise null
*/
protected Repository getRepository(ExecutionEvent event) {
ISelection selection = HandlerUtil.getCurrentSelection(event);
return getRepository(selection);
}
/**
* Get repository from selection
*
* @param selection
* @return a {@link Repository} if all elements in the current selection map
* to the same {@link Repository}, otherwise null
*/
protected Repository getRepository(ISelection selection) {
if (selection == null || selection.isEmpty())
return null;
if (selection instanceof IStructuredSelection) {
IStructuredSelection ssel = (IStructuredSelection) selection;
Repository result = null;
for (Object element : ssel.toList()) {
Repository elementRepository = null;
if (element instanceof RepositoryTreeNode) {
elementRepository = ((RepositoryTreeNode) element)
.getRepository();
} else if (element instanceof IResource) {
IResource resource = (IResource) element;
RepositoryMapping mapping = RepositoryMapping
.getMapping(resource.getProject());
if (mapping != null)
elementRepository = mapping.getRepository();
} else if (element instanceof IAdaptable) {
IResource adapted = (IResource) ((IAdaptable) element)
.getAdapter(IResource.class);
if (adapted != null) {
RepositoryMapping mapping = RepositoryMapping
.getMapping(adapted.getProject());
if (mapping != null)
elementRepository = mapping.getRepository();
}
}
if (elementRepository == null)
continue;
if (result != null && !elementRepository.equals(result))
return null;
if (result == null)
result = elementRepository;
}
return result;
}
if (selection instanceof TextSelection) {
IEditorInput activeEditor = WORKBENCH.getActiveWorkbenchWindow()
.getActivePage().getActiveEditor().getEditorInput();
IResource resource = (IResource) activeEditor
.getAdapter(IResource.class);
- if (resource != null)
- return RepositoryMapping.getMapping(resource).getRepository();
+ if (resource != null) {
+ RepositoryMapping mapping = RepositoryMapping
+ .getMapping(resource);
+ if (mapping != null)
+ return mapping.getRepository();
+ }
}
return null;
}
/**
*
* @param selected
* @return {@link Ref} connected with given {@code selected} node or
* {@code null} when ref cannot be determined
*/
protected Ref getRef(Object selected) {
if (selected instanceof RepositoryTreeNode<?>) {
RepositoryTreeNode node = (RepositoryTreeNode) selected;
if (node.getType() == RepositoryTreeNodeType.REF)
return ((RefNode) node).getObject();
}
return null;
}
/**
*
* @param event
* @return {@link Shell} connected with given {@code event}, or {@code null}
* when shell cannot be determined
*/
protected Shell getShell(ExecutionEvent event) {
return HandlerUtil.getActiveShell(event);
}
}
| true | true | protected Repository getRepository(ISelection selection) {
if (selection == null || selection.isEmpty())
return null;
if (selection instanceof IStructuredSelection) {
IStructuredSelection ssel = (IStructuredSelection) selection;
Repository result = null;
for (Object element : ssel.toList()) {
Repository elementRepository = null;
if (element instanceof RepositoryTreeNode) {
elementRepository = ((RepositoryTreeNode) element)
.getRepository();
} else if (element instanceof IResource) {
IResource resource = (IResource) element;
RepositoryMapping mapping = RepositoryMapping
.getMapping(resource.getProject());
if (mapping != null)
elementRepository = mapping.getRepository();
} else if (element instanceof IAdaptable) {
IResource adapted = (IResource) ((IAdaptable) element)
.getAdapter(IResource.class);
if (adapted != null) {
RepositoryMapping mapping = RepositoryMapping
.getMapping(adapted.getProject());
if (mapping != null)
elementRepository = mapping.getRepository();
}
}
if (elementRepository == null)
continue;
if (result != null && !elementRepository.equals(result))
return null;
if (result == null)
result = elementRepository;
}
return result;
}
if (selection instanceof TextSelection) {
IEditorInput activeEditor = WORKBENCH.getActiveWorkbenchWindow()
.getActivePage().getActiveEditor().getEditorInput();
IResource resource = (IResource) activeEditor
.getAdapter(IResource.class);
if (resource != null)
return RepositoryMapping.getMapping(resource).getRepository();
}
return null;
}
| protected Repository getRepository(ISelection selection) {
if (selection == null || selection.isEmpty())
return null;
if (selection instanceof IStructuredSelection) {
IStructuredSelection ssel = (IStructuredSelection) selection;
Repository result = null;
for (Object element : ssel.toList()) {
Repository elementRepository = null;
if (element instanceof RepositoryTreeNode) {
elementRepository = ((RepositoryTreeNode) element)
.getRepository();
} else if (element instanceof IResource) {
IResource resource = (IResource) element;
RepositoryMapping mapping = RepositoryMapping
.getMapping(resource.getProject());
if (mapping != null)
elementRepository = mapping.getRepository();
} else if (element instanceof IAdaptable) {
IResource adapted = (IResource) ((IAdaptable) element)
.getAdapter(IResource.class);
if (adapted != null) {
RepositoryMapping mapping = RepositoryMapping
.getMapping(adapted.getProject());
if (mapping != null)
elementRepository = mapping.getRepository();
}
}
if (elementRepository == null)
continue;
if (result != null && !elementRepository.equals(result))
return null;
if (result == null)
result = elementRepository;
}
return result;
}
if (selection instanceof TextSelection) {
IEditorInput activeEditor = WORKBENCH.getActiveWorkbenchWindow()
.getActivePage().getActiveEditor().getEditorInput();
IResource resource = (IResource) activeEditor
.getAdapter(IResource.class);
if (resource != null) {
RepositoryMapping mapping = RepositoryMapping
.getMapping(resource);
if (mapping != null)
return mapping.getRepository();
}
}
return null;
}
|
diff --git a/mpicbg/ij/clahe/Flat.java b/mpicbg/ij/clahe/Flat.java
index ee27d65..22e0f10 100644
--- a/mpicbg/ij/clahe/Flat.java
+++ b/mpicbg/ij/clahe/Flat.java
@@ -1,259 +1,273 @@
/**
* License: GPL
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License 2
* as published by the Free Software Foundation.
*
* 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package mpicbg.ij.clahe;
import java.awt.Rectangle;
import ij.ImagePlus;
import ij.gui.Roi;
import ij.process.ByteProcessor;
import ij.process.ImageProcessor;
/**
* &lsquot;Contrast Limited Adaptive Histogram Equalization&rsquot; as
* described in
*
* <br />BibTeX:
* <pre>
* @article{zuiderveld94,
* author = {Zuiderveld, Karel},
* title = {Contrast limited adaptive histogram equalization},
* book = {Graphics gems IV},
* year = {1994},
* isbn = {0-12-336155-9},
* pages = {474--485},
* publisher = {Academic Press Professional, Inc.},
* address = {San Diego, CA, USA},
* }
* </pre>
*
* @author Stephan Saalfeld <[email protected]>
* @version 0.1b
*/
public class Flat
{
/**
* Process and {@link ImagePlus} with a given set of parameters. Create
* mask and bounding box from the {@link Roi} of that {@link ImagePlus} and
* the passed mask if any.
*
* @param imp
* @param blockRadius
* @param bins
* @param slope
* @param mask can be null
*/
final static public void run(
final ImagePlus imp,
final int blockRadius,
final int bins,
final float slope,
final ByteProcessor mask )
{
final Roi roi = imp.getRoi();
if ( roi == null )
run( imp, blockRadius, bins, slope, null, mask );
else
{
final Rectangle roiBox = roi.getBounds();
final ImageProcessor roiMask = roi.getMask();
if ( mask != null )
{
final Rectangle oldRoi = mask.getRoi();
mask.setRoi( roi );
final ByteProcessor cropMask = ( ByteProcessor )mask.crop().convertToByte( true );
if ( roiMask != null )
{
final byte[] roiMaskPixels = ( byte[] )roiMask.getPixels();
final byte[] cropMaskPixels = ( byte[] )cropMask.getPixels();
for ( int i = 0; i < roiMaskPixels.length; ++i )
cropMaskPixels[ i ] = ( byte )Util.roundPositive( ( cropMaskPixels[ i ] & 0xff ) * ( roiMaskPixels[ i ] & 0xff ) / 255.0f );
}
run( imp, blockRadius, bins, slope, roiBox, cropMask );
mask.setRoi( oldRoi );
}
else if ( roiMask == null )
run( imp, blockRadius, bins, slope, roiBox, null );
else
run( imp, blockRadius, bins, slope, roiBox, ( ByteProcessor )roiMask.convertToByte( false ) );
}
}
/**
* Process and {@link ImagePlus} with a given set of parameters including
* the bounding box and mask.
*
* @param imp
* @param blockRadius
* @param bins
* @param slope
* @param roiBox can be null
* @param mask can be null
*/
final static public void run(
final ImagePlus imp,
final int blockRadius,
final int bins,
final float slope,
final java.awt.Rectangle roiBox,
final ByteProcessor mask )
{
/* initialize box if necessary */
final Rectangle box;
if ( roiBox == null )
{
if ( mask == null )
box = new Rectangle( 0, 0, imp.getWidth(), imp.getHeight() );
else
box = new Rectangle( 0, 0, Math.min( imp.getWidth(), mask.getWidth() ), Math.min( imp.getHeight(), mask.getHeight() ) );
}
else
box = roiBox;
/* make sure that the box is not larger than the mask */
if ( mask != null )
{
box.width = Math.min( mask.getWidth(), box.width );
box.height = Math.min( mask.getHeight(), box.height );
}
/* make sure that the box is not larger than the image */
box.width = Math.min( imp.getWidth() - box.x, box.width );
box.height = Math.min( imp.getHeight() - box.y, box.height );
final int boxXMax = box.x + box.width;
final int boxYMax = box.y + box.height;
/* convert 8bit processors with a LUT to RGB and create Undo-step */
final ImageProcessor ip;
if ( imp.getType() == ImagePlus.COLOR_256 )
{
ip = imp.getProcessor().convertToRGB();
imp.setProcessor( imp.getTitle(), ip );
}
else
ip = imp.getProcessor();
/* work on ByteProcessors that reflect the user defined intensity range */
final ByteProcessor src;
if ( imp.getType() == ImagePlus.GRAY8 )
src = ( ByteProcessor )ip.convertToByte( true ).duplicate();
else
src = ( ByteProcessor )ip.convertToByte( true );
final ByteProcessor dst = ( ByteProcessor )src.duplicate();
for ( int y = box.y; y < boxYMax; ++y )
{
final int yMin = Math.max( 0, y - blockRadius );
final int yMax = Math.min( imp.getHeight(), y + blockRadius + 1 );
final int h = yMax - yMin;
final int xMin0 = Math.max( 0, box.x - blockRadius );
final int xMax0 = Math.min( imp.getWidth() - 1, box.x + blockRadius );
/* initially fill histogram */
final int[] hist = new int[ bins + 1 ];
final int[] clippedHist = new int[ bins + 1 ];
for ( int yi = yMin; yi < yMax; ++yi )
for ( int xi = xMin0; xi < xMax0; ++xi )
++hist[ Util.roundPositive( src.get( xi, yi ) / 255.0f * bins ) ];
for ( int x = box.x; x < boxXMax; ++x )
{
final int v = Util.roundPositive( src.get( x, y ) / 255.0f * bins );
final int xMin = Math.max( 0, x - blockRadius );
final int xMax = x + blockRadius + 1;
final int w = Math.min( imp.getWidth(), xMax ) - xMin;
final int n = h * w;
final int limit;
if ( mask == null )
limit = ( int )( slope * n / bins + 0.5f );
else
limit = ( int )( ( 1 + mask.get( x - box.x, y - box.y ) / 255.0f * ( slope - 1 ) ) * n / bins + 0.5f );
/* remove left behind values from histogram */
if ( xMin > 0 )
{
final int xMin1 = xMin - 1;
for ( int yi = yMin; yi < yMax; ++yi )
--hist[ Util.roundPositive( src.get( xMin1, yi ) / 255.0f * bins ) ];
}
/* add newly included values to histogram */
if ( xMax <= imp.getWidth() )
{
final int xMax1 = xMax - 1;
for ( int yi = yMin; yi < yMax; ++yi )
++hist[ Util.roundPositive( src.get( xMax1, yi ) / 255.0f * bins ) ];
}
- /* transfer value and set to dst */
dst.set( x, y, Util.roundPositive( Util.transferValue( v, hist, clippedHist, limit, bins ) * 255.0f ) );
}
/* multiply the current row into ip */
final int t = y * imp.getWidth();
if ( imp.getType() == ImagePlus.GRAY8 )
{
for ( int x = box.x; x < boxXMax; ++x )
{
final int i = t + x;
ip.set( i, dst.get( i ) );
}
}
else if ( imp.getType() == ImagePlus.GRAY16 )
{
final int min = ( int )ip.getMin();
for ( int x = box.x; x < boxXMax; ++x )
{
final int i = t + x;
final int v = ip.get( i );
- final float a = ( float )dst.get( i ) / src.get( i );
+ final float vSrc = src.get( i );
+ final float a;
+ if ( vSrc == 0 )
+ a = 1.0f;
+ else
+ a = ( float )dst.get( i ) / vSrc;
ip.set( i, Math.max( 0, Math.min( 65535, Util.roundPositive( a * ( v - min ) + min ) ) ) );
}
}
else if ( imp.getType() == ImagePlus.GRAY32 )
{
final float min = ( float )ip.getMin();
for ( int x = box.x; x < boxXMax; ++x )
{
final int i = t + x;
final float v = ip.getf( i );
- final float a = ( float )dst.get( i ) / src.get( i );
+ final float vSrc = src.get( i );
+ final float a;
+ if ( vSrc == 0 )
+ a = 1.0f;
+ else
+ a = ( float )dst.get( i ) / vSrc;
ip.setf( i, a * ( v - min ) + min );
}
}
else if ( imp.getType() == ImagePlus.COLOR_RGB )
{
for ( int x = box.x; x < boxXMax; ++x )
{
final int i = t + x;
final int argb = ip.get( i );
- final float a = ( float )dst.get( i ) / src.get( i );
+ final float vSrc = src.get( i );
+ final float a;
+ if ( vSrc == 0 )
+ a = 1.0f;
+ else
+ a = ( float )dst.get( i ) / vSrc;
final int r = Math.max( 0, Math.min( 255, Util.roundPositive( a * ( ( argb >> 16 ) & 0xff ) ) ) );
final int g = Math.max( 0, Math.min( 255, Util.roundPositive( a * ( ( argb >> 8 ) & 0xff ) ) ) );
final int b = Math.max( 0, Math.min( 255, Util.roundPositive( a * ( argb & 0xff ) ) ) );
ip.set( i, ( r << 16 ) | ( g << 8 ) | b );
}
}
imp.updateAndDraw();
}
}
}
| false | true | final static public void run(
final ImagePlus imp,
final int blockRadius,
final int bins,
final float slope,
final java.awt.Rectangle roiBox,
final ByteProcessor mask )
{
/* initialize box if necessary */
final Rectangle box;
if ( roiBox == null )
{
if ( mask == null )
box = new Rectangle( 0, 0, imp.getWidth(), imp.getHeight() );
else
box = new Rectangle( 0, 0, Math.min( imp.getWidth(), mask.getWidth() ), Math.min( imp.getHeight(), mask.getHeight() ) );
}
else
box = roiBox;
/* make sure that the box is not larger than the mask */
if ( mask != null )
{
box.width = Math.min( mask.getWidth(), box.width );
box.height = Math.min( mask.getHeight(), box.height );
}
/* make sure that the box is not larger than the image */
box.width = Math.min( imp.getWidth() - box.x, box.width );
box.height = Math.min( imp.getHeight() - box.y, box.height );
final int boxXMax = box.x + box.width;
final int boxYMax = box.y + box.height;
/* convert 8bit processors with a LUT to RGB and create Undo-step */
final ImageProcessor ip;
if ( imp.getType() == ImagePlus.COLOR_256 )
{
ip = imp.getProcessor().convertToRGB();
imp.setProcessor( imp.getTitle(), ip );
}
else
ip = imp.getProcessor();
/* work on ByteProcessors that reflect the user defined intensity range */
final ByteProcessor src;
if ( imp.getType() == ImagePlus.GRAY8 )
src = ( ByteProcessor )ip.convertToByte( true ).duplicate();
else
src = ( ByteProcessor )ip.convertToByte( true );
final ByteProcessor dst = ( ByteProcessor )src.duplicate();
for ( int y = box.y; y < boxYMax; ++y )
{
final int yMin = Math.max( 0, y - blockRadius );
final int yMax = Math.min( imp.getHeight(), y + blockRadius + 1 );
final int h = yMax - yMin;
final int xMin0 = Math.max( 0, box.x - blockRadius );
final int xMax0 = Math.min( imp.getWidth() - 1, box.x + blockRadius );
/* initially fill histogram */
final int[] hist = new int[ bins + 1 ];
final int[] clippedHist = new int[ bins + 1 ];
for ( int yi = yMin; yi < yMax; ++yi )
for ( int xi = xMin0; xi < xMax0; ++xi )
++hist[ Util.roundPositive( src.get( xi, yi ) / 255.0f * bins ) ];
for ( int x = box.x; x < boxXMax; ++x )
{
final int v = Util.roundPositive( src.get( x, y ) / 255.0f * bins );
final int xMin = Math.max( 0, x - blockRadius );
final int xMax = x + blockRadius + 1;
final int w = Math.min( imp.getWidth(), xMax ) - xMin;
final int n = h * w;
final int limit;
if ( mask == null )
limit = ( int )( slope * n / bins + 0.5f );
else
limit = ( int )( ( 1 + mask.get( x - box.x, y - box.y ) / 255.0f * ( slope - 1 ) ) * n / bins + 0.5f );
/* remove left behind values from histogram */
if ( xMin > 0 )
{
final int xMin1 = xMin - 1;
for ( int yi = yMin; yi < yMax; ++yi )
--hist[ Util.roundPositive( src.get( xMin1, yi ) / 255.0f * bins ) ];
}
/* add newly included values to histogram */
if ( xMax <= imp.getWidth() )
{
final int xMax1 = xMax - 1;
for ( int yi = yMin; yi < yMax; ++yi )
++hist[ Util.roundPositive( src.get( xMax1, yi ) / 255.0f * bins ) ];
}
/* transfer value and set to dst */
dst.set( x, y, Util.roundPositive( Util.transferValue( v, hist, clippedHist, limit, bins ) * 255.0f ) );
}
/* multiply the current row into ip */
final int t = y * imp.getWidth();
if ( imp.getType() == ImagePlus.GRAY8 )
{
for ( int x = box.x; x < boxXMax; ++x )
{
final int i = t + x;
ip.set( i, dst.get( i ) );
}
}
else if ( imp.getType() == ImagePlus.GRAY16 )
{
final int min = ( int )ip.getMin();
for ( int x = box.x; x < boxXMax; ++x )
{
final int i = t + x;
final int v = ip.get( i );
final float a = ( float )dst.get( i ) / src.get( i );
ip.set( i, Math.max( 0, Math.min( 65535, Util.roundPositive( a * ( v - min ) + min ) ) ) );
}
}
else if ( imp.getType() == ImagePlus.GRAY32 )
{
final float min = ( float )ip.getMin();
for ( int x = box.x; x < boxXMax; ++x )
{
final int i = t + x;
final float v = ip.getf( i );
final float a = ( float )dst.get( i ) / src.get( i );
ip.setf( i, a * ( v - min ) + min );
}
}
else if ( imp.getType() == ImagePlus.COLOR_RGB )
{
for ( int x = box.x; x < boxXMax; ++x )
{
final int i = t + x;
final int argb = ip.get( i );
final float a = ( float )dst.get( i ) / src.get( i );
final int r = Math.max( 0, Math.min( 255, Util.roundPositive( a * ( ( argb >> 16 ) & 0xff ) ) ) );
final int g = Math.max( 0, Math.min( 255, Util.roundPositive( a * ( ( argb >> 8 ) & 0xff ) ) ) );
final int b = Math.max( 0, Math.min( 255, Util.roundPositive( a * ( argb & 0xff ) ) ) );
ip.set( i, ( r << 16 ) | ( g << 8 ) | b );
}
}
imp.updateAndDraw();
}
}
| final static public void run(
final ImagePlus imp,
final int blockRadius,
final int bins,
final float slope,
final java.awt.Rectangle roiBox,
final ByteProcessor mask )
{
/* initialize box if necessary */
final Rectangle box;
if ( roiBox == null )
{
if ( mask == null )
box = new Rectangle( 0, 0, imp.getWidth(), imp.getHeight() );
else
box = new Rectangle( 0, 0, Math.min( imp.getWidth(), mask.getWidth() ), Math.min( imp.getHeight(), mask.getHeight() ) );
}
else
box = roiBox;
/* make sure that the box is not larger than the mask */
if ( mask != null )
{
box.width = Math.min( mask.getWidth(), box.width );
box.height = Math.min( mask.getHeight(), box.height );
}
/* make sure that the box is not larger than the image */
box.width = Math.min( imp.getWidth() - box.x, box.width );
box.height = Math.min( imp.getHeight() - box.y, box.height );
final int boxXMax = box.x + box.width;
final int boxYMax = box.y + box.height;
/* convert 8bit processors with a LUT to RGB and create Undo-step */
final ImageProcessor ip;
if ( imp.getType() == ImagePlus.COLOR_256 )
{
ip = imp.getProcessor().convertToRGB();
imp.setProcessor( imp.getTitle(), ip );
}
else
ip = imp.getProcessor();
/* work on ByteProcessors that reflect the user defined intensity range */
final ByteProcessor src;
if ( imp.getType() == ImagePlus.GRAY8 )
src = ( ByteProcessor )ip.convertToByte( true ).duplicate();
else
src = ( ByteProcessor )ip.convertToByte( true );
final ByteProcessor dst = ( ByteProcessor )src.duplicate();
for ( int y = box.y; y < boxYMax; ++y )
{
final int yMin = Math.max( 0, y - blockRadius );
final int yMax = Math.min( imp.getHeight(), y + blockRadius + 1 );
final int h = yMax - yMin;
final int xMin0 = Math.max( 0, box.x - blockRadius );
final int xMax0 = Math.min( imp.getWidth() - 1, box.x + blockRadius );
/* initially fill histogram */
final int[] hist = new int[ bins + 1 ];
final int[] clippedHist = new int[ bins + 1 ];
for ( int yi = yMin; yi < yMax; ++yi )
for ( int xi = xMin0; xi < xMax0; ++xi )
++hist[ Util.roundPositive( src.get( xi, yi ) / 255.0f * bins ) ];
for ( int x = box.x; x < boxXMax; ++x )
{
final int v = Util.roundPositive( src.get( x, y ) / 255.0f * bins );
final int xMin = Math.max( 0, x - blockRadius );
final int xMax = x + blockRadius + 1;
final int w = Math.min( imp.getWidth(), xMax ) - xMin;
final int n = h * w;
final int limit;
if ( mask == null )
limit = ( int )( slope * n / bins + 0.5f );
else
limit = ( int )( ( 1 + mask.get( x - box.x, y - box.y ) / 255.0f * ( slope - 1 ) ) * n / bins + 0.5f );
/* remove left behind values from histogram */
if ( xMin > 0 )
{
final int xMin1 = xMin - 1;
for ( int yi = yMin; yi < yMax; ++yi )
--hist[ Util.roundPositive( src.get( xMin1, yi ) / 255.0f * bins ) ];
}
/* add newly included values to histogram */
if ( xMax <= imp.getWidth() )
{
final int xMax1 = xMax - 1;
for ( int yi = yMin; yi < yMax; ++yi )
++hist[ Util.roundPositive( src.get( xMax1, yi ) / 255.0f * bins ) ];
}
dst.set( x, y, Util.roundPositive( Util.transferValue( v, hist, clippedHist, limit, bins ) * 255.0f ) );
}
/* multiply the current row into ip */
final int t = y * imp.getWidth();
if ( imp.getType() == ImagePlus.GRAY8 )
{
for ( int x = box.x; x < boxXMax; ++x )
{
final int i = t + x;
ip.set( i, dst.get( i ) );
}
}
else if ( imp.getType() == ImagePlus.GRAY16 )
{
final int min = ( int )ip.getMin();
for ( int x = box.x; x < boxXMax; ++x )
{
final int i = t + x;
final int v = ip.get( i );
final float vSrc = src.get( i );
final float a;
if ( vSrc == 0 )
a = 1.0f;
else
a = ( float )dst.get( i ) / vSrc;
ip.set( i, Math.max( 0, Math.min( 65535, Util.roundPositive( a * ( v - min ) + min ) ) ) );
}
}
else if ( imp.getType() == ImagePlus.GRAY32 )
{
final float min = ( float )ip.getMin();
for ( int x = box.x; x < boxXMax; ++x )
{
final int i = t + x;
final float v = ip.getf( i );
final float vSrc = src.get( i );
final float a;
if ( vSrc == 0 )
a = 1.0f;
else
a = ( float )dst.get( i ) / vSrc;
ip.setf( i, a * ( v - min ) + min );
}
}
else if ( imp.getType() == ImagePlus.COLOR_RGB )
{
for ( int x = box.x; x < boxXMax; ++x )
{
final int i = t + x;
final int argb = ip.get( i );
final float vSrc = src.get( i );
final float a;
if ( vSrc == 0 )
a = 1.0f;
else
a = ( float )dst.get( i ) / vSrc;
final int r = Math.max( 0, Math.min( 255, Util.roundPositive( a * ( ( argb >> 16 ) & 0xff ) ) ) );
final int g = Math.max( 0, Math.min( 255, Util.roundPositive( a * ( ( argb >> 8 ) & 0xff ) ) ) );
final int b = Math.max( 0, Math.min( 255, Util.roundPositive( a * ( argb & 0xff ) ) ) );
ip.set( i, ( r << 16 ) | ( g << 8 ) | b );
}
}
imp.updateAndDraw();
}
}
|
diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/repository/RepositoryHelperTest.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/repository/RepositoryHelperTest.java
index a4fb9e4c8..9f19f8d01 100644
--- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/repository/RepositoryHelperTest.java
+++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/repository/RepositoryHelperTest.java
@@ -1,46 +1,46 @@
/*******************************************************************************
* Copyright (c) 2009 Cloudsmith 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
*
* Contributors:
* Cloudsmith Inc - initial API and implementation
*******************************************************************************/
package org.eclipse.equinox.p2.tests.repository;
import java.net.URI;
import java.net.URISyntaxException;
import junit.framework.TestCase;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.equinox.internal.p2.repository.helpers.RepositoryHelper;
/**
* Tests RepositoryHandler
*/
public class RepositoryHelperTest extends TestCase {
public void testURISyntaxChecker() throws URISyntaxException {
URI location = new URI("http://somwhere.com/path");
IStatus result = RepositoryHelper.checkRepositoryLocationSyntax(location);
assertTrue("1.0 Valid URI should be ok", result.isOK());
location = new URI("ftp://somwhere.com/path");
result = RepositoryHelper.checkRepositoryLocationSyntax(location);
assertTrue("2.0 Valid URI should be ok", result.isOK());
location = new URI("https://somwhere.com/path");
result = RepositoryHelper.checkRepositoryLocationSyntax(location);
- assertTrue("2.0 Valid URI should be ok", result.isOK());
+ assertTrue("3.0 Valid URI should be ok", result.isOK());
location = new URI("htp://somwhere.com/path");
result = RepositoryHelper.checkRepositoryLocationSyntax(location);
- assertFalse("1.0 Invalid URI should not be ok", result.isOK());
+ assertFalse("4.0 Invalid URI should not be ok", result.isOK());
location = new URI("/somwhere.com/path");
result = RepositoryHelper.checkRepositoryLocationSyntax(location);
- assertFalse("2.0 Invalid URI should not be ok", result.isOK());
+ assertFalse("5.0 Invalid URI should not be ok", result.isOK());
}
}
| false | true | public void testURISyntaxChecker() throws URISyntaxException {
URI location = new URI("http://somwhere.com/path");
IStatus result = RepositoryHelper.checkRepositoryLocationSyntax(location);
assertTrue("1.0 Valid URI should be ok", result.isOK());
location = new URI("ftp://somwhere.com/path");
result = RepositoryHelper.checkRepositoryLocationSyntax(location);
assertTrue("2.0 Valid URI should be ok", result.isOK());
location = new URI("https://somwhere.com/path");
result = RepositoryHelper.checkRepositoryLocationSyntax(location);
assertTrue("2.0 Valid URI should be ok", result.isOK());
location = new URI("htp://somwhere.com/path");
result = RepositoryHelper.checkRepositoryLocationSyntax(location);
assertFalse("1.0 Invalid URI should not be ok", result.isOK());
location = new URI("/somwhere.com/path");
result = RepositoryHelper.checkRepositoryLocationSyntax(location);
assertFalse("2.0 Invalid URI should not be ok", result.isOK());
}
| public void testURISyntaxChecker() throws URISyntaxException {
URI location = new URI("http://somwhere.com/path");
IStatus result = RepositoryHelper.checkRepositoryLocationSyntax(location);
assertTrue("1.0 Valid URI should be ok", result.isOK());
location = new URI("ftp://somwhere.com/path");
result = RepositoryHelper.checkRepositoryLocationSyntax(location);
assertTrue("2.0 Valid URI should be ok", result.isOK());
location = new URI("https://somwhere.com/path");
result = RepositoryHelper.checkRepositoryLocationSyntax(location);
assertTrue("3.0 Valid URI should be ok", result.isOK());
location = new URI("htp://somwhere.com/path");
result = RepositoryHelper.checkRepositoryLocationSyntax(location);
assertFalse("4.0 Invalid URI should not be ok", result.isOK());
location = new URI("/somwhere.com/path");
result = RepositoryHelper.checkRepositoryLocationSyntax(location);
assertFalse("5.0 Invalid URI should not be ok", result.isOK());
}
|
diff --git a/eclipse/plugins/net.sf.orcc.core/src/net/sf/orcc/network/Broadcast.java b/eclipse/plugins/net.sf.orcc.core/src/net/sf/orcc/network/Broadcast.java
index 11e66d303..f9dfa479d 100644
--- a/eclipse/plugins/net.sf.orcc.core/src/net/sf/orcc/network/Broadcast.java
+++ b/eclipse/plugins/net.sf.orcc.core/src/net/sf/orcc/network/Broadcast.java
@@ -1,157 +1,157 @@
/*
* Copyright (c) 2009, IETR/INSA of Rennes
* 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 IETR/INSA of Rennes 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 net.sf.orcc.network;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.orcc.ir.IrFactory;
import net.sf.orcc.ir.Port;
import net.sf.orcc.ir.Type;
import net.sf.orcc.util.OrderedMap;
import org.eclipse.emf.ecore.util.EcoreUtil;
/**
* This class defines a broadcast as a particular instance.
*
* @author Matthieu Wipliez
*
*/
public class Broadcast {
public static final String CLASS = "";
private OrderedMap<String, Port> inputs;
private int numOutputs;
private List<Integer> outputList;
private OrderedMap<String, Port> outputs;
private Map<Port, Integer> portMap;
private Type type;
/**
* Creates a new broadcast whose name is composed from the given actor name
* and port name. The broadcast will have the number of outputs given and
* the given type. Type is copied.
*
* @param actorName
* name of the source actor
* @param portName
* name of the source output port connected to this broadcast
* @param numOutput
* number of outputs
* @param type
* type of this broadcast
*/
public Broadcast(int numOutputs, Type type) {
this.numOutputs = numOutputs;
this.type = EcoreUtil.copy(type);
inputs = new OrderedMap<String, Port>();
String name = "input";
inputs.put(name,
IrFactory.eINSTANCE.createPort(EcoreUtil.copy(type), name));
outputs = new OrderedMap<String, Port>();
for (int i = 0; i < numOutputs; i++) {
name = "output_" + i;
outputs.put(name,
IrFactory.eINSTANCE.createPort(EcoreUtil.copy(type), name));
}
portMap = new HashMap<Port, Integer>();
- portMap.put(getInput(), 0);
+ portMap.put(getInput(), 1);
for (int i = 0; i < numOutputs; i++) {
portMap.put(getOutputs().getList().get(i), i + 1);
}
}
public Port getInput() {
return inputs.get("input");
}
/**
* Returns the ordered map of input ports.
*
* @return the ordered map of input ports
*/
public OrderedMap<String, Port> getInputs() {
return inputs;
}
public int getNumOutputs() {
return numOutputs;
}
public Port getOutput(String name) {
return outputs.get(name);
}
/**
* Returns a list of integers containing [0, 1, ..., n - 1] where n is the
* number of ports of this broadcast.
*
* @return a list of integers
*/
public List<Integer> getOutputList() {
if (outputList == null) {
outputList = new ArrayList<Integer>();
for (int i = 0; i < numOutputs; i++) {
outputList.add(i);
}
}
return outputList;
}
/**
* Returns the ordered map of output ports.
*
* @return the ordered map of output ports
*/
public OrderedMap<String, Port> getOutputs() {
return outputs;
}
public Map<Port, Integer> getPortMap() {
return portMap;
}
public Type getType() {
return type;
}
}
| true | true | public Broadcast(int numOutputs, Type type) {
this.numOutputs = numOutputs;
this.type = EcoreUtil.copy(type);
inputs = new OrderedMap<String, Port>();
String name = "input";
inputs.put(name,
IrFactory.eINSTANCE.createPort(EcoreUtil.copy(type), name));
outputs = new OrderedMap<String, Port>();
for (int i = 0; i < numOutputs; i++) {
name = "output_" + i;
outputs.put(name,
IrFactory.eINSTANCE.createPort(EcoreUtil.copy(type), name));
}
portMap = new HashMap<Port, Integer>();
portMap.put(getInput(), 0);
for (int i = 0; i < numOutputs; i++) {
portMap.put(getOutputs().getList().get(i), i + 1);
}
}
| public Broadcast(int numOutputs, Type type) {
this.numOutputs = numOutputs;
this.type = EcoreUtil.copy(type);
inputs = new OrderedMap<String, Port>();
String name = "input";
inputs.put(name,
IrFactory.eINSTANCE.createPort(EcoreUtil.copy(type), name));
outputs = new OrderedMap<String, Port>();
for (int i = 0; i < numOutputs; i++) {
name = "output_" + i;
outputs.put(name,
IrFactory.eINSTANCE.createPort(EcoreUtil.copy(type), name));
}
portMap = new HashMap<Port, Integer>();
portMap.put(getInput(), 1);
for (int i = 0; i < numOutputs; i++) {
portMap.put(getOutputs().getList().get(i), i + 1);
}
}
|
diff --git a/src/test/java/org/vanbest/xmltv/RTLTest.java b/src/test/java/org/vanbest/xmltv/RTLTest.java
index 69b64e0..d8470fc 100644
--- a/src/test/java/org/vanbest/xmltv/RTLTest.java
+++ b/src/test/java/org/vanbest/xmltv/RTLTest.java
@@ -1,159 +1,162 @@
package org.vanbest.xmltv;
import static org.junit.Assert.*;
import java.util.Calendar;
import java.util.List;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class RTLTest {
private static RTL rtl;
private final static int RTL_SOURCE_ID = 2;
private static List<Channel> channels = null;
@BeforeClass
public static void setUp() throws Exception {
Config config = Config.getDefaultConfig();
rtl = new RTL(RTL_SOURCE_ID, config);
rtl.clearCache();
}
@AfterClass
public static void tearDown() throws Exception {
rtl.close();
}
@Test
public void testGetName() {
assertEquals("RTL name should be known", "rtl.nl", rtl.getName());
}
@Test
public void testgetChannels() {
fetchChannels();
// there should be a least 20 channels
assertTrue("There should be at least 20 channels from rtl.nl",
channels.size() >= 20);
// there should be an "RTL 4" channel
boolean foundRTL4 = false;
for (Channel c : channels) {
if (c.defaultName().equals("RTL 4")) {
foundRTL4 = true;
assertFalse("RTL 4 channel should have at least one icon",
c.icons.isEmpty());
}
assertEquals("All channels should have RTL.nl source id",
RTL_SOURCE_ID, c.source);
}
if (!foundRTL4) {
fail("Channel RTL4 not found, should be there");
}
}
private void fetchChannels() {
if (channels == null)
channels = rtl.getChannels();
}
@Test
public void testFindGTSTRerun() throws Exception {
fetchChannels();
Channel rtl4 = null;
for (Channel c : channels) {
if (c.defaultName().equals("RTL 4")) {
rtl4 = c;
break;
}
}
assertNotNull("Should be able to find RTL 4 channel", rtl4);
List<Programme> today = rtl.getProgrammes(rtl4, 0);
assertTrue("Expect at leat 10 programmes for a day", today.size() >= 10);
Calendar now = Calendar.getInstance();
if (now.get(Calendar.MONTH) <= Calendar.MAY
|| now.get(Calendar.MONTH) >= Calendar.SEPTEMBER) {
int offset;
switch (now.get(Calendar.DAY_OF_WEEK)) {
case Calendar.SATURDAY:
offset = 2;
break;
case Calendar.SUNDAY:
offset = 1;
break;
default:
offset = 0;
}
int rerun;
switch (now.get(Calendar.DAY_OF_WEEK)) {
case Calendar.FRIDAY:
rerun = 3;
break;
case Calendar.SATURDAY:
+ rerun = 3;
+ break;
+ case Calendar.SUNDAY:
rerun = 2;
break;
default:
rerun = 1;
}
List<Programme> first = rtl.getProgrammes(rtl4, offset);
Programme gtstOriginal = null;
for (Programme p : first) {
if (p.getFirstTitle().matches("Goede Tijden.*")) {
if (p.startTime.getHours() >= 19) {
gtstOriginal = p;
break;
}
}
}
assertNotNull(
"Should have a programme called Goede Tijden, Slechte Tijden after 19:00 on date with offset "
+ offset + " for today", gtstOriginal);
assertNotNull("GTST should have a description",
gtstOriginal.descriptions);
assertTrue("GTST should have at least one description",
gtstOriginal.descriptions.size() > 0);
assertNotNull(
"GTST should have at least one non-empty description",
gtstOriginal.descriptions.get(0).title);
assertFalse("GTST should have at least one non-empty description",
gtstOriginal.descriptions.get(0).title.isEmpty());
assertNotNull("GTST should have kijkwijzer information",
gtstOriginal.ratings);
assertTrue("GTST should have at least one kijkwijzer ratings",
gtstOriginal.ratings.size() >= 1);
assertNotNull("GTST rating should have kijkwijzer system",
gtstOriginal.ratings.get(0).system);
assertTrue("GTST rating should have kijkwijzer system filled in",
gtstOriginal.ratings.get(0).system.matches(".*ijkwijz.*"));
assertNotNull("GTST rating should have value",
gtstOriginal.ratings.get(0).value);
assertFalse("GTST rating should have value",
gtstOriginal.ratings.get(0).value.isEmpty());
List<Programme> reruns = rtl.getProgrammes(rtl4, rerun);
Programme gtstRerun = null;
for (Programme p : reruns) {
if (p.getFirstTitle().matches("Goede Tijden.*")) {
if (p.startTime.getHours() <= 15) {
gtstRerun = p;
break;
}
}
}
assertNotNull(
"Should have a programme called Goede Tijden, Slechte Tijden before 15:00 on date with offset "
+ rerun, gtstRerun);
assertEquals(
"GTST rerun should have the same description as the original",
gtstRerun.descriptions.get(0).title,
gtstOriginal.descriptions.get(0).title);
}
}
}
| true | true | public void testFindGTSTRerun() throws Exception {
fetchChannels();
Channel rtl4 = null;
for (Channel c : channels) {
if (c.defaultName().equals("RTL 4")) {
rtl4 = c;
break;
}
}
assertNotNull("Should be able to find RTL 4 channel", rtl4);
List<Programme> today = rtl.getProgrammes(rtl4, 0);
assertTrue("Expect at leat 10 programmes for a day", today.size() >= 10);
Calendar now = Calendar.getInstance();
if (now.get(Calendar.MONTH) <= Calendar.MAY
|| now.get(Calendar.MONTH) >= Calendar.SEPTEMBER) {
int offset;
switch (now.get(Calendar.DAY_OF_WEEK)) {
case Calendar.SATURDAY:
offset = 2;
break;
case Calendar.SUNDAY:
offset = 1;
break;
default:
offset = 0;
}
int rerun;
switch (now.get(Calendar.DAY_OF_WEEK)) {
case Calendar.FRIDAY:
rerun = 3;
break;
case Calendar.SATURDAY:
rerun = 2;
break;
default:
rerun = 1;
}
List<Programme> first = rtl.getProgrammes(rtl4, offset);
Programme gtstOriginal = null;
for (Programme p : first) {
if (p.getFirstTitle().matches("Goede Tijden.*")) {
if (p.startTime.getHours() >= 19) {
gtstOriginal = p;
break;
}
}
}
assertNotNull(
"Should have a programme called Goede Tijden, Slechte Tijden after 19:00 on date with offset "
+ offset + " for today", gtstOriginal);
assertNotNull("GTST should have a description",
gtstOriginal.descriptions);
assertTrue("GTST should have at least one description",
gtstOriginal.descriptions.size() > 0);
assertNotNull(
"GTST should have at least one non-empty description",
gtstOriginal.descriptions.get(0).title);
assertFalse("GTST should have at least one non-empty description",
gtstOriginal.descriptions.get(0).title.isEmpty());
assertNotNull("GTST should have kijkwijzer information",
gtstOriginal.ratings);
assertTrue("GTST should have at least one kijkwijzer ratings",
gtstOriginal.ratings.size() >= 1);
assertNotNull("GTST rating should have kijkwijzer system",
gtstOriginal.ratings.get(0).system);
assertTrue("GTST rating should have kijkwijzer system filled in",
gtstOriginal.ratings.get(0).system.matches(".*ijkwijz.*"));
assertNotNull("GTST rating should have value",
gtstOriginal.ratings.get(0).value);
assertFalse("GTST rating should have value",
gtstOriginal.ratings.get(0).value.isEmpty());
List<Programme> reruns = rtl.getProgrammes(rtl4, rerun);
Programme gtstRerun = null;
for (Programme p : reruns) {
if (p.getFirstTitle().matches("Goede Tijden.*")) {
if (p.startTime.getHours() <= 15) {
gtstRerun = p;
break;
}
}
}
assertNotNull(
"Should have a programme called Goede Tijden, Slechte Tijden before 15:00 on date with offset "
+ rerun, gtstRerun);
assertEquals(
"GTST rerun should have the same description as the original",
gtstRerun.descriptions.get(0).title,
gtstOriginal.descriptions.get(0).title);
}
}
| public void testFindGTSTRerun() throws Exception {
fetchChannels();
Channel rtl4 = null;
for (Channel c : channels) {
if (c.defaultName().equals("RTL 4")) {
rtl4 = c;
break;
}
}
assertNotNull("Should be able to find RTL 4 channel", rtl4);
List<Programme> today = rtl.getProgrammes(rtl4, 0);
assertTrue("Expect at leat 10 programmes for a day", today.size() >= 10);
Calendar now = Calendar.getInstance();
if (now.get(Calendar.MONTH) <= Calendar.MAY
|| now.get(Calendar.MONTH) >= Calendar.SEPTEMBER) {
int offset;
switch (now.get(Calendar.DAY_OF_WEEK)) {
case Calendar.SATURDAY:
offset = 2;
break;
case Calendar.SUNDAY:
offset = 1;
break;
default:
offset = 0;
}
int rerun;
switch (now.get(Calendar.DAY_OF_WEEK)) {
case Calendar.FRIDAY:
rerun = 3;
break;
case Calendar.SATURDAY:
rerun = 3;
break;
case Calendar.SUNDAY:
rerun = 2;
break;
default:
rerun = 1;
}
List<Programme> first = rtl.getProgrammes(rtl4, offset);
Programme gtstOriginal = null;
for (Programme p : first) {
if (p.getFirstTitle().matches("Goede Tijden.*")) {
if (p.startTime.getHours() >= 19) {
gtstOriginal = p;
break;
}
}
}
assertNotNull(
"Should have a programme called Goede Tijden, Slechte Tijden after 19:00 on date with offset "
+ offset + " for today", gtstOriginal);
assertNotNull("GTST should have a description",
gtstOriginal.descriptions);
assertTrue("GTST should have at least one description",
gtstOriginal.descriptions.size() > 0);
assertNotNull(
"GTST should have at least one non-empty description",
gtstOriginal.descriptions.get(0).title);
assertFalse("GTST should have at least one non-empty description",
gtstOriginal.descriptions.get(0).title.isEmpty());
assertNotNull("GTST should have kijkwijzer information",
gtstOriginal.ratings);
assertTrue("GTST should have at least one kijkwijzer ratings",
gtstOriginal.ratings.size() >= 1);
assertNotNull("GTST rating should have kijkwijzer system",
gtstOriginal.ratings.get(0).system);
assertTrue("GTST rating should have kijkwijzer system filled in",
gtstOriginal.ratings.get(0).system.matches(".*ijkwijz.*"));
assertNotNull("GTST rating should have value",
gtstOriginal.ratings.get(0).value);
assertFalse("GTST rating should have value",
gtstOriginal.ratings.get(0).value.isEmpty());
List<Programme> reruns = rtl.getProgrammes(rtl4, rerun);
Programme gtstRerun = null;
for (Programme p : reruns) {
if (p.getFirstTitle().matches("Goede Tijden.*")) {
if (p.startTime.getHours() <= 15) {
gtstRerun = p;
break;
}
}
}
assertNotNull(
"Should have a programme called Goede Tijden, Slechte Tijden before 15:00 on date with offset "
+ rerun, gtstRerun);
assertEquals(
"GTST rerun should have the same description as the original",
gtstRerun.descriptions.get(0).title,
gtstOriginal.descriptions.get(0).title);
}
}
|
diff --git a/src/com/vaadin/terminal/gwt/client/ui/VFilterSelect.java b/src/com/vaadin/terminal/gwt/client/ui/VFilterSelect.java
index 998abc157..5b834f9f4 100644
--- a/src/com/vaadin/terminal/gwt/client/ui/VFilterSelect.java
+++ b/src/com/vaadin/terminal/gwt/client/ui/VFilterSelect.java
@@ -1,1130 +1,1136 @@
/*
@ITMillApache2LicenseForJavaFiles@
*/
package com.vaadin.terminal.gwt.client.ui;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.FocusHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.event.dom.client.LoadEvent;
import com.google.gwt.event.dom.client.LoadHandler;
import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.PopupPanel.PositionCallback;
import com.google.gwt.user.client.ui.SuggestOracle.Suggestion;
import com.vaadin.terminal.gwt.client.ApplicationConnection;
import com.vaadin.terminal.gwt.client.BrowserInfo;
import com.vaadin.terminal.gwt.client.Focusable;
import com.vaadin.terminal.gwt.client.Paintable;
import com.vaadin.terminal.gwt.client.UIDL;
import com.vaadin.terminal.gwt.client.Util;
import com.vaadin.terminal.gwt.client.VTooltip;
/**
*
* TODO needs major refactoring (to be extensible etc)
*/
public class VFilterSelect extends Composite implements Paintable, Field,
KeyDownHandler, KeyUpHandler, ClickHandler, FocusHandler, BlurHandler,
Focusable {
public class FilterSelectSuggestion implements Suggestion, Command {
private final String key;
private final String caption;
private String iconUri;
public FilterSelectSuggestion(UIDL uidl) {
key = uidl.getStringAttribute("key");
caption = uidl.getStringAttribute("caption");
if (uidl.hasAttribute("icon")) {
iconUri = client.translateVaadinUri(uidl
.getStringAttribute("icon"));
}
}
public String getDisplayString() {
final StringBuffer sb = new StringBuffer();
if (iconUri != null) {
sb.append("<img src=\"");
sb.append(iconUri);
sb.append("\" alt=\"\" class=\"v-icon\" />");
}
sb.append("<span>" + Util.escapeHTML(caption) + "</span>");
return sb.toString();
}
public String getReplacementString() {
return caption;
}
public int getOptionKey() {
return Integer.parseInt(key);
}
public String getIconUri() {
return iconUri;
}
public void execute() {
onSuggestionSelected(this);
}
}
public class SuggestionPopup extends VOverlay implements PositionCallback,
CloseHandler<PopupPanel> {
private static final String Z_INDEX = "30000";
private final SuggestionMenu menu;
private final Element up = DOM.createDiv();
private final Element down = DOM.createDiv();
private final Element status = DOM.createDiv();
private boolean isPagingEnabled = true;
private long lastAutoClosed;
private int popupOuterPadding = -1;
private int topPosition;
SuggestionPopup() {
super(true, false, true);
menu = new SuggestionMenu();
setWidget(menu);
setStyleName(CLASSNAME + "-suggestpopup");
DOM.setStyleAttribute(getElement(), "zIndex", Z_INDEX);
final Element root = getContainerElement();
DOM.setInnerHTML(up, "<span>Prev</span>");
DOM.sinkEvents(up, Event.ONCLICK);
DOM.setInnerHTML(down, "<span>Next</span>");
DOM.sinkEvents(down, Event.ONCLICK);
DOM.insertChild(root, up, 0);
DOM.appendChild(root, down);
DOM.appendChild(root, status);
DOM.setElementProperty(status, "className", CLASSNAME + "-status");
addCloseHandler(this);
}
public void showSuggestions(
Collection<FilterSelectSuggestion> currentSuggestions,
int currentPage, int totalSuggestions) {
// Add TT anchor point
DOM.setElementProperty(getElement(), "id",
"VAADIN_COMBOBOX_OPTIONLIST");
menu.setSuggestions(currentSuggestions);
final int x = VFilterSelect.this.getAbsoluteLeft();
topPosition = tb.getAbsoluteTop();
topPosition += tb.getOffsetHeight();
setPopupPosition(x, topPosition);
final int first = currentPage * pageLength
+ (nullSelectionAllowed && currentPage > 0 ? 0 : 1);
final int last = first + currentSuggestions.size() - 1;
final int matches = totalSuggestions
- (nullSelectionAllowed ? 1 : 0);
if (last > 0) {
// nullsel not counted, as requested by user
DOM.setInnerText(status, (matches == 0 ? 0 : first)
+ "-"
+ ("".equals(lastFilter) && nullSelectionAllowed
&& currentPage == 0 ? last - 1 : last) + "/"
+ matches);
} else {
DOM.setInnerText(status, "");
}
// We don't need to show arrows or statusbar if there is only one
// page
if (matches <= pageLength) {
setPagingEnabled(false);
} else {
setPagingEnabled(true);
}
setPrevButtonActive(first > 1);
setNextButtonActive(last < matches);
// clear previously fixed width
menu.setWidth("");
DOM.setStyleAttribute(DOM.getFirstChild(menu.getElement()),
"width", "");
setPopupPositionAndShow(this);
}
private void setNextButtonActive(boolean b) {
if (b) {
DOM.sinkEvents(down, Event.ONCLICK);
DOM.setElementProperty(down, "className", CLASSNAME
+ "-nextpage");
} else {
DOM.sinkEvents(down, 0);
DOM.setElementProperty(down, "className", CLASSNAME
+ "-nextpage-off");
}
}
private void setPrevButtonActive(boolean b) {
if (b) {
DOM.sinkEvents(up, Event.ONCLICK);
DOM
.setElementProperty(up, "className", CLASSNAME
+ "-prevpage");
} else {
DOM.sinkEvents(up, 0);
DOM.setElementProperty(up, "className", CLASSNAME
+ "-prevpage-off");
}
}
public void selectNextItem() {
final MenuItem cur = menu.getSelectedItem();
final int index = 1 + menu.getItems().indexOf(cur);
if (menu.getItems().size() > index) {
final MenuItem newSelectedItem = (MenuItem) menu.getItems()
.get(index);
menu.selectItem(newSelectedItem);
tb.setText(newSelectedItem.getText());
tb.setSelectionRange(lastFilter.length(), newSelectedItem
.getText().length()
- lastFilter.length());
} else if (hasNextPage()) {
lastIndex = index - 1; // save for paging
filterOptions(currentPage + 1, lastFilter);
}
}
public void selectPrevItem() {
final MenuItem cur = menu.getSelectedItem();
final int index = -1 + menu.getItems().indexOf(cur);
if (index > -1) {
final MenuItem newSelectedItem = (MenuItem) menu.getItems()
.get(index);
menu.selectItem(newSelectedItem);
tb.setText(newSelectedItem.getText());
tb.setSelectionRange(lastFilter.length(), newSelectedItem
.getText().length()
- lastFilter.length());
} else if (index == -1) {
if (currentPage > 0) {
lastIndex = index + 1; // save for paging
filterOptions(currentPage - 1, lastFilter);
}
} else {
final MenuItem newSelectedItem = (MenuItem) menu.getItems()
.get(menu.getItems().size() - 1);
menu.selectItem(newSelectedItem);
tb.setText(newSelectedItem.getText());
tb.setSelectionRange(lastFilter.length(), newSelectedItem
.getText().length()
- lastFilter.length());
}
}
@Override
public void onBrowserEvent(Event event) {
final Element target = DOM.eventGetTarget(event);
if (DOM.compare(target, up)
|| DOM.compare(target, DOM.getChild(up, 0))) {
filterOptions(currentPage - 1, lastFilter);
} else if (DOM.compare(target, down)
|| DOM.compare(target, DOM.getChild(down, 0))) {
filterOptions(currentPage + 1, lastFilter);
}
tb.setFocus(true);
}
public void setPagingEnabled(boolean paging) {
if (isPagingEnabled == paging) {
return;
}
if (paging) {
DOM.setStyleAttribute(down, "display", "");
DOM.setStyleAttribute(up, "display", "");
DOM.setStyleAttribute(status, "display", "");
} else {
DOM.setStyleAttribute(down, "display", "none");
DOM.setStyleAttribute(up, "display", "none");
DOM.setStyleAttribute(status, "display", "none");
}
isPagingEnabled = paging;
}
/*
* (non-Javadoc)
*
* @see
* com.google.gwt.user.client.ui.PopupPanel$PositionCallback#setPosition
* (int, int)
*/
public void setPosition(int offsetWidth, int offsetHeight) {
int top = -1;
int left = -1;
// reset menu size and retrieve its "natural" size
menu.setHeight("");
if (currentPage > 0) {
// fix height to avoid height change when getting to last page
menu.fixHeightTo(pageLength);
}
offsetHeight = getOffsetHeight();
final int desiredWidth = getMainWidth();
int naturalMenuWidth = DOM.getElementPropertyInt(DOM
.getFirstChild(menu.getElement()), "offsetWidth");
if (popupOuterPadding == -1) {
popupOuterPadding = Util.measureHorizontalPaddingAndBorder(
getElement(), 2);
}
if (naturalMenuWidth < desiredWidth) {
menu.setWidth((desiredWidth - popupOuterPadding) + "px");
DOM.setStyleAttribute(DOM.getFirstChild(menu.getElement()),
"width", "100%");
naturalMenuWidth = desiredWidth;
}
if (BrowserInfo.get().isIE()) {
/*
* IE requires us to specify the width for the container
* element. Otherwise it will be 100% wide
*/
int rootWidth = naturalMenuWidth - popupOuterPadding;
DOM.setStyleAttribute(getContainerElement(), "width", rootWidth
+ "px");
}
if (offsetHeight + getPopupTop() > Window.getClientHeight()
+ Window.getScrollTop()) {
// popup on top of input instead
top = getPopupTop() - offsetHeight
- VFilterSelect.this.getOffsetHeight();
if (top < 0) {
top = 0;
}
} else {
top = getPopupTop();
/*
* Take popup top margin into account. getPopupTop() returns the
* top value including the margin but the value we give must not
* include the margin.
*/
int topMargin = (top - topPosition);
top -= topMargin;
}
// fetch real width (mac FF bugs here due GWT popups overflow:auto )
offsetWidth = DOM.getElementPropertyInt(DOM.getFirstChild(menu
.getElement()), "offsetWidth");
if (offsetWidth + getPopupLeft() > Window.getClientWidth()
+ Window.getScrollLeft()) {
left = VFilterSelect.this.getAbsoluteLeft()
+ VFilterSelect.this.getOffsetWidth()
+ Window.getScrollLeft() - offsetWidth;
if (left < 0) {
left = 0;
}
} else {
left = getPopupLeft();
}
setPopupPosition(left, top);
}
/**
* @return true if popup was just closed
*/
public boolean isJustClosed() {
final long now = (new Date()).getTime();
return (lastAutoClosed > 0 && (now - lastAutoClosed) < 200);
}
public void onClose(CloseEvent<PopupPanel> event) {
if (event.isAutoClosed()) {
lastAutoClosed = (new Date()).getTime();
}
}
/**
* Updates style names in suggestion popup to help theme building.
*/
public void updateStyleNames(UIDL uidl) {
if (uidl.hasAttribute("style")) {
setStyleName(CLASSNAME + "-suggestpopup");
final String[] styles = uidl.getStringAttribute("style").split(
" ");
for (int i = 0; i < styles.length; i++) {
addStyleDependentName(styles[i]);
}
}
}
}
public class SuggestionMenu extends MenuBar {
SuggestionMenu() {
super(true);
setStyleName(CLASSNAME + "-suggestmenu");
}
/**
* Fixes menus height to use same space as full page would use. Needed
* to avoid height changes when quickly "scrolling" to last page
*/
public void fixHeightTo(int pagelenth) {
if (currentSuggestions.size() > 0) {
final int pixels = pagelenth * (getOffsetHeight() - 2)
/ currentSuggestions.size();
setHeight((pixels + 2) + "px");
}
}
public void setSuggestions(
Collection<FilterSelectSuggestion> suggestions) {
clearItems();
final Iterator<FilterSelectSuggestion> it = suggestions.iterator();
while (it.hasNext()) {
final FilterSelectSuggestion s = it.next();
final MenuItem mi = new MenuItem(s.getDisplayString(), true, s);
com.google.gwt.dom.client.Element child = mi.getElement()
.getFirstChildElement();
while (child != null) {
if (child.getNodeName().toLowerCase().equals("img")) {
DOM
.sinkEvents((Element) child.cast(),
(DOM.getEventsSunk((Element) child
.cast()) | Event.ONLOAD));
}
child = child.getNextSiblingElement();
}
this.addItem(mi);
if (s == currentSuggestion) {
selectItem(mi);
}
}
}
public void doSelectedItemAction() {
final MenuItem item = getSelectedItem();
final String enteredItemValue = tb.getText();
if (nullSelectionAllowed && "".equals(enteredItemValue)) {
if (nullSelectItem) {
reset();
return;
}
// null is not visible on pages != 0, and not visible when
// filtering: handle separately
client.updateVariable(paintableId, "filter", "", false);
client.updateVariable(paintableId, "page", 0, false);
client.updateVariable(paintableId, "selected", new String[] {},
immediate);
suggestionPopup.hide();
return;
}
// check for exact match in menu
int p = getItems().size();
if (p > 0) {
for (int i = 0; i < p; i++) {
final MenuItem potentialExactMatch = (MenuItem) getItems()
.get(i);
if (potentialExactMatch.getText().equals(enteredItemValue)) {
selectItem(potentialExactMatch);
doItemAction(potentialExactMatch, true);
suggestionPopup.hide();
return;
}
}
}
if (allowNewItem) {
if (!prompting && !enteredItemValue.equals(lastNewItemString)) {
/*
* Store last sent new item string to avoid double sends
*/
lastNewItemString = enteredItemValue;
client.updateVariable(paintableId, "newitem",
enteredItemValue, immediate);
}
} else if (item != null
&& !"".equals(lastFilter)
&& item.getText().toLowerCase().startsWith(
lastFilter.toLowerCase())) {
doItemAction(item, true);
} else {
// currentSuggestion has key="" for nullselection
if (currentSuggestion != null
&& !currentSuggestion.key.equals("")) {
// An item (not null) selected
String text = currentSuggestion.getReplacementString();
tb.setText(text);
selectedOptionKey = currentSuggestion.key;
} else {
// Null selected
tb.setText("");
selectedOptionKey = null;
}
}
suggestionPopup.hide();
}
@Override
public void onBrowserEvent(Event event) {
if (event.getTypeInt() == Event.ONLOAD) {
if (suggestionPopup.isVisible()) {
setWidth("");
DOM.setStyleAttribute(DOM.getFirstChild(getElement()),
"width", "");
suggestionPopup.setPopupPositionAndShow(suggestionPopup);
}
}
super.onBrowserEvent(event);
}
}
public static final int FILTERINGMODE_OFF = 0;
public static final int FILTERINGMODE_STARTSWITH = 1;
public static final int FILTERINGMODE_CONTAINS = 2;
private static final String CLASSNAME = "v-filterselect";
protected int pageLength = 10;
private final FlowPanel panel = new FlowPanel();
private final TextBox tb = new TextBox() {
@Override
public void onBrowserEvent(Event event) {
super.onBrowserEvent(event);
if (client != null) {
client.handleTooltipEvent(event, VFilterSelect.this);
}
}
};
private final SuggestionPopup suggestionPopup = new SuggestionPopup();
private final HTML popupOpener = new HTML("") {
@Override
public void onBrowserEvent(Event event) {
super.onBrowserEvent(event);
if (client != null) {
client.handleTooltipEvent(event, VFilterSelect.this);
}
}
};
private final Image selectedItemIcon = new Image();
private ApplicationConnection client;
private String paintableId;
private int currentPage;
private final Collection<FilterSelectSuggestion> currentSuggestions = new ArrayList<FilterSelectSuggestion>();
private boolean immediate;
private String selectedOptionKey;
private boolean filtering = false;
private String lastFilter = "";
private int lastIndex = -1; // last selected index when using arrows
private FilterSelectSuggestion currentSuggestion;
private int totalMatches;
private boolean allowNewItem;
private boolean nullSelectionAllowed;
private boolean nullSelectItem;
private boolean enabled;
// shown in unfocused empty field, disappears on focus (e.g "Search here")
private static final String CLASSNAME_PROMPT = "prompt";
private static final String ATTR_INPUTPROMPT = "prompt";
private String inputPrompt = "";
private boolean prompting = false;
// Set true when popupopened has been clicked. Cleared on each UIDL-update.
// This handles the special case where are not filtering yet and the
// selected value has changed on the server-side. See #2119
private boolean popupOpenerClicked;
private String width = null;
private int textboxPadding = -1;
private int componentPadding = -1;
private int suggestionPopupMinWidth = 0;
/*
* Stores the last new item string to avoid double submissions. Cleared on
* uidl updates
*/
private String lastNewItemString;
private boolean focused = false;
private int horizPaddingAndBorder = 2;
public VFilterSelect() {
selectedItemIcon.setStyleName("v-icon");
selectedItemIcon.addLoadHandler(new LoadHandler() {
public void onLoad(LoadEvent event) {
updateRootWidth();
updateSelectedIconPosition();
}
});
tb.sinkEvents(VTooltip.TOOLTIP_EVENTS);
popupOpener.sinkEvents(VTooltip.TOOLTIP_EVENTS);
panel.add(tb);
panel.add(popupOpener);
initWidget(panel);
setStyleName(CLASSNAME);
tb.addKeyDownHandler(this);
tb.addKeyUpHandler(this);
tb.setStyleName(CLASSNAME + "-input");
tb.addFocusHandler(this);
tb.addBlurHandler(this);
popupOpener.setStyleName(CLASSNAME + "-button");
popupOpener.addClickHandler(this);
}
public boolean hasNextPage() {
if (totalMatches > (currentPage + 1) * pageLength) {
return true;
} else {
return false;
}
}
public void filterOptions(int page) {
filterOptions(page, tb.getText());
}
public void filterOptions(int page, String filter) {
if (filter.equals(lastFilter) && currentPage == page) {
if (!suggestionPopup.isAttached()) {
suggestionPopup.showSuggestions(currentSuggestions,
currentPage, totalMatches);
}
return;
}
if (!filter.equals(lastFilter)) {
// we are on subsequent page and text has changed -> reset page
if ("".equals(filter)) {
// let server decide
page = -1;
} else {
page = 0;
}
}
filtering = true;
client.updateVariable(paintableId, "filter", filter, false);
client.updateVariable(paintableId, "page", page, true);
lastFilter = filter;
currentPage = page;
}
@SuppressWarnings("deprecation")
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
paintableId = uidl.getId();
this.client = client;
boolean readonly = uidl.hasAttribute("readonly");
boolean disabled = uidl.hasAttribute("disabled");
if (disabled || readonly) {
tb.setEnabled(false);
enabled = false;
} else {
tb.setEnabled(true);
enabled = true;
}
if (client.updateComponent(this, uidl, true)) {
return;
}
// not a FocusWidget -> needs own tabindex handling
if (uidl.hasAttribute("tabindex")) {
tb.setTabIndex(uidl.getIntAttribute("tabindex"));
}
immediate = uidl.hasAttribute("immediate");
nullSelectionAllowed = uidl.hasAttribute("nullselect");
nullSelectItem = uidl.hasAttribute("nullselectitem")
&& uidl.getBooleanAttribute("nullselectitem");
currentPage = uidl.getIntVariable("page");
if (uidl.hasAttribute("pagelength")) {
pageLength = uidl.getIntAttribute("pagelength");
}
if (uidl.hasAttribute(ATTR_INPUTPROMPT)) {
// input prompt changed from server
inputPrompt = uidl.getStringAttribute(ATTR_INPUTPROMPT);
} else {
inputPrompt = "";
}
suggestionPopup.setPagingEnabled(true);
suggestionPopup.updateStyleNames(uidl);
allowNewItem = uidl.hasAttribute("allownewitem");
lastNewItemString = null;
currentSuggestions.clear();
final UIDL options = uidl.getChildUIDL(0);
totalMatches = uidl.getIntAttribute("totalMatches");
String captions = inputPrompt;
for (final Iterator i = options.getChildIterator(); i.hasNext();) {
final UIDL optionUidl = (UIDL) i.next();
final FilterSelectSuggestion suggestion = new FilterSelectSuggestion(
optionUidl);
currentSuggestions.add(suggestion);
if (optionUidl.hasAttribute("selected")) {
if (!filtering || popupOpenerClicked) {
setPromptingOff(suggestion.getReplacementString());
selectedOptionKey = "" + suggestion.getOptionKey();
}
currentSuggestion = suggestion;
setSelectedItemIcon(suggestion.getIconUri());
}
// Collect captions so we can calculate minimum width for textarea
if (captions.length() > 0) {
captions += "|";
}
captions += suggestion.getReplacementString();
}
if ((!filtering || popupOpenerClicked) && uidl.hasVariable("selected")
&& uidl.getStringArrayVariable("selected").length == 0) {
// select nulled
if (!filtering || !popupOpenerClicked) {
+ /*
+ * client.updateComponent overwrites all styles so we must
+ * ALWAYS set the prompting style at this point, even though we
+ * think it has been set already...
+ */
+ prompting = false;
setPromptingOn();
}
selectedOptionKey = null;
}
if (filtering
&& lastFilter.toLowerCase().equals(
uidl.getStringVariable("filter"))) {
suggestionPopup.showSuggestions(currentSuggestions, currentPage,
totalMatches);
filtering = false;
if (!popupOpenerClicked && lastIndex != -1) {
// we're paging w/ arrows
MenuItem activeMenuItem;
if (lastIndex == 0) {
// going up, select last item
int lastItem = pageLength - 1;
List items = suggestionPopup.menu.getItems();
/*
* The first page can contain less than 10 items if the null
* selection item is filtered away
*/
if (lastItem >= items.size()) {
lastItem = items.size() - 1;
}
activeMenuItem = (MenuItem) items.get(lastItem);
suggestionPopup.menu.selectItem(activeMenuItem);
} else {
// going down, select first item
activeMenuItem = (MenuItem) suggestionPopup.menu.getItems()
.get(0);
suggestionPopup.menu.selectItem(activeMenuItem);
}
tb.setText(activeMenuItem.getText());
tb.setSelectionRange(lastFilter.length(), activeMenuItem
.getText().length()
- lastFilter.length());
lastIndex = -1; // reset
}
}
// Calculate minumum textarea width
suggestionPopupMinWidth = minWidth(captions);
popupOpenerClicked = false;
updateRootWidth();
}
private void setPromptingOn() {
if (!prompting) {
prompting = true;
addStyleDependentName(CLASSNAME_PROMPT);
}
tb.setText(inputPrompt);
}
private void setPromptingOff(String text) {
tb.setText(text);
if (prompting) {
prompting = false;
removeStyleDependentName(CLASSNAME_PROMPT);
}
}
public void onSuggestionSelected(FilterSelectSuggestion suggestion) {
currentSuggestion = suggestion;
String newKey;
if (suggestion.key.equals("")) {
// "nullselection"
newKey = "";
} else {
// normal selection
newKey = String.valueOf(suggestion.getOptionKey());
}
String text = suggestion.getReplacementString();
if ("".equals(newKey) && !focused) {
setPromptingOn();
} else {
setPromptingOff(text);
}
setSelectedItemIcon(suggestion.getIconUri());
if (!newKey.equals(selectedOptionKey)) {
selectedOptionKey = newKey;
client.updateVariable(paintableId, "selected",
new String[] { selectedOptionKey }, immediate);
// currentPage = -1; // forget the page
}
suggestionPopup.hide();
}
private void setSelectedItemIcon(String iconUri) {
if (iconUri == null || iconUri == "") {
panel.remove(selectedItemIcon);
updateRootWidth();
} else {
selectedItemIcon.setUrl(iconUri);
panel.insert(selectedItemIcon, 0);
updateRootWidth();
updateSelectedIconPosition();
}
}
private void updateSelectedIconPosition() {
// Position icon vertically to middle
int availableHeight = getOffsetHeight();
int iconHeight = Util.getRequiredHeight(selectedItemIcon);
int marginTop = (availableHeight - iconHeight) / 2;
DOM.setStyleAttribute(selectedItemIcon.getElement(), "marginTop",
marginTop + "px");
}
public void onKeyDown(KeyDownEvent event) {
if (enabled) {
if (suggestionPopup.isAttached()) {
popupKeyDown(event);
} else {
inputFieldKeyDown(event);
}
}
}
private void inputFieldKeyDown(KeyDownEvent event) {
switch (event.getNativeKeyCode()) {
case KeyCodes.KEY_DOWN:
case KeyCodes.KEY_UP:
case KeyCodes.KEY_PAGEDOWN:
case KeyCodes.KEY_PAGEUP:
if (suggestionPopup.isAttached()) {
break;
} else {
// open popup as from gadget
filterOptions(-1, "");
lastFilter = "";
tb.selectAll();
break;
}
}
}
private void popupKeyDown(KeyDownEvent event) {
switch (event.getNativeKeyCode()) {
case KeyCodes.KEY_DOWN:
suggestionPopup.selectNextItem();
DOM.eventPreventDefault(DOM.eventGetCurrentEvent());
break;
case KeyCodes.KEY_UP:
suggestionPopup.selectPrevItem();
DOM.eventPreventDefault(DOM.eventGetCurrentEvent());
break;
case KeyCodes.KEY_PAGEDOWN:
if (hasNextPage()) {
filterOptions(currentPage + 1, lastFilter);
}
break;
case KeyCodes.KEY_PAGEUP:
if (currentPage > 0) {
filterOptions(currentPage - 1, lastFilter);
}
break;
case KeyCodes.KEY_ENTER:
case KeyCodes.KEY_TAB:
suggestionPopup.menu.doSelectedItemAction();
break;
}
}
public void onKeyUp(KeyUpEvent event) {
if (enabled) {
switch (event.getNativeKeyCode()) {
case KeyCodes.KEY_ENTER:
case KeyCodes.KEY_TAB:
case KeyCodes.KEY_SHIFT:
case KeyCodes.KEY_CTRL:
case KeyCodes.KEY_ALT:
case KeyCodes.KEY_DOWN:
case KeyCodes.KEY_UP:
case KeyCodes.KEY_PAGEDOWN:
case KeyCodes.KEY_PAGEUP:
; // NOP
break;
case KeyCodes.KEY_ESCAPE:
reset();
break;
default:
filterOptions(currentPage);
break;
}
}
}
private void reset() {
if (currentSuggestion != null) {
String text = currentSuggestion.getReplacementString();
setPromptingOff(text);
selectedOptionKey = currentSuggestion.key;
} else {
setPromptingOn();
selectedOptionKey = null;
}
lastFilter = "";
suggestionPopup.hide();
}
/**
* Listener for popupopener
*/
public void onClick(ClickEvent event) {
if (enabled) {
// ask suggestionPopup if it was just closed, we are using GWT
// Popup's auto close feature
if (!suggestionPopup.isJustClosed()) {
filterOptions(-1, "");
popupOpenerClicked = true;
lastFilter = "";
} else if (selectedOptionKey == null) {
tb.setText(inputPrompt);
prompting = true;
}
DOM.eventPreventDefault(DOM.eventGetCurrentEvent());
tb.setFocus(true);
tb.selectAll();
}
}
/*
* Calculate minumum width for FilterSelect textarea
*/
private native int minWidth(String captions)
/*-{
if(!captions || captions.length <= 0)
return 0;
captions = captions.split("|");
var d = $wnd.document.createElement("div");
var html = "";
for(var i=0; i < captions.length; i++) {
html += "<div>" + captions[i] + "</div>";
// TODO apply same CSS classname as in suggestionmenu
}
d.style.position = "absolute";
d.style.top = "0";
d.style.left = "0";
d.style.visibility = "hidden";
d.innerHTML = html;
$wnd.document.body.appendChild(d);
var w = d.offsetWidth;
$wnd.document.body.removeChild(d);
return w;
}-*/;
public void onFocus(FocusEvent event) {
focused = true;
if (prompting) {
setPromptingOff("");
}
addStyleDependentName("focus");
}
public void onBlur(BlurEvent event) {
focused = false;
if (!suggestionPopup.isAttached() || suggestionPopup.isJustClosed()) {
// typing so fast the popup was never opened, or it's just closed
suggestionPopup.menu.doSelectedItemAction();
}
if (selectedOptionKey == null) {
setPromptingOn();
}
removeStyleDependentName("focus");
}
public void focus() {
focused = true;
if (prompting) {
setPromptingOff("");
}
tb.setFocus(true);
}
@Override
public void setWidth(String width) {
if (width == null || width.equals("")) {
this.width = null;
} else {
this.width = width;
}
horizPaddingAndBorder = Util.setWidthExcludingPaddingAndBorder(this,
width, horizPaddingAndBorder);
updateRootWidth();
}
@Override
public void setHeight(String height) {
super.setHeight(height);
Util.setHeightExcludingPaddingAndBorder(tb, height, 3);
}
private void updateRootWidth() {
if (width == null) {
/*
* When the width is not specified we must specify width for root
* div so the popupopener won't wrap to the next line and also so
* the size of the combobox won't change over time.
*/
int tbWidth = Util.getRequiredWidth(tb);
int openerWidth = Util.getRequiredWidth(popupOpener);
int iconWidth = selectedItemIcon.isAttached() ? Util
.measureMarginLeft(tb.getElement())
- Util.measureMarginLeft(selectedItemIcon.getElement()) : 0;
int w = tbWidth + openerWidth + iconWidth;
if (suggestionPopupMinWidth > w) {
setTextboxWidth(suggestionPopupMinWidth);
w = suggestionPopupMinWidth;
} else {
/*
* Firefox3 has its own way of doing rendering so we need to
* specify the width for the TextField to make sure it actually
* is rendered as wide as FF3 says it is
*/
tb.setWidth((tbWidth - getTextboxPadding()) + "px");
}
super.setWidth((w) + "px");
// Freeze the initial width, so that it won't change even if the
// icon size changes
width = w + "px";
} else {
/*
* When the width is specified we also want to explicitly specify
* widths for textbox and popupopener
*/
setTextboxWidth(getMainWidth() - getComponentPadding());
}
}
private int getMainWidth() {
int componentWidth;
if (BrowserInfo.get().isIE6()) {
// Required in IE when textfield is wider than this.width
DOM.setStyleAttribute(getElement(), "overflow", "hidden");
componentWidth = getOffsetWidth();
DOM.setStyleAttribute(getElement(), "overflow", "");
} else {
componentWidth = getOffsetWidth();
}
return componentWidth;
}
private void setTextboxWidth(int componentWidth) {
int padding = getTextboxPadding();
int popupOpenerWidth = Util.getRequiredWidth(popupOpener);
int iconWidth = selectedItemIcon.isAttached() ? Util
.getRequiredWidth(selectedItemIcon) : 0;
int textboxWidth = componentWidth - padding - popupOpenerWidth
- iconWidth;
if (textboxWidth < 0) {
textboxWidth = 0;
}
tb.setWidth(textboxWidth + "px");
}
private int getTextboxPadding() {
if (textboxPadding < 0) {
textboxPadding = Util.measureHorizontalPaddingAndBorder(tb
.getElement(), 4);
}
return textboxPadding;
}
private int getComponentPadding() {
if (componentPadding < 0) {
componentPadding = Util.measureHorizontalPaddingAndBorder(
getElement(), 3);
}
return componentPadding;
}
}
| true | true | public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
paintableId = uidl.getId();
this.client = client;
boolean readonly = uidl.hasAttribute("readonly");
boolean disabled = uidl.hasAttribute("disabled");
if (disabled || readonly) {
tb.setEnabled(false);
enabled = false;
} else {
tb.setEnabled(true);
enabled = true;
}
if (client.updateComponent(this, uidl, true)) {
return;
}
// not a FocusWidget -> needs own tabindex handling
if (uidl.hasAttribute("tabindex")) {
tb.setTabIndex(uidl.getIntAttribute("tabindex"));
}
immediate = uidl.hasAttribute("immediate");
nullSelectionAllowed = uidl.hasAttribute("nullselect");
nullSelectItem = uidl.hasAttribute("nullselectitem")
&& uidl.getBooleanAttribute("nullselectitem");
currentPage = uidl.getIntVariable("page");
if (uidl.hasAttribute("pagelength")) {
pageLength = uidl.getIntAttribute("pagelength");
}
if (uidl.hasAttribute(ATTR_INPUTPROMPT)) {
// input prompt changed from server
inputPrompt = uidl.getStringAttribute(ATTR_INPUTPROMPT);
} else {
inputPrompt = "";
}
suggestionPopup.setPagingEnabled(true);
suggestionPopup.updateStyleNames(uidl);
allowNewItem = uidl.hasAttribute("allownewitem");
lastNewItemString = null;
currentSuggestions.clear();
final UIDL options = uidl.getChildUIDL(0);
totalMatches = uidl.getIntAttribute("totalMatches");
String captions = inputPrompt;
for (final Iterator i = options.getChildIterator(); i.hasNext();) {
final UIDL optionUidl = (UIDL) i.next();
final FilterSelectSuggestion suggestion = new FilterSelectSuggestion(
optionUidl);
currentSuggestions.add(suggestion);
if (optionUidl.hasAttribute("selected")) {
if (!filtering || popupOpenerClicked) {
setPromptingOff(suggestion.getReplacementString());
selectedOptionKey = "" + suggestion.getOptionKey();
}
currentSuggestion = suggestion;
setSelectedItemIcon(suggestion.getIconUri());
}
// Collect captions so we can calculate minimum width for textarea
if (captions.length() > 0) {
captions += "|";
}
captions += suggestion.getReplacementString();
}
if ((!filtering || popupOpenerClicked) && uidl.hasVariable("selected")
&& uidl.getStringArrayVariable("selected").length == 0) {
// select nulled
if (!filtering || !popupOpenerClicked) {
setPromptingOn();
}
selectedOptionKey = null;
}
if (filtering
&& lastFilter.toLowerCase().equals(
uidl.getStringVariable("filter"))) {
suggestionPopup.showSuggestions(currentSuggestions, currentPage,
totalMatches);
filtering = false;
if (!popupOpenerClicked && lastIndex != -1) {
// we're paging w/ arrows
MenuItem activeMenuItem;
if (lastIndex == 0) {
// going up, select last item
int lastItem = pageLength - 1;
List items = suggestionPopup.menu.getItems();
/*
* The first page can contain less than 10 items if the null
* selection item is filtered away
*/
if (lastItem >= items.size()) {
lastItem = items.size() - 1;
}
activeMenuItem = (MenuItem) items.get(lastItem);
suggestionPopup.menu.selectItem(activeMenuItem);
} else {
// going down, select first item
activeMenuItem = (MenuItem) suggestionPopup.menu.getItems()
.get(0);
suggestionPopup.menu.selectItem(activeMenuItem);
}
tb.setText(activeMenuItem.getText());
tb.setSelectionRange(lastFilter.length(), activeMenuItem
.getText().length()
- lastFilter.length());
lastIndex = -1; // reset
}
}
// Calculate minumum textarea width
suggestionPopupMinWidth = minWidth(captions);
popupOpenerClicked = false;
updateRootWidth();
}
| public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
paintableId = uidl.getId();
this.client = client;
boolean readonly = uidl.hasAttribute("readonly");
boolean disabled = uidl.hasAttribute("disabled");
if (disabled || readonly) {
tb.setEnabled(false);
enabled = false;
} else {
tb.setEnabled(true);
enabled = true;
}
if (client.updateComponent(this, uidl, true)) {
return;
}
// not a FocusWidget -> needs own tabindex handling
if (uidl.hasAttribute("tabindex")) {
tb.setTabIndex(uidl.getIntAttribute("tabindex"));
}
immediate = uidl.hasAttribute("immediate");
nullSelectionAllowed = uidl.hasAttribute("nullselect");
nullSelectItem = uidl.hasAttribute("nullselectitem")
&& uidl.getBooleanAttribute("nullselectitem");
currentPage = uidl.getIntVariable("page");
if (uidl.hasAttribute("pagelength")) {
pageLength = uidl.getIntAttribute("pagelength");
}
if (uidl.hasAttribute(ATTR_INPUTPROMPT)) {
// input prompt changed from server
inputPrompt = uidl.getStringAttribute(ATTR_INPUTPROMPT);
} else {
inputPrompt = "";
}
suggestionPopup.setPagingEnabled(true);
suggestionPopup.updateStyleNames(uidl);
allowNewItem = uidl.hasAttribute("allownewitem");
lastNewItemString = null;
currentSuggestions.clear();
final UIDL options = uidl.getChildUIDL(0);
totalMatches = uidl.getIntAttribute("totalMatches");
String captions = inputPrompt;
for (final Iterator i = options.getChildIterator(); i.hasNext();) {
final UIDL optionUidl = (UIDL) i.next();
final FilterSelectSuggestion suggestion = new FilterSelectSuggestion(
optionUidl);
currentSuggestions.add(suggestion);
if (optionUidl.hasAttribute("selected")) {
if (!filtering || popupOpenerClicked) {
setPromptingOff(suggestion.getReplacementString());
selectedOptionKey = "" + suggestion.getOptionKey();
}
currentSuggestion = suggestion;
setSelectedItemIcon(suggestion.getIconUri());
}
// Collect captions so we can calculate minimum width for textarea
if (captions.length() > 0) {
captions += "|";
}
captions += suggestion.getReplacementString();
}
if ((!filtering || popupOpenerClicked) && uidl.hasVariable("selected")
&& uidl.getStringArrayVariable("selected").length == 0) {
// select nulled
if (!filtering || !popupOpenerClicked) {
/*
* client.updateComponent overwrites all styles so we must
* ALWAYS set the prompting style at this point, even though we
* think it has been set already...
*/
prompting = false;
setPromptingOn();
}
selectedOptionKey = null;
}
if (filtering
&& lastFilter.toLowerCase().equals(
uidl.getStringVariable("filter"))) {
suggestionPopup.showSuggestions(currentSuggestions, currentPage,
totalMatches);
filtering = false;
if (!popupOpenerClicked && lastIndex != -1) {
// we're paging w/ arrows
MenuItem activeMenuItem;
if (lastIndex == 0) {
// going up, select last item
int lastItem = pageLength - 1;
List items = suggestionPopup.menu.getItems();
/*
* The first page can contain less than 10 items if the null
* selection item is filtered away
*/
if (lastItem >= items.size()) {
lastItem = items.size() - 1;
}
activeMenuItem = (MenuItem) items.get(lastItem);
suggestionPopup.menu.selectItem(activeMenuItem);
} else {
// going down, select first item
activeMenuItem = (MenuItem) suggestionPopup.menu.getItems()
.get(0);
suggestionPopup.menu.selectItem(activeMenuItem);
}
tb.setText(activeMenuItem.getText());
tb.setSelectionRange(lastFilter.length(), activeMenuItem
.getText().length()
- lastFilter.length());
lastIndex = -1; // reset
}
}
// Calculate minumum textarea width
suggestionPopupMinWidth = minWidth(captions);
popupOpenerClicked = false;
updateRootWidth();
}
|
diff --git a/wsdef/wsdef-common/src/main/java/org/openecard/ws/soap/SOAPMessage.java b/wsdef/wsdef-common/src/main/java/org/openecard/ws/soap/SOAPMessage.java
index e517ceab..1dba4708 100644
--- a/wsdef/wsdef-common/src/main/java/org/openecard/ws/soap/SOAPMessage.java
+++ b/wsdef/wsdef-common/src/main/java/org/openecard/ws/soap/SOAPMessage.java
@@ -1,131 +1,132 @@
/****************************************************************************
* Copyright (C) 2012 ecsec GmbH.
* All rights reserved.
* Contact: ecsec GmbH ([email protected])
*
* This file is part of the Open eCard App.
*
* GNU General Public License Usage
* This file may be used under the terms of the GNU General Public
* License version 3.0 as published by the Free Software Foundation
* and appearing in the file LICENSE.GPL included in the packaging of
* this file. Please review the following information to ensure the
* GNU General Public License version 3.0 requirements will be met:
* http://www.gnu.org/copyleft/gpl.html.
*
* Other Usage
* Alternatively, this file may be used in accordance with the terms
* and conditions contained in a signed written agreement between
* you and ecsec GmbH.
*
***************************************************************************/
package org.openecard.ws.soap;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
*
* @author Tobias Wich <[email protected]>
*/
public class SOAPMessage {
private final Document doc;
private final String namespace;
private final SOAPEnvelope env;
private final SOAPHeader head;
private final SOAPBody body;
protected SOAPMessage(DocumentBuilder docBuilder, String namespace) throws SOAPException {
doc = docBuilder.newDocument();
this.namespace = namespace;
// add envelope and that stuff
Element envElem = doc.createElementNS(namespace, "Envelope");
env = new SOAPEnvelope(envElem);
doc.appendChild(envElem);
Element headElem = env.addChildElement(new QName(namespace, "Header"));
head = new SOAPHeader(headElem);
Element bodyElem = env.addChildElement(new QName(namespace, "Body"));
body = new SOAPBody(bodyElem);
}
protected SOAPMessage(Document doc) throws SOAPException {
this.doc = doc;
Element envElem = (Element) doc.getFirstChild();
if (envElem == null) {
throw new SOAPException("No Envelope element in SOAP message.");
}
env = new SOAPEnvelope(envElem);
namespace = MessageFactory.verifyNamespace(envElem.getNamespaceURI());
// extract envelope and stuff from doc
boolean headProcessed = false;
Element headElem = null;
boolean bodyProcessed = false;
Element bodyElem = null;
// extract info
NodeList nodes = envElem.getChildNodes();
for (int i=0; i < nodes.getLength(); i++) {
Node n = nodes.item(i);
if (n.getNodeType() == Node.ELEMENT_NODE) {
Element e = (Element) n;
if (e.getNamespaceURI().equals(namespace)) {
// head is next
if (!headProcessed && !bodyProcessed && "Header".equals(e.getLocalName())) {
headProcessed = true;
headElem = e;
} else if (!bodyProcessed && "Body".equals(e.getLocalName())) {
bodyProcessed = true;
bodyElem = e;
} else {
throw new SOAPException("Undefined element (" + e.getLocalName() + ") in SOAP message.");
}
} else {
throw new SOAPException("Undefined namespace (" + e.getNamespaceURI() + ") in SOAP message.");
}
} else if (n.getNodeType() == Node.TEXT_NODE || n.getNodeType() == Node.CDATA_SECTION_NODE) {
- throw new SOAPException("Undefined node type in SOAP message.");
+ //throw new SOAPException("Undefined node type in SOAP message.");
+ System.out.println("Undefined node type in SOAP message: " + n.getNodeType() + n.getNodeName() + n.getNodeValue() + n.getTextContent());
}
}
// check if all info is present, else create it
if (! bodyProcessed) {
throw new SOAPException("No Body element present in SOAP message.");
}
if (! headProcessed) {
headElem = doc.createElementNS(namespace, "Header");
headElem = (Element) envElem.insertBefore(headElem, bodyElem);
}
head = new SOAPHeader(headElem);
body = new SOAPBody(bodyElem);
}
public Document getDocument() {
return doc;
}
public SOAPEnvelope getSOAPEnvelope() {
return env;
}
public SOAPHeader getSOAPHeader() {
return head;
}
public SOAPBody getSOAPBody() {
return body;
}
}
| true | true | protected SOAPMessage(Document doc) throws SOAPException {
this.doc = doc;
Element envElem = (Element) doc.getFirstChild();
if (envElem == null) {
throw new SOAPException("No Envelope element in SOAP message.");
}
env = new SOAPEnvelope(envElem);
namespace = MessageFactory.verifyNamespace(envElem.getNamespaceURI());
// extract envelope and stuff from doc
boolean headProcessed = false;
Element headElem = null;
boolean bodyProcessed = false;
Element bodyElem = null;
// extract info
NodeList nodes = envElem.getChildNodes();
for (int i=0; i < nodes.getLength(); i++) {
Node n = nodes.item(i);
if (n.getNodeType() == Node.ELEMENT_NODE) {
Element e = (Element) n;
if (e.getNamespaceURI().equals(namespace)) {
// head is next
if (!headProcessed && !bodyProcessed && "Header".equals(e.getLocalName())) {
headProcessed = true;
headElem = e;
} else if (!bodyProcessed && "Body".equals(e.getLocalName())) {
bodyProcessed = true;
bodyElem = e;
} else {
throw new SOAPException("Undefined element (" + e.getLocalName() + ") in SOAP message.");
}
} else {
throw new SOAPException("Undefined namespace (" + e.getNamespaceURI() + ") in SOAP message.");
}
} else if (n.getNodeType() == Node.TEXT_NODE || n.getNodeType() == Node.CDATA_SECTION_NODE) {
throw new SOAPException("Undefined node type in SOAP message.");
}
}
// check if all info is present, else create it
if (! bodyProcessed) {
throw new SOAPException("No Body element present in SOAP message.");
}
if (! headProcessed) {
headElem = doc.createElementNS(namespace, "Header");
headElem = (Element) envElem.insertBefore(headElem, bodyElem);
}
head = new SOAPHeader(headElem);
body = new SOAPBody(bodyElem);
}
| protected SOAPMessage(Document doc) throws SOAPException {
this.doc = doc;
Element envElem = (Element) doc.getFirstChild();
if (envElem == null) {
throw new SOAPException("No Envelope element in SOAP message.");
}
env = new SOAPEnvelope(envElem);
namespace = MessageFactory.verifyNamespace(envElem.getNamespaceURI());
// extract envelope and stuff from doc
boolean headProcessed = false;
Element headElem = null;
boolean bodyProcessed = false;
Element bodyElem = null;
// extract info
NodeList nodes = envElem.getChildNodes();
for (int i=0; i < nodes.getLength(); i++) {
Node n = nodes.item(i);
if (n.getNodeType() == Node.ELEMENT_NODE) {
Element e = (Element) n;
if (e.getNamespaceURI().equals(namespace)) {
// head is next
if (!headProcessed && !bodyProcessed && "Header".equals(e.getLocalName())) {
headProcessed = true;
headElem = e;
} else if (!bodyProcessed && "Body".equals(e.getLocalName())) {
bodyProcessed = true;
bodyElem = e;
} else {
throw new SOAPException("Undefined element (" + e.getLocalName() + ") in SOAP message.");
}
} else {
throw new SOAPException("Undefined namespace (" + e.getNamespaceURI() + ") in SOAP message.");
}
} else if (n.getNodeType() == Node.TEXT_NODE || n.getNodeType() == Node.CDATA_SECTION_NODE) {
//throw new SOAPException("Undefined node type in SOAP message.");
System.out.println("Undefined node type in SOAP message: " + n.getNodeType() + n.getNodeName() + n.getNodeValue() + n.getTextContent());
}
}
// check if all info is present, else create it
if (! bodyProcessed) {
throw new SOAPException("No Body element present in SOAP message.");
}
if (! headProcessed) {
headElem = doc.createElementNS(namespace, "Header");
headElem = (Element) envElem.insertBefore(headElem, bodyElem);
}
head = new SOAPHeader(headElem);
body = new SOAPBody(bodyElem);
}
|
diff --git a/core/src/test/java/org/infinispan/config/parsing/GlobalConfigurationParserTest.java b/core/src/test/java/org/infinispan/config/parsing/GlobalConfigurationParserTest.java
index 3bd7b111b1..5af3edcbe9 100644
--- a/core/src/test/java/org/infinispan/config/parsing/GlobalConfigurationParserTest.java
+++ b/core/src/test/java/org/infinispan/config/parsing/GlobalConfigurationParserTest.java
@@ -1,214 +1,214 @@
package org.infinispan.config.parsing;
import org.infinispan.config.GlobalConfiguration;
import org.infinispan.executors.DefaultExecutorFactory;
import org.infinispan.executors.DefaultScheduledExecutorFactory;
import org.infinispan.marshall.MarshallerImpl;
import org.infinispan.marshall.VersionAwareMarshaller;
import org.infinispan.remoting.transport.jgroups.JGroupsTransport;
import org.testng.annotations.Test;
import org.w3c.dom.Element;
@Test(groups = "unit", testName = "config.parsing.GlobalConfigurationParserTest")
public class GlobalConfigurationParserTest {
public void testTransport() throws Exception {
XmlConfigurationParserImpl parser = new XmlConfigurationParserImpl();
String transportClass = "org.blah.Blah";
String xml = "<transport transportClass=\"" + transportClass + "\"><property name=\"something\" value=\"value\"/></transport>";
Element e = XmlConfigHelper.stringToElement(xml);
GlobalConfiguration gc = new GlobalConfiguration();
parser.configureTransport(e, gc);
assert gc.getTransportClass().equals(transportClass);
assert gc.getTransportProperties().size() == 1;
assert gc.getTransportProperties().getProperty("something").equals("value");
}
public void testDefaultTransport() throws Exception {
XmlConfigurationParserImpl parser = new XmlConfigurationParserImpl();
String xml = "<transport />";
Element e = XmlConfigHelper.stringToElement(xml);
GlobalConfiguration gc = new GlobalConfiguration();
parser.configureTransport(e, gc);
assert gc.getTransportClass().equals(JGroupsTransport.class.getName());
assert gc.getTransportProperties().size() == 0;
}
public void testGlobalJmxStatistics() throws Exception {
XmlConfigurationParserImpl parser = new XmlConfigurationParserImpl();
String xml = "<globalJmxStatistics enabled=\"true\" jmxDomain=\"horizons\" mBeanServerLookup=\"org.infinispan.jmx.PerThreadMBeanServerLookup\" allowDuplicateDomains=\"true\"/>";
Element e = XmlConfigHelper.stringToElement(xml);
GlobalConfiguration c = new GlobalConfiguration();
parser.configureGlobalJmxStatistics(e, c);
assert c.isExposeGlobalJmxStatistics();
assert c.getJmxDomain().equals("horizons");
assert c.getMBeanServerLookup().equals("org.infinispan.jmx.PerThreadMBeanServerLookup");
assert c.isAllowDuplicateDomains();
}
public void testShutdown() throws Exception {
XmlConfigurationParserImpl parser = new XmlConfigurationParserImpl();
String xml = "<shutdown hookBehavior=\"REGISTER\" />";
Element e = XmlConfigHelper.stringToElement(xml);
GlobalConfiguration gc = new GlobalConfiguration();
parser.configureShutdown(e, gc);
assert gc.getShutdownHookBehavior() == GlobalConfiguration.ShutdownHookBehavior.REGISTER;
}
public void testDefaultShutdown() throws Exception {
XmlConfigurationParserImpl parser = new XmlConfigurationParserImpl();
String xml = "<shutdown />";
Element e = XmlConfigHelper.stringToElement(xml);
GlobalConfiguration gc = new GlobalConfiguration();
parser.configureShutdown(e, gc);
assert gc.getShutdownHookBehavior() == GlobalConfiguration.ShutdownHookBehavior.DEFAULT;
}
public void testMarshalling() throws Exception {
XmlConfigurationParserImpl parser = new XmlConfigurationParserImpl();
- String xml = "<serialization marshallerClass=\"org.infinispan.marshall.HorizonMarshaller\" version=\"9.2\"\n" +
+ String xml = "<serialization marshallerClass=\"org.infinispan.marshall.MarshallerImpl\" version=\"9.2\"\n" +
" objectInputStreamPoolSize=\"100\" objectOutputStreamPoolSize=\"100\"/>";
Element e = XmlConfigHelper.stringToElement(xml);
GlobalConfiguration gc = new GlobalConfiguration();
parser.configureSerialization(e, gc);
assert gc.getMarshallerClass().equals(MarshallerImpl.class.getName());
assert gc.getMarshallVersionString().equals("9.2");
assert gc.getObjectInputStreamPoolSize() == 100;
assert gc.getObjectOutputStreamPoolSize() == 100;
}
public void testMarshallingDefaults() throws Exception {
XmlConfigurationParserImpl parser = new XmlConfigurationParserImpl();
String xml = "<serialization />";
Element e = XmlConfigHelper.stringToElement(xml);
GlobalConfiguration gc = new GlobalConfiguration();
parser.configureSerialization(e, gc);
assert gc.getMarshallerClass().equals(VersionAwareMarshaller.class.getName());
assert gc.getMarshallVersionString().equals("4.0");
assert gc.getObjectInputStreamPoolSize() == 50;
assert gc.getObjectOutputStreamPoolSize() == 50;
}
public void testAsyncListenerExecutor() throws Exception {
XmlConfigurationParserImpl parser = new XmlConfigurationParserImpl();
String xml = "<asyncListenerExecutor factory=\"com.mycompany.Factory\">\n" +
" <property name=\"maxThreads\" value=\"5\" />" +
" </asyncListenerExecutor>";
Element e = XmlConfigHelper.stringToElement(xml);
GlobalConfiguration gc = new GlobalConfiguration();
parser.configureAsyncListenerExecutor(e, gc);
assert gc.getAsyncListenerExecutorFactoryClass().equals("com.mycompany.Factory");
assert gc.getAsyncListenerExecutorProperties().size() == 1;
assert gc.getAsyncListenerExecutorProperties().get("maxThreads").equals("5");
}
public void testAsyncSerializationExecutor() throws Exception {
XmlConfigurationParserImpl parser = new XmlConfigurationParserImpl();
String xml = "<asyncSerializationExecutor factory=\"com.mycompany.Factory\">\n" +
" <property name=\"maxThreads\" value=\"5\" />" +
" </asyncSerializationExecutor>";
Element e = XmlConfigHelper.stringToElement(xml);
GlobalConfiguration gc = new GlobalConfiguration();
parser.configureAsyncSerializationExecutor(e, gc);
assert gc.getAsyncSerializationExecutorFactoryClass().equals("com.mycompany.Factory");
assert gc.getAsyncSerializationExecutorProperties().size() == 1;
assert gc.getAsyncSerializationExecutorProperties().get("maxThreads").equals("5");
}
public void testEvictionScheduledExecutor() throws Exception {
XmlConfigurationParserImpl parser = new XmlConfigurationParserImpl();
String xml = "<evictionScheduledExecutor factory=\"com.mycompany.Factory\">\n" +
" <property name=\"maxThreads\" value=\"5\" />" +
" </evictionScheduledExecutor>";
Element e = XmlConfigHelper.stringToElement(xml);
GlobalConfiguration gc = new GlobalConfiguration();
parser.configureEvictionScheduledExecutor(e, gc);
assert gc.getEvictionScheduledExecutorFactoryClass().equals("com.mycompany.Factory");
assert gc.getEvictionScheduledExecutorProperties().size() == 1;
assert gc.getEvictionScheduledExecutorProperties().get("maxThreads").equals("5");
}
public void testReplicationQueueScheduledExecutor() throws Exception {
XmlConfigurationParserImpl parser = new XmlConfigurationParserImpl();
String xml = "<replicationQueueScheduledExecutor factory=\"com.mycompany.Factory\">\n" +
" <property name=\"maxThreads\" value=\"5\" />" +
" </replicationQueueScheduledExecutor>";
Element e = XmlConfigHelper.stringToElement(xml);
GlobalConfiguration gc = new GlobalConfiguration();
parser.configureReplicationQueueScheduledExecutor(e, gc);
assert gc.getReplicationQueueScheduledExecutorFactoryClass().equals("com.mycompany.Factory");
assert gc.getReplicationQueueScheduledExecutorProperties().size() == 1;
assert gc.getReplicationQueueScheduledExecutorProperties().get("maxThreads").equals("5");
}
public void testAsyncListenerExecutorDefaults() throws Exception {
XmlConfigurationParserImpl parser = new XmlConfigurationParserImpl();
String xml = "<asyncListenerExecutor />";
Element e = XmlConfigHelper.stringToElement(xml);
GlobalConfiguration gc = new GlobalConfiguration();
parser.configureAsyncListenerExecutor(e, gc);
assert gc.getAsyncListenerExecutorFactoryClass().equals(DefaultExecutorFactory.class.getName());
assert gc.getAsyncListenerExecutorProperties().size() == 0;
}
public void testAsyncSerializationExecutorDefaults() throws Exception {
XmlConfigurationParserImpl parser = new XmlConfigurationParserImpl();
String xml = "<asyncSerializationExecutor />";
Element e = XmlConfigHelper.stringToElement(xml);
GlobalConfiguration gc = new GlobalConfiguration();
parser.configureAsyncSerializationExecutor(e, gc);
assert gc.getAsyncSerializationExecutorFactoryClass().equals(DefaultExecutorFactory.class.getName());
assert gc.getAsyncSerializationExecutorProperties().size() == 0;
}
public void testEvictionScheduledExecutorDefaults() throws Exception {
XmlConfigurationParserImpl parser = new XmlConfigurationParserImpl();
String xml = "<evictionScheduledExecutor />";
Element e = XmlConfigHelper.stringToElement(xml);
GlobalConfiguration gc = new GlobalConfiguration();
parser.configureEvictionScheduledExecutor(e, gc);
assert gc.getEvictionScheduledExecutorFactoryClass().equals(DefaultScheduledExecutorFactory.class.getName());
assert gc.getEvictionScheduledExecutorProperties().size() == 0;
}
public void testReplicationQueueScheduledExecutorDefaults() throws Exception {
XmlConfigurationParserImpl parser = new XmlConfigurationParserImpl();
String xml = "<replicationQueueScheduledExecutor />";
Element e = XmlConfigHelper.stringToElement(xml);
GlobalConfiguration gc = new GlobalConfiguration();
parser.configureReplicationQueueScheduledExecutor(e, gc);
assert gc.getReplicationQueueScheduledExecutorFactoryClass().equals(DefaultScheduledExecutorFactory.class.getName());
assert gc.getReplicationQueueScheduledExecutorProperties().size() == 0;
}
}
| true | true | public void testMarshalling() throws Exception {
XmlConfigurationParserImpl parser = new XmlConfigurationParserImpl();
String xml = "<serialization marshallerClass=\"org.infinispan.marshall.HorizonMarshaller\" version=\"9.2\"\n" +
" objectInputStreamPoolSize=\"100\" objectOutputStreamPoolSize=\"100\"/>";
Element e = XmlConfigHelper.stringToElement(xml);
GlobalConfiguration gc = new GlobalConfiguration();
parser.configureSerialization(e, gc);
assert gc.getMarshallerClass().equals(MarshallerImpl.class.getName());
assert gc.getMarshallVersionString().equals("9.2");
assert gc.getObjectInputStreamPoolSize() == 100;
assert gc.getObjectOutputStreamPoolSize() == 100;
}
| public void testMarshalling() throws Exception {
XmlConfigurationParserImpl parser = new XmlConfigurationParserImpl();
String xml = "<serialization marshallerClass=\"org.infinispan.marshall.MarshallerImpl\" version=\"9.2\"\n" +
" objectInputStreamPoolSize=\"100\" objectOutputStreamPoolSize=\"100\"/>";
Element e = XmlConfigHelper.stringToElement(xml);
GlobalConfiguration gc = new GlobalConfiguration();
parser.configureSerialization(e, gc);
assert gc.getMarshallerClass().equals(MarshallerImpl.class.getName());
assert gc.getMarshallVersionString().equals("9.2");
assert gc.getObjectInputStreamPoolSize() == 100;
assert gc.getObjectOutputStreamPoolSize() == 100;
}
|
diff --git a/src/java/org/jivesoftware/sparkimpl/preference/sounds/SoundPreference.java b/src/java/org/jivesoftware/sparkimpl/preference/sounds/SoundPreference.java
index 09030f2f..d9729170 100644
--- a/src/java/org/jivesoftware/sparkimpl/preference/sounds/SoundPreference.java
+++ b/src/java/org/jivesoftware/sparkimpl/preference/sounds/SoundPreference.java
@@ -1,320 +1,320 @@
/**
* $Revision: $
* $Date: $
*
* Copyright (C) 2006 Jive Software. All rights reserved.
*
* This software is published under the terms of the GNU Lesser Public License (LGPL),
* a copy of which is included in this distribution.
*/
package org.jivesoftware.sparkimpl.preference.sounds;
import com.thoughtworks.xstream.XStream;
import org.jivesoftware.Spark;
import org.jivesoftware.resource.SparkRes;
import org.jivesoftware.spark.preference.Preference;
import org.jivesoftware.spark.util.ResourceUtils;
import org.jivesoftware.spark.util.SwingWorker;
import org.jivesoftware.spark.util.WindowsFileSystemView;
import org.jivesoftware.spark.util.log.Log;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**
* Preferences to handle Sounds played within Spark.
*
* @author Derek DeMoro
*/
public class SoundPreference implements Preference {
private XStream xstream = new XStream();
private SoundPreferences preferences;
private SoundPanel soundPanel;
public static String NAMESPACE = "Sounds";
public SoundPreference() {
xstream.alias("sounds", SoundPreferences.class);
}
public String getTitle() {
return "Sound Preferences";
}
public Icon getIcon() {
return SparkRes.getImageIcon(SparkRes.SOUND_PREFERENCES_IMAGE);
}
public String getTooltip() {
return "Sounds";
}
public String getListName() {
return "Sounds";
}
public String getNamespace() {
return NAMESPACE;
}
public JComponent getGUI() {
if (soundPanel == null) {
soundPanel = new SoundPanel();
}
return soundPanel;
}
public void loadFromFile() {
if (preferences != null) {
return;
}
if (!getSoundSettingsFile().exists()) {
preferences = new SoundPreferences();
}
else {
// Do Initial Load from FileSystem.
File settingsFile = getSoundSettingsFile();
try {
FileReader reader = new FileReader(settingsFile);
preferences = (SoundPreferences)xstream.fromXML(reader);
}
catch (Exception e) {
Log.error("Error loading Sound Preferences.", e);
preferences = new SoundPreferences();
}
}
}
public void load() {
if (soundPanel == null) {
soundPanel = new SoundPanel();
}
SwingWorker worker = new SwingWorker() {
public Object construct() {
loadFromFile();
return preferences;
}
public void finished() {
// Set default settings
soundPanel.setIncomingMessageSound(preferences.getIncomingSound());
soundPanel.playIncomingSound(preferences.isPlayIncomingSound());
soundPanel.setOutgoingMessageSound(preferences.getOutgoingSound());
soundPanel.playOutgoingSound(preferences.isPlayOutgoingSound());
soundPanel.setOfflineSound(preferences.getOfflineSound());
soundPanel.playOfflineSound(preferences.isPlayOfflineSound());
}
};
worker.start();
}
public void commit() {
preferences.setIncomingSound(soundPanel.getIncomingSound());
preferences.setOutgoingSound(soundPanel.getOutgoingSound());
preferences.setOfflineSound(soundPanel.getOfflineSound());
preferences.setPlayIncomingSound(soundPanel.playIncomingSound());
preferences.setPlayOutgoingSound(soundPanel.playOutgoingSound());
preferences.setPlayOfflineSound(soundPanel.playOfflineSound());
saveSoundsFile();
}
public boolean isDataValid() {
return true;
}
public String getErrorMessage() {
return null;
}
public Object getData() {
return null;
}
private class SoundPanel extends JPanel {
final JCheckBox incomingMessageBox = new JCheckBox();
final JTextField incomingMessageSound = new JTextField();
final JButton incomingBrowseButton = new JButton();
final JCheckBox outgoingMessageBox = new JCheckBox();
final JTextField outgoingMessageSound = new JTextField();
final JButton outgoingBrowseButton = new JButton();
final JCheckBox userOfflineCheckbox = new JCheckBox();
final JTextField userOfflineField = new JTextField();
final JButton offlineBrowseButton = new JButton();
private JFileChooser fc;
public SoundPanel() {
setLayout(new GridBagLayout());
// Add ResourceUtils
- ResourceUtils.resButton(incomingMessageBox, "&Play sound when new message arrives");
- ResourceUtils.resButton(outgoingMessageBox, "&Play sound when a message is sent");
- ResourceUtils.resButton(userOfflineCheckbox, "&Play sound when user goes offline");
+ ResourceUtils.resButton(incomingMessageBox, "Play sound when new message &arrives");
+ ResourceUtils.resButton(outgoingMessageBox, "Play sound when a message is &sent");
+ ResourceUtils.resButton(userOfflineCheckbox, "Play sound when user goes &offline");
ResourceUtils.resButton(incomingBrowseButton, "&Browse");
ResourceUtils.resButton(outgoingBrowseButton, "B&rowse");
ResourceUtils.resButton(offlineBrowseButton, "Br&owse");
// Handle incoming sounds
add(incomingMessageBox, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
add(incomingMessageSound, new GridBagConstraints(0, 1, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
add(incomingBrowseButton, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
// Handle sending sounds
add(outgoingMessageBox, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
add(outgoingMessageSound, new GridBagConstraints(0, 3, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
add(outgoingBrowseButton, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
// Handle User Online Sound
add(userOfflineCheckbox, new GridBagConstraints(0, 4, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
add(userOfflineField, new GridBagConstraints(0, 5, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
add(offlineBrowseButton, new GridBagConstraints(1, 5, 1, 1, 0.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
incomingBrowseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
pickFile("Choose Incoming Sound File", incomingMessageSound);
}
});
outgoingBrowseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
pickFile("Choose Outgoing Sound File", outgoingMessageSound);
}
});
offlineBrowseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
pickFile("Choose Offline Sound File", userOfflineField);
}
});
}
public void setIncomingMessageSound(String path) {
incomingMessageSound.setText(path);
}
public void setOutgoingMessageSound(String path) {
outgoingMessageSound.setText(path);
}
public void setOfflineSound(String path) {
userOfflineField.setText(path);
}
public void playIncomingSound(boolean play) {
incomingMessageBox.setSelected(play);
}
public void playOutgoingSound(boolean play) {
outgoingMessageBox.setSelected(play);
}
public void playOfflineSound(boolean play) {
userOfflineCheckbox.setSelected(play);
}
public String getIncomingSound() {
return incomingMessageSound.getText();
}
public boolean playIncomingSound() {
return incomingMessageBox.isSelected();
}
public boolean playOutgoingSound() {
return outgoingMessageBox.isSelected();
}
public String getOutgoingSound() {
return outgoingMessageSound.getText();
}
public boolean playOfflineSound() {
return userOfflineCheckbox.isSelected();
}
public String getOfflineSound() {
return userOfflineField.getText();
}
private void pickFile(String title, JTextField field) {
if (fc == null) {
fc = new JFileChooser();
if (Spark.isWindows()) {
fc.setFileSystemView(new WindowsFileSystemView());
}
}
fc.setDialogTitle(title);
int returnVal = fc.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
field.setText(file.getAbsolutePath());
}
else {
}
}
}
private File getSoundSettingsFile() {
File file = new File(Spark.getUserHome(), "Spark");
if (!file.exists()) {
file.mkdirs();
}
return new File(file, "sound-settings.xml");
}
private void saveSoundsFile() {
try {
FileWriter writer = new FileWriter(getSoundSettingsFile());
xstream.toXML(preferences, writer);
}
catch (Exception e) {
Log.error("Error saving sound settings.", e);
}
}
public SoundPreferences getPreferences() {
if (preferences == null) {
load();
}
return preferences;
}
public void shutdown() {
}
}
| true | true | public SoundPanel() {
setLayout(new GridBagLayout());
// Add ResourceUtils
ResourceUtils.resButton(incomingMessageBox, "&Play sound when new message arrives");
ResourceUtils.resButton(outgoingMessageBox, "&Play sound when a message is sent");
ResourceUtils.resButton(userOfflineCheckbox, "&Play sound when user goes offline");
ResourceUtils.resButton(incomingBrowseButton, "&Browse");
ResourceUtils.resButton(outgoingBrowseButton, "B&rowse");
ResourceUtils.resButton(offlineBrowseButton, "Br&owse");
// Handle incoming sounds
add(incomingMessageBox, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
add(incomingMessageSound, new GridBagConstraints(0, 1, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
add(incomingBrowseButton, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
// Handle sending sounds
add(outgoingMessageBox, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
add(outgoingMessageSound, new GridBagConstraints(0, 3, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
add(outgoingBrowseButton, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
// Handle User Online Sound
add(userOfflineCheckbox, new GridBagConstraints(0, 4, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
add(userOfflineField, new GridBagConstraints(0, 5, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
add(offlineBrowseButton, new GridBagConstraints(1, 5, 1, 1, 0.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
incomingBrowseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
pickFile("Choose Incoming Sound File", incomingMessageSound);
}
});
outgoingBrowseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
pickFile("Choose Outgoing Sound File", outgoingMessageSound);
}
});
offlineBrowseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
pickFile("Choose Offline Sound File", userOfflineField);
}
});
}
| public SoundPanel() {
setLayout(new GridBagLayout());
// Add ResourceUtils
ResourceUtils.resButton(incomingMessageBox, "Play sound when new message &arrives");
ResourceUtils.resButton(outgoingMessageBox, "Play sound when a message is &sent");
ResourceUtils.resButton(userOfflineCheckbox, "Play sound when user goes &offline");
ResourceUtils.resButton(incomingBrowseButton, "&Browse");
ResourceUtils.resButton(outgoingBrowseButton, "B&rowse");
ResourceUtils.resButton(offlineBrowseButton, "Br&owse");
// Handle incoming sounds
add(incomingMessageBox, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
add(incomingMessageSound, new GridBagConstraints(0, 1, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
add(incomingBrowseButton, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
// Handle sending sounds
add(outgoingMessageBox, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
add(outgoingMessageSound, new GridBagConstraints(0, 3, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
add(outgoingBrowseButton, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
// Handle User Online Sound
add(userOfflineCheckbox, new GridBagConstraints(0, 4, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
add(userOfflineField, new GridBagConstraints(0, 5, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
add(offlineBrowseButton, new GridBagConstraints(1, 5, 1, 1, 0.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
incomingBrowseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
pickFile("Choose Incoming Sound File", incomingMessageSound);
}
});
outgoingBrowseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
pickFile("Choose Outgoing Sound File", outgoingMessageSound);
}
});
offlineBrowseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
pickFile("Choose Offline Sound File", userOfflineField);
}
});
}
|
diff --git a/src/net/zyclonite/gw2live/model/GuildDetails.java b/src/net/zyclonite/gw2live/model/GuildDetails.java
index 288adb3..c89aa00 100644
--- a/src/net/zyclonite/gw2live/model/GuildDetails.java
+++ b/src/net/zyclonite/gw2live/model/GuildDetails.java
@@ -1,77 +1,80 @@
/*
* gw2live - GuildWars 2 Dynamic Map
*
* Website: http://gw2map.com
*
* Copyright 2013 zyclonite networx
* http://zyclonite.net
* Developer: Lukas Prettenthaler
*/
package net.zyclonite.gw2live.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.Date;
import org.mongojack.ObjectId;
/**
*
* @author zyclonite
*/
@JsonIgnoreProperties({"_id"})
public class GuildDetails {
private final static int CACHETIME_HOURS = 24;
@ObjectId
private String _guild_id;
private String _guild_name;
private String _tag;
private GuildEmblem _emblem;
private Date _timestamp;
public String getGuild_id() {
return _guild_id;
}
public void setGuild_id(final String id) {
this._guild_id = id;
}
public String getGuild_name() {
return _guild_name;
}
public void setGuild_name(final String name) {
this._guild_name = name;
}
public String getTag() {
return _tag;
}
public void setTag(final String tag) {
this._tag = tag;
}
public GuildEmblem getEmblem() {
return _emblem;
}
public void setEmblem(final GuildEmblem emblem) {
this._emblem = emblem;
}
public Date getTimestamp() {
return _timestamp;
}
public void setTimestamp(Date _timestamp) {
this._timestamp = _timestamp;
}
public Boolean needsRenewal() {
+ if(this._timestamp == null){
+ return true;
+ }
final long timediff = (new Date()).getTime()-this._timestamp.getTime();
if((CACHETIME_HOURS*60*60*1000) < timediff){
return true;
}
return false;
}
}
| true | true | public Boolean needsRenewal() {
final long timediff = (new Date()).getTime()-this._timestamp.getTime();
if((CACHETIME_HOURS*60*60*1000) < timediff){
return true;
}
return false;
}
| public Boolean needsRenewal() {
if(this._timestamp == null){
return true;
}
final long timediff = (new Date()).getTime()-this._timestamp.getTime();
if((CACHETIME_HOURS*60*60*1000) < timediff){
return true;
}
return false;
}
|
diff --git a/framework/script-engine/src/main/java/org/apache/manifoldcf/scriptengine/VariableConfigurationNode.java b/framework/script-engine/src/main/java/org/apache/manifoldcf/scriptengine/VariableConfigurationNode.java
index 3150cbd0c..15d373689 100644
--- a/framework/script-engine/src/main/java/org/apache/manifoldcf/scriptengine/VariableConfigurationNode.java
+++ b/framework/script-engine/src/main/java/org/apache/manifoldcf/scriptengine/VariableConfigurationNode.java
@@ -1,306 +1,315 @@
/* $Id$ */
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.manifoldcf.scriptengine;
import org.apache.manifoldcf.core.interfaces.*;
import java.util.*;
/** Variable wrapper for ConfigurationNode object.
*/
public class VariableConfigurationNode extends VariableBase
{
protected ConfigurationNode configurationNode;
public VariableConfigurationNode(String name)
{
configurationNode = new ConfigurationNode(name);
}
public VariableConfigurationNode(ConfigurationNode node)
{
configurationNode = node;
}
/** Get the variable's script value */
public String getScriptValue()
throws ScriptException
{
StringBuilder sb = new StringBuilder();
sb.append("<< ");
sb.append(new VariableString(configurationNode.getType()).getScriptValue());
sb.append(" : ");
String valueField = configurationNode.getValue();
if (valueField == null)
valueField = "";
sb.append(new VariableString(valueField).getScriptValue());
sb.append(" : ");
boolean needComma = false;
Iterator<String> iter = configurationNode.getAttributes();
+ String[] attrs = new String[configurationNode.getAttributeCount()];
+ int i = 0;
while (iter.hasNext())
{
String attrName = iter.next();
+ attrs[i++] = attrName;
+ }
+ java.util.Arrays.sort(attrs);
+ i = 0;
+ while (i < attrs.length)
+ {
+ String attrName = attrs[i++];
String value = configurationNode.getAttributeValue(attrName);
if (needComma)
sb.append(", ");
else
needComma = true;
sb.append(new VariableString(attrName).getScriptValue());
sb.append("=");
sb.append(new VariableString(value).getScriptValue());
}
sb.append(" : ");
- int i = 0;
+ i = 0;
while (i < configurationNode.getChildCount())
{
ConfigurationNode child = configurationNode.findChild(i);
if (i > 0)
sb.append(", ");
sb.append(new VariableConfigurationNode(child).getScriptValue());
i++;
}
sb.append(" >>");
return sb.toString();
}
/** Convert to a value */
public String getStringValue()
throws ScriptException
{
if (configurationNode.getValue() == null)
return "";
return configurationNode.getValue();
}
/** Get the variable's value as a ConfigurationNode object */
public ConfigurationNode getConfigurationNodeValue()
throws ScriptException
{
return configurationNode;
}
/** Get a named attribute of the variable; e.g. xxx.yyy */
public VariableReference getAttribute(String attributeName)
throws ScriptException
{
// We recognize the __size__ attribute
if (attributeName.equals(ATTRIBUTE_SIZE))
return new VariableInt(configurationNode.getChildCount());
// Also, the __type__ attribute
if (attributeName.equals(ATTRIBUTE_TYPE))
return new VariableString(configurationNode.getType());
// And the __value__ attribute
if (attributeName.equals(ATTRIBUTE_VALUE))
return new ValueReference();
if (attributeName.equals(ATTRIBUTE_DICT))
{
VariableDict dict = new VariableDict();
int i = 0;
while (i < configurationNode.getChildCount())
{
ConfigurationNode child = configurationNode.findChild(i++);
String type = child.getType();
dict.getIndexed(new VariableString(type)).setReference(new VariableConfigurationNode(child));
}
return dict;
}
if (attributeName.equals(ATTRIBUTE_SCRIPT) ||
attributeName.equals(ATTRIBUTE_STRING) ||
attributeName.equals(ATTRIBUTE_INT) ||
attributeName.equals(ATTRIBUTE_FLOAT) ||
attributeName.equals(ATTRIBUTE_BOOLEAN))
return super.getAttribute(attributeName);
// All others are presumed to be attributes of the configuration node, which can be set or cleared.
return new AttributeReference(attributeName);
}
/** Get an indexed property of the variable */
public VariableReference getIndexed(Variable index)
throws ScriptException
{
if (index == null)
throw new ScriptException(composeMessage("Subscript cannot be null"));
int indexValue = index.getIntValue();
if (indexValue >= 0 && indexValue < configurationNode.getChildCount())
return new NodeReference(indexValue);
throw new ScriptException(composeMessage("Subscript is out of bounds: "+indexValue));
}
/** Insert an object into this variable at a position. */
public void insertAt(Variable v, Variable index)
throws ScriptException
{
if (v == null)
throw new ScriptException(composeMessage("Can't insert a null object"));
if (index == null)
configurationNode.addChild(configurationNode.getChildCount(),v.getConfigurationNodeValue());
else
{
int indexValue = index.getIntValue();
if (indexValue < 0 || indexValue > configurationNode.getChildCount())
throw new ScriptException(composeMessage("Insert out of bounds: "+indexValue));
configurationNode.addChild(indexValue,v.getConfigurationNodeValue());
}
}
/** Delete an object from this variable at a position. */
public void removeAt(Variable index)
throws ScriptException
{
if (index == null)
throw new ScriptException(composeMessage("Remove index cannot be null"));
int indexValue = index.getIntValue();
if (indexValue < 0 || indexValue >= configurationNode.getChildCount())
throw new ScriptException(composeMessage("Remove index out of bounds: "+indexValue));
configurationNode.removeChild(indexValue);
}
public VariableReference plus(Variable v)
throws ScriptException
{
if (v == null)
throw new ScriptException(composeMessage("Can't add a null object"));
ConfigurationNode node = v.getConfigurationNodeValue();
ConfigurationNode cn = new ConfigurationNode(configurationNode.getType());
cn.setValue(configurationNode.getValue());
Iterator<String> attIter = configurationNode.getAttributes();
while (attIter.hasNext())
{
String attrName = attIter.next();
String attrValue = configurationNode.getAttributeValue(attrName);
cn.setAttribute(attrName,attrValue);
}
int i = 0;
while (i < configurationNode.getChildCount())
{
ConfigurationNode child = configurationNode.findChild(i++);
cn.addChild(cn.getChildCount(),child);
}
cn.addChild(cn.getChildCount(),node);
return new VariableConfigurationNode(cn);
}
/** Implement VariableReference to allow values to be set or cleared */
protected class ValueReference implements VariableReference
{
public ValueReference()
{
}
public void setReference(Variable v)
throws ScriptException
{
if (v == null)
configurationNode.setValue(null);
else
{
String value = v.getStringValue();
configurationNode.setValue(value);
}
}
public Variable resolve()
throws ScriptException
{
String value = configurationNode.getValue();
if (value == null)
value = "";
return new VariableString(value);
}
public boolean isNull()
{
return false;
}
}
/** Implement VariableReference to allow attributes to be set or cleared */
protected class AttributeReference implements VariableReference
{
protected String attributeName;
public AttributeReference(String attributeName)
{
this.attributeName = attributeName;
}
public void setReference(Variable v)
throws ScriptException
{
if (v == null)
configurationNode.setAttribute(attributeName,null);
else
{
String value = v.getStringValue();
configurationNode.setAttribute(attributeName,value);
}
}
public Variable resolve()
throws ScriptException
{
String attrValue = configurationNode.getAttributeValue(attributeName);
if (attrValue == null)
throw new ScriptException(composeMessage("No attribute named '"+attributeName+"'"));
return new VariableString(attrValue);
}
public boolean isNull()
{
return (configurationNode.getAttributeValue(attributeName) == null);
}
}
/** Extend VariableReference class so we capture attempts to set the reference, and actually overwrite the child when that is done */
protected class NodeReference implements VariableReference
{
protected int index;
public NodeReference(int index)
{
this.index = index;
}
public void setReference(Variable v)
throws ScriptException
{
if (index < 0 || index >= configurationNode.getChildCount())
throw new ScriptException(composeMessage("Index out of range: "+index));
ConfigurationNode confNode = v.getConfigurationNodeValue();
configurationNode.removeChild(index);
configurationNode.addChild(index,confNode);
}
public Variable resolve()
throws ScriptException
{
if (index < 0 || index >= configurationNode.getChildCount())
throw new ScriptException(composeMessage("Index out of range: "+index));
return new VariableConfigurationNode(configurationNode.findChild(index));
}
/** Check if this reference is null */
public boolean isNull()
{
return index < 0 || index >= configurationNode.getChildCount();
}
}
}
| false | true | public String getScriptValue()
throws ScriptException
{
StringBuilder sb = new StringBuilder();
sb.append("<< ");
sb.append(new VariableString(configurationNode.getType()).getScriptValue());
sb.append(" : ");
String valueField = configurationNode.getValue();
if (valueField == null)
valueField = "";
sb.append(new VariableString(valueField).getScriptValue());
sb.append(" : ");
boolean needComma = false;
Iterator<String> iter = configurationNode.getAttributes();
while (iter.hasNext())
{
String attrName = iter.next();
String value = configurationNode.getAttributeValue(attrName);
if (needComma)
sb.append(", ");
else
needComma = true;
sb.append(new VariableString(attrName).getScriptValue());
sb.append("=");
sb.append(new VariableString(value).getScriptValue());
}
sb.append(" : ");
int i = 0;
while (i < configurationNode.getChildCount())
{
ConfigurationNode child = configurationNode.findChild(i);
if (i > 0)
sb.append(", ");
sb.append(new VariableConfigurationNode(child).getScriptValue());
i++;
}
sb.append(" >>");
return sb.toString();
}
| public String getScriptValue()
throws ScriptException
{
StringBuilder sb = new StringBuilder();
sb.append("<< ");
sb.append(new VariableString(configurationNode.getType()).getScriptValue());
sb.append(" : ");
String valueField = configurationNode.getValue();
if (valueField == null)
valueField = "";
sb.append(new VariableString(valueField).getScriptValue());
sb.append(" : ");
boolean needComma = false;
Iterator<String> iter = configurationNode.getAttributes();
String[] attrs = new String[configurationNode.getAttributeCount()];
int i = 0;
while (iter.hasNext())
{
String attrName = iter.next();
attrs[i++] = attrName;
}
java.util.Arrays.sort(attrs);
i = 0;
while (i < attrs.length)
{
String attrName = attrs[i++];
String value = configurationNode.getAttributeValue(attrName);
if (needComma)
sb.append(", ");
else
needComma = true;
sb.append(new VariableString(attrName).getScriptValue());
sb.append("=");
sb.append(new VariableString(value).getScriptValue());
}
sb.append(" : ");
i = 0;
while (i < configurationNode.getChildCount())
{
ConfigurationNode child = configurationNode.findChild(i);
if (i > 0)
sb.append(", ");
sb.append(new VariableConfigurationNode(child).getScriptValue());
i++;
}
sb.append(" >>");
return sb.toString();
}
|
diff --git a/src/org/xierch/mpiwifi/NetworkBroadcast.java b/src/org/xierch/mpiwifi/NetworkBroadcast.java
index 58f6112..2da4026 100644
--- a/src/org/xierch/mpiwifi/NetworkBroadcast.java
+++ b/src/org/xierch/mpiwifi/NetworkBroadcast.java
@@ -1,48 +1,50 @@
package org.xierch.mpiwifi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.StrictMode;
public class NetworkBroadcast extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (!intent.getAction().equals
(ConnectivityManager.CONNECTIVITY_ACTION))
return;
SharedPreferences settings = context
.getSharedPreferences("settings", Context.MODE_PRIVATE);
if (!settings.getBoolean("autoLogin", false)) return;
SharedPreferences loginInfo = context
.getSharedPreferences("loginInfo", Context.MODE_PRIVATE);
String netId = loginInfo.getString("netId", "");
String pwd = loginInfo.getString("pwd", "");
if (netId.isEmpty() || pwd.isEmpty()) {
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("autoLogin", false);
editor.commit();
return;
}
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.permitNetwork().build());
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
if (!wifiManager.isWifiEnabled()) return;
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
- if (wifiInfo != null)
+ if (wifiInfo == null) return;
+ String ssid = wifiInfo.getSSID();
+ if (ssid != null)
if (wifiInfo.getSSID().equals("NamOn_Hostel"))
WifiLoginer.loginNamon(context, netId, pwd, true);
}
}
| true | true | public void onReceive(Context context, Intent intent) {
if (!intent.getAction().equals
(ConnectivityManager.CONNECTIVITY_ACTION))
return;
SharedPreferences settings = context
.getSharedPreferences("settings", Context.MODE_PRIVATE);
if (!settings.getBoolean("autoLogin", false)) return;
SharedPreferences loginInfo = context
.getSharedPreferences("loginInfo", Context.MODE_PRIVATE);
String netId = loginInfo.getString("netId", "");
String pwd = loginInfo.getString("pwd", "");
if (netId.isEmpty() || pwd.isEmpty()) {
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("autoLogin", false);
editor.commit();
return;
}
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.permitNetwork().build());
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
if (!wifiManager.isWifiEnabled()) return;
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
if (wifiInfo != null)
if (wifiInfo.getSSID().equals("NamOn_Hostel"))
WifiLoginer.loginNamon(context, netId, pwd, true);
}
| public void onReceive(Context context, Intent intent) {
if (!intent.getAction().equals
(ConnectivityManager.CONNECTIVITY_ACTION))
return;
SharedPreferences settings = context
.getSharedPreferences("settings", Context.MODE_PRIVATE);
if (!settings.getBoolean("autoLogin", false)) return;
SharedPreferences loginInfo = context
.getSharedPreferences("loginInfo", Context.MODE_PRIVATE);
String netId = loginInfo.getString("netId", "");
String pwd = loginInfo.getString("pwd", "");
if (netId.isEmpty() || pwd.isEmpty()) {
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("autoLogin", false);
editor.commit();
return;
}
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.permitNetwork().build());
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
if (!wifiManager.isWifiEnabled()) return;
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
if (wifiInfo == null) return;
String ssid = wifiInfo.getSSID();
if (ssid != null)
if (wifiInfo.getSSID().equals("NamOn_Hostel"))
WifiLoginer.loginNamon(context, netId, pwd, true);
}
|
diff --git a/src/main/java/org/spout/engine/command/TestCommands.java b/src/main/java/org/spout/engine/command/TestCommands.java
index 6c625973d..b16301ff9 100644
--- a/src/main/java/org/spout/engine/command/TestCommands.java
+++ b/src/main/java/org/spout/engine/command/TestCommands.java
@@ -1,172 +1,172 @@
/*
* This file is part of Spout.
*
* Copyright (c) 2011-2012, SpoutDev <http://www.spout.org/>
* Spout is licensed under the SpoutDev License Version 1.
*
* Spout 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.
*
* In addition, 180 days after any changes are published, you can use the
* software, incorporating those changes, under the terms of the MIT license,
* as described in the SpoutDev License Version 1.
*
* Spout 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,
* the MIT license and the SpoutDev License Version 1 along with this program.
* If not, see <http://www.gnu.org/licenses/> for the GNU Lesser General Public
* License and see <http://www.spout.org/SpoutDevLicenseV1.txt> for the full license,
* including the MIT license.
*/
package org.spout.engine.command;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.spout.api.Spout;
import org.spout.api.command.CommandContext;
import org.spout.api.command.CommandSource;
import org.spout.api.command.annotated.Command;
import org.spout.api.command.annotated.CommandPermissions;
import org.spout.api.exception.CommandException;
import org.spout.api.geo.World;
import org.spout.api.plugin.Plugin;
import org.spout.engine.SpoutEngine;
public class TestCommands {
private final SpoutEngine engine;
public TestCommands(SpoutEngine engine) {
this.engine = engine;
}
@Command(aliases = {"dbg"}, desc = "Debug Output")
public void debugOutput(CommandContext args, CommandSource source) {
World world = engine.getDefaultWorld();
source.sendMessage("World Entity count: ", world.getAll().size());
}
@Command(aliases = "testmsg", desc = "Test extracting chat styles from a message and printing them")
public void testMsg(CommandContext args, CommandSource source) throws CommandException {
source.sendMessage(args.getJoinedString(0));
}
@Command(aliases = "plugins-tofile", usage = "[filename]", desc = "Creates a file containing all loaded plugins and their version", min = 0, max = 1)
@CommandPermissions("spout.command.pluginstofile")
public void getPluginDetails(CommandContext args, CommandSource source) throws CommandException {
// File and filename
String filename = "";
- String standpath = "/pluginreports";
+ String standpath = "pluginreports";
File file = null;
// Getting date
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
String parse = dateFormat.format(date);
// Create file with passed filename or current date and time as name
if (args.length() == 1) {
filename = args.getString(0);
file = new File(standpath.concat("/" + replaceInvalidCharsWin(filename)));
} else {
file = new File(standpath.concat("/" + replaceInvalidCharsWin(parse)).concat(".txt"));
}
// Delete the file if existent
if (file.exists()) {
file.delete();
}
String linesep = System.getProperty("line.separator");
// Create a new file
try {
- new File("/pluginreports").mkdirs();
+ new File("pluginreports").mkdirs();
file.createNewFile();
} catch (IOException e) {
throw new CommandException("Couldn't create report-file!" + linesep + "Please make sure to only use valid chars in the filename.");
}
// Content Builder
StringBuilder sbuild = new StringBuilder();
sbuild.append("# This file was created on the " + dateFormat.format(date).concat(linesep));
sbuild.append("# Plugin Name | Version | Authors".concat(linesep));
// Plugins to write down
List<Plugin> plugins = Spout.getEngine().getPluginManager().getPlugins();
// Getting plugin informations
for (Plugin plugin : plugins) {
// Name and Version
sbuild.append(plugin.getName().concat(" | "));
sbuild.append(plugin.getDescription().getVersion());
// Authors
List<String> authors = plugin.getDescription().getAuthors();
StringBuilder authbuilder = new StringBuilder();
if (authors != null && authors.size() > 0) {
int size = authors.size();
int count = 0;
for (String s : authors) {
count++;
if (count != size) {
authbuilder.append(s + ", ");
} else {
authbuilder.append(s);
}
}
sbuild.append(" | ".concat(authbuilder.toString()).concat(linesep));
} else {
sbuild.append(linesep);
}
}
BufferedWriter writer = null;
// Write to file
if (file != null) {
try {
writer = new BufferedWriter(new FileWriter(file));
writer.write(sbuild.toString());
} catch (IOException e) {
throw new CommandException("Couldn't write to report-file!");
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
source.sendMessage("Plugins-report successfully created! " + linesep + "Stored in: " + standpath);
}
/**
* Replaces chars which are not allowed in filenames on windows with "-".
*/
private String replaceInvalidCharsWin(String s) {
if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) {
return s.replaceAll("[\\/:*?\"<>|]", "-");
} else {
return s;
}
}
}
| false | true | public void getPluginDetails(CommandContext args, CommandSource source) throws CommandException {
// File and filename
String filename = "";
String standpath = "/pluginreports";
File file = null;
// Getting date
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
String parse = dateFormat.format(date);
// Create file with passed filename or current date and time as name
if (args.length() == 1) {
filename = args.getString(0);
file = new File(standpath.concat("/" + replaceInvalidCharsWin(filename)));
} else {
file = new File(standpath.concat("/" + replaceInvalidCharsWin(parse)).concat(".txt"));
}
// Delete the file if existent
if (file.exists()) {
file.delete();
}
String linesep = System.getProperty("line.separator");
// Create a new file
try {
new File("/pluginreports").mkdirs();
file.createNewFile();
} catch (IOException e) {
throw new CommandException("Couldn't create report-file!" + linesep + "Please make sure to only use valid chars in the filename.");
}
// Content Builder
StringBuilder sbuild = new StringBuilder();
sbuild.append("# This file was created on the " + dateFormat.format(date).concat(linesep));
sbuild.append("# Plugin Name | Version | Authors".concat(linesep));
// Plugins to write down
List<Plugin> plugins = Spout.getEngine().getPluginManager().getPlugins();
// Getting plugin informations
for (Plugin plugin : plugins) {
// Name and Version
sbuild.append(plugin.getName().concat(" | "));
sbuild.append(plugin.getDescription().getVersion());
// Authors
List<String> authors = plugin.getDescription().getAuthors();
StringBuilder authbuilder = new StringBuilder();
if (authors != null && authors.size() > 0) {
int size = authors.size();
int count = 0;
for (String s : authors) {
count++;
if (count != size) {
authbuilder.append(s + ", ");
} else {
authbuilder.append(s);
}
}
sbuild.append(" | ".concat(authbuilder.toString()).concat(linesep));
} else {
sbuild.append(linesep);
}
}
BufferedWriter writer = null;
// Write to file
if (file != null) {
try {
writer = new BufferedWriter(new FileWriter(file));
writer.write(sbuild.toString());
} catch (IOException e) {
throw new CommandException("Couldn't write to report-file!");
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
source.sendMessage("Plugins-report successfully created! " + linesep + "Stored in: " + standpath);
}
| public void getPluginDetails(CommandContext args, CommandSource source) throws CommandException {
// File and filename
String filename = "";
String standpath = "pluginreports";
File file = null;
// Getting date
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
String parse = dateFormat.format(date);
// Create file with passed filename or current date and time as name
if (args.length() == 1) {
filename = args.getString(0);
file = new File(standpath.concat("/" + replaceInvalidCharsWin(filename)));
} else {
file = new File(standpath.concat("/" + replaceInvalidCharsWin(parse)).concat(".txt"));
}
// Delete the file if existent
if (file.exists()) {
file.delete();
}
String linesep = System.getProperty("line.separator");
// Create a new file
try {
new File("pluginreports").mkdirs();
file.createNewFile();
} catch (IOException e) {
throw new CommandException("Couldn't create report-file!" + linesep + "Please make sure to only use valid chars in the filename.");
}
// Content Builder
StringBuilder sbuild = new StringBuilder();
sbuild.append("# This file was created on the " + dateFormat.format(date).concat(linesep));
sbuild.append("# Plugin Name | Version | Authors".concat(linesep));
// Plugins to write down
List<Plugin> plugins = Spout.getEngine().getPluginManager().getPlugins();
// Getting plugin informations
for (Plugin plugin : plugins) {
// Name and Version
sbuild.append(plugin.getName().concat(" | "));
sbuild.append(plugin.getDescription().getVersion());
// Authors
List<String> authors = plugin.getDescription().getAuthors();
StringBuilder authbuilder = new StringBuilder();
if (authors != null && authors.size() > 0) {
int size = authors.size();
int count = 0;
for (String s : authors) {
count++;
if (count != size) {
authbuilder.append(s + ", ");
} else {
authbuilder.append(s);
}
}
sbuild.append(" | ".concat(authbuilder.toString()).concat(linesep));
} else {
sbuild.append(linesep);
}
}
BufferedWriter writer = null;
// Write to file
if (file != null) {
try {
writer = new BufferedWriter(new FileWriter(file));
writer.write(sbuild.toString());
} catch (IOException e) {
throw new CommandException("Couldn't write to report-file!");
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
source.sendMessage("Plugins-report successfully created! " + linesep + "Stored in: " + standpath);
}
|
diff --git a/com/buglabs/application/ServiceTrackerHelper.java b/com/buglabs/application/ServiceTrackerHelper.java
index 9242be8..c912735 100644
--- a/com/buglabs/application/ServiceTrackerHelper.java
+++ b/com/buglabs/application/ServiceTrackerHelper.java
@@ -1,343 +1,342 @@
/*******************************************************************************
* Copyright (c) 2008, 2009 Bug Labs, Inc.
* 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 Bug Labs, Inc. 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.buglabs.application;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.Filter;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.service.log.LogService;
import org.osgi.util.tracker.ServiceTracker;
import org.osgi.util.tracker.ServiceTrackerCustomizer;
import com.buglabs.util.LogServiceUtil;
import com.buglabs.util.ServiceFilterGenerator;
/**
* Helper class to construct ServiceTrackers.
*
* @author kgilmer
*
*/
public class ServiceTrackerHelper implements ServiceTrackerCustomizer {
private final ManagedRunnable runnable;
private final String[] services;
private volatile int sc;
private final BundleContext bc;
private Thread thread;
private final Map serviceMap;
private LogService log;
/**
* A runnable that provides access to OSGi services passed to
* ServiceTrackerHelper.
*
* Runnable will be started when all service are available, and interrupted
* if any services become unavailable.
*
* @author kgilmer
*
*/
public interface ManagedRunnable {
/**
* This is called for execution of application logic when OSGi services are available.
* @param services key contains String of service name, value is service instance.
*/
public abstract void run(Map services);
/**
* Called directly before the thread is interrupted. Client may optionally add necessary code to shutdown thread.
*/
public abstract void shutdown();
}
/**
* A Runnable and ServiceTrackerCustomizer that allows for fine-grained
* application behavior based on OSGi service activity. An implementation of
* this can be passed anywhere a ServiceTrackerRunnable is expected and
* behavior will change accordingly.
*
* Runnable is not started automatically. It is up to the implementor to
* decide when and how to create and start the thread.
*
* @author kgilmer
* @deprecated Use ServiceTrackerCustomizer instead.
*
*/
public interface UnmanagedRunnable extends ManagedRunnable, ServiceTrackerCustomizer {
}
/**
* A ManagedRunnable that calls run() in-line with parent thread. This is useful if the client
* does not need to create a new thread or wants to manage thread creation independently.
* @author kgilmer
*
*/
public interface ManagedInlineRunnable extends ManagedRunnable {
}
public ServiceTrackerHelper(BundleContext bc, ManagedRunnable t, String[] services) {
this.bc = bc;
this.runnable = t;
this.services = services;
this.serviceMap = new HashMap();
this.log = LogServiceUtil.getLogService(bc);
sc = 0;
}
public Object addingService(ServiceReference arg0) {
sc++;
Object svc = bc.getService(arg0);
String key = ((String []) arg0.getProperty(Constants.OBJECTCLASS))[0];
serviceMap.put(key, svc);
- log.log(LogService.LOG_DEBUG, "STH ~ Loaded service " + key + " impl: " + svc.getClass().getName());
if (thread == null && sc == services.length && !(runnable instanceof UnmanagedRunnable)) {
if (runnable instanceof ManagedInlineRunnable) {
//Client wants to run in same thread, just call method.
runnable.run(serviceMap);
} else {
//Create new thread and pass off to client Runnable implementation.
thread = new Thread(new Runnable() {
public void run() {
runnable.run(serviceMap);
}
});
thread.start();
}
}
if (runnable instanceof UnmanagedRunnable) {
//Simply call the unmanaged runnable in-line.
return ((UnmanagedRunnable) runnable).addingService(arg0);
}
return svc;
}
public void modifiedService(ServiceReference arg0, Object arg1) {
String key = ((String []) arg0.getProperty(Constants.OBJECTCLASS))[0];
serviceMap.put(key, arg1);
if (runnable instanceof UnmanagedRunnable) {
((UnmanagedRunnable) runnable).modifiedService(arg0, arg1);
}
}
public void removedService(ServiceReference arg0, Object arg1) {
String key = ((String []) arg0.getProperty(Constants.OBJECTCLASS))[0];
serviceMap.remove(key);
sc--;
if (!(thread == null) && !thread.isInterrupted() && !(runnable instanceof UnmanagedRunnable)) {
runnable.shutdown();
thread.interrupt();
return;
}
if (runnable instanceof UnmanagedRunnable) {
((UnmanagedRunnable) runnable).removedService(arg0, arg1);
}
if (runnable instanceof ManagedInlineRunnable) {
((ManagedInlineRunnable) runnable).shutdown();
}
}
/**
* Convenience method for creating and opening a
* ServiceTrackerRunnable-based ServiceTracker.
*
* @param context
* @param services
* @param runnable
* @return
* @throws InvalidSyntaxException
*/
public static ServiceTracker openServiceTracker(BundleContext context, String[] services, ManagedRunnable runnable) throws InvalidSyntaxException {
ServiceTracker st = new ClosingServiceTracker(context, ServiceFilterGenerator.generateServiceFilter(context, services), new ServiceTrackerHelper(context, runnable, services), services);
st.open();
return st;
}
/**
* Convenience method for creating and opening a
* ServiceTrackerRunnable-based ServiceTracker.
*
* @param context
* @param services
* @param filter
* @param runnable
* @return
* @throws InvalidSyntaxException
*/
public static ServiceTracker openServiceTracker(BundleContext context, String[] services, Filter filter, ManagedRunnable runnable) throws InvalidSyntaxException {
ServiceTracker st = new ClosingServiceTracker(context, filter, new ServiceTrackerHelper(context, runnable, services), services);
st.open();
return st;
}
/**
* Convenience method for creating and opening a
* ServiceTracker.
*
* @param context
* @param services
* @param filter
* @param customizer
* @return
* @throws InvalidSyntaxException
*/
public static ServiceTracker openServiceTracker(BundleContext context, String[] services, Filter filter, ServiceTrackerCustomizer customizer) throws InvalidSyntaxException {
ServiceTracker st = new ClosingServiceTracker(context, filter, customizer, services);
st.open();
return st;
}
/**
* @param context
* BundleContext
* @param services
* Services to be tracked
* @param runnable
* Object handling service changes
* @return
* @throws InvalidSyntaxException
*/
public static ServiceTracker createAndOpen(BundleContext context, List services, RunnableWithServices runnable) throws InvalidSyntaxException {
Filter filter = context.createFilter(ServiceFilterGenerator.generateServiceFilter(services));
ServiceTracker st = new ServiceTracker(context, filter, new ServiceTrackerCustomizerAdapter(context, runnable, services));
st.open();
return st;
}
/**
* @param context
* BundleContext
* @param services
* Services to be tracked
* @param runnable
* Object handling service changes
* @return
* @throws InvalidSyntaxException
*
*/
public static ServiceTracker createAndOpen(BundleContext context, String[] services, RunnableWithServices runnable) throws InvalidSyntaxException {
Filter filter = context.createFilter(ServiceFilterGenerator.generateServiceFilter(Arrays.asList(services)));
ServiceTracker st = new ServiceTracker(context, filter, new ServiceTrackerCustomizerAdapter(context, runnable, Arrays.asList(services)));
st.open();
return st;
}
/**
* @param context
* BundleContext
* @param service
* Service to be tracked
* @param runnable
* Object handling service changes
* @return
* @throws InvalidSyntaxException
*/
public static ServiceTracker createAndOpen(BundleContext context, String service, RunnableWithServices runnable) throws InvalidSyntaxException {
Filter filter = context.createFilter(ServiceFilterGenerator.generateServiceFilter(Arrays.asList(new String[] { service })));
ServiceTracker st = new ServiceTracker(context, filter, new ServiceTrackerCustomizerAdapter(context, runnable, Arrays.asList(new String[] { service })));
st.open();
return st;
}
/**
* @param context
* BundleContext
* @param services
* Services to be tracked
* @param runnable
* Object handling service changes
* @return
* @throws InvalidSyntaxException
*/
public static ServiceTracker createAndOpen(BundleContext context, List services, ServiceChangeListener runnable) throws InvalidSyntaxException {
Filter filter = context.createFilter(ServiceFilterGenerator.generateServiceFilter(services));
ServiceTracker st = new ServiceTracker(context, filter, new ServiceTrackerCustomizerAdapter(context, runnable, services));
st.open();
return st;
}
/**
* @param context
* BundleContext
* @param services
* Services to be tracked
* @param runnable
* Object handling service changes
* @return
* @throws InvalidSyntaxException
*/
public static ServiceTracker createAndOpen(BundleContext context, String[] services, ServiceChangeListener runnable) throws InvalidSyntaxException {
Filter filter = context.createFilter(ServiceFilterGenerator.generateServiceFilter(Arrays.asList(services)));
ServiceTracker st = new ServiceTracker(context, filter, new ServiceTrackerCustomizerAdapter(context, runnable, Arrays.asList(services)));
st.open();
return st;
}
/**
* @param context
* BundleContext
* @param services
* Services to be tracked
* @param runnable
* Object handling service changes
* @return
* @throws InvalidSyntaxException
*/
public static ServiceTracker createAndOpen(BundleContext context, String service, ServiceChangeListener runnable) throws InvalidSyntaxException {
Filter filter = context.createFilter(ServiceFilterGenerator.generateServiceFilter(Arrays.asList(new String[] { service })));
ServiceTracker st = new ServiceTracker(context, filter, new ServiceTrackerCustomizerAdapter(context, runnable, Arrays.asList(new String[] { service })));
st.open();
return st;
}
}
| true | true | public Object addingService(ServiceReference arg0) {
sc++;
Object svc = bc.getService(arg0);
String key = ((String []) arg0.getProperty(Constants.OBJECTCLASS))[0];
serviceMap.put(key, svc);
log.log(LogService.LOG_DEBUG, "STH ~ Loaded service " + key + " impl: " + svc.getClass().getName());
if (thread == null && sc == services.length && !(runnable instanceof UnmanagedRunnable)) {
if (runnable instanceof ManagedInlineRunnable) {
//Client wants to run in same thread, just call method.
runnable.run(serviceMap);
} else {
//Create new thread and pass off to client Runnable implementation.
thread = new Thread(new Runnable() {
public void run() {
runnable.run(serviceMap);
}
});
thread.start();
}
}
if (runnable instanceof UnmanagedRunnable) {
//Simply call the unmanaged runnable in-line.
return ((UnmanagedRunnable) runnable).addingService(arg0);
}
return svc;
}
| public Object addingService(ServiceReference arg0) {
sc++;
Object svc = bc.getService(arg0);
String key = ((String []) arg0.getProperty(Constants.OBJECTCLASS))[0];
serviceMap.put(key, svc);
if (thread == null && sc == services.length && !(runnable instanceof UnmanagedRunnable)) {
if (runnable instanceof ManagedInlineRunnable) {
//Client wants to run in same thread, just call method.
runnable.run(serviceMap);
} else {
//Create new thread and pass off to client Runnable implementation.
thread = new Thread(new Runnable() {
public void run() {
runnable.run(serviceMap);
}
});
thread.start();
}
}
if (runnable instanceof UnmanagedRunnable) {
//Simply call the unmanaged runnable in-line.
return ((UnmanagedRunnable) runnable).addingService(arg0);
}
return svc;
}
|
diff --git a/bennu-core/src/myorg/domain/contents/Node.java b/bennu-core/src/myorg/domain/contents/Node.java
index a3fb753d..6c2fbd4a 100644
--- a/bennu-core/src/myorg/domain/contents/Node.java
+++ b/bennu-core/src/myorg/domain/contents/Node.java
@@ -1,234 +1,232 @@
/*
* @(#)Node.java
*
* Copyright 2009 Instituto Superior Tecnico
* Founding Authors: João Figueiredo, Luis Cruz, Paulo Abrantes, Susana Fernandes
*
* https://fenix-ashes.ist.utl.pt/
*
* This file is part of the Bennu Web Application Infrastructure.
*
* The Bennu Web Application Infrastructure 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.*
*
* Bennu 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 Bennu. If not, see <http://www.gnu.org/licenses/>.
*
*/
package myorg.domain.contents;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import myorg.applicationTier.Authenticate.UserView;
import myorg.domain.MyOrg;
import myorg.domain.User;
import myorg.domain.VirtualHost;
import myorg.domain.groups.PersistentGroup;
import myorg.presentationTier.Context;
import myorg.presentationTier.actions.ContextBaseAction;
import pt.ist.fenixWebFramework.services.Service;
import pt.ist.fenixframework.pstm.AbstractDomainObject;
public abstract class Node extends Node_Base implements INode {
public Node() {
super();
setMyOrg(MyOrg.getInstance());
setOjbConcreteClass(getClass().getName());
}
public String getUrl() {
final StringBuilder stringBuilder = new StringBuilder();
appendUrlPrefix(stringBuilder);
stringBuilder.append("&");
stringBuilder.append(ContextBaseAction.CONTEXT_PATH);
stringBuilder.append('=');
appendNodePath(stringBuilder);
return stringBuilder.toString();
}
protected void appendNodePath(final StringBuilder stringBuilder) {
final Node parentNode = getParentNode();
if (parentNode != null) {
parentNode.appendNodePath(stringBuilder);
stringBuilder.append(Context.PATH_PART_SEPERATOR);
}
stringBuilder.append(getExternalId());
}
public String getContextPath() {
final StringBuilder stringBuilder = new StringBuilder();
appendNodePath(stringBuilder);
return stringBuilder.toString();
}
protected abstract void appendUrlPrefix(final StringBuilder stringBuilder);
@Override
public Set<INode> getChildren() {
return (Set) getChildNodesSet();
}
@Override
public Integer getOrder() {
return getNodeOrder();
}
@Override
public INode getParent() {
return getParentNode();
}
public void init(final VirtualHost virtualHost, final Node parentNode, final Integer order) {
if (parentNode == null) {
setNodeOrder(virtualHost.getTopLevelNodesSet(), order);
setVirtualHost(virtualHost);
} else {
setNodeOrder(parentNode.getChildNodesSet(), order);
setParentNode(parentNode);
}
}
private void setNodeOrder(final Set<Node> siblings, final Integer order) {
if (order == null) {
setNodeOrder(siblings.size() + 1);
} else {
final int newNodeOrder = order.intValue();
for (final Node node : siblings) {
final int currentNodeOrder = node.getNodeOrder().intValue();
if (currentNodeOrder >= newNodeOrder) {
node.setNodeOrder(Integer.valueOf(currentNodeOrder + 1));
}
}
}
}
public static Node getFirstTopLevelNode() {
final Set<Node> nodes = VirtualHost.getVirtualHostForThread().getTopLevelNodesSet();
return nodes.isEmpty() ? null : Collections.min(nodes, COMPARATOR_BY_ORDER);
}
public static Node getFirstAvailableTopLevelNode() {
final Set<Node> nodes = VirtualHost.getVirtualHostForThread().getOrderedTopLevelNodes();
for (final Node node : nodes) {
if (node.isAccessible()) {
return node;
}
}
return null;
}
protected void descNodeOrders(final Set<Node> nodes) {
final int threshold = getNodeOrder().intValue();
for (final Node node : nodes) {
final int currentNodeOrder = node.getNodeOrder().intValue();
if (currentNodeOrder >= threshold) {
node.setNodeOrder(Integer.valueOf(currentNodeOrder - 1));
}
}
}
public static SortedSet<Node> getOrderedTopLevelNodes() {
final VirtualHost virtualHost = VirtualHost.getVirtualHostForThread();
return virtualHost.getOrderedTopLevelNodes();
}
public Set<INode> getOrderedChildren() {
final Set<INode> nodes = new TreeSet<INode>(COMPARATOR_BY_ORDER);
nodes.addAll(getChildren());
return nodes;
}
@Override
public String asString() {
return getExternalId();
}
public static INode fromString(final String string) {
Node node = AbstractDomainObject.fromExternalId(string);
return node;
}
@Service
public void deleteService() {
delete();
}
public void delete() {
final Node parentNode = getParentNode();
if (parentNode == null) {
final VirtualHost virtualHost = VirtualHost.getVirtualHostForThread();
descNodeOrders(virtualHost.getTopLevelNodesSet());
} else {
removeParentNode();
descNodeOrders(parentNode.getChildNodesSet());
}
for (final Node childNode : getChildNodesSet()) {
childNode.delete();
}
removeVirtualHost();
removeMyOrg();
removeAccessibilityGroup();
- for (; !getNodeMapping().isEmpty(); getNodeMapping().get(0).delete())
- ;
deleteDomainObject();
}
@Service
public static void reorderTopLevelNodes(final List<Node> nodes) throws Error {
final VirtualHost virtualHost = VirtualHost.getVirtualHostForThread();
for (final Node node : virtualHost.getTopLevelNodesSet()) {
if (!nodes.contains(node)) {
throwError();
}
}
int i = 0;
for (final Node node : nodes) {
if (!virtualHost.hasTopLevelNodes(node)) {
throwError();
}
node.setNodeOrder(Integer.valueOf(i++));
}
}
@Service
public void reorderNodes(final List<Node> nodes) {
for (final Node node : getChildNodesSet()) {
if (!nodes.contains(node)) {
throwError();
}
}
int i = 0;
for (final Node node : nodes) {
if (!hasChildNodes(node)) {
throwError();
}
node.setNodeOrder(Integer.valueOf(i++));
}
}
private static void throwError() {
throw new Error("Nodes changed!");
}
public boolean isAccessible() {
final PersistentGroup persistentGroup = getAccessibilityGroup();
final User user = UserView.getCurrentUser();
return persistentGroup != null && persistentGroup.isMember(user);
}
}
| true | true | public void delete() {
final Node parentNode = getParentNode();
if (parentNode == null) {
final VirtualHost virtualHost = VirtualHost.getVirtualHostForThread();
descNodeOrders(virtualHost.getTopLevelNodesSet());
} else {
removeParentNode();
descNodeOrders(parentNode.getChildNodesSet());
}
for (final Node childNode : getChildNodesSet()) {
childNode.delete();
}
removeVirtualHost();
removeMyOrg();
removeAccessibilityGroup();
for (; !getNodeMapping().isEmpty(); getNodeMapping().get(0).delete())
;
deleteDomainObject();
}
| public void delete() {
final Node parentNode = getParentNode();
if (parentNode == null) {
final VirtualHost virtualHost = VirtualHost.getVirtualHostForThread();
descNodeOrders(virtualHost.getTopLevelNodesSet());
} else {
removeParentNode();
descNodeOrders(parentNode.getChildNodesSet());
}
for (final Node childNode : getChildNodesSet()) {
childNode.delete();
}
removeVirtualHost();
removeMyOrg();
removeAccessibilityGroup();
deleteDomainObject();
}
|
diff --git a/src/com/prealpha/extempdb/server/parse/GuardianArticleParser.java b/src/com/prealpha/extempdb/server/parse/GuardianArticleParser.java
index 48ccb02..631fca5 100644
--- a/src/com/prealpha/extempdb/server/parse/GuardianArticleParser.java
+++ b/src/com/prealpha/extempdb/server/parse/GuardianArticleParser.java
@@ -1,131 +1,138 @@
/*
* GuardianArticleParser.java
* Copyright (C) 2011 Meyer Kizner, Ty Overby
* All rights reserved.
*/
package com.prealpha.extempdb.server.parse;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.Namespace;
import org.jdom.filter.Filter;
import org.jdom.input.DOMBuilder;
import org.w3c.tidy.Tidy;
import com.google.inject.Inject;
import com.prealpha.extempdb.server.http.HttpClient;
import com.prealpha.extempdb.server.http.RobotsExclusionException;
import com.prealpha.extempdb.server.util.XmlUtils;
class GuardianArticleParser extends AbstractArticleParser {
/*
* Package visibility for unit testing.
*/
static final DateFormat DATE_FORMAT = new SimpleDateFormat(
"EEEEE d MMMMM yyyy");
private final HttpClient httpClient;
private final Tidy tidy;
private final DOMBuilder builder;
@Inject
public GuardianArticleParser(HttpClient httpClient, Tidy tidy,
DOMBuilder builder) {
this.httpClient = httpClient;
this.tidy = tidy;
this.builder = builder;
}
@Override
public ProtoArticle parse(String url) throws ArticleParseException {
try {
Map<String, String> params = Collections.emptyMap();
InputStream stream = httpClient.doGet(url, params);
return getFromHtml(stream);
} catch (IOException iox) {
throw new ArticleParseException(iox);
} catch (RobotsExclusionException rex) {
throw new ArticleParseException(rex);
}
}
private ProtoArticle getFromHtml(InputStream html)
throws ArticleParseException {
org.w3c.dom.Document doc = tidy.parseDOM(html, null);
doc.removeChild(doc.getDoctype());
Document document = builder.build(doc);
Namespace namespace = document.getRootElement().getNamespace();
// get the title
Filter titleElementFilter = XmlUtils.getElementFilter("div", "id",
"main-article-info");
Element titleElement = (Element) (document
.getDescendants(titleElementFilter)).next();
Element heading = titleElement.getChild("h1", namespace);
String title = heading.getValue();
- // get the byline
+ // get the byline, if there is one
+ // http://www.guardian.co.uk/world/feedarticle/9475892
+ String byline;
Filter bylineElementFilter = XmlUtils.getElementFilter("a", "class",
"contributor");
- Element bylineElement = (Element) (document
- .getDescendants(bylineElementFilter)).next();
- String byline = bylineElement.getValue();
+ Iterator<?> bylineIterator = document
+ .getDescendants(bylineElementFilter);
+ if (bylineIterator.hasNext()) {
+ Element bylineElement = (Element) bylineIterator.next();
+ byline = bylineElement.getValue();
+ } else {
+ byline = null;
+ }
/*
* Get the date. The actual date is in a non-standard <time> element,
* which JTidy doesn't like and seems to remove. So we use the parent
* element and parse out the date. For example, the parent element might
* contain "The Guardian, Thursday 27 January 2011". So we split() on
* the comma and take the second fragment for parsing.
*/
Filter dateElementFilter = XmlUtils.getElementFilter("li", "class",
"publication");
Element dateElement = (Element) (document
.getDescendants(dateElementFilter)).next();
String dateString = dateElement.getValue().split(",")[1].trim();
Date date;
try {
date = DATE_FORMAT.parse(dateString);
} catch (ParseException px) {
throw new ArticleParseException(px);
}
// get the body text
Filter bodyElementFilter = XmlUtils.getElementFilter("div", "id",
"article-wrapper");
Iterator<?> i1 = document.getDescendants(bodyElementFilter);
List<String> paragraphs = new ArrayList<String>();
while (i1.hasNext()) {
Element bodyElement = (Element) i1.next();
Filter paragraphFilter = XmlUtils.getElementFilter("p", null, null);
Iterator<?> i2 = bodyElement.getDescendants(paragraphFilter);
while (i2.hasNext()) {
Element paragraph = (Element) i2.next();
String text = paragraph.getValue().trim();
if (!text.isEmpty()) {
paragraphs.add(text);
}
}
}
return new ProtoArticle(title, byline, date, paragraphs);
}
}
| false | true | private ProtoArticle getFromHtml(InputStream html)
throws ArticleParseException {
org.w3c.dom.Document doc = tidy.parseDOM(html, null);
doc.removeChild(doc.getDoctype());
Document document = builder.build(doc);
Namespace namespace = document.getRootElement().getNamespace();
// get the title
Filter titleElementFilter = XmlUtils.getElementFilter("div", "id",
"main-article-info");
Element titleElement = (Element) (document
.getDescendants(titleElementFilter)).next();
Element heading = titleElement.getChild("h1", namespace);
String title = heading.getValue();
// get the byline
Filter bylineElementFilter = XmlUtils.getElementFilter("a", "class",
"contributor");
Element bylineElement = (Element) (document
.getDescendants(bylineElementFilter)).next();
String byline = bylineElement.getValue();
/*
* Get the date. The actual date is in a non-standard <time> element,
* which JTidy doesn't like and seems to remove. So we use the parent
* element and parse out the date. For example, the parent element might
* contain "The Guardian, Thursday 27 January 2011". So we split() on
* the comma and take the second fragment for parsing.
*/
Filter dateElementFilter = XmlUtils.getElementFilter("li", "class",
"publication");
Element dateElement = (Element) (document
.getDescendants(dateElementFilter)).next();
String dateString = dateElement.getValue().split(",")[1].trim();
Date date;
try {
date = DATE_FORMAT.parse(dateString);
} catch (ParseException px) {
throw new ArticleParseException(px);
}
// get the body text
Filter bodyElementFilter = XmlUtils.getElementFilter("div", "id",
"article-wrapper");
Iterator<?> i1 = document.getDescendants(bodyElementFilter);
List<String> paragraphs = new ArrayList<String>();
while (i1.hasNext()) {
Element bodyElement = (Element) i1.next();
Filter paragraphFilter = XmlUtils.getElementFilter("p", null, null);
Iterator<?> i2 = bodyElement.getDescendants(paragraphFilter);
while (i2.hasNext()) {
Element paragraph = (Element) i2.next();
String text = paragraph.getValue().trim();
if (!text.isEmpty()) {
paragraphs.add(text);
}
}
}
return new ProtoArticle(title, byline, date, paragraphs);
}
| private ProtoArticle getFromHtml(InputStream html)
throws ArticleParseException {
org.w3c.dom.Document doc = tidy.parseDOM(html, null);
doc.removeChild(doc.getDoctype());
Document document = builder.build(doc);
Namespace namespace = document.getRootElement().getNamespace();
// get the title
Filter titleElementFilter = XmlUtils.getElementFilter("div", "id",
"main-article-info");
Element titleElement = (Element) (document
.getDescendants(titleElementFilter)).next();
Element heading = titleElement.getChild("h1", namespace);
String title = heading.getValue();
// get the byline, if there is one
// http://www.guardian.co.uk/world/feedarticle/9475892
String byline;
Filter bylineElementFilter = XmlUtils.getElementFilter("a", "class",
"contributor");
Iterator<?> bylineIterator = document
.getDescendants(bylineElementFilter);
if (bylineIterator.hasNext()) {
Element bylineElement = (Element) bylineIterator.next();
byline = bylineElement.getValue();
} else {
byline = null;
}
/*
* Get the date. The actual date is in a non-standard <time> element,
* which JTidy doesn't like and seems to remove. So we use the parent
* element and parse out the date. For example, the parent element might
* contain "The Guardian, Thursday 27 January 2011". So we split() on
* the comma and take the second fragment for parsing.
*/
Filter dateElementFilter = XmlUtils.getElementFilter("li", "class",
"publication");
Element dateElement = (Element) (document
.getDescendants(dateElementFilter)).next();
String dateString = dateElement.getValue().split(",")[1].trim();
Date date;
try {
date = DATE_FORMAT.parse(dateString);
} catch (ParseException px) {
throw new ArticleParseException(px);
}
// get the body text
Filter bodyElementFilter = XmlUtils.getElementFilter("div", "id",
"article-wrapper");
Iterator<?> i1 = document.getDescendants(bodyElementFilter);
List<String> paragraphs = new ArrayList<String>();
while (i1.hasNext()) {
Element bodyElement = (Element) i1.next();
Filter paragraphFilter = XmlUtils.getElementFilter("p", null, null);
Iterator<?> i2 = bodyElement.getDescendants(paragraphFilter);
while (i2.hasNext()) {
Element paragraph = (Element) i2.next();
String text = paragraph.getValue().trim();
if (!text.isEmpty()) {
paragraphs.add(text);
}
}
}
return new ProtoArticle(title, byline, date, paragraphs);
}
|
diff --git a/src/java/org/apache/commons/math/linear/DenseRealMatrix.java b/src/java/org/apache/commons/math/linear/DenseRealMatrix.java
index 7ff95bfe0..4b4e50556 100644
--- a/src/java/org/apache/commons/math/linear/DenseRealMatrix.java
+++ b/src/java/org/apache/commons/math/linear/DenseRealMatrix.java
@@ -1,1622 +1,1622 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.math.linear;
import java.io.Serializable;
import java.util.Arrays;
import org.apache.commons.math.MathRuntimeException;
/**
* Cache-friendly implementation of RealMatrix using a flat arrays to store
* square blocks of the matrix.
* <p>
* This implementation is specially designed to be cache-friendly. Square blocks are
* stored as small arrays and allow efficient traversal of data both in row major direction
* and columns major direction, one block at a time. This greatly increases performances
* for algorithms that use crossed directions loops like multiplication or transposition.
* </p>
* <p>
* The size of square blocks is a static parameter. It may be tuned according to the cache
* size of the target computer processor. As a rule of thumbs, it should be the largest
* value that allows three blocks to be simultaneously cached (this is necessary for example
* for matrix multiplication). The default value is to use 52x52 blocks which is well suited
* for processors with 64k L1 cache (one block holds 2704 values or 21632 bytes). This value
* could be lowered to 36x36 for processors with 32k L1 cache.
* </p>
* <p>
* The regular blocks represent {@link #BLOCK_SIZE} x {@link #BLOCK_SIZE} squares. Blocks
* at right hand side and bottom side which may be smaller to fit matrix dimensions. The square
* blocks are flattened in row major order in single dimension arrays which are therefore
* {@link #BLOCK_SIZE}<sup>2</sup> elements long for regular blocks. The blocks are themselves
* organized in row major order.
* </p>
* <p>
* As an example, for a block size of 52x52, a 100x60 matrix would be stored in 4 blocks.
* Block 0 would be a double[2704] array holding the upper left 52x52 square, block 1 would be
* a double[416] array holding the upper right 52x8 rectangle, block 2 would be a double[2496]
* array holding the lower left 48x52 rectangle and block 3 would be a double[384] array
* holding the lower right 48x8 rectangle.
* </p>
* <p>
* The layout complexity overhead versus simple mapping of matrices to java
* arrays is negligible for small matrices (about 1%). The gain from cache efficiency leads
* to up to 3-fold improvements for matrices of moderate to large size.
* </p>
* @version $Revision$ $Date$
* @since 2.0
*/
public class DenseRealMatrix extends AbstractRealMatrix implements Serializable {
/** Serializable version identifier */
private static final long serialVersionUID = 4991895511313664478L;
/** Block size. */
public static final int BLOCK_SIZE = 52;
/** Blocks of matrix entries. */
private final double blocks[][];
/** Number of rows of the matrix. */
private final int rows;
/** Number of columns of the matrix. */
private final int columns;
/** Number of block rows of the matrix. */
private final int blockRows;
/** Number of block columns of the matrix. */
private final int blockColumns;
/**
* Create a new matrix with the supplied row and column dimensions.
*
* @param rows the number of rows in the new matrix
* @param columns the number of columns in the new matrix
* @throws IllegalArgumentException if row or column dimension is not
* positive
*/
public DenseRealMatrix(final int rows, final int columns)
throws IllegalArgumentException {
super(rows, columns);
this.rows = rows;
this.columns = columns;
// number of blocks
blockRows = (rows + BLOCK_SIZE - 1) / BLOCK_SIZE;
blockColumns = (columns + BLOCK_SIZE - 1) / BLOCK_SIZE;
// allocate storage blocks, taking care of smaller ones at right and bottom
blocks = createBlocksLayout(rows, columns);
}
/**
* Create a new dense matrix copying entries from raw layout data.
* <p>The input array <em>must</em> already be in raw layout.</p>
* <p>Calling this constructor is equivalent to call:
* <pre>matrix = new DenseRealMatrix(rawData.length, rawData[0].length,
* toBlocksLayout(rawData), false);</pre>
* </p>
* @param rawData data for new matrix, in raw layout
*
* @exception IllegalArgumentException if <code>blockData</code> shape is
* inconsistent with block layout
* @see #DenseRealMatrix(int, int, double[][], boolean)
*/
public DenseRealMatrix(final double[][] rawData)
throws IllegalArgumentException {
this(rawData.length, rawData[0].length, toBlocksLayout(rawData), false);
}
/**
* Create a new dense matrix copying entries from block layout data.
* <p>The input array <em>must</em> already be in blocks layout.</p>
* @param rows the number of rows in the new matrix
* @param columns the number of columns in the new matrix
* @param blockData data for new matrix
* @param copyArray if true, the input array will be copied, otherwise
* it will be referenced
*
* @exception IllegalArgumentException if <code>blockData</code> shape is
* inconsistent with block layout
* @see #createBlocksLayout(int, int)
* @see #toBlocksLayout(double[][])
* @see #DenseRealMatrix(double[][])
*/
public DenseRealMatrix(final int rows, final int columns,
final double[][] blockData, final boolean copyArray)
throws IllegalArgumentException {
super(rows, columns);
this.rows = rows;
this.columns = columns;
// number of blocks
blockRows = (rows + BLOCK_SIZE - 1) / BLOCK_SIZE;
blockColumns = (columns + BLOCK_SIZE - 1) / BLOCK_SIZE;
if (copyArray) {
// allocate storage blocks, taking care of smaller ones at right and bottom
blocks = new double[blockRows * blockColumns][];
} else {
// reference existing array
blocks = blockData;
}
int index = 0;
for (int iBlock = 0; iBlock < blockRows; ++iBlock) {
final int iHeight = blockHeight(iBlock);
for (int jBlock = 0; jBlock < blockColumns; ++jBlock, ++index) {
if (blockData[index].length != iHeight * blockWidth(jBlock)) {
throw MathRuntimeException.createIllegalArgumentException("wrong array shape (block length = {0}, expected {1})",
new Object[] {
blockData[index].length,
iHeight * blockWidth(jBlock)
});
}
if (copyArray) {
blocks[index] = blockData[index].clone();
}
}
}
}
/**
* Convert a data array from raw layout to blocks layout.
* <p>
* Raw layout is the straightforward layout where element at row i and
* column j is in array element <code>rawData[i][j]</code>. Blocks layout
* is the layout used in {@link DenseRealMatrix} instances, where the matrix
* is split in square blocks (except at right and bottom side where blocks may
* be rectangular to fit matrix size) and each block is stored in a flattened
* one-dimensional array.
* </p>
* <p>
* This method creates an array in blocks layout from an input array in raw layout.
* It can be used to provide the array argument of the {@link
* DenseRealMatrix#DenseRealMatrix(int, int, double[][], boolean)} constructor.
* </p>
* @param rawData data array in raw layout
* @return a new data array containing the same entries but in blocks layout
* @exception IllegalArgumentException if <code>rawData</code> is not rectangular
* (not all rows have the same length)
* @see #createBlocksLayout(int, int)
* @see #DenseRealMatrix(int, int, double[][], boolean)
*/
public static double[][] toBlocksLayout(final double[][] rawData)
throws IllegalArgumentException {
final int rows = rawData.length;
final int columns = rawData[0].length;
final int blockRows = (rows + BLOCK_SIZE - 1) / BLOCK_SIZE;
final int blockColumns = (columns + BLOCK_SIZE - 1) / BLOCK_SIZE;
// safety checks
for (int i = 0; i < rawData.length; ++i) {
final int length = rawData[i].length;
if (length != columns) {
throw MathRuntimeException.createIllegalArgumentException(
"some rows have length {0} while others have length {1}",
new Object[] { columns, length });
}
}
// convert array
final double[][] blocks = new double[blockRows * blockColumns][];
for (int iBlock = 0, blockIndex = 0; iBlock < blockRows; ++iBlock) {
final int pStart = iBlock * BLOCK_SIZE;
final int pEnd = Math.min(pStart + BLOCK_SIZE, rows);
final int iHeight = pEnd - pStart;
for (int jBlock = 0; jBlock < blockColumns; ++jBlock, ++blockIndex) {
final int qStart = jBlock * BLOCK_SIZE;
final int qEnd = Math.min(qStart + BLOCK_SIZE, columns);
final int jWidth = qEnd - qStart;
// allocate new block
final double[] block = new double[iHeight * jWidth];
blocks[blockIndex] = block;
// copy data
for (int p = pStart, index = 0; p < pEnd; ++p, index += jWidth) {
System.arraycopy(rawData[p], qStart, block, index, jWidth);
}
}
}
return blocks;
}
/**
* Create a data array in blocks layout.
* <p>
* This method can be used to create the array argument of the {@link
* DenseRealMatrix#DenseRealMatrix(int, int, double[][], boolean)} constructor.
* </p>
* @param rows the number of rows in the new matrix
* @param columns the number of columns in the new matrix
* @return a new data array in blocks layout
* @see #toBlocksLayout(double[][])
* @see #DenseRealMatrix(int, int, double[][], boolean)
*/
public static double[][] createBlocksLayout(final int rows, final int columns)
throws IllegalArgumentException {
final int blockRows = (rows + BLOCK_SIZE - 1) / BLOCK_SIZE;
final int blockColumns = (columns + BLOCK_SIZE - 1) / BLOCK_SIZE;
final double[][] blocks = new double[blockRows * blockColumns][];
for (int iBlock = 0, blockIndex = 0; iBlock < blockRows; ++iBlock) {
final int pStart = iBlock * BLOCK_SIZE;
final int pEnd = Math.min(pStart + BLOCK_SIZE, rows);
final int iHeight = pEnd - pStart;
for (int jBlock = 0; jBlock < blockColumns; ++jBlock, ++blockIndex) {
final int qStart = jBlock * BLOCK_SIZE;
final int qEnd = Math.min(qStart + BLOCK_SIZE, columns);
final int jWidth = qEnd - qStart;
blocks[blockIndex] = new double[iHeight * jWidth];
}
}
return blocks;
}
/** {@inheritDoc} */
public RealMatrix createMatrix(final int rowDimension, final int columnDimension)
throws IllegalArgumentException {
return new DenseRealMatrix(rowDimension, columnDimension);
}
/** {@inheritDoc} */
public RealMatrix copy() {
// create an empty matrix
DenseRealMatrix copied = new DenseRealMatrix(rows, columns);
// copy the blocks
for (int i = 0; i < blocks.length; ++i) {
System.arraycopy(blocks[i], 0, copied.blocks[i], 0, blocks[i].length);
}
return copied;
}
/** {@inheritDoc} */
public RealMatrix add(final RealMatrix m)
throws IllegalArgumentException {
try {
return add((DenseRealMatrix) m);
} catch (ClassCastException cce) {
// safety check
checkAdditionCompatible(m);
final DenseRealMatrix out = new DenseRealMatrix(rows, columns);
// perform addition block-wise, to ensure good cache behavior
int blockIndex = 0;
for (int iBlock = 0; iBlock < out.blockRows; ++iBlock) {
for (int jBlock = 0; jBlock < out.blockColumns; ++jBlock) {
// perform addition on the current block
final double[] outBlock = out.blocks[blockIndex];
final double[] tBlock = blocks[blockIndex];
final int pStart = iBlock * BLOCK_SIZE;
final int pEnd = Math.min(pStart + BLOCK_SIZE, rows);
final int qStart = jBlock * BLOCK_SIZE;
final int qEnd = Math.min(qStart + BLOCK_SIZE, columns);
for (int p = pStart, k = 0; p < pEnd; ++p) {
for (int q = qStart; q < qEnd; ++q, ++k) {
outBlock[k] = tBlock[k] + m.getEntry(p, q);
}
}
// go to next block
++blockIndex;
}
}
return out;
}
}
/**
* Compute the sum of this and <code>m</code>.
*
* @param m matrix to be added
* @return this + m
* @throws IllegalArgumentException if m is not the same size as this
*/
public DenseRealMatrix add(final DenseRealMatrix m)
throws IllegalArgumentException {
// safety check
checkAdditionCompatible(m);
final DenseRealMatrix out = new DenseRealMatrix(rows, columns);
// perform addition block-wise, to ensure good cache behavior
for (int blockIndex = 0; blockIndex < out.blocks.length; ++blockIndex) {
final double[] outBlock = out.blocks[blockIndex];
final double[] tBlock = blocks[blockIndex];
final double[] mBlock = m.blocks[blockIndex];
for (int k = 0; k < outBlock.length; ++k) {
outBlock[k] = tBlock[k] + mBlock[k];
}
}
return out;
}
/** {@inheritDoc} */
public RealMatrix subtract(final RealMatrix m)
throws IllegalArgumentException {
try {
return subtract((DenseRealMatrix) m);
} catch (ClassCastException cce) {
// safety check
checkSubtractionCompatible(m);
final DenseRealMatrix out = new DenseRealMatrix(rows, columns);
// perform subtraction block-wise, to ensure good cache behavior
int blockIndex = 0;
for (int iBlock = 0; iBlock < out.blockRows; ++iBlock) {
for (int jBlock = 0; jBlock < out.blockColumns; ++jBlock) {
// perform subtraction on the current block
final double[] outBlock = out.blocks[blockIndex];
final double[] tBlock = blocks[blockIndex];
final int pStart = iBlock * BLOCK_SIZE;
final int pEnd = Math.min(pStart + BLOCK_SIZE, rows);
final int qStart = jBlock * BLOCK_SIZE;
final int qEnd = Math.min(qStart + BLOCK_SIZE, columns);
for (int p = pStart, k = 0; p < pEnd; ++p) {
for (int q = qStart; q < qEnd; ++q, ++k) {
outBlock[k] = tBlock[k] - m.getEntry(p, q);
}
}
// go to next block
++blockIndex;
}
}
return out;
}
}
/**
* Compute this minus <code>m</code>.
*
* @param m matrix to be subtracted
* @return this - m
* @throws IllegalArgumentException if m is not the same size as this
*/
public DenseRealMatrix subtract(final DenseRealMatrix m)
throws IllegalArgumentException {
// safety check
checkSubtractionCompatible(m);
final DenseRealMatrix out = new DenseRealMatrix(rows, columns);
// perform subtraction block-wise, to ensure good cache behavior
for (int blockIndex = 0; blockIndex < out.blocks.length; ++blockIndex) {
final double[] outBlock = out.blocks[blockIndex];
final double[] tBlock = blocks[blockIndex];
final double[] mBlock = m.blocks[blockIndex];
for (int k = 0; k < outBlock.length; ++k) {
outBlock[k] = tBlock[k] - mBlock[k];
}
}
return out;
}
/** {@inheritDoc} */
public RealMatrix scalarAdd(final double d)
throws IllegalArgumentException {
final DenseRealMatrix out = new DenseRealMatrix(rows, columns);
// perform subtraction block-wise, to ensure good cache behavior
for (int blockIndex = 0; blockIndex < out.blocks.length; ++blockIndex) {
final double[] outBlock = out.blocks[blockIndex];
final double[] tBlock = blocks[blockIndex];
for (int k = 0; k < outBlock.length; ++k) {
outBlock[k] = tBlock[k] + d;
}
}
return out;
}
/** {@inheritDoc} */
public RealMatrix scalarMultiply(final double d)
throws IllegalArgumentException {
final DenseRealMatrix out = new DenseRealMatrix(rows, columns);
// perform subtraction block-wise, to ensure good cache behavior
for (int blockIndex = 0; blockIndex < out.blocks.length; ++blockIndex) {
final double[] outBlock = out.blocks[blockIndex];
final double[] tBlock = blocks[blockIndex];
for (int k = 0; k < outBlock.length; ++k) {
outBlock[k] = tBlock[k] * d;
}
}
return out;
}
/** {@inheritDoc} */
public RealMatrix multiply(final RealMatrix m)
throws IllegalArgumentException {
try {
return multiply((DenseRealMatrix) m);
} catch (ClassCastException cce) {
// safety check
checkMultiplicationCompatible(m);
final DenseRealMatrix out = new DenseRealMatrix(rows, m.getColumnDimension());
// perform multiplication block-wise, to ensure good cache behavior
int blockIndex = 0;
for (int iBlock = 0; iBlock < out.blockRows; ++iBlock) {
final int pStart = iBlock * BLOCK_SIZE;
final int pEnd = Math.min(pStart + BLOCK_SIZE, rows);
for (int jBlock = 0; jBlock < out.blockColumns; ++jBlock) {
final int qStart = jBlock * BLOCK_SIZE;
final int qEnd = Math.min(qStart + BLOCK_SIZE, m.getColumnDimension());
// select current block
final double[] outBlock = out.blocks[blockIndex];
// perform multiplication on current block
for (int kBlock = 0; kBlock < blockColumns; ++kBlock) {
final int kWidth = blockWidth(kBlock);
final double[] tBlock = blocks[iBlock * blockColumns + kBlock];
final int rStart = kBlock * BLOCK_SIZE;
for (int p = pStart, k = 0; p < pEnd; ++p) {
final int lStart = (p - pStart) * kWidth;
final int lEnd = lStart + kWidth;
for (int q = qStart; q < qEnd; ++q) {
double sum = 0;
for (int l = lStart, r = rStart; l < lEnd; ++l, ++r) {
sum += tBlock[l] * m.getEntry(r, q);
}
outBlock[k++] += sum;
}
}
}
// go to next block
++blockIndex;
}
}
return out;
}
}
/**
* Returns the result of postmultiplying this by m.
*
* @param m matrix to postmultiply by
* @return this * m
* @throws IllegalArgumentException
* if columnDimension(this) != rowDimension(m)
*/
public DenseRealMatrix multiply(DenseRealMatrix m) throws IllegalArgumentException {
// safety check
checkMultiplicationCompatible(m);
final DenseRealMatrix out = new DenseRealMatrix(rows, m.columns);
// perform multiplication block-wise, to ensure good cache behavior
int blockIndex = 0;
for (int iBlock = 0; iBlock < out.blockRows; ++iBlock) {
final int pStart = iBlock * BLOCK_SIZE;
final int pEnd = Math.min(pStart + BLOCK_SIZE, rows);
for (int jBlock = 0; jBlock < out.blockColumns; ++jBlock) {
final int jWidth = out.blockWidth(jBlock);
final int jWidth2 = jWidth + jWidth;
final int jWidth3 = jWidth2 + jWidth;
final int jWidth4 = jWidth3 + jWidth;
// select current block
final double[] outBlock = out.blocks[blockIndex];
// perform multiplication on current block
for (int kBlock = 0; kBlock < blockColumns; ++kBlock) {
final int kWidth = blockWidth(kBlock);
final double[] tBlock = blocks[iBlock * blockColumns + kBlock];
final double[] mBlock = m.blocks[kBlock * m.blockColumns + jBlock];
for (int p = pStart, k = 0; p < pEnd; ++p) {
final int lStart = (p - pStart) * kWidth;
final int lEnd = lStart + kWidth;
for (int nStart = 0; nStart < jWidth; ++nStart) {
double sum = 0;
int l = lStart;
int n = nStart;
while (l < lEnd - 3) {
sum += tBlock[l] * mBlock[n] +
tBlock[l + 1] * mBlock[n + jWidth] +
tBlock[l + 2] * mBlock[n + jWidth2] +
tBlock[l + 3] * mBlock[n + jWidth3];
l += 4;
n += jWidth4;
}
while (l < lEnd) {
sum += tBlock[l++] * mBlock[n];
n += jWidth;
}
outBlock[k++] += sum;
}
}
}
// go to next block
++blockIndex;
}
}
return out;
}
/** {@inheritDoc} */
public double[][] getData() {
final double[][] data = new double[getRowDimension()][getColumnDimension()];
final int lastColumns = columns - (blockColumns - 1) * BLOCK_SIZE;
for (int iBlock = 0; iBlock < blockRows; ++iBlock) {
final int pStart = iBlock * BLOCK_SIZE;
final int pEnd = Math.min(pStart + BLOCK_SIZE, rows);
int regularPos = 0;
int lastPos = 0;
for (int p = pStart; p < pEnd; ++p) {
final double[] dataP = data[p];
int blockIndex = iBlock * blockColumns;
int dataPos = 0;
for (int jBlock = 0; jBlock < blockColumns - 1; ++jBlock) {
System.arraycopy(blocks[blockIndex++], regularPos, dataP, dataPos, BLOCK_SIZE);
dataPos += BLOCK_SIZE;
}
System.arraycopy(blocks[blockIndex], lastPos, dataP, dataPos, lastColumns);
regularPos += BLOCK_SIZE;
lastPos += lastColumns;
}
}
return data;
}
/** {@inheritDoc} */
public double getNorm() {
final double[] colSums = new double[BLOCK_SIZE];
double maxColSum = 0;
for (int jBlock = 0; jBlock < blockColumns; jBlock++) {
final int jWidth = blockWidth(jBlock);
Arrays.fill(colSums, 0, jWidth, 0.0);
for (int iBlock = 0; iBlock < blockRows; ++iBlock) {
final int iHeight = blockHeight(iBlock);
final double[] block = blocks[iBlock * blockColumns + jBlock];
for (int j = 0; j < jWidth; ++j) {
double sum = 0;
for (int i = 0; i < iHeight; ++i) {
sum += Math.abs(block[i * jWidth + j]);
}
colSums[j] += sum;
}
}
for (int j = 0; j < jWidth; ++j) {
maxColSum = Math.max(maxColSum, colSums[j]);
}
}
return maxColSum;
}
/** {@inheritDoc} */
public double getFrobeniusNorm() {
double sum2 = 0;
for (int blockIndex = 0; blockIndex < blocks.length; ++blockIndex) {
for (final double entry : blocks[blockIndex]) {
sum2 += entry * entry;
}
}
return Math.sqrt(sum2);
}
/** {@inheritDoc} */
public RealMatrix getSubMatrix(final int startRow, final int endRow,
final int startColumn, final int endColumn)
throws MatrixIndexException {
// safety checks
checkSubMatrixIndex(startRow, endRow, startColumn, endColumn);
// create the output matrix
final DenseRealMatrix out =
new DenseRealMatrix(endRow - startRow + 1, endColumn - startColumn + 1);
// compute blocks shifts
final int blockStartRow = startRow / BLOCK_SIZE;
final int rowsShift = startRow % BLOCK_SIZE;
final int blockStartColumn = startColumn / BLOCK_SIZE;
final int columnsShift = startColumn % BLOCK_SIZE;
// perform extraction block-wise, to ensure good cache behavior
for (int iBlock = 0, pBlock = blockStartRow; iBlock < out.blockRows; ++iBlock, ++pBlock) {
final int iHeight = out.blockHeight(iBlock);
for (int jBlock = 0, qBlock = blockStartColumn; jBlock < out.blockColumns; ++jBlock, ++qBlock) {
final int jWidth = out.blockWidth(jBlock);
// handle one block of the output matrix
final int outIndex = iBlock * out.blockColumns + jBlock;
final double[] outBlock = out.blocks[outIndex];
final int index = pBlock * blockColumns + qBlock;
- final int width = blockWidth(index);
+ final int width = blockWidth(qBlock);
final int heightExcess = iHeight + rowsShift - BLOCK_SIZE;
final int widthExcess = jWidth + columnsShift - BLOCK_SIZE;
if (heightExcess > 0) {
// the submatrix block spans on two blocks rows from the original matrix
if (widthExcess > 0) {
// the submatrix block spans on two blocks columns from the original matrix
- final int width2 = blockWidth(index + 1);
+ final int width2 = blockWidth(qBlock + 1);
copyBlockPart(blocks[index], width,
rowsShift, BLOCK_SIZE,
columnsShift, BLOCK_SIZE,
outBlock, jWidth, 0, 0);
copyBlockPart(blocks[index + 1], width2,
rowsShift, BLOCK_SIZE,
0, widthExcess,
outBlock, jWidth, 0, jWidth - widthExcess);
copyBlockPart(blocks[index + blockColumns], width,
0, heightExcess,
columnsShift, BLOCK_SIZE,
outBlock, jWidth, iHeight - heightExcess, 0);
copyBlockPart(blocks[index + blockColumns + 1], width2,
0, heightExcess,
0, widthExcess,
outBlock, jWidth, iHeight - heightExcess, jWidth - widthExcess);
} else {
// the submatrix block spans on one block column from the original matrix
copyBlockPart(blocks[index], width,
rowsShift, BLOCK_SIZE,
columnsShift, jWidth + columnsShift,
outBlock, jWidth, 0, 0);
copyBlockPart(blocks[index + blockColumns], width,
0, heightExcess,
columnsShift, jWidth + columnsShift,
outBlock, jWidth, iHeight - heightExcess, 0);
}
} else {
// the submatrix block spans on one block row from the original matrix
if (widthExcess > 0) {
// the submatrix block spans on two blocks columns from the original matrix
- final int width2 = blockWidth(index + 1);
+ final int width2 = blockWidth(qBlock + 1);
copyBlockPart(blocks[index], width,
rowsShift, iHeight + rowsShift,
columnsShift, BLOCK_SIZE,
outBlock, jWidth, 0, 0);
copyBlockPart(blocks[index + 1], width2,
rowsShift, iHeight + rowsShift,
0, widthExcess,
outBlock, jWidth, 0, jWidth - widthExcess);
} else {
// the submatrix block spans on one block column from the original matrix
copyBlockPart(blocks[index], width,
rowsShift, iHeight + rowsShift,
columnsShift, jWidth + columnsShift,
outBlock, jWidth, 0, 0);
}
}
}
}
return out;
}
/**
* Copy a part of a block into another one
* <p>This method can be called only when the specified part fits in both
* blocks, no verification is done here.</p>
* @param srcBlock source block
* @param srcWidth source block width ({@link #BLOCK_SIZE} or smaller)
* @param srcStartRow start row in the source block
* @param srcEndRow end row (exclusive) in the source block
* @param srcStartColumn start column in the source block
* @param srcEndColumn end column (exclusive) in the source block
* @param dstBlock destination block
* @param dstWidth destination block width ({@link #BLOCK_SIZE} or smaller)
* @param dstStartRow start row in the destination block
* @param dstStartColumn start column in the destination block
*/
private void copyBlockPart(final double[] srcBlock, final int srcWidth,
final int srcStartRow, final int srcEndRow,
final int srcStartColumn, final int srcEndColumn,
final double[] dstBlock, final int dstWidth,
final int dstStartRow, final int dstStartColumn) {
final int length = srcEndColumn - srcStartColumn;
int srcPos = srcStartRow * srcWidth + srcStartColumn;
int dstPos = dstStartRow * dstWidth + dstStartColumn;
for (int srcRow = srcStartRow; srcRow < srcEndRow; ++srcRow) {
System.arraycopy(srcBlock, srcPos, dstBlock, dstPos, length);
srcPos += srcWidth;
dstPos += dstWidth;
}
}
/** {@inheritDoc} */
public void setSubMatrix(final double[][] subMatrix, final int row, final int column)
throws MatrixIndexException {
// safety checks
final int refLength = subMatrix[0].length;
if (refLength < 1) {
throw MathRuntimeException.createIllegalArgumentException("matrix must have at least one column",
null);
}
final int endRow = row + subMatrix.length - 1;
final int endColumn = column + refLength - 1;
checkSubMatrixIndex(row, endRow, column, endColumn);
for (final double[] subRow : subMatrix) {
if (subRow.length != refLength) {
throw MathRuntimeException.createIllegalArgumentException("some rows have length {0} while others have length {1}",
new Object[] {
refLength, subRow.length
});
}
}
// compute blocks bounds
final int blockStartRow = row / BLOCK_SIZE;
final int blockEndRow = (endRow + BLOCK_SIZE) / BLOCK_SIZE;
final int blockStartColumn = column / BLOCK_SIZE;
final int blockEndColumn = (endColumn + BLOCK_SIZE) / BLOCK_SIZE;
// perform copy block-wise, to ensure good cache behavior
for (int iBlock = blockStartRow; iBlock < blockEndRow; ++iBlock) {
final int iHeight = blockHeight(iBlock);
final int firstRow = iBlock * BLOCK_SIZE;
final int iStart = Math.max(row, firstRow);
final int iEnd = Math.min(endRow + 1, firstRow + iHeight);
for (int jBlock = blockStartColumn; jBlock < blockEndColumn; ++jBlock) {
final int jWidth = blockWidth(jBlock);
final int firstColumn = jBlock * BLOCK_SIZE;
final int jStart = Math.max(column, firstColumn);
final int jEnd = Math.min(endColumn + 1, firstColumn + jWidth);
final int jLength = jEnd - jStart;
// handle one block, row by row
final double[] block = blocks[iBlock * blockColumns + jBlock];
for (int i = iStart; i < iEnd; ++i) {
System.arraycopy(subMatrix[i - row], jStart - column,
block, (i - firstRow) * jWidth + (jStart - firstColumn),
jLength);
}
}
}
}
/** {@inheritDoc} */
public RealMatrix getRowMatrix(final int row)
throws MatrixIndexException {
checkRowIndex(row);
final DenseRealMatrix out = new DenseRealMatrix(1, columns);
// perform copy block-wise, to ensure good cache behavior
final int iBlock = row / BLOCK_SIZE;
final int iRow = row - iBlock * BLOCK_SIZE;
int outBlockIndex = 0;
int outIndex = 0;
double[] outBlock = out.blocks[outBlockIndex];
for (int jBlock = 0; jBlock < blockColumns; ++jBlock) {
final int jWidth = blockWidth(jBlock);
final double[] block = blocks[iBlock * blockColumns + jBlock];
final int available = outBlock.length - outIndex;
if (jWidth > available) {
System.arraycopy(block, iRow * jWidth, outBlock, outIndex, available);
outBlock = out.blocks[++outBlockIndex];
System.arraycopy(block, iRow * jWidth, outBlock, 0, jWidth - available);
outIndex = jWidth - available;
} else {
System.arraycopy(block, iRow * jWidth, outBlock, outIndex, jWidth);
outIndex += jWidth;
}
}
return out;
}
/** {@inheritDoc} */
public void setRowMatrix(final int row, final RealMatrix matrix)
throws MatrixIndexException, InvalidMatrixException {
try {
setRowMatrix(row, (DenseRealMatrix) matrix);
} catch (ClassCastException cce) {
super.setRowMatrix(row, matrix);
}
}
/**
* Sets the entries in row number <code>row</code>
* as a row matrix. Row indices start at 0.
*
* @param row the row to be set
* @param matrix row matrix (must have one row and the same number of columns
* as the instance)
* @throws MatrixIndexException if the specified row index is invalid
* @throws InvalidMatrixException if the matrix dimensions do not match one
* instance row
*/
public void setRowMatrix(final int row, final DenseRealMatrix matrix)
throws MatrixIndexException, InvalidMatrixException {
checkRowIndex(row);
final int nCols = getColumnDimension();
if ((matrix.getRowDimension() != 1) ||
(matrix.getColumnDimension() != nCols)) {
throw new InvalidMatrixException("dimensions mismatch: got {0}x{1} but expected {2}x{3}",
new Object[] {
matrix.getRowDimension(),
matrix.getColumnDimension(),
1, nCols
});
}
// perform copy block-wise, to ensure good cache behavior
final int iBlock = row / BLOCK_SIZE;
final int iRow = row - iBlock * BLOCK_SIZE;
int mBlockIndex = 0;
int mIndex = 0;
double[] mBlock = matrix.blocks[mBlockIndex];
for (int jBlock = 0; jBlock < blockColumns; ++jBlock) {
final int jWidth = blockWidth(jBlock);
final double[] block = blocks[iBlock * blockColumns + jBlock];
final int available = mBlock.length - mIndex;
if (jWidth > available) {
System.arraycopy(mBlock, mIndex, block, iRow * jWidth, available);
mBlock = matrix.blocks[++mBlockIndex];
System.arraycopy(mBlock, 0, block, iRow * jWidth, jWidth - available);
mIndex = jWidth - available;
} else {
System.arraycopy(mBlock, mIndex, block, iRow * jWidth, jWidth);
mIndex += jWidth;
}
}
}
/** {@inheritDoc} */
public RealMatrix getColumnMatrix(final int column)
throws MatrixIndexException {
checkColumnIndex(column);
final DenseRealMatrix out = new DenseRealMatrix(rows, 1);
// perform copy block-wise, to ensure good cache behavior
final int jBlock = column / BLOCK_SIZE;
final int jColumn = column - jBlock * BLOCK_SIZE;
final int jWidth = blockWidth(jBlock);
int outBlockIndex = 0;
int outIndex = 0;
double[] outBlock = out.blocks[outBlockIndex];
for (int iBlock = 0; iBlock < blockRows; ++iBlock) {
final int iHeight = blockHeight(iBlock);
final double[] block = blocks[iBlock * blockColumns + jBlock];
for (int i = 0; i < iHeight; ++i) {
if (outIndex >= outBlock.length) {
outBlock = out.blocks[++outBlockIndex];
outIndex = 0;
}
outBlock[outIndex++] = block[i * jWidth + jColumn];
}
}
return out;
}
/** {@inheritDoc} */
public void setColumnMatrix(final int column, final RealMatrix matrix)
throws MatrixIndexException, InvalidMatrixException {
try {
setColumnMatrix(column, (DenseRealMatrix) matrix);
} catch (ClassCastException cce) {
super.setColumnMatrix(column, matrix);
}
}
/**
* Sets the entries in column number <code>column</code>
* as a column matrix. Column indices start at 0.
*
* @param column the column to be set
* @param matrix column matrix (must have one column and the same number of rows
* as the instance)
* @throws MatrixIndexException if the specified column index is invalid
* @throws InvalidMatrixException if the matrix dimensions do not match one
* instance column
*/
void setColumnMatrix(final int column, final DenseRealMatrix matrix)
throws MatrixIndexException, InvalidMatrixException {
checkColumnIndex(column);
final int nRows = getRowDimension();
if ((matrix.getRowDimension() != nRows) ||
(matrix.getColumnDimension() != 1)) {
throw new InvalidMatrixException("dimensions mismatch: got {0}x{1} but expected {2}x{3}",
new Object[] {
matrix.getRowDimension(),
matrix.getColumnDimension(),
nRows, 1
});
}
// perform copy block-wise, to ensure good cache behavior
final int jBlock = column / BLOCK_SIZE;
final int jColumn = column - jBlock * BLOCK_SIZE;
final int jWidth = blockWidth(jBlock);
int mBlockIndex = 0;
int mIndex = 0;
double[] mBlock = matrix.blocks[mBlockIndex];
for (int iBlock = 0; iBlock < blockRows; ++iBlock) {
final int iHeight = blockHeight(iBlock);
final double[] block = blocks[iBlock * blockColumns + jBlock];
for (int i = 0; i < iHeight; ++i) {
if (mIndex >= mBlock.length) {
mBlock = matrix.blocks[++mBlockIndex];
mIndex = 0;
}
block[i * jWidth + jColumn] = mBlock[mIndex++];
}
}
}
/** {@inheritDoc} */
public RealVector getRowVector(final int row)
throws MatrixIndexException {
checkRowIndex(row);
final double[] outData = new double[columns];
// perform copy block-wise, to ensure good cache behavior
final int iBlock = row / BLOCK_SIZE;
final int iRow = row - iBlock * BLOCK_SIZE;
int outIndex = 0;
for (int jBlock = 0; jBlock < blockColumns; ++jBlock) {
final int jWidth = blockWidth(jBlock);
final double[] block = blocks[iBlock * blockColumns + jBlock];
System.arraycopy(block, iRow * jWidth, outData, outIndex, jWidth);
outIndex += jWidth;
}
return new RealVectorImpl(outData, false);
}
/** {@inheritDoc} */
public void setRowVector(final int row, final RealVector vector)
throws MatrixIndexException, InvalidMatrixException {
try {
setRow(row, ((RealVectorImpl) vector).getDataRef());
} catch (ClassCastException cce) {
super.setRowVector(row, vector);
}
}
/** {@inheritDoc} */
public RealVector getColumnVector(final int column)
throws MatrixIndexException {
checkColumnIndex(column);
final double[] outData = new double[rows];
// perform copy block-wise, to ensure good cache behavior
final int jBlock = column / BLOCK_SIZE;
final int jColumn = column - jBlock * BLOCK_SIZE;
final int jWidth = blockWidth(jBlock);
int outIndex = 0;
for (int iBlock = 0; iBlock < blockRows; ++iBlock) {
final int iHeight = blockHeight(iBlock);
final double[] block = blocks[iBlock * blockColumns + jBlock];
for (int i = 0; i < iHeight; ++i) {
outData[outIndex++] = block[i * jWidth + jColumn];
}
}
return new RealVectorImpl(outData, false);
}
/** {@inheritDoc} */
public void setColumnVector(final int column, final RealVector vector)
throws MatrixIndexException, InvalidMatrixException {
try {
setColumn(column, ((RealVectorImpl) vector).getDataRef());
} catch (ClassCastException cce) {
super.setColumnVector(column, vector);
}
}
/** {@inheritDoc} */
public double[] getRow(final int row)
throws MatrixIndexException {
checkRowIndex(row);
final double[] out = new double[columns];
// perform copy block-wise, to ensure good cache behavior
final int iBlock = row / BLOCK_SIZE;
final int iRow = row - iBlock * BLOCK_SIZE;
int outIndex = 0;
for (int jBlock = 0; jBlock < blockColumns; ++jBlock) {
final int jWidth = blockWidth(jBlock);
final double[] block = blocks[iBlock * blockColumns + jBlock];
System.arraycopy(block, iRow * jWidth, out, outIndex, jWidth);
outIndex += jWidth;
}
return out;
}
/** {@inheritDoc} */
public void setRow(final int row, final double[] array)
throws MatrixIndexException, InvalidMatrixException {
checkRowIndex(row);
final int nCols = getColumnDimension();
if (array.length != nCols) {
throw new InvalidMatrixException("dimensions mismatch: got {0}x{1} but expected {2}x{3}",
new Object[] {
1, array.length,
1, nCols
});
}
// perform copy block-wise, to ensure good cache behavior
final int iBlock = row / BLOCK_SIZE;
final int iRow = row - iBlock * BLOCK_SIZE;
int outIndex = 0;
for (int jBlock = 0; jBlock < blockColumns; ++jBlock) {
final int jWidth = blockWidth(jBlock);
final double[] block = blocks[iBlock * blockColumns + jBlock];
System.arraycopy(array, outIndex, block, iRow * jWidth, jWidth);
outIndex += jWidth;
}
}
/** {@inheritDoc} */
public double[] getColumn(final int column)
throws MatrixIndexException {
checkColumnIndex(column);
final double[] out = new double[rows];
// perform copy block-wise, to ensure good cache behavior
final int jBlock = column / BLOCK_SIZE;
final int jColumn = column - jBlock * BLOCK_SIZE;
final int jWidth = blockWidth(jBlock);
int outIndex = 0;
for (int iBlock = 0; iBlock < blockRows; ++iBlock) {
final int iHeight = blockHeight(iBlock);
final double[] block = blocks[iBlock * blockColumns + jBlock];
for (int i = 0; i < iHeight; ++i) {
out[outIndex++] = block[i * jWidth + jColumn];
}
}
return out;
}
/** {@inheritDoc} */
public void setColumn(final int column, final double[] array)
throws MatrixIndexException, InvalidMatrixException {
checkColumnIndex(column);
final int nRows = getRowDimension();
if (array.length != nRows) {
throw new InvalidMatrixException("dimensions mismatch: got {0}x{1} but expected {2}x{3}",
new Object[] {
array.length, 1,
nRows, 1
});
}
// perform copy block-wise, to ensure good cache behavior
final int jBlock = column / BLOCK_SIZE;
final int jColumn = column - jBlock * BLOCK_SIZE;
final int jWidth = blockWidth(jBlock);
int outIndex = 0;
for (int iBlock = 0; iBlock < blockRows; ++iBlock) {
final int iHeight = blockHeight(iBlock);
final double[] block = blocks[iBlock * blockColumns + jBlock];
for (int i = 0; i < iHeight; ++i) {
block[i * jWidth + jColumn] = array[outIndex++];
}
}
}
/** {@inheritDoc} */
public double getEntry(final int row, final int column)
throws MatrixIndexException {
try {
final int iBlock = row / BLOCK_SIZE;
final int jBlock = column / BLOCK_SIZE;
final int k = (row - iBlock * BLOCK_SIZE) * blockWidth(jBlock) +
(column - jBlock * BLOCK_SIZE);
return blocks[iBlock * blockColumns + jBlock][k];
} catch (ArrayIndexOutOfBoundsException e) {
throw new MatrixIndexException("no entry at indices ({0}, {1}) in a {2}x{3} matrix",
new Object[] {
row, column,
getRowDimension(), getColumnDimension()
});
}
}
/** {@inheritDoc} */
public void setEntry(final int row, final int column, final double value)
throws MatrixIndexException {
try {
final int iBlock = row / BLOCK_SIZE;
final int jBlock = column / BLOCK_SIZE;
final int k = (row - iBlock * BLOCK_SIZE) * blockWidth(jBlock) +
(column - jBlock * BLOCK_SIZE);
blocks[iBlock * blockColumns + jBlock][k] = value;
} catch (ArrayIndexOutOfBoundsException e) {
throw new MatrixIndexException("no entry at indices ({0}, {1}) in a {2}x{3} matrix",
new Object[] {
row, column,
getRowDimension(), getColumnDimension()
});
}
}
/** {@inheritDoc} */
public void addToEntry(final int row, final int column, final double increment)
throws MatrixIndexException {
try {
final int iBlock = row / BLOCK_SIZE;
final int jBlock = column / BLOCK_SIZE;
final int k = (row - iBlock * BLOCK_SIZE) * blockWidth(jBlock) +
(column - jBlock * BLOCK_SIZE);
blocks[iBlock * blockColumns + jBlock][k] += increment;
} catch (ArrayIndexOutOfBoundsException e) {
throw new MatrixIndexException("no entry at indices ({0}, {1}) in a {2}x{3} matrix",
new Object[] {
row, column,
getRowDimension(), getColumnDimension()
});
}
}
/** {@inheritDoc} */
public void multiplyEntry(final int row, final int column, final double factor)
throws MatrixIndexException {
try {
final int iBlock = row / BLOCK_SIZE;
final int jBlock = column / BLOCK_SIZE;
final int k = (row - iBlock * BLOCK_SIZE) * blockWidth(jBlock) +
(column - jBlock * BLOCK_SIZE);
blocks[iBlock * blockColumns + jBlock][k] *= factor;
} catch (ArrayIndexOutOfBoundsException e) {
throw new MatrixIndexException("no entry at indices ({0}, {1}) in a {2}x{3} matrix",
new Object[] {
row, column,
getRowDimension(), getColumnDimension()
});
}
}
/** {@inheritDoc} */
public RealMatrix transpose() {
final int nRows = getRowDimension();
final int nCols = getColumnDimension();
final DenseRealMatrix out = new DenseRealMatrix(nCols, nRows);
// perform transpose block-wise, to ensure good cache behavior
int blockIndex = 0;
for (int iBlock = 0; iBlock < blockColumns; ++iBlock) {
for (int jBlock = 0; jBlock < blockRows; ++jBlock) {
// transpose current block
final double[] outBlock = out.blocks[blockIndex];
final double[] tBlock = blocks[jBlock * blockColumns + iBlock];
final int pStart = iBlock * BLOCK_SIZE;
final int pEnd = Math.min(pStart + BLOCK_SIZE, columns);
final int qStart = jBlock * BLOCK_SIZE;
final int qEnd = Math.min(qStart + BLOCK_SIZE, rows);
for (int p = pStart, k = 0; p < pEnd; ++p) {
final int lInc = pEnd - pStart;
for (int q = qStart, l = p - pStart; q < qEnd; ++q, l+= lInc) {
outBlock[k++] = tBlock[l];
}
}
// go to next block
++blockIndex;
}
}
return out;
}
/** {@inheritDoc} */
public int getRowDimension() {
return rows;
}
/** {@inheritDoc} */
public int getColumnDimension() {
return columns;
}
/** {@inheritDoc} */
public double[] operate(final double[] v)
throws IllegalArgumentException {
if (v.length != columns) {
throw MathRuntimeException.createIllegalArgumentException("vector length mismatch:" +
" got {0} but expected {1}",
new Object[] {
v.length, columns
});
}
final double[] out = new double[rows];
// perform multiplication block-wise, to ensure good cache behavior
for (int iBlock = 0; iBlock < blockRows; ++iBlock) {
final int pStart = iBlock * BLOCK_SIZE;
final int pEnd = Math.min(pStart + BLOCK_SIZE, rows);
for (int jBlock = 0; jBlock < blockColumns; ++jBlock) {
final double[] block = blocks[iBlock * blockColumns + jBlock];
final int qStart = jBlock * BLOCK_SIZE;
final int qEnd = Math.min(qStart + BLOCK_SIZE, columns);
for (int p = pStart, k = 0; p < pEnd; ++p) {
double sum = 0;
int q = qStart;
while (q < qEnd - 3) {
sum += block[k] * v[q] +
block[k + 1] * v[q + 1] +
block[k + 2] * v[q + 2] +
block[k + 3] * v[q + 3];
k += 4;
q += 4;
}
while (q < qEnd) {
sum += block[k++] * v[q++];
}
out[p] += sum;
}
}
}
return out;
}
/** {@inheritDoc} */
public double[] preMultiply(final double[] v)
throws IllegalArgumentException {
if (v.length != rows) {
throw MathRuntimeException.createIllegalArgumentException("vector length mismatch:" +
" got {0} but expected {1}",
new Object[] {
v.length, rows
});
}
final double[] out = new double[columns];
// perform multiplication block-wise, to ensure good cache behavior
for (int jBlock = 0; jBlock < blockColumns; ++jBlock) {
final int jWidth = blockWidth(jBlock);
final int jWidth2 = jWidth + jWidth;
final int jWidth3 = jWidth2 + jWidth;
final int jWidth4 = jWidth3 + jWidth;
final int qStart = jBlock * BLOCK_SIZE;
final int qEnd = Math.min(qStart + BLOCK_SIZE, columns);
for (int iBlock = 0; iBlock < blockRows; ++iBlock) {
final double[] block = blocks[iBlock * blockColumns + jBlock];
final int pStart = iBlock * BLOCK_SIZE;
final int pEnd = Math.min(pStart + BLOCK_SIZE, rows);
for (int q = qStart; q < qEnd; ++q) {
int k = q - qStart;
double sum = 0;
int p = pStart;
while (p < pEnd - 3) {
sum += block[k] * v[p] +
block[k + jWidth] * v[p + 1] +
block[k + jWidth2] * v[p + 2] +
block[k + jWidth3] * v[p + 3];
k += jWidth4;
p += 4;
}
while (p < pEnd) {
sum += block[k] * v[p++];
k += jWidth;
}
out[q] += sum;
}
}
}
return out;
}
/** {@inheritDoc} */
public double walkInRowOrder(final RealMatrixChangingVisitor visitor)
throws MatrixVisitorException {
visitor.start(rows, columns, 0, rows - 1, 0, columns - 1);
for (int iBlock = 0; iBlock < blockRows; ++iBlock) {
final int pStart = iBlock * BLOCK_SIZE;
final int pEnd = Math.min(pStart + BLOCK_SIZE, rows);
for (int p = pStart; p < pEnd; ++p) {
for (int jBlock = 0; jBlock < blockColumns; ++jBlock) {
final int jWidth = blockWidth(jBlock);
final int qStart = jBlock * BLOCK_SIZE;
final int qEnd = Math.min(qStart + BLOCK_SIZE, columns);
final double[] block = blocks[iBlock * blockColumns + jBlock];
for (int q = qStart, k = (p - pStart) * jWidth; q < qEnd; ++q, ++k) {
block[k] = visitor.visit(p, q, block[k]);
}
}
}
}
return visitor.end();
}
/** {@inheritDoc} */
public double walkInRowOrder(final RealMatrixPreservingVisitor visitor)
throws MatrixVisitorException {
visitor.start(rows, columns, 0, rows - 1, 0, columns - 1);
for (int iBlock = 0; iBlock < blockRows; ++iBlock) {
final int pStart = iBlock * BLOCK_SIZE;
final int pEnd = Math.min(pStart + BLOCK_SIZE, rows);
for (int p = pStart; p < pEnd; ++p) {
for (int jBlock = 0; jBlock < blockColumns; ++jBlock) {
final int jWidth = blockWidth(jBlock);
final int qStart = jBlock * BLOCK_SIZE;
final int qEnd = Math.min(qStart + BLOCK_SIZE, columns);
final double[] block = blocks[iBlock * blockColumns + jBlock];
for (int q = qStart, k = (p - pStart) * jWidth; q < qEnd; ++q, ++k) {
visitor.visit(p, q, block[k]);
}
}
}
}
return visitor.end();
}
/** {@inheritDoc} */
public double walkInRowOrder(final RealMatrixChangingVisitor visitor,
final int startRow, final int endRow,
final int startColumn, final int endColumn)
throws MatrixIndexException, MatrixVisitorException {
checkSubMatrixIndex(startRow, endRow, startColumn, endColumn);
visitor.start(rows, columns, startRow, endRow, startColumn, endColumn);
for (int iBlock = startRow / BLOCK_SIZE; iBlock < 1 + endRow / BLOCK_SIZE; ++iBlock) {
final int p0 = iBlock * BLOCK_SIZE;
final int pStart = Math.max(startRow, p0);
final int pEnd = Math.min((iBlock + 1) * BLOCK_SIZE, 1 + endRow);
for (int p = pStart; p < pEnd; ++p) {
for (int jBlock = startColumn / BLOCK_SIZE; jBlock < 1 + endColumn / BLOCK_SIZE; ++jBlock) {
final int jWidth = blockWidth(jBlock);
final int q0 = jBlock * BLOCK_SIZE;
final int qStart = Math.max(startColumn, q0);
final int qEnd = Math.min((jBlock + 1) * BLOCK_SIZE, 1 + endColumn);
final double[] block = blocks[iBlock * blockColumns + jBlock];
for (int q = qStart, k = (p - p0) * jWidth + qStart - q0; q < qEnd; ++q, ++k) {
block[k] = visitor.visit(p, q, block[k]);
}
}
}
}
return visitor.end();
}
/** {@inheritDoc} */
public double walkInRowOrder(final RealMatrixPreservingVisitor visitor,
final int startRow, final int endRow,
final int startColumn, final int endColumn)
throws MatrixIndexException, MatrixVisitorException {
checkSubMatrixIndex(startRow, endRow, startColumn, endColumn);
visitor.start(rows, columns, startRow, endRow, startColumn, endColumn);
for (int iBlock = startRow / BLOCK_SIZE; iBlock < 1 + endRow / BLOCK_SIZE; ++iBlock) {
final int p0 = iBlock * BLOCK_SIZE;
final int pStart = Math.max(startRow, p0);
final int pEnd = Math.min((iBlock + 1) * BLOCK_SIZE, 1 + endRow);
for (int p = pStart; p < pEnd; ++p) {
for (int jBlock = startColumn / BLOCK_SIZE; jBlock < 1 + endColumn / BLOCK_SIZE; ++jBlock) {
final int jWidth = blockWidth(jBlock);
final int q0 = jBlock * BLOCK_SIZE;
final int qStart = Math.max(startColumn, q0);
final int qEnd = Math.min((jBlock + 1) * BLOCK_SIZE, 1 + endColumn);
final double[] block = blocks[iBlock * blockColumns + jBlock];
for (int q = qStart, k = (p - p0) * jWidth + qStart - q0; q < qEnd; ++q, ++k) {
visitor.visit(p, q, block[k]);
}
}
}
}
return visitor.end();
}
/** {@inheritDoc} */
public double walkInOptimizedOrder(final RealMatrixChangingVisitor visitor)
throws MatrixVisitorException {
visitor.start(rows, columns, 0, rows - 1, 0, columns - 1);
for (int iBlock = 0, blockIndex = 0; iBlock < blockRows; ++iBlock) {
final int pStart = iBlock * BLOCK_SIZE;
final int pEnd = Math.min(pStart + BLOCK_SIZE, rows);
for (int jBlock = 0; jBlock < blockColumns; ++jBlock, ++blockIndex) {
final int qStart = jBlock * BLOCK_SIZE;
final int qEnd = Math.min(qStart + BLOCK_SIZE, columns);
final double[] block = blocks[blockIndex];
for (int p = pStart, k = 0; p < pEnd; ++p) {
for (int q = qStart; q < qEnd; ++q, ++k) {
block[k] = visitor.visit(p, q, block[k]);
}
}
}
}
return visitor.end();
}
/** {@inheritDoc} */
public double walkInOptimizedOrder(final RealMatrixPreservingVisitor visitor)
throws MatrixVisitorException {
visitor.start(rows, columns, 0, rows - 1, 0, columns - 1);
for (int iBlock = 0, blockIndex = 0; iBlock < blockRows; ++iBlock) {
final int pStart = iBlock * BLOCK_SIZE;
final int pEnd = Math.min(pStart + BLOCK_SIZE, rows);
for (int jBlock = 0; jBlock < blockColumns; ++jBlock, ++blockIndex) {
final int qStart = jBlock * BLOCK_SIZE;
final int qEnd = Math.min(qStart + BLOCK_SIZE, columns);
final double[] block = blocks[blockIndex];
for (int p = pStart, k = 0; p < pEnd; ++p) {
for (int q = qStart; q < qEnd; ++q, ++k) {
visitor.visit(p, q, block[k]);
}
}
}
}
return visitor.end();
}
/** {@inheritDoc} */
public double walkInOptimizedOrder(final RealMatrixChangingVisitor visitor,
final int startRow, final int endRow,
final int startColumn, final int endColumn)
throws MatrixIndexException, MatrixVisitorException {
checkSubMatrixIndex(startRow, endRow, startColumn, endColumn);
visitor.start(rows, columns, startRow, endRow, startColumn, endColumn);
for (int iBlock = startRow / BLOCK_SIZE; iBlock < 1 + endRow / BLOCK_SIZE; ++iBlock) {
final int p0 = iBlock * BLOCK_SIZE;
final int pStart = Math.max(startRow, p0);
final int pEnd = Math.min((iBlock + 1) * BLOCK_SIZE, 1 + endRow);
for (int jBlock = startColumn / BLOCK_SIZE; jBlock < 1 + endColumn / BLOCK_SIZE; ++jBlock) {
final int jWidth = blockWidth(jBlock);
final int q0 = jBlock * BLOCK_SIZE;
final int qStart = Math.max(startColumn, q0);
final int qEnd = Math.min((jBlock + 1) * BLOCK_SIZE, 1 + endColumn);
final double[] block = blocks[iBlock * blockColumns + jBlock];
for (int p = pStart; p < pEnd; ++p) {
for (int q = qStart, k = (p - p0) * jWidth + qStart - q0; q < qEnd; ++q, ++k) {
block[k] = visitor.visit(p, q, block[k]);
}
}
}
}
return visitor.end();
}
/** {@inheritDoc} */
public double walkInOptimizedOrder(final RealMatrixPreservingVisitor visitor,
final int startRow, final int endRow,
final int startColumn, final int endColumn)
throws MatrixIndexException, MatrixVisitorException {
checkSubMatrixIndex(startRow, endRow, startColumn, endColumn);
visitor.start(rows, columns, startRow, endRow, startColumn, endColumn);
for (int iBlock = startRow / BLOCK_SIZE; iBlock < 1 + endRow / BLOCK_SIZE; ++iBlock) {
final int p0 = iBlock * BLOCK_SIZE;
final int pStart = Math.max(startRow, p0);
final int pEnd = Math.min((iBlock + 1) * BLOCK_SIZE, 1 + endRow);
for (int jBlock = startColumn / BLOCK_SIZE; jBlock < 1 + endColumn / BLOCK_SIZE; ++jBlock) {
final int jWidth = blockWidth(jBlock);
final int q0 = jBlock * BLOCK_SIZE;
final int qStart = Math.max(startColumn, q0);
final int qEnd = Math.min((jBlock + 1) * BLOCK_SIZE, 1 + endColumn);
final double[] block = blocks[iBlock * blockColumns + jBlock];
for (int p = pStart; p < pEnd; ++p) {
for (int q = qStart, k = (p - p0) * jWidth + qStart - q0; q < qEnd; ++q, ++k) {
visitor.visit(p, q, block[k]);
}
}
}
}
return visitor.end();
}
/**
* Get the height of a block.
* @param blockRow row index (in block sense) of the block
* @return height (number of rows) of the block
*/
private int blockHeight(final int blockRow) {
return (blockRow == blockRows - 1) ? rows - blockRow * BLOCK_SIZE : BLOCK_SIZE;
}
/**
* Get the width of a block.
* @param blockColumn column index (in block sense) of the block
* @return width (number of columns) of the block
*/
private int blockWidth(final int blockColumn) {
return (blockColumn == blockColumns - 1) ? columns - blockColumn * BLOCK_SIZE : BLOCK_SIZE;
}
}
| false | true | public RealMatrix getSubMatrix(final int startRow, final int endRow,
final int startColumn, final int endColumn)
throws MatrixIndexException {
// safety checks
checkSubMatrixIndex(startRow, endRow, startColumn, endColumn);
// create the output matrix
final DenseRealMatrix out =
new DenseRealMatrix(endRow - startRow + 1, endColumn - startColumn + 1);
// compute blocks shifts
final int blockStartRow = startRow / BLOCK_SIZE;
final int rowsShift = startRow % BLOCK_SIZE;
final int blockStartColumn = startColumn / BLOCK_SIZE;
final int columnsShift = startColumn % BLOCK_SIZE;
// perform extraction block-wise, to ensure good cache behavior
for (int iBlock = 0, pBlock = blockStartRow; iBlock < out.blockRows; ++iBlock, ++pBlock) {
final int iHeight = out.blockHeight(iBlock);
for (int jBlock = 0, qBlock = blockStartColumn; jBlock < out.blockColumns; ++jBlock, ++qBlock) {
final int jWidth = out.blockWidth(jBlock);
// handle one block of the output matrix
final int outIndex = iBlock * out.blockColumns + jBlock;
final double[] outBlock = out.blocks[outIndex];
final int index = pBlock * blockColumns + qBlock;
final int width = blockWidth(index);
final int heightExcess = iHeight + rowsShift - BLOCK_SIZE;
final int widthExcess = jWidth + columnsShift - BLOCK_SIZE;
if (heightExcess > 0) {
// the submatrix block spans on two blocks rows from the original matrix
if (widthExcess > 0) {
// the submatrix block spans on two blocks columns from the original matrix
final int width2 = blockWidth(index + 1);
copyBlockPart(blocks[index], width,
rowsShift, BLOCK_SIZE,
columnsShift, BLOCK_SIZE,
outBlock, jWidth, 0, 0);
copyBlockPart(blocks[index + 1], width2,
rowsShift, BLOCK_SIZE,
0, widthExcess,
outBlock, jWidth, 0, jWidth - widthExcess);
copyBlockPart(blocks[index + blockColumns], width,
0, heightExcess,
columnsShift, BLOCK_SIZE,
outBlock, jWidth, iHeight - heightExcess, 0);
copyBlockPart(blocks[index + blockColumns + 1], width2,
0, heightExcess,
0, widthExcess,
outBlock, jWidth, iHeight - heightExcess, jWidth - widthExcess);
} else {
// the submatrix block spans on one block column from the original matrix
copyBlockPart(blocks[index], width,
rowsShift, BLOCK_SIZE,
columnsShift, jWidth + columnsShift,
outBlock, jWidth, 0, 0);
copyBlockPart(blocks[index + blockColumns], width,
0, heightExcess,
columnsShift, jWidth + columnsShift,
outBlock, jWidth, iHeight - heightExcess, 0);
}
} else {
// the submatrix block spans on one block row from the original matrix
if (widthExcess > 0) {
// the submatrix block spans on two blocks columns from the original matrix
final int width2 = blockWidth(index + 1);
copyBlockPart(blocks[index], width,
rowsShift, iHeight + rowsShift,
columnsShift, BLOCK_SIZE,
outBlock, jWidth, 0, 0);
copyBlockPart(blocks[index + 1], width2,
rowsShift, iHeight + rowsShift,
0, widthExcess,
outBlock, jWidth, 0, jWidth - widthExcess);
} else {
// the submatrix block spans on one block column from the original matrix
copyBlockPart(blocks[index], width,
rowsShift, iHeight + rowsShift,
columnsShift, jWidth + columnsShift,
outBlock, jWidth, 0, 0);
}
}
}
}
return out;
}
| public RealMatrix getSubMatrix(final int startRow, final int endRow,
final int startColumn, final int endColumn)
throws MatrixIndexException {
// safety checks
checkSubMatrixIndex(startRow, endRow, startColumn, endColumn);
// create the output matrix
final DenseRealMatrix out =
new DenseRealMatrix(endRow - startRow + 1, endColumn - startColumn + 1);
// compute blocks shifts
final int blockStartRow = startRow / BLOCK_SIZE;
final int rowsShift = startRow % BLOCK_SIZE;
final int blockStartColumn = startColumn / BLOCK_SIZE;
final int columnsShift = startColumn % BLOCK_SIZE;
// perform extraction block-wise, to ensure good cache behavior
for (int iBlock = 0, pBlock = blockStartRow; iBlock < out.blockRows; ++iBlock, ++pBlock) {
final int iHeight = out.blockHeight(iBlock);
for (int jBlock = 0, qBlock = blockStartColumn; jBlock < out.blockColumns; ++jBlock, ++qBlock) {
final int jWidth = out.blockWidth(jBlock);
// handle one block of the output matrix
final int outIndex = iBlock * out.blockColumns + jBlock;
final double[] outBlock = out.blocks[outIndex];
final int index = pBlock * blockColumns + qBlock;
final int width = blockWidth(qBlock);
final int heightExcess = iHeight + rowsShift - BLOCK_SIZE;
final int widthExcess = jWidth + columnsShift - BLOCK_SIZE;
if (heightExcess > 0) {
// the submatrix block spans on two blocks rows from the original matrix
if (widthExcess > 0) {
// the submatrix block spans on two blocks columns from the original matrix
final int width2 = blockWidth(qBlock + 1);
copyBlockPart(blocks[index], width,
rowsShift, BLOCK_SIZE,
columnsShift, BLOCK_SIZE,
outBlock, jWidth, 0, 0);
copyBlockPart(blocks[index + 1], width2,
rowsShift, BLOCK_SIZE,
0, widthExcess,
outBlock, jWidth, 0, jWidth - widthExcess);
copyBlockPart(blocks[index + blockColumns], width,
0, heightExcess,
columnsShift, BLOCK_SIZE,
outBlock, jWidth, iHeight - heightExcess, 0);
copyBlockPart(blocks[index + blockColumns + 1], width2,
0, heightExcess,
0, widthExcess,
outBlock, jWidth, iHeight - heightExcess, jWidth - widthExcess);
} else {
// the submatrix block spans on one block column from the original matrix
copyBlockPart(blocks[index], width,
rowsShift, BLOCK_SIZE,
columnsShift, jWidth + columnsShift,
outBlock, jWidth, 0, 0);
copyBlockPart(blocks[index + blockColumns], width,
0, heightExcess,
columnsShift, jWidth + columnsShift,
outBlock, jWidth, iHeight - heightExcess, 0);
}
} else {
// the submatrix block spans on one block row from the original matrix
if (widthExcess > 0) {
// the submatrix block spans on two blocks columns from the original matrix
final int width2 = blockWidth(qBlock + 1);
copyBlockPart(blocks[index], width,
rowsShift, iHeight + rowsShift,
columnsShift, BLOCK_SIZE,
outBlock, jWidth, 0, 0);
copyBlockPart(blocks[index + 1], width2,
rowsShift, iHeight + rowsShift,
0, widthExcess,
outBlock, jWidth, 0, jWidth - widthExcess);
} else {
// the submatrix block spans on one block column from the original matrix
copyBlockPart(blocks[index], width,
rowsShift, iHeight + rowsShift,
columnsShift, jWidth + columnsShift,
outBlock, jWidth, 0, 0);
}
}
}
}
return out;
}
|
diff --git a/src/to/joe/j2mc/teleport/command/WarpCommand.java b/src/to/joe/j2mc/teleport/command/WarpCommand.java
index 74e981b..ead24c9 100644
--- a/src/to/joe/j2mc/teleport/command/WarpCommand.java
+++ b/src/to/joe/j2mc/teleport/command/WarpCommand.java
@@ -1,50 +1,48 @@
package to.joe.j2mc.teleport.command;
import java.util.HashMap;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import to.joe.j2mc.core.command.MasterCommand;
import to.joe.j2mc.teleport.J2MC_Teleport;
public class WarpCommand extends MasterCommand {
public WarpCommand(J2MC_Teleport plugin) {
super(plugin);
}
@Override
public void exec(CommandSender sender, String commandName, String[] args, Player player, boolean isPlayer) {
if (isPlayer) {
if (args.length == 0) {
final HashMap<String, Location> warps = ((J2MC_Teleport) this.plugin).getWarps("");
if (warps.size() == 0) {
player.sendMessage(ChatColor.RED + "No warps available");
} else {
final StringBuilder warpsList = new StringBuilder();
- final boolean first = true;
for (final String warpName : warps.keySet()) {
- if (!first) {
- warpsList.append(", ");
- }
warpsList.append(warpName);
+ warpsList.append(", ");
}
+ warpsList.setLength(warpsList.length() - 2);
player.sendMessage(ChatColor.RED + "Warps: " + ChatColor.WHITE + warpsList);
player.sendMessage(ChatColor.RED + "To go to a warp, say /warp warpname");
}
} else {
final Location target = ((J2MC_Teleport) this.plugin).getNamedWarp("", args[0]);
if ((target != null)) {
player.sendMessage(ChatColor.RED + "Welcome to: " + ChatColor.LIGHT_PURPLE + target);
this.plugin.getLogger().info(ChatColor.AQUA + "Player " + player.getName() + " went to warp " + target);
((J2MC_Teleport) this.plugin).teleport(player, target);
} else {
player.sendMessage(ChatColor.RED + "Warp does not exist. For a list, say /warp");
}
}
}
}
}
| false | true | public void exec(CommandSender sender, String commandName, String[] args, Player player, boolean isPlayer) {
if (isPlayer) {
if (args.length == 0) {
final HashMap<String, Location> warps = ((J2MC_Teleport) this.plugin).getWarps("");
if (warps.size() == 0) {
player.sendMessage(ChatColor.RED + "No warps available");
} else {
final StringBuilder warpsList = new StringBuilder();
final boolean first = true;
for (final String warpName : warps.keySet()) {
if (!first) {
warpsList.append(", ");
}
warpsList.append(warpName);
}
player.sendMessage(ChatColor.RED + "Warps: " + ChatColor.WHITE + warpsList);
player.sendMessage(ChatColor.RED + "To go to a warp, say /warp warpname");
}
} else {
final Location target = ((J2MC_Teleport) this.plugin).getNamedWarp("", args[0]);
if ((target != null)) {
player.sendMessage(ChatColor.RED + "Welcome to: " + ChatColor.LIGHT_PURPLE + target);
this.plugin.getLogger().info(ChatColor.AQUA + "Player " + player.getName() + " went to warp " + target);
((J2MC_Teleport) this.plugin).teleport(player, target);
} else {
player.sendMessage(ChatColor.RED + "Warp does not exist. For a list, say /warp");
}
}
}
}
| public void exec(CommandSender sender, String commandName, String[] args, Player player, boolean isPlayer) {
if (isPlayer) {
if (args.length == 0) {
final HashMap<String, Location> warps = ((J2MC_Teleport) this.plugin).getWarps("");
if (warps.size() == 0) {
player.sendMessage(ChatColor.RED + "No warps available");
} else {
final StringBuilder warpsList = new StringBuilder();
for (final String warpName : warps.keySet()) {
warpsList.append(warpName);
warpsList.append(", ");
}
warpsList.setLength(warpsList.length() - 2);
player.sendMessage(ChatColor.RED + "Warps: " + ChatColor.WHITE + warpsList);
player.sendMessage(ChatColor.RED + "To go to a warp, say /warp warpname");
}
} else {
final Location target = ((J2MC_Teleport) this.plugin).getNamedWarp("", args[0]);
if ((target != null)) {
player.sendMessage(ChatColor.RED + "Welcome to: " + ChatColor.LIGHT_PURPLE + target);
this.plugin.getLogger().info(ChatColor.AQUA + "Player " + player.getName() + " went to warp " + target);
((J2MC_Teleport) this.plugin).teleport(player, target);
} else {
player.sendMessage(ChatColor.RED + "Warp does not exist. For a list, say /warp");
}
}
}
}
|
diff --git a/src/com/jpii/navalbattle/game/gui/MidHud.java b/src/com/jpii/navalbattle/game/gui/MidHud.java
index 8a7e2b4c..c8ceba7c 100644
--- a/src/com/jpii/navalbattle/game/gui/MidHud.java
+++ b/src/com/jpii/navalbattle/game/gui/MidHud.java
@@ -1,264 +1,264 @@
package com.jpii.navalbattle.game.gui;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import com.jpii.navalbattle.game.entity.MoveableEntity;
import com.jpii.navalbattle.game.entity.Submarine;
import com.jpii.navalbattle.pavo.grid.Entity;
import com.jpii.navalbattle.pavo.gui.controls.Control;
import com.jpii.navalbattle.pavo.gui.controls.PButton;
import com.jpii.navalbattle.pavo.gui.controls.PImage;
import com.jpii.navalbattle.pavo.gui.events.PMouseEvent;
import com.jpii.navalbattle.turn.TurnManager;
import com.jpii.navalbattle.util.FileUtils;
public class MidHud{
boolean attackGuns = false;
boolean attackMissiles = false;
PImage missile;
PImage bullet;
PImage move;
PImage diplomacy;
PImage shop;
PImage elevation;
PButton missileB;
PButton bulletB;
PButton moveB;
PButton diplomacyB;
PButton shopB;
PButton elevationB;
PButton nextMove;
PButton nextEntity;
Entity display;
MoveableEntity moveE;
int width,height;
TurnManager tm;
public MidHud(Control c, TurnManager tm){
initButtons(c);
width = c.getWidth();
height = c.getHeight();
this.tm = tm;
}
public void draw(Graphics2D g){
drawText(g);
}
public void setEntity(Entity e,MoveableEntity me){
moveE = me;
if(display!=null){
if(moveE==null || !display.equals(moveE)){
if(display.getHandle()%10 == 1){
MoveableEntity display = (MoveableEntity)this.display;
if(display.isMovableTileBeingShown()){
display.toggleMovable();
}
if(display.isAttackTileBeingShown()){
display.toggleAttackRange();
}
}
}
}
display = e;
}
private void drawText(Graphics2D g){
g.setColor(Color.green);
Font temp = g.getFont();
Font perks = new Font("Arial",0,10);
g.setFont(perks);
g.drawString("Shop",(width/2)-148,height-62);
g.drawString("Missile",(width/2)-91,height-62);
g.drawString("Guns",(width/2)-28,height-62);
g.drawString("Diplomacy",(width/2)+18,height-62);
g.drawString("Move",(width/2)+92,height-62);
g.drawString("Submerge",(width/2)+142,height-62);
g.setFont(temp);
}
public void update(){
move.setVisible(false);
moveB.setVisible(false);
missile.setVisible(false);
missileB.setVisible(false);
bullet.setVisible(false);
bulletB.setVisible(false);
diplomacy.setVisible(false);
diplomacyB.setVisible(false);
shop.setVisible(false);
shopB.setVisible(false);
elevation.setVisible(false);
elevationB.setVisible(false);
if(display!=null){
diplomacy.setVisible(true);
diplomacyB.setVisible(true);
if(moveE!=null){
if(moveE.getHandle()==11){
Submarine sub = (Submarine)moveE;
elevationB.setVisible(true);
if(!sub.isSumberged()&&tm.getTurn().getPlayer().myEntity(sub))
elevation.setVisible(true);
}
if(moveE.getMaxMovement()!=moveE.getMoved())
move.setVisible(true);
if(!moveE.getUsedGuns())
bullet.setVisible(true);
if(!moveE.getUsedMissiles())
missile.setVisible(true);
if(tm.getTurn().getPlayer().myEntity(moveE)){
diplomacy.setVisible(false);
diplomacyB.setVisible(false);
shop.setVisible(true);
shopB.setVisible(true);
}
moveB.setVisible(true);
missileB.setVisible(true);
bulletB.setVisible(true);
}
}
}
private void initButtons(Control c){
- c.addControl(shopB = new PButton(c,(c.getWidth()/2)-150,c.getHeight()-60,30,30));
- c.addControl(missileB = new PButton(c,(c.getWidth()/2)-90,c.getHeight()-60,30,30));
- c.addControl(bulletB = new PButton(c,(c.getWidth()/2)-30,c.getHeight()-60,30,30));
- c.addControl(diplomacyB = new PButton(c,(c.getWidth()/2)+30,c.getHeight()-60,30,30));
- c.addControl(moveB = new PButton(c,(c.getWidth()/2)+90,c.getHeight()-60,30,30));
- c.addControl(elevationB = new PButton(c,(c.getWidth()/2)+150,c.getHeight()-60,30,30));
+ c.addControl(shopB = new PButton(c,(c.getWidth()/2)-150,c.getHeight()-60,32,31));
+ c.addControl(missileB = new PButton(c,(c.getWidth()/2)-90,c.getHeight()-60,32,31));
+ c.addControl(bulletB = new PButton(c,(c.getWidth()/2)-30,c.getHeight()-60,32,31));
+ c.addControl(diplomacyB = new PButton(c,(c.getWidth()/2)+30,c.getHeight()-60,32,31));
+ c.addControl(moveB = new PButton(c,(c.getWidth()/2)+90,c.getHeight()-60,32,31));
+ c.addControl(elevationB = new PButton(c,(c.getWidth()/2)+150,c.getHeight()-60,32,31));
c.addControl(nextMove = new PButton(c,"End Turn",(c.getWidth()/2)-60,c.getHeight()-130,150,40));
c.addControl(nextEntity = new PButton(c,"Next Ship",(c.getWidth()/2)+120,c.getHeight()-130,70,20));
nextMove.setFont(new Font("Arial",0,35));
nextEntity.setFont(new Font("Arial",0,15));
missile = new PImage(c);
bullet = new PImage(c);
move = new PImage(c);
diplomacy = new PImage(c);
shop = new PImage(c);
elevation = new PImage(c);
shop.setLoc((c.getWidth()/2)-150,c.getHeight()-60);
missile.setLoc((c.getWidth()/2)-90,c.getHeight()-60);
bullet.setLoc((c.getWidth()/2)-30,c.getHeight()-60);
diplomacy.setLoc((c.getWidth()/2)+30,c.getHeight()-60);
move.setLoc((c.getWidth()/2)+90,c.getHeight()-60);
elevation.setLoc((c.getWidth()/2)+150,c.getHeight()-60);
shop.setSize(30,30);
missile.setSize(30,30);
bullet.setSize(30,30);
diplomacy.setSize(30,30);
move.setSize(30,30);
elevation.setSize(30,30);
shop.setImage(PImage.registerImage(FileUtils.getImage("drawable-game/Buttons/Shop.png")));
missile.setImage(PImage.registerImage(FileUtils.getImage("drawable-game/Buttons/Missile.png")));
bullet.setImage(PImage.registerImage(FileUtils.getImage("drawable-game/Buttons/Bullet.png")));
diplomacy.setImage(PImage.registerImage(FileUtils.getImage("drawable-game/Buttons/Diplomacy.png")));
move.setImage(PImage.registerImage(FileUtils.getImage("drawable-game/Buttons/Move.png")));
elevation.setImage(PImage.registerImage(FileUtils.getImage("drawable-game/Buttons/Elevation.png")));
shop.repaint();
missile.repaint();
bullet.repaint();
diplomacy.repaint();
move.repaint();
elevation.repaint();
c.addControl(shop);
c.addControl(missile);
c.addControl(bullet);
c.addControl(diplomacy);
c.addControl(move);
c.addControl(elevation);
moveB.addMouseListener(new PMouseEvent(){
public void mouseDown(int x, int y, int buttonid) {
if(move.isVisible()){
if(moveE!=null){
if(moveE.isAttackTileBeingShown())
moveE.toggleAttackRange();
moveE.toggleMovable();
}
}
update();
}
});
nextMove.addMouseListener(new PMouseEvent(){
public void mouseDown(int x, int y, int buttonid) {
if(nextMove.isVisible()){
final TurnManager tm2 = tm;
tm2.nextTurn();
}
update();
}
});
bulletB.addMouseListener(new PMouseEvent(){
public void mouseDown(int x, int y, int buttonid) {
if(bullet.isVisible()){
if(moveE!=null){
if(moveE.isMovableTileBeingShown())
moveE.toggleMovable();
if(moveE.isAttackTileBeingShown()&&attackMissiles){
}
else
moveE.toggleAttackRange();
attackGuns = true;
attackMissiles = false;
}
}
update();
}
});
missileB.addMouseListener(new PMouseEvent(){
public void mouseDown(int x, int y, int buttonid) {
if(missile.isVisible()){
if(moveE!=null){
if(moveE.isMovableTileBeingShown())
moveE.toggleMovable();
if(moveE.isAttackTileBeingShown()&&attackGuns){
}
else
moveE.toggleAttackRange();
attackMissiles = true;
attackGuns = false;
}
}
update();
}
});
elevationB.addMouseListener(new PMouseEvent(){
public void mouseDown(int x, int y, int buttonid) {
if(elevation.isVisible()){
Submarine sub = (Submarine)display;
if(!sub.isSumberged()){
sub.toggleElevation();
sub.useGuns();
sub.useMissiles();
}
}
update();
}
});
c.repaint();
}
}
| true | true | private void initButtons(Control c){
c.addControl(shopB = new PButton(c,(c.getWidth()/2)-150,c.getHeight()-60,30,30));
c.addControl(missileB = new PButton(c,(c.getWidth()/2)-90,c.getHeight()-60,30,30));
c.addControl(bulletB = new PButton(c,(c.getWidth()/2)-30,c.getHeight()-60,30,30));
c.addControl(diplomacyB = new PButton(c,(c.getWidth()/2)+30,c.getHeight()-60,30,30));
c.addControl(moveB = new PButton(c,(c.getWidth()/2)+90,c.getHeight()-60,30,30));
c.addControl(elevationB = new PButton(c,(c.getWidth()/2)+150,c.getHeight()-60,30,30));
c.addControl(nextMove = new PButton(c,"End Turn",(c.getWidth()/2)-60,c.getHeight()-130,150,40));
c.addControl(nextEntity = new PButton(c,"Next Ship",(c.getWidth()/2)+120,c.getHeight()-130,70,20));
nextMove.setFont(new Font("Arial",0,35));
nextEntity.setFont(new Font("Arial",0,15));
missile = new PImage(c);
bullet = new PImage(c);
move = new PImage(c);
diplomacy = new PImage(c);
shop = new PImage(c);
elevation = new PImage(c);
shop.setLoc((c.getWidth()/2)-150,c.getHeight()-60);
missile.setLoc((c.getWidth()/2)-90,c.getHeight()-60);
bullet.setLoc((c.getWidth()/2)-30,c.getHeight()-60);
diplomacy.setLoc((c.getWidth()/2)+30,c.getHeight()-60);
move.setLoc((c.getWidth()/2)+90,c.getHeight()-60);
elevation.setLoc((c.getWidth()/2)+150,c.getHeight()-60);
shop.setSize(30,30);
missile.setSize(30,30);
bullet.setSize(30,30);
diplomacy.setSize(30,30);
move.setSize(30,30);
elevation.setSize(30,30);
shop.setImage(PImage.registerImage(FileUtils.getImage("drawable-game/Buttons/Shop.png")));
missile.setImage(PImage.registerImage(FileUtils.getImage("drawable-game/Buttons/Missile.png")));
bullet.setImage(PImage.registerImage(FileUtils.getImage("drawable-game/Buttons/Bullet.png")));
diplomacy.setImage(PImage.registerImage(FileUtils.getImage("drawable-game/Buttons/Diplomacy.png")));
move.setImage(PImage.registerImage(FileUtils.getImage("drawable-game/Buttons/Move.png")));
elevation.setImage(PImage.registerImage(FileUtils.getImage("drawable-game/Buttons/Elevation.png")));
shop.repaint();
missile.repaint();
bullet.repaint();
diplomacy.repaint();
move.repaint();
elevation.repaint();
c.addControl(shop);
c.addControl(missile);
c.addControl(bullet);
c.addControl(diplomacy);
c.addControl(move);
c.addControl(elevation);
moveB.addMouseListener(new PMouseEvent(){
public void mouseDown(int x, int y, int buttonid) {
if(move.isVisible()){
if(moveE!=null){
if(moveE.isAttackTileBeingShown())
moveE.toggleAttackRange();
moveE.toggleMovable();
}
}
update();
}
});
nextMove.addMouseListener(new PMouseEvent(){
public void mouseDown(int x, int y, int buttonid) {
if(nextMove.isVisible()){
final TurnManager tm2 = tm;
tm2.nextTurn();
}
update();
}
});
bulletB.addMouseListener(new PMouseEvent(){
public void mouseDown(int x, int y, int buttonid) {
if(bullet.isVisible()){
if(moveE!=null){
if(moveE.isMovableTileBeingShown())
moveE.toggleMovable();
if(moveE.isAttackTileBeingShown()&&attackMissiles){
}
else
moveE.toggleAttackRange();
attackGuns = true;
attackMissiles = false;
}
}
update();
}
});
missileB.addMouseListener(new PMouseEvent(){
public void mouseDown(int x, int y, int buttonid) {
if(missile.isVisible()){
if(moveE!=null){
if(moveE.isMovableTileBeingShown())
moveE.toggleMovable();
if(moveE.isAttackTileBeingShown()&&attackGuns){
}
else
moveE.toggleAttackRange();
attackMissiles = true;
attackGuns = false;
}
}
update();
}
});
elevationB.addMouseListener(new PMouseEvent(){
public void mouseDown(int x, int y, int buttonid) {
if(elevation.isVisible()){
Submarine sub = (Submarine)display;
if(!sub.isSumberged()){
sub.toggleElevation();
sub.useGuns();
sub.useMissiles();
}
}
update();
}
});
c.repaint();
}
| private void initButtons(Control c){
c.addControl(shopB = new PButton(c,(c.getWidth()/2)-150,c.getHeight()-60,32,31));
c.addControl(missileB = new PButton(c,(c.getWidth()/2)-90,c.getHeight()-60,32,31));
c.addControl(bulletB = new PButton(c,(c.getWidth()/2)-30,c.getHeight()-60,32,31));
c.addControl(diplomacyB = new PButton(c,(c.getWidth()/2)+30,c.getHeight()-60,32,31));
c.addControl(moveB = new PButton(c,(c.getWidth()/2)+90,c.getHeight()-60,32,31));
c.addControl(elevationB = new PButton(c,(c.getWidth()/2)+150,c.getHeight()-60,32,31));
c.addControl(nextMove = new PButton(c,"End Turn",(c.getWidth()/2)-60,c.getHeight()-130,150,40));
c.addControl(nextEntity = new PButton(c,"Next Ship",(c.getWidth()/2)+120,c.getHeight()-130,70,20));
nextMove.setFont(new Font("Arial",0,35));
nextEntity.setFont(new Font("Arial",0,15));
missile = new PImage(c);
bullet = new PImage(c);
move = new PImage(c);
diplomacy = new PImage(c);
shop = new PImage(c);
elevation = new PImage(c);
shop.setLoc((c.getWidth()/2)-150,c.getHeight()-60);
missile.setLoc((c.getWidth()/2)-90,c.getHeight()-60);
bullet.setLoc((c.getWidth()/2)-30,c.getHeight()-60);
diplomacy.setLoc((c.getWidth()/2)+30,c.getHeight()-60);
move.setLoc((c.getWidth()/2)+90,c.getHeight()-60);
elevation.setLoc((c.getWidth()/2)+150,c.getHeight()-60);
shop.setSize(30,30);
missile.setSize(30,30);
bullet.setSize(30,30);
diplomacy.setSize(30,30);
move.setSize(30,30);
elevation.setSize(30,30);
shop.setImage(PImage.registerImage(FileUtils.getImage("drawable-game/Buttons/Shop.png")));
missile.setImage(PImage.registerImage(FileUtils.getImage("drawable-game/Buttons/Missile.png")));
bullet.setImage(PImage.registerImage(FileUtils.getImage("drawable-game/Buttons/Bullet.png")));
diplomacy.setImage(PImage.registerImage(FileUtils.getImage("drawable-game/Buttons/Diplomacy.png")));
move.setImage(PImage.registerImage(FileUtils.getImage("drawable-game/Buttons/Move.png")));
elevation.setImage(PImage.registerImage(FileUtils.getImage("drawable-game/Buttons/Elevation.png")));
shop.repaint();
missile.repaint();
bullet.repaint();
diplomacy.repaint();
move.repaint();
elevation.repaint();
c.addControl(shop);
c.addControl(missile);
c.addControl(bullet);
c.addControl(diplomacy);
c.addControl(move);
c.addControl(elevation);
moveB.addMouseListener(new PMouseEvent(){
public void mouseDown(int x, int y, int buttonid) {
if(move.isVisible()){
if(moveE!=null){
if(moveE.isAttackTileBeingShown())
moveE.toggleAttackRange();
moveE.toggleMovable();
}
}
update();
}
});
nextMove.addMouseListener(new PMouseEvent(){
public void mouseDown(int x, int y, int buttonid) {
if(nextMove.isVisible()){
final TurnManager tm2 = tm;
tm2.nextTurn();
}
update();
}
});
bulletB.addMouseListener(new PMouseEvent(){
public void mouseDown(int x, int y, int buttonid) {
if(bullet.isVisible()){
if(moveE!=null){
if(moveE.isMovableTileBeingShown())
moveE.toggleMovable();
if(moveE.isAttackTileBeingShown()&&attackMissiles){
}
else
moveE.toggleAttackRange();
attackGuns = true;
attackMissiles = false;
}
}
update();
}
});
missileB.addMouseListener(new PMouseEvent(){
public void mouseDown(int x, int y, int buttonid) {
if(missile.isVisible()){
if(moveE!=null){
if(moveE.isMovableTileBeingShown())
moveE.toggleMovable();
if(moveE.isAttackTileBeingShown()&&attackGuns){
}
else
moveE.toggleAttackRange();
attackMissiles = true;
attackGuns = false;
}
}
update();
}
});
elevationB.addMouseListener(new PMouseEvent(){
public void mouseDown(int x, int y, int buttonid) {
if(elevation.isVisible()){
Submarine sub = (Submarine)display;
if(!sub.isSumberged()){
sub.toggleElevation();
sub.useGuns();
sub.useMissiles();
}
}
update();
}
});
c.repaint();
}
|
diff --git a/src/com/vaadin/terminal/gwt/client/ApplicationConfiguration.java b/src/com/vaadin/terminal/gwt/client/ApplicationConfiguration.java
index 470045154..4ea806e29 100644
--- a/src/com/vaadin/terminal/gwt/client/ApplicationConfiguration.java
+++ b/src/com/vaadin/terminal/gwt/client/ApplicationConfiguration.java
@@ -1,261 +1,260 @@
package com.vaadin.terminal.gwt.client;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArrayString;
import com.vaadin.terminal.gwt.client.ui.VUnknownComponent;
public class ApplicationConfiguration {
// can only be inited once, to avoid multiple-entrypoint-problem
private static WidgetSet initedWidgetSet;
private String id;
private String themeUri;
private String pathInfo;
private String appUri;
private JavaScriptObject versionInfo;
private String windowName;
private String communicationErrorCaption;
private String communicationErrorMessage;
private String communicationErrorUrl;
private boolean useDebugIdInDom = true;
private boolean usePortletURLs = false;
private String portletUidlURLBase;
private HashMap<String, String> unknownComponents;
private Class<? extends Paintable>[] classes = new Class[1024];
private static ArrayList<ApplicationConnection> unstartedApplications = new ArrayList<ApplicationConnection>();
private static ArrayList<ApplicationConnection> runningApplications = new ArrayList<ApplicationConnection>();
public boolean usePortletURLs() {
return usePortletURLs;
}
public String getPortletUidlURLBase() {
return portletUidlURLBase;
}
public String getRootPanelId() {
return id;
}
/**
* Gets the application base URI. Using this other than as the download
* action URI can cause problems in Portlet 2.0 deployments.
*
* @return application base URI
*/
public String getApplicationUri() {
return appUri;
}
public String getPathInfo() {
return pathInfo;
}
public String getThemeUri() {
return themeUri;
}
public void setAppId(String appId) {
id = appId;
}
public void setInitialWindowName(String name) {
windowName = name;
}
public String getInitialWindowName() {
return windowName;
}
public JavaScriptObject getVersionInfoJSObject() {
return versionInfo;
}
public String getCommunicationErrorCaption() {
return communicationErrorCaption;
}
public String getCommunicationErrorMessage() {
return communicationErrorMessage;
}
public String getCommunicationErrorUrl() {
return communicationErrorUrl;
}
private native void loadFromDOM()
/*-{
var id = [email protected]::id;
if($wnd.vaadin.vaadinConfigurations && $wnd.vaadin.vaadinConfigurations[id]) {
var jsobj = $wnd.vaadin.vaadinConfigurations[id];
var uri = jsobj.appUri;
if(uri != null && uri[uri.length -1] != "/") {
uri = uri + "/";
}
[email protected]::appUri = uri;
[email protected]::pathInfo = jsobj.pathInfo;
[email protected]::themeUri = jsobj.themeUri;
if(jsobj.windowName) {
[email protected]::windowName = jsobj.windowName;
}
if('useDebugIdInDom' in jsobj && typeof(jsobj.useDebugIdInDom) == "boolean") {
[email protected]::useDebugIdInDom = jsobj.useDebugIdInDom;
}
if(jsobj.versionInfo) {
[email protected]::versionInfo = jsobj.versionInfo;
}
if(jsobj.comErrMsg) {
[email protected]::communicationErrorCaption = jsobj.comErrMsg.caption;
[email protected]::communicationErrorMessage = jsobj.comErrMsg.message;
[email protected]::communicationErrorUrl = jsobj.comErrMsg.url;
}
if (jsobj.usePortletURLs) {
[email protected]::usePortletURLs = jsobj.usePortletURLs;
}
if (jsobj.portletUidlURLBase) {
[email protected]::portletUidlURLBase = jsobj.portletUidlURLBase;
}
} else {
$wnd.alert("Vaadin app failed to initialize: " + this.id);
}
}-*/;
/**
* Inits the ApplicationConfiguration by reading the DOM and instantiating
* ApplicationConnections accordingly. Call {@link #startNextApplication()}
* to actually start the applications.
*
* @param widgetset
* the widgetset that is running the apps
*/
public static void initConfigurations(WidgetSet widgetset) {
String wsname = widgetset.getClass().getName();
String module = GWT.getModuleName();
int lastdot = module.lastIndexOf(".");
String base = module.substring(0, lastdot);
String simpleName = module.substring(lastdot + 1);
// if (!wsname.startsWith(base) || !wsname.endsWith(simpleName)) {
// // WidgetSet module name does not match implementation name;
// // probably inherited WidgetSet with entry-point. Skip.
// GWT.log("Ignored init for " + wsname + " when starting " + module,
// null);
// return;
// }
if (initedWidgetSet != null) {
// Something went wrong: multiple widgetsets inited
String msg = "Tried to init " + widgetset.getClass().getName()
+ ", but " + initedWidgetSet.getClass().getName()
- + " is already inited.";
- System.err.println(msg);
- throw new IllegalStateException(msg);
+ + " was already inited.";
+ ApplicationConnection.getConsole().log(msg);
}
initedWidgetSet = widgetset;
ArrayList<String> appIds = new ArrayList<String>();
loadAppIdListFromDOM(appIds);
for (Iterator<String> it = appIds.iterator(); it.hasNext();) {
String appId = it.next();
ApplicationConfiguration appConf = getConfigFromDOM(appId);
ApplicationConnection a = new ApplicationConnection(widgetset,
appConf);
unstartedApplications.add(a);
}
}
/**
* Starts the next unstarted application. The WidgetSet should call this
* once to start the first application; after that, each application should
* call this once it has started. This ensures that the applications are
* started synchronously, which is neccessary to avoid session-id problems.
*
* @return true if an unstarted application was found
*/
public static boolean startNextApplication() {
if (unstartedApplications.size() > 0) {
ApplicationConnection a = unstartedApplications.remove(0);
a.start();
runningApplications.add(a);
return true;
} else {
return false;
}
}
public static List<ApplicationConnection> getRunningApplications() {
return runningApplications;
}
private native static void loadAppIdListFromDOM(ArrayList<String> list)
/*-{
var j;
for(j in $wnd.vaadin.vaadinConfigurations) {
[email protected]::add(Ljava/lang/Object;)(j);
}
}-*/;
public static ApplicationConfiguration getConfigFromDOM(String appId) {
ApplicationConfiguration conf = new ApplicationConfiguration();
conf.setAppId(appId);
conf.loadFromDOM();
return conf;
}
public native String getServletVersion()
/*-{
return [email protected]::versionInfo.vaadinVersion;
}-*/;
public native String getApplicationVersion()
/*-{
return [email protected]::versionInfo.applicationVersion;
}-*/;
public boolean useDebugIdInDOM() {
return useDebugIdInDom;
}
public Class<? extends Paintable> getWidgetClassByEncodedTag(String tag) {
try {
int parseInt = Integer.parseInt(tag);
return classes[parseInt];
} catch (Exception e) {
// component was not present in mappings
return VUnknownComponent.class;
}
}
public void addComponentMappings(ValueMap valueMap, WidgetSet widgetSet) {
JsArrayString keyArray = valueMap.getKeyArray();
for (int i = 0; i < keyArray.length(); i++) {
String key = keyArray.get(i);
int value = valueMap.getInt(key);
classes[value] = widgetSet.getImplementationByClassName(key);
if (classes[value] == VUnknownComponent.class) {
if (unknownComponents == null) {
unknownComponents = new HashMap<String, String>();
}
unknownComponents.put("" + value, key);
}
}
}
String getUnknownServerClassNameByEncodedTagName(String tag) {
if (unknownComponents != null) {
return unknownComponents.get(tag);
}
return null;
}
}
| true | true | public static void initConfigurations(WidgetSet widgetset) {
String wsname = widgetset.getClass().getName();
String module = GWT.getModuleName();
int lastdot = module.lastIndexOf(".");
String base = module.substring(0, lastdot);
String simpleName = module.substring(lastdot + 1);
// if (!wsname.startsWith(base) || !wsname.endsWith(simpleName)) {
// // WidgetSet module name does not match implementation name;
// // probably inherited WidgetSet with entry-point. Skip.
// GWT.log("Ignored init for " + wsname + " when starting " + module,
// null);
// return;
// }
if (initedWidgetSet != null) {
// Something went wrong: multiple widgetsets inited
String msg = "Tried to init " + widgetset.getClass().getName()
+ ", but " + initedWidgetSet.getClass().getName()
+ " is already inited.";
System.err.println(msg);
throw new IllegalStateException(msg);
}
initedWidgetSet = widgetset;
ArrayList<String> appIds = new ArrayList<String>();
loadAppIdListFromDOM(appIds);
for (Iterator<String> it = appIds.iterator(); it.hasNext();) {
String appId = it.next();
ApplicationConfiguration appConf = getConfigFromDOM(appId);
ApplicationConnection a = new ApplicationConnection(widgetset,
appConf);
unstartedApplications.add(a);
}
}
| public static void initConfigurations(WidgetSet widgetset) {
String wsname = widgetset.getClass().getName();
String module = GWT.getModuleName();
int lastdot = module.lastIndexOf(".");
String base = module.substring(0, lastdot);
String simpleName = module.substring(lastdot + 1);
// if (!wsname.startsWith(base) || !wsname.endsWith(simpleName)) {
// // WidgetSet module name does not match implementation name;
// // probably inherited WidgetSet with entry-point. Skip.
// GWT.log("Ignored init for " + wsname + " when starting " + module,
// null);
// return;
// }
if (initedWidgetSet != null) {
// Something went wrong: multiple widgetsets inited
String msg = "Tried to init " + widgetset.getClass().getName()
+ ", but " + initedWidgetSet.getClass().getName()
+ " was already inited.";
ApplicationConnection.getConsole().log(msg);
}
initedWidgetSet = widgetset;
ArrayList<String> appIds = new ArrayList<String>();
loadAppIdListFromDOM(appIds);
for (Iterator<String> it = appIds.iterator(); it.hasNext();) {
String appId = it.next();
ApplicationConfiguration appConf = getConfigFromDOM(appId);
ApplicationConnection a = new ApplicationConnection(widgetset,
appConf);
unstartedApplications.add(a);
}
}
|
diff --git a/srcj/com/sun/electric/tool/user/menus/ToolMenu.java b/srcj/com/sun/electric/tool/user/menus/ToolMenu.java
index 426f17efc..15cf45327 100644
--- a/srcj/com/sun/electric/tool/user/menus/ToolMenu.java
+++ b/srcj/com/sun/electric/tool/user/menus/ToolMenu.java
@@ -1,2081 +1,2083 @@
/* -*- tab-width: 4 -*-
*
* Electric(tm) VLSI Design System
*
* File: ToolMenu.java
*
* Copyright (c) 2003 Sun Microsystems and Static Free Software
*
* Electric(tm) is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Electric(tm) 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Electric(tm); see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, Mass 02111-1307, USA.
*/
package com.sun.electric.tool.user.menus;
import static com.sun.electric.tool.user.menus.EMenuItem.SEPARATOR;
import com.sun.electric.database.geometry.EPoint;
import com.sun.electric.database.geometry.GeometryHandler;
import com.sun.electric.database.geometry.Poly;
import com.sun.electric.database.hierarchy.Cell;
import com.sun.electric.database.hierarchy.Export;
import com.sun.electric.database.hierarchy.HierarchyEnumerator;
import com.sun.electric.database.hierarchy.Library;
import com.sun.electric.database.hierarchy.Nodable;
import com.sun.electric.database.hierarchy.View;
import com.sun.electric.database.id.CellUsage;
import com.sun.electric.database.network.Netlist;
import com.sun.electric.database.network.Network;
import com.sun.electric.database.network.NetworkTool;
import com.sun.electric.database.prototype.NodeProto;
import com.sun.electric.database.prototype.PortCharacteristic;
import com.sun.electric.database.prototype.PortProto;
import com.sun.electric.database.text.TextUtils;
import com.sun.electric.database.topology.ArcInst;
import com.sun.electric.database.topology.Connection;
import com.sun.electric.database.topology.NodeInst;
import com.sun.electric.database.topology.PortInst;
import com.sun.electric.database.variable.DisplayedText;
import com.sun.electric.database.variable.EditWindow_;
import com.sun.electric.database.variable.ElectricObject;
import com.sun.electric.database.variable.EvalJavaBsh;
import com.sun.electric.database.variable.TextDescriptor;
import com.sun.electric.database.variable.VarContext;
import com.sun.electric.database.variable.Variable;
import com.sun.electric.lib.LibFile;
import com.sun.electric.technology.DRCTemplate;
import com.sun.electric.technology.Foundry;
import com.sun.electric.technology.Layer;
import com.sun.electric.technology.PrimitiveNode;
import com.sun.electric.technology.PrimitivePort;
import com.sun.electric.technology.Technology;
import com.sun.electric.technology.technologies.Generic;
import com.sun.electric.technology.technologies.Schematics;
import com.sun.electric.tool.Job;
import com.sun.electric.tool.JobException;
import com.sun.electric.tool.Tool;
import com.sun.electric.tool.compaction.Compaction;
import com.sun.electric.tool.drc.AssuraDrcErrors;
import com.sun.electric.tool.drc.CalibreDrcErrors;
import com.sun.electric.tool.drc.DRC;
import com.sun.electric.tool.drc.MTDRCLayoutTool;
import com.sun.electric.tool.erc.ERCAntenna;
import com.sun.electric.tool.erc.ERCWellCheck;
import com.sun.electric.tool.extract.Connectivity;
import com.sun.electric.tool.extract.LayerCoverageTool;
import com.sun.electric.tool.extract.ParasiticTool;
import com.sun.electric.tool.generator.PadGenerator;
import com.sun.electric.tool.generator.ROMGenerator;
import com.sun.electric.tool.generator.cmosPLA.PLA;
import com.sun.electric.tool.generator.layout.GateLayoutGenerator;
import com.sun.electric.tool.generator.layout.TechType;
import com.sun.electric.tool.io.FileType;
import com.sun.electric.tool.io.input.LibraryFiles;
import com.sun.electric.tool.io.input.Simulate;
import com.sun.electric.tool.io.output.Spice;
import com.sun.electric.tool.io.output.Verilog;
import com.sun.electric.tool.logicaleffort.LENetlister;
import com.sun.electric.tool.logicaleffort.LETool;
import com.sun.electric.tool.ncc.AllSchemNamesToLay;
import com.sun.electric.tool.ncc.Ncc;
import com.sun.electric.tool.ncc.NccCrossProbing;
import com.sun.electric.tool.ncc.NccJob;
import com.sun.electric.tool.ncc.NccOptions;
import com.sun.electric.tool.ncc.Pie;
import com.sun.electric.tool.ncc.SchemNamesToLay;
import com.sun.electric.tool.ncc.basic.NccCellAnnotations;
import com.sun.electric.tool.ncc.basic.NccUtils;
import com.sun.electric.tool.ncc.netlist.NccNetlist;
import com.sun.electric.tool.ncc.result.NccResult;
import com.sun.electric.tool.ncc.result.NccResults;
import com.sun.electric.tool.ncc.result.equivalence.Equivalence;
import com.sun.electric.tool.routing.AutoStitch;
import com.sun.electric.tool.routing.Maze;
import com.sun.electric.tool.routing.MimicStitch;
import com.sun.electric.tool.routing.River;
import com.sun.electric.tool.routing.Routing;
import com.sun.electric.tool.routing.SeaOfGates;
import com.sun.electric.tool.sc.GetNetlist;
import com.sun.electric.tool.sc.Maker;
import com.sun.electric.tool.sc.Place;
import com.sun.electric.tool.sc.Route;
import com.sun.electric.tool.sc.SilComp;
import com.sun.electric.tool.simulation.Simulation;
import com.sun.electric.tool.user.CompileVHDL;
import com.sun.electric.tool.user.GenerateVHDL;
import com.sun.electric.tool.user.Highlight2;
import com.sun.electric.tool.user.Highlighter;
import com.sun.electric.tool.user.User;
import com.sun.electric.tool.user.dialogs.FastHenryArc;
import com.sun.electric.tool.user.dialogs.FillGenDialog;
import com.sun.electric.tool.user.dialogs.OpenFile;
import com.sun.electric.tool.user.ncc.HighlightEquivalent;
import com.sun.electric.tool.user.ui.EditWindow;
import com.sun.electric.tool.user.ui.TextWindow;
import com.sun.electric.tool.user.ui.TopLevel;
import com.sun.electric.tool.user.ui.WindowFrame;
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.awt.geom.Point2D;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
/**
* Class to handle the commands in the "Tool" pulldown menu.
*/
public class ToolMenu {
static EMenu makeMenu() {
/****************************** THE TOOL MENU ******************************/
// mnemonic keys available: B F H JK PQ XYZ
return new EMenu("_Tool",
//------------------- DRC
// mnemonic keys available: B EFG IJK MNOPQR UVWXYZ
new EMenu("_DRC",
new EMenuItem("Check _Hierarchically", KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0))
{ public void run() {
- if (DRC.isMultiThreaded())
+ Cell cell = Job.getUserInterface().needCurrentCell();
+ // Multi-threaded code is only available for layout
+ if (DRC.isMultiThreaded() && cell.isLayout())
{
- new MTDRCLayoutTool(Job.getUserInterface().needCurrentCell(), true, null).startJob();
+ new MTDRCLayoutTool(cell, true, null).startJob();
}
else
{
- DRC.checkDRCHierarchically(Job.getUserInterface().needCurrentCell(), null, GeometryHandler.GHMode.ALGO_SWEEP, false);
+ DRC.checkDRCHierarchically(cell, null, GeometryHandler.GHMode.ALGO_SWEEP, false);
}
}},
new EMenuItem("Check _Selection Area Hierarchically") { public void run() {
EditWindow_ wnd = Job.getUserInterface().getCurrentEditWindow_();
if (wnd == null) return;
DRC.checkDRCHierarchically(wnd.getCell(), wnd.getHighlightedArea(), GeometryHandler.GHMode.ALGO_SWEEP, false); }},
new EMenuItem("Check Area _Coverage") { public void run() {
LayerCoverageTool.layerCoverageCommand(WindowFrame.needCurCell(), GeometryHandler.GHMode.ALGO_SWEEP, true); }},
new EMenuItem("_List Layer Coverage on Cell") { public void run() {
layerCoverageCommand(LayerCoverageTool.LCMode.AREA, GeometryHandler.GHMode.ALGO_SWEEP); }},
SEPARATOR,
new EMenuItem("Import _Assura DRC Errors for Current Cell...") { public void run() {
importAssuraDrcErrors(); }},
new EMenuItem("Import Calibre _DRC Errors for Current Cell...") { public void run() {
importCalibreDrcErrors(); }},
SEPARATOR,
new EMenuItem("Export DRC Deck...") { public void run() {
exportDRCDeck(); }},
new EMenuItem("Import DRC Deck...") { public void run() {
importDRCDeck(); }}),
//------------------- Simulation (Built-in)
// mnemonic keys available: B JK N PQ XYZ
new EMenu("Simulation (Built-in)",
Simulation.hasIRSIM() ? new EMenuItem("IRSI_M: Simulate Current Cell") { public void run() {
Simulation.startSimulation(Simulation.IRSIM_ENGINE, false, null, null); }} : null,
Simulation.hasIRSIM() ? new EMenuItem("IRSIM: _Write Deck...") { public void run() {
FileMenu.exportCommand(FileType.IRSIM, true); }} : null,
Simulation.hasIRSIM() ? new EMenuItem("_IRSIM: Simulate Deck...") { public void run() {
Simulation.startSimulation(Simulation.IRSIM_ENGINE, true, null, null); }} : null,
Simulation.hasIRSIM() ? SEPARATOR : null,
new EMenuItem("_ALS: Simulate Current Cell") { public void run() {
Simulation.startSimulation(Simulation.ALS_ENGINE, false, null, null); }},
Simulation.hasFLEET() ? SEPARATOR : null,
Simulation.hasFLEET() ? Simulation.FLEETMenu() : null,
SEPARATOR,
new EMenuItem("Set Signal _High at Main Time", KeyStroke.getKeyStroke('V', 0)) { public void run() {
Simulation.setSignalHigh(); }},
new EMenuItem("Set Signal _Low at Main Time", KeyStroke.getKeyStroke('G', 0)) { public void run() {
Simulation.setSignalLow(); }},
new EMenuItem("Set Signal Un_defined at Main Time", KeyStroke.getKeyStroke('X', 0)) { public void run() {
Simulation.setSignalX(); }},
new EMenuItem("Set Clock on Selected Signal...") { public void run() {
Simulation.setClock(); }},
SEPARATOR,
new EMenuItem("_Update Simulation Window") { public void run() {
Simulation.update(); }},
new EMenuItem("_Get Information about Selected Signals") { public void run() {
Simulation.showSignalInfo(); }},
SEPARATOR,
new EMenuItem("_Clear Selected Stimuli") { public void run() {
Simulation.removeSelectedStimuli(); }},
new EMenuItem("Clear All Stimuli _on Selected Signals") { public void run() {
Simulation.removeStimuliFromSignal(); }},
new EMenuItem("Clear All S_timuli") { public void run() {
Simulation.removeAllStimuli(); }},
SEPARATOR,
new EMenuItem("_Save Stimuli to Disk...") { public void run() {
Simulation.saveStimuli(); }},
new EMenuItem("_Restore Stimuli from Disk...") { public void run() {
Simulation.restoreStimuli(); }}),
//------------------- Simulation (SPICE)
// mnemonic keys available: AB IJK NO QR VWXYZ
new EMenu("Simulation (_Spice)",
new EMenuItem("Write Spice _Deck...") { public void run() {
FileMenu.exportCommand(FileType.SPICE, true); }},
new EMenuItem("Write _CDL Deck...") { public void run() {
FileMenu.exportCommand(FileType.CDL, true); }},
new EMenuItem("Plot Spice _Listing...") { public void run() {
Simulate.plotSpiceResults(); }},
new EMenuItem("Plot Spice _for This Cell") { public void run() {
Simulate.plotSpiceResultsThisCell(); }},
new EMenuItem("Set Spice _Model...") { public void run() {
Simulation.setSpiceModel(); }},
new EMenuItem("Add M_ultiplier") { public void run() {
addMultiplierCommand(); }},
new EMenuItem("Add Flat Cod_e") { public void run() {
makeTemplate(Spice.SPICE_CODE_FLAT_KEY); }},
SEPARATOR,
new EMenuItem("Set Generic Spice _Template") { public void run() {
makeTemplate(Spice.SPICE_TEMPLATE_KEY); }},
new EMenuItem("Set Spice _2 Template") { public void run() {
makeTemplate(Spice.SPICE_2_TEMPLATE_KEY); }},
new EMenuItem("Set Spice _3 Template") { public void run() {
makeTemplate(Spice.SPICE_3_TEMPLATE_KEY); }},
new EMenuItem("Set _HSpice Template") { public void run() {
makeTemplate(Spice.SPICE_H_TEMPLATE_KEY); }},
new EMenuItem("Set _PSpice Template") { public void run() {
makeTemplate(Spice.SPICE_P_TEMPLATE_KEY); }},
new EMenuItem("Set _GnuCap Template") { public void run() {
makeTemplate(Spice.SPICE_GC_TEMPLATE_KEY); }},
new EMenuItem("Set _SmartSpice Template") { public void run() {
makeTemplate(Spice.SPICE_SM_TEMPLATE_KEY); }},
new EMenuItem("Set Assura CDL Template") { public void run() {
makeTemplate(Spice.SPICE_A_TEMPLATE_KEY); }},
new EMenuItem("Set Calibre Spice Template") { public void run() {
makeTemplate(Spice.SPICE_C_TEMPLATE_KEY); }},
new EMenuItem("Set Netlist Cell From File") { public void run() {
makeTemplate(Spice.SPICE_NETLIST_FILE_KEY); }}),
//------------------- Simulation (Verilog)
// mnemonic keys available: AB EFGHIJKLMNO QRS U WXYZ
new EMenu("Simulation (_Verilog)",
new EMenuItem("Write _Verilog Deck...") { public void run() {
Simulation.setVerilogStopAtStandardCells(false);
FileMenu.exportCommand(FileType.VERILOG, true); }},
new EMenuItem("Plot Verilog VCD _Dump...") { public void run() {
Simulate.plotVerilogResults(); }},
new EMenuItem("Plot Verilog for This _Cell") { public void run() {
Simulate.plotVerilogResultsThisCell(); }},
SEPARATOR,
new EMenuItem("Set Verilog _Template") { public void run() {
makeTemplate(Verilog.VERILOG_TEMPLATE_KEY); }},
new EMenuItem("Set Verilog Default _Parameter") { public void run() {
makeTemplate(Verilog.VERILOG_DEFPARAM_KEY); }},
SEPARATOR,
// mnemonic keys available: ABC EFGHIJKLMNOPQRS UV XYZ
new EMenu("Set Verilog _Wire",
new EMenuItem("_Wire") { public void run() {
Simulation.setVerilogWireCommand(0); }},
new EMenuItem("_Trireg") { public void run() {
Simulation.setVerilogWireCommand(1); }},
new EMenuItem("_Default") { public void run() {
Simulation.setVerilogWireCommand(2); }}),
// mnemonic keys available: ABCDEFGHIJKLM OPQRSTUV XYZ
new EMenu("_Transistor Strength",
new EMenuItem("_Weak") { public void run() {
Simulation.setTransistorStrengthCommand(true); }},
new EMenuItem("_Normal") { public void run() {
Simulation.setTransistorStrengthCommand(false); }})),
//------------------- Simulation (others)
// mnemonic keys available: B D G KL N Q UVWXYZ
new EMenu("Simulation (_Others)",
new EMenuItem("Write _Maxwell Deck...") { public void run() {
FileMenu.exportCommand(FileType.MAXWELL, true); }},
new EMenuItem("Write _Tegas Deck...") { public void run() {
FileMenu.exportCommand(FileType.TEGAS, true); }},
new EMenuItem("Write _SILOS Deck...") { public void run() {
FileMenu.exportCommand(FileType.SILOS, true); }},
new EMenuItem("Write _PAL Deck...") { public void run() {
FileMenu.exportCommand(FileType.PAL, true); }},
SEPARATOR,
!Simulation.hasIRSIM() ? new EMenuItem("Write _IRSIM Deck...") { public void run() {
FileMenu.exportCommand(FileType.IRSIM, true); }} : null,
new EMenuItem("Write _ESIM/RNL Deck...") { public void run() {
FileMenu.exportCommand(FileType.ESIM, true); }},
new EMenuItem("Write _RSIM Deck...") { public void run() {
FileMenu.exportCommand(FileType.RSIM, true); }},
new EMenuItem("Write _COSMOS Deck...") { public void run() {
FileMenu.exportCommand(FileType.COSMOS, true); }},
new EMenuItem("Write M_OSSIM Deck...") { public void run() {
FileMenu.exportCommand(FileType.MOSSIM, true); }},
SEPARATOR,
new EMenuItem("Write _FastHenry Deck...") { public void run() {
FileMenu.exportCommand(FileType.FASTHENRY, true); }},
new EMenuItem("Fast_Henry Arc Properties...") { public void run() {
FastHenryArc.showFastHenryArcDialog(); }},
SEPARATOR,
new EMenuItem("Write _ArchSim Deck...") { public void run() {
FileMenu.exportCommand(FileType.ARCHSIM, true); }},
new EMenuItem("Display ArchSim _Journal...") { public void run() {
Simulate.plotArchSimResults(); }}),
//------------------- ERC
// mnemonic keys available: BCDEFGHIJKLMNOPQRSTUV XYZ
new EMenu("_ERC",
new EMenuItem("Check _Wells") { public void run() {
ERCWellCheck.analyzeCurCell(GeometryHandler.GHMode.ALGO_SWEEP); }},
new EMenuItem("_Antenna Check") { public void run() {
ERCAntenna.doAntennaCheck(); }}),
// ------------------- NCC
// mnemonic keys available: AB DEFGHIJKLMNOPQRS UVWXYZ
new EMenu("_NCC",
new EMenuItem("Schematic and Layout Views of Cell in _Current Window") { public void run() {
new NccJob(1); }},
new EMenuItem("Cells from _Two Windows") { public void run() {
new NccJob(2); }},
SEPARATOR,
new EMenuItem("Copy Schematic _User Names to Layout") { public void run() {
new SchemNamesToLay.RenameJob(); }},
new EMenuItem("Copy All Schematic _Names to Layout") { public void run() {
new AllSchemNamesToLay.RenameJob(); }},
new EMenuItem("Highlight _Equivalent") { public void run() {
HighlightEquivalent.highlight(); }},
new EMenuItem("Run NCC for Schematic Cross-Probing") { public void run() {
runNccSchematicCrossProbing(); }},
new EMenu("Add NCC _Annotation to Cell",
new EMenuItem("Exports Connected by Parent _vdd") { public void run() {
NccCellAnnotations.makeNCCAnnotationMenuCommand("exportsConnectedByParent vdd /vdd_[0-9]+/"); }},
new EMenuItem("Exports Connected By Parent _gnd") { public void run() {
NccCellAnnotations.makeNCCAnnotationMenuCommand("exportsConnectedByParent gnd /gnd_[0-9]+/"); }},
new EMenuItem("_Skip NCC") { public void run() {
NccCellAnnotations.makeNCCAnnotationMenuCommand("skipNCC <comment explaining why>"); }},
new EMenuItem("_Not a Subcircuit") { public void run() {
NccCellAnnotations.makeNCCAnnotationMenuCommand("notSubcircuit <comment explaining why>"); }},
new EMenuItem("_Flatten Instances") { public void run() {
NccCellAnnotations.makeNCCAnnotationMenuCommand("flattenInstances <list of instance names>"); }},
new EMenuItem("_Join Group") { public void run() {
NccCellAnnotations.makeNCCAnnotationMenuCommand("joinGroup <cell name>"); }},
new EMenuItem("_Transistor Type") { public void run() {
NccCellAnnotations.makeNCCAnnotationMenuCommand("transistorType <typeName>"); }},
new EMenuItem("_Resistor Type") { public void run() {
NccCellAnnotations.makeNCCAnnotationMenuCommand("resistorType <typeName>"); }},
new EMenuItem("Force _Part Match") { public void run() {
NccCellAnnotations.makeNCCAnnotationMenuCommand("forcePartMatch <Part name shared by schematic and layout>"); }},
new EMenuItem("Force _Wire Match") { public void run() {
NccCellAnnotations.makeNCCAnnotationMenuCommand("forceWireMatch <Wire name shared by schematic and layout>"); }},
new EMenuItem("_Black Box") { public void run() {
NccCellAnnotations.makeNCCAnnotationMenuCommand("blackBox <comment explaining why>"); }})),
// ------------------- PIE
// If Pie package is installed then add menu entries to call it
Pie.hasPie() ? new EMenu("_PIE",
new EMenuItem("PIE Schematic and Layout Views of Cell in Current Window") { public void run() {
Pie.invokePieNcc(1); }},
new EMenuItem("Cells from _Two Windows") { public void run() {
Pie.invokePieNcc(2); }}) : null,
// ------------------- Architecture Generator
// // If ArchGen package is installed then add menu entries to call it
// ArchGenPlugin.hasArchGen() ? ArchGenPlugin.getEMenu() : null,
//------------------- Network
// mnemonic keys available: D F IJK M O Q S W YZ
new EMenu("Net_work",
new EMenuItem("Show _Network", 'K') { public void run() {
showNetworkCommand(); }},
new EMenuItem("_List Networks") { public void run() {
listNetworksCommand(); }},
new EMenuItem("List _Connections on Network") { public void run() {
listConnectionsOnNetworkCommand(); }},
new EMenuItem("List _Exports on Network") { public void run() {
listExportsOnNetworkCommand(); }},
new EMenuItem("List Exports _below Network") { public void run() {
listExportsBelowNetworkCommand(); }},
new EMenuItem("List _Geometry on Network") { public void run() {
listGeometryOnNetworkCommand(GeometryHandler.GHMode.ALGO_SWEEP); }},
new EMenuItem("Show _All Networks") { public void run() {
showAllNetworksCommand(); }},
new EMenuItem("List _Total Wire Lengths on All Networks") { public void run() {
listGeomsAllNetworksCommand(); }},
SEPARATOR,
new EMenuItem("E_xtract Current Cell") { public void run() {
Connectivity.extractCurCell(false); }},
new EMenuItem("Extract Current _Hierarchy") { public void run() {
Connectivity.extractCurCell(true); }},
SEPARATOR,
new EMenuItem("Show _Power and Ground") { public void run() {
showPowerAndGround(); }},
new EMenuItem("_Validate Power and Ground") { public void run() {
validatePowerAndGround(false); }},
new EMenuItem("_Repair Power and Ground") { public void run() {
new RepairPowerAndGround(); }},
new EMenuItem("Redo Network N_umbering") { public void run() {
NetworkTool.renumberNetlists(); }}),
//------------------- Logical Effort
// mnemonic keys available: D FGH JK M PQRSTUVWXYZ
new EMenu("_Logical Effort",
new EMenuItem("_Optimize for Equal Gate Delays") { public void run() {
optimizeEqualGateDelaysCommand(true); }},
new EMenuItem("Optimize for Equal Gate Delays (no _caching)") { public void run() {
optimizeEqualGateDelaysCommand(false); }},
new EMenuItem("List _Info for Selected Node") { public void run() {
printLEInfoCommand(); }},
new EMenuItem("_Back Annotate Wire Lengths for Current Cell") { public void run() {
backAnnotateCommand(); }},
new EMenuItem("Clear Sizes on Selected _Node(s)") { public void run() {
clearSizesNodableCommand(); }},
new EMenuItem("Clear Sizes in _all Libraries") { public void run() {
clearSizesCommand(); }},
new EMenuItem("_Estimate Delays") { public void run() {
estimateDelaysCommand(); }},
new EMenuItem("Add LE Attribute to Selected Export") { public void run() {
addLEAttribute(); }},
SEPARATOR,
new EMenuItem("_Load Logical Effort Libraries (Purple, Red, and Orange)") { public void run() {
loadLogicalEffortLibraries(); }}),
//------------------- Routing
// mnemonic keys available: B D F IJK OPQ V XY
new EMenu("_Routing",
new EMenuItem.CheckBox("Enable _Auto-Stitching") {
public boolean isSelected() { return Routing.isAutoStitchOn(); }
public void setSelected(boolean b) {
Routing.setAutoStitchOn(b);
System.out.println("Auto-stitching " + (b ? "enabled" : "disabled"));
}
},
new EMenuItem("Auto-_Stitch Now") { public void run() {
AutoStitch.autoStitch(false, true); }},
new EMenuItem("Auto-Stitch _Highlighted Now", KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0)) { public void run() {
AutoStitch.autoStitch(true, true); }},
SEPARATOR,
new EMenuItem.CheckBox("Enable _Mimic-Stitching") {
public boolean isSelected() { return Routing.isMimicStitchOn(); }
public void setSelected(boolean b) {
Routing.setMimicStitchOn(b);
System.out.println("Mimic-stitching " + (b ? "enabled" : "disabled"));
}
},
new EMenuItem("Mimic-Stitch _Now", KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0)) { public void run() {
MimicStitch.mimicStitch(true); }},
new EMenuItem("Mimic S_elected") { public void run() {
Routing.getRoutingTool().mimicSelected(); }},
SEPARATOR,
new EMenuItem("Ma_ze Route") { public void run() {
Maze.mazeRoute(); }},
SEPARATOR,
new EMenuItem("_River-Route") { public void run() {
River.riverRoute(); }},
SEPARATOR,
new EMenuItem("Sea-Of-_Gates Route") { public void run() {
SeaOfGates.seaOfGatesRoute(); }},
Routing.hasSunRouter() ? SEPARATOR : null,
Routing.hasSunRouter() ? new EMenuItem("Sun _Lava Router") { public void run() {
Routing.sunRouteCurrentCell(); }} : null,
SEPARATOR,
new EMenuItem("_Unroute") { public void run() {
Routing.unrouteCurrent(); }},
new EMenuItem("Get Unrouted _Wire") { public void run() {
getUnroutedArcCommand(); }},
new EMenuItem("_Copy Routing Topology") { public void run() {
Routing.copyRoutingTopology(); }},
new EMenuItem("Pas_te Routing Topology") { public void run() {
Routing.pasteRoutingTopology(); }}),
//------------------- Generation
// mnemonic keys available: AB DE GH JK N Q TUVWXYZ
new EMenu("_Generation",
new EMenuItem("_Coverage Implants Generator") { public void run() {
layerCoverageCommand(LayerCoverageTool.LCMode.IMPLANT, GeometryHandler.GHMode.ALGO_SWEEP); }},
new EMenuItem("_Pad Frame Generator...") { public void run() {
padFrameGeneratorCommand(); }},
new EMenuItem("_ROM Generator...") { public void run() {
ROMGenerator.generateROM(); }},
new EMenuItem("MOSIS CMOS P_LA Generator...") { public void run() {
PLA.generate(); }},
new EMenuItem("_Fill (MoCMOS)...") { public void run() {
FillGenDialog.openFillGeneratorDialog(Technology.getMocmosTechnology()); }},
Technology.getTSMC180Technology() != null ? new EMenuItem("Fi_ll (TSMC180)...") { public void run() {
FillGenDialog.openFillGeneratorDialog(Technology.getTSMC180Technology()); }} : null,
Technology.getCMOS90Technology() != null ? new EMenuItem("F_ill (CMOS90)...") { public void run() {
FillGenDialog.openFillGeneratorDialog(Technology.getCMOS90Technology()); }} : null,
new EMenuItem("Generate gate layouts (_MoCMOS)") { public void run() {
GateLayoutGenerator.generateFromSchematicsJob(TechType.TechTypeEnum.MOCMOS); }},
Technology.getTSMC180Technology() != null ? new EMenuItem("Generate gate layouts (T_SMC180)") { public void run() {
GateLayoutGenerator.generateFromSchematicsJob(TechType.TechTypeEnum.TSMC180); }} : null,
Technology.getCMOS90Technology() != null ? new EMenuItem("Generate gate layouts (CM_OS90)") { public void run() {
GateLayoutGenerator.generateFromSchematicsJob(TechType.TechTypeEnum.CMOS90); }} : null),
//------------------- Silicon Compiler
// mnemonic keys available: AB DEFGHIJKLM OPQRSTUVWXYZ
new EMenu("Silicon Co_mpiler",
new EMenuItem("_Convert Current Cell to Layout") { public void run() {
doSiliconCompilation(WindowFrame.needCurCell(), false); }},
SEPARATOR,
new EMenuItem("Compile VHDL to _Netlist View") { public void run() {
compileVHDL(); }}),
//------------------- Compaction
// mnemonic keys available: AB DEFGHIJKLMNOPQRSTUVWXYZ
new EMenu("_Compaction",
new EMenuItem("Do _Compaction") { public void run() {
Compaction.compactNow(); }}),
//------------------- Others
SEPARATOR,
new EMenuItem("List _Tools") { public void run() {
listToolsCommand(); }},
// mnemonic keys available: ABCDEFGHIJKLMNOPQ STUVWXYZ
new EMenu("Lang_uages",
new EMenuItem("_Run Java Bean Shell Script") { public void run() {
javaBshScriptCommand(); }}));
}
// ---------------------------- Tool Menu Commands ----------------------------
// Logical Effort Tool
public static void optimizeEqualGateDelaysCommand(boolean newAlg)
{
EditWindow curEdit = EditWindow.needCurrent();
if (curEdit == null) return;
LETool letool = LETool.getLETool();
if (letool == null) {
System.out.println("Logical Effort tool not found");
return;
}
// set current cell to use global context
curEdit.setCell(curEdit.getCell(), VarContext.globalContext, null);
// optimize cell for equal gate delays
if (curEdit.getCell() == null) {
System.out.println("No current cell");
return;
}
letool.optimizeEqualGateDelays(curEdit.getCell(), curEdit.getVarContext(), newAlg);
}
/** Print Logical Effort info for highlighted nodes */
public static void printLEInfoCommand() {
EditWindow wnd = EditWindow.needCurrent();
if (wnd == null) return;
Highlighter highlighter = wnd.getHighlighter();
VarContext context = wnd.getVarContext();
if (highlighter.getNumHighlights() == 0) {
System.out.println("Nothing highlighted");
return;
}
for (Highlight2 h : highlighter.getHighlights()) {
if (!h.isHighlightEOBJ()) continue;
ElectricObject eobj = h.getElectricObject();
if (eobj instanceof PortInst) {
PortInst pi = (PortInst)eobj;
pi.getInfo();
eobj = pi.getNodeInst();
}
if (eobj instanceof NodeInst) {
NodeInst ni = (NodeInst)eobj;
LETool.printResults(ni, context);
}
}
}
public static void backAnnotateCommand() {
EditWindow wnd = EditWindow.needCurrent();
if (wnd == null) return;
Cell cell = wnd.getCell();
if (cell == null) return;
BackAnnotateJob job = new BackAnnotateJob(cell);
job.startJob();
}
/**
* Method to handle the "List Layer Coverage", "Coverage Implant Generator", polygons merge
* except "List Geometry on Network" commands.
*/
public static void layerCoverageCommand(LayerCoverageTool.LCMode func, GeometryHandler.GHMode mode)
{
Cell curCell = WindowFrame.needCurCell();
if (curCell == null) return;
LayerCoverageTool.layerCoverageCommand(func, mode, curCell, true);
}
private static class BackAnnotateJob extends Job {
private Cell cell;
public BackAnnotateJob(Cell cell) {
super("BackAnnotate", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER);
this.cell = cell;
}
public boolean doIt() throws JobException {
Cell[] schLayCells = NccUtils.findSchematicAndLayout(cell);
if (schLayCells == null) {
System.out.println("Could not find schematic and layout cells for "+cell.describe(true));
return false;
}
if (cell.getView() == View.LAYOUT) {
// check if layout cells match, if not, replace
schLayCells[1] = cell;
}
// run NCC, get results
NccOptions options = new NccOptions();
NccResults results = Ncc.compare(schLayCells[0], null, schLayCells[1], null, options, this);
// get result of comparison of top schematic and layout Cells
NccResult result = results.getResultFromRootCells();
if (!result.match()) {
System.out.println("Ncc failed, can't back-annotate");
return false;
}
// find all wire models in schematic
int wiresUpdated = 0;
ArrayList<Network> networks = new ArrayList<Network>();
HashMap<Network,NodeInst> map = new HashMap<Network,NodeInst>(); // map of networks to associated wire model nodeinst
for (Iterator<NodeInst> it = schLayCells[0].getNodes(); it.hasNext(); ) {
NodeInst ni = it.next();
Variable var = ni.getParameterOrVariable(LENetlister.ATTR_LEWIRE);
if (var == null) continue;
var = ni.getParameterOrVariable(LENetlister.ATTR_L);
if (var == null) {
System.out.println("No attribute L on wire model "+ni.describe(true)+", ignoring it.");
continue;
}
// grab network wire model is on
PortInst pi = ni.getPortInst(0);
if (pi == null) continue;
Netlist netlist = schLayCells[0].getNetlist(NccNetlist.SHORT_RESISTORS);
Network schNet = netlist.getNetwork(pi);
networks.add(schNet);
map.put(schNet, ni);
}
// sort networks by name
Collections.sort(networks, new TextUtils.NetworksByName());
// update wire models
for (Network schNet : networks) {
// find equivalent network in layouy
Equivalence equiv = result.getEquivalence();
HierarchyEnumerator.NetNameProxy proxy = equiv.findEquivalentNet(VarContext.globalContext, schNet);
if (proxy == null) {
System.out.println("No matching network in layout for "+schNet.getName()+", ignoring");
continue;
}
Network layNet = proxy.getNet();
Cell netcell = layNet.getParent();
// get wire length
HashSet<Network> nets = new HashSet<Network>();
nets.add(layNet);
LayerCoverageTool.GeometryOnNetwork geoms = LayerCoverageTool.listGeometryOnNetworks(netcell, nets,
false, GeometryHandler.GHMode.ALGO_SWEEP);
double length = geoms.getTotalWireLength();
// update wire length
NodeInst ni = map.get(schNet);
ni.updateVar(LENetlister.ATTR_L, new Double(length));
wiresUpdated++;
System.out.println("Updated wire model "+ni.getName()+" on layout network "+proxy.toString()+" to: "+length+" lambda");
}
System.out.println("Updated "+wiresUpdated+" wire models in "+schLayCells[0]+" from layout "+schLayCells[1]);
return true;
}
}
public static void clearSizesNodableCommand() {
EditWindow wnd = EditWindow.needCurrent();
if (wnd == null) return;
Highlighter highlighter = wnd.getHighlighter();
if (highlighter.getNumHighlights() == 0) {
System.out.println("Nothing highlighted");
return;
}
for (Highlight2 h : highlighter.getHighlights()) {
if (!h.isHighlightEOBJ()) continue;
ElectricObject eobj = h.getElectricObject();
if (eobj instanceof PortInst) {
PortInst pi = (PortInst)eobj;
pi.getInfo();
eobj = pi.getNodeInst();
}
if (eobj instanceof NodeInst) {
NodeInst ni = (NodeInst)eobj;
LETool.clearStoredSizesJob(ni);
}
}
System.out.println("Sizes cleared");
}
public static void clearSizesCommand() {
for (Library lib : Library.getVisibleLibraries())
{
LETool.clearStoredSizesJob(lib);
}
System.out.println("Sizes cleared");
}
private static final double COEFFICIENTMETAL = 0.25;
private static final double COEFFICIENTPOLY = 0.25;
private static final double COEFFICIENTDIFF = 0.7;
public static void estimateDelaysCommand()
{
Cell cell = WindowFrame.needCurCell();
if (cell == null) return;
System.out.println("Delay estimation for each network is a ratio of the following:");
System.out.println(" Numerator is the sum of these layers on the network:");
System.out.println(" Transistor widths");
System.out.println(" Diffusion half-perimeter, weighted by " + COEFFICIENTDIFF);
System.out.println(" Polysilicon half-perimeter, weighted by " + COEFFICIENTPOLY);
System.out.println(" Metal half-perimeter, weighted by " + COEFFICIENTMETAL);
System.out.println(" Denominator is the width of transistors on the network");
System.out.println(" Separate results are computed for N and P transistors, as well as their sum");
System.out.println("-----------------------------------------------------------------------------");
Netlist nl = cell.acquireUserNetlist();
for(Iterator<Network> it = nl.getNetworks(); it.hasNext(); )
{
Network net = it.next();
Set<Network> nets = new HashSet<Network>();
nets.add(net);
LayerCoverageTool.GeometryOnNetwork geoms = LayerCoverageTool.listGeometryOnNetworks(cell, nets,
false, GeometryHandler.GHMode.ALGO_SWEEP);
LayerCoverageTool.TransistorInfo p_gate = geoms.getPGate();
LayerCoverageTool.TransistorInfo n_gate = geoms.getNGate();
LayerCoverageTool.TransistorInfo p_active = geoms.getPActive();
LayerCoverageTool.TransistorInfo n_active = geoms.getNActive();
// compute the numerator, starting with gate widths
double numerator = p_gate.width + n_gate.width;
if (numerator == 0) continue;
System.out.println("Network " + net.describe(true) + " ratio computation:");
System.out.println(" N Gate width = " + n_gate.width + ", P Gate width = " + p_gate.width);
// numerator also sums half-perimeter of each layer
List<Layer> layers = geoms.getLayers();
List<Double> halfPerimeters = geoms.getHalfPerimeters();
for(int i=0; i<layers.size(); i++)
{
Layer layer = layers.get(i);
Layer.Function fun = layer.getFunction();
if (!fun.isDiff() && !fun.isMetal() && !fun.isPoly()) continue;
if (fun.isGatePoly()) continue;
Double halfPerimeter = halfPerimeters.get(i);
double coefficient = COEFFICIENTDIFF;
if (fun.isMetal()) coefficient = COEFFICIENTMETAL;
if (fun.isPoly()) coefficient = COEFFICIENTPOLY;
double result = halfPerimeter.doubleValue() * coefficient;
System.out.println(" Layer " + layer.getName() + " half-perimeter is " + TextUtils.formatDouble(halfPerimeter.doubleValue()) +
" x " + coefficient + " = " + TextUtils.formatDouble(result));
numerator += result;
}
System.out.println(" Numerator is the sum of these factors (" + TextUtils.formatDouble(numerator) + ")");
// show the results
double pdenominator = p_active.width;
double ndenominator = n_active.width;
if (ndenominator == 0) System.out.println(" N denominator undefined"); else
System.out.println(" N denominator = " + ndenominator + ", ratio = " + TextUtils.formatDouble(numerator/ndenominator));
if (pdenominator == 0) System.out.println(" P denominator undefined"); else
System.out.println(" P denominator = " + pdenominator + ", ratio = " + TextUtils.formatDouble(numerator/pdenominator));
if (ndenominator+pdenominator == 0) System.out.println(" N+P Denominator undefined"); else
System.out.println(" N+P Denominator = " + (ndenominator+pdenominator) + ", ratio = " +
TextUtils.formatDouble(numerator/(ndenominator+pdenominator)));
}
}
public static void addLEAttribute()
{
EditWindow wnd = EditWindow.needCurrent();
if (wnd == null) return;
Highlighter highlighter = wnd.getHighlighter();
List<DisplayedText> textlist = highlighter.getHighlightedText(true);
for (DisplayedText text : textlist) {
if (text.getElectricObject() instanceof Export) {
new AddLEAttribute((Export)text.getElectricObject());
return;
}
}
}
private static class AddLEAttribute extends Job
{
private Export ex;
protected AddLEAttribute(Export ex)
{
super("Add LE Attribute", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER);
this.ex = ex;
startJob();
}
public boolean doIt() throws JobException
{
TextDescriptor td = TextDescriptor.getAnnotationTextDescriptor().withDispPart(TextDescriptor.DispPos.NAMEVALUE).withOff(-1.5, -1);
ex.newVar(LENetlister.ATTR_le, new Double(1.0), td);
return true;
}
}
public static void loadLogicalEffortLibraries()
{
if (Library.findLibrary("purpleGeneric180") != null) return;
URL url = LibFile.getLibFile("purpleGeneric180.jelib");
new FileMenu.ReadLibrary(url, FileType.JELIB, null);
}
/**
* Method to handle the "Show Network" command.
*/
public static void showNetworkCommand()
{
EditWindow wnd = EditWindow.needCurrent();
if (wnd == null) return;
Cell cell = wnd.getCell();
if (wnd == null) return;
Highlighter highlighter = wnd.getHighlighter();
Set<Network> nets = highlighter.getHighlightedNetworks();
Netlist netlist = cell.acquireUserNetlist();
if (netlist == null)
{
System.out.println("Sorry, a deadlock aborted netlist display (network information unavailable). Please try again");
return;
}
highlighter.showNetworks(nets, netlist, cell);
// 3D display if available
WindowFrame.show3DHighlight();
highlighter.finished();
}
/**
* Method to handle the "List Networks" command.
*/
public static void listNetworksCommand()
{
Cell cell = WindowFrame.getCurrentCell();
if (cell == null) return;
Netlist netlist = cell.acquireUserNetlist();
if (netlist == null)
{
System.out.println("Sorry, a deadlock aborted netlist display (network information unavailable). Please try again");
return;
}
int total = 0;
for(Iterator<Network> it = netlist.getNetworks(); it.hasNext(); )
{
Network net = it.next();
String netName = net.describe(false);
if (netName.length() == 0) continue;
StringBuffer infstr = new StringBuffer();
infstr.append("'" + netName + "'");
// if (net->buswidth > 1)
// {
// formatinfstr(infstr, _(" (bus with %d signals)"), net->buswidth);
// }
boolean connected = false;
for(Iterator<ArcInst> aIt = net.getArcs(); aIt.hasNext(); )
{
ArcInst ai = aIt.next();
if (!connected)
{
connected = true;
infstr.append(", on arcs:");
}
infstr.append(" " + ai.describe(true));
}
boolean exported = false;
for(Iterator<Export> eIt = net.getExports(); eIt.hasNext(); )
{
Export pp = eIt.next();
if (!exported)
{
exported = true;
infstr.append(", with exports:");
}
infstr.append(" " + pp.getName());
}
System.out.println(infstr.toString());
total++;
}
if (total == 0) System.out.println("There are no networks in this cell");
}
/**
* Method to handle the "List Connections On Network" command.
*/
public static void listConnectionsOnNetworkCommand()
{
Cell cell = WindowFrame.needCurCell();
if (cell == null) return;
EditWindow wnd = EditWindow.needCurrent();
if (wnd == null) return;
Highlighter highlighter = wnd.getHighlighter();
Set<Network> nets = highlighter.getHighlightedNetworks();
Netlist netlist = cell.acquireUserNetlist();
if (netlist == null)
{
System.out.println("Sorry, a deadlock aborted query (network information unavailable). Please try again");
return;
}
for(Network net : nets)
{
System.out.println("Network " + net.describe(true) + ":");
int total = 0;
for(Iterator<Nodable> nIt = netlist.getNodables(); nIt.hasNext(); )
{
Nodable no = nIt.next();
NodeProto np = no.getProto();
HashMap<Network,HashSet<Object>> portNets = new HashMap<Network,HashSet<Object>>();
for(Iterator<PortProto> pIt = np.getPorts(); pIt.hasNext(); )
{
PortProto pp = pIt.next();
if (pp instanceof PrimitivePort && ((PrimitivePort)pp).isIsolated())
{
NodeInst ni = (NodeInst)no;
for(Iterator<Connection> cIt = ni.getConnections(); cIt.hasNext(); )
{
Connection con = cIt.next();
ArcInst ai = con.getArc();
Network oNet = netlist.getNetwork(ai, 0);
HashSet<Object> ports = portNets.get(oNet);
if (ports == null) {
ports = new HashSet<Object>();
portNets.put(oNet, ports);
}
ports.add(pp);
}
} else
{
int width = 1;
if (pp instanceof Export)
{
Export e = (Export)pp;
width = netlist.getBusWidth(e);
}
for(int i=0; i<width; i++)
{
Network oNet = netlist.getNetwork(no, pp, i);
HashSet<Object> ports = portNets.get(oNet);
if (ports == null) {
ports = new HashSet<Object>();
portNets.put(oNet, ports);
}
ports.add(pp);
}
}
}
// if there is only 1 net connected, the node is unimportant
if (portNets.size() <= 1) continue;
HashSet<Object> ports = portNets.get(net);
if (ports == null) continue;
if (total == 0) System.out.println(" Connects to:");
String name = null;
if (no instanceof NodeInst) name = ((NodeInst)no).describe(false); else
{
name = no.getName();
}
for (Object obj : ports) {
PortProto pp = (PortProto)obj;
System.out.println(" Node " + name + ", port " + pp.getName());
total++;
}
}
if (total == 0) System.out.println(" Not connected");
}
}
/**
* Method to handle the "List Exports On Network" command.
*/
public static void listExportsOnNetworkCommand()
{
Cell cell = WindowFrame.needCurCell();
if (cell == null) return;
EditWindow wnd = EditWindow.needCurrent();
if (wnd == null) return;
Highlighter highlighter = wnd.getHighlighter();
Set<Network> nets = highlighter.getHighlightedNetworks();
Netlist netlist = cell.acquireUserNetlist();
if (netlist == null)
{
System.out.println("Sorry, a deadlock aborted query (network information unavailable). Please try again");
return;
}
for(Network net : nets)
{
System.out.println("Network " + net.describe(true) + ":");
// find all exports on network "net"
HashSet<Export> listedExports = new HashSet<Export>();
System.out.println(" Going up the hierarchy from " + cell + ":");
if (findPortsUp(netlist, net, cell, listedExports)) break;
System.out.println(" Going down the hierarchy from " + cell + ":");
if (findPortsDown(netlist, net, listedExports)) break;
}
}
/**
* Method to handle the "List Exports Below Network" command.
*/
public static void listExportsBelowNetworkCommand()
{
Cell cell = WindowFrame.needCurCell();
if (cell == null) return;
EditWindow wnd = EditWindow.needCurrent();
if (wnd == null) return;
Highlighter highlighter = wnd.getHighlighter();
Set<Network> nets = highlighter.getHighlightedNetworks();
Netlist netlist = cell.acquireUserNetlist();
if (netlist == null)
{
System.out.println("Sorry, a deadlock aborted query (network information unavailable). Please try again");
return;
}
for(Network net : nets)
{
System.out.println("Network " + net.describe(true) + ":");
// find all exports on network "net"
if (findPortsDown(netlist, net, new HashSet<Export>())) break;
}
}
/**
* helper method for "telltool network list-hierarchical-ports" to print all
* ports connected to net "net" in cell "cell", and recurse up the hierarchy.
* @return true if an error occurred.
*/
private static boolean findPortsUp(Netlist netlist, Network net, Cell cell, HashSet<Export> listedExports)
{
// look at every node in the cell
for(Iterator<PortProto> it = cell.getPorts(); it.hasNext(); )
{
Export pp = (Export)it.next();
int width = netlist.getBusWidth(pp);
for(int i=0; i<width; i++)
{
Network ppNet = netlist.getNetwork(pp, i);
if (ppNet != net) continue;
if (listedExports.contains(pp)) continue;
listedExports.add(pp);
System.out.println(" Export " + pp.getName() + " in " + cell);
// code to find the proper instance
Cell instanceCell = cell.iconView();
if (instanceCell == null) instanceCell = cell;
// ascend to higher cell and continue
for(Iterator<CellUsage> uIt = instanceCell.getUsagesOf(); uIt.hasNext(); )
{
CellUsage u = uIt.next();
Cell superCell = u.getParent();
Netlist superNetlist = cell.acquireUserNetlist();
if (superNetlist == null)
{
System.out.println("Sorry, a deadlock aborted query (network information unavailable). Please try again");
return true;
}
for(Iterator<Nodable> nIt = superNetlist.getNodables(); nIt.hasNext(); )
{
Nodable no = nIt.next();
if (no.getProto() != cell) continue;
Network superNet = superNetlist.getNetwork(no, pp, i);
if (findPortsUp(superNetlist, superNet, superCell, listedExports)) return true;
}
}
}
}
return false;
}
/**
* helper method for "telltool network list-hierarchical-ports" to print all
* ports connected to net "net" in cell "cell", and recurse down the hierarchy
* @return true on error.
*/
private static boolean findPortsDown(Netlist netlist, Network net, HashSet<Export> listedExports)
{
// look at every node in the cell
for(Iterator<Nodable> it = netlist.getNodables(); it.hasNext(); )
{
Nodable no = it.next();
// only want complex nodes
if (!no.isCellInstance()) continue;
Cell subCell = (Cell)no.getProto();
// look at all wires connected to the node
for(Iterator<PortProto> pIt = subCell.getPorts(); pIt.hasNext(); )
{
Export pp = (Export)pIt.next();
int width = netlist.getBusWidth(pp);
for(int i=0; i<width; i++)
{
Network oNet = netlist.getNetwork(no, pp, i);
if (oNet != net) continue;
// found the net here: report it
if (listedExports.contains(pp)) continue;
listedExports.add(pp);
System.out.println(" Export " + pp.getName() + " in " + subCell);
Netlist subNetlist = subCell.acquireUserNetlist();
if (subNetlist == null)
{
System.out.println("Sorry, a deadlock aborted query (network information unavailable). Please try again");
return true;
}
Network subNet = subNetlist.getNetwork(pp, i);
if (findPortsDown(subNetlist, subNet, listedExports)) return true;
}
}
}
return false;
}
/**
* Method to handle the "List Geometry On Network" command.
*/
public static void listGeometryOnNetworkCommand(GeometryHandler.GHMode mode)
{
Cell cell = WindowFrame.needCurCell();
if (cell == null) return;
EditWindow wnd = EditWindow.needCurrent();
if (wnd == null) return;
HashSet<Network> nets = (HashSet<Network>)wnd.getHighlighter().getHighlightedNetworks();
if (nets.isEmpty())
{
System.out.println("No network in " + cell + " selected");
return;
}
LayerCoverageTool.listGeometryOnNetworks(cell, nets, true, mode);
}
private static final double SQSIZE = 0.4;
/**
* Method to highlight every network in the current cell
* using a different color
*/
private static void showAllNetworksCommand()
{
EditWindow wnd = EditWindow.needCurrent();
if (wnd == null) return;
Cell cell = wnd.getCell();
if (cell == null) return;
wnd.clearHighlighting();
Netlist nl = cell.acquireUserNetlist();
int colors = nl.getNumNetworks();
Color [] netColors = makeUniqueColors(colors);
int index = 0;
Highlighter h = wnd.getHighlighter();
for(Iterator<Network> it = nl.getNetworks(); it.hasNext(); )
{
Network net = it.next();
Iterator<ArcInst> aIt = net.getArcs();
if (!aIt.hasNext()) continue;
Color col = netColors[index++];
for( ; aIt.hasNext(); )
{
ArcInst ai = aIt.next();
Point2D [] points = new Point2D[2];
points[0] = ai.getHeadLocation();
points[1] = ai.getTailLocation();
Poly poly = new Poly(points);
poly.setStyle(Poly.Type.OPENED);
h.addPoly(poly, cell, col);
if (ai.getHeadPortInst().getNodeInst().isCellInstance())
{
points = new Point2D[4];
EPoint ctr = ai.getHeadLocation();
points[0] = new EPoint(ctr.getX()-SQSIZE, ctr.getY()-SQSIZE);
points[1] = new EPoint(ctr.getX()-SQSIZE, ctr.getY()+SQSIZE);
points[2] = new EPoint(ctr.getX()+SQSIZE, ctr.getY()+SQSIZE);
points[3] = new EPoint(ctr.getX()+SQSIZE, ctr.getY()-SQSIZE);
poly = new Poly(points);
poly.setStyle(Poly.Type.CLOSED);
h.addPoly(poly, cell, col);
}
if (ai.getTailPortInst().getNodeInst().isCellInstance())
{
points = new Point2D[4];
EPoint ctr = ai.getTailLocation();
points[0] = new EPoint(ctr.getX()-SQSIZE, ctr.getY()-SQSIZE);
points[1] = new EPoint(ctr.getX()-SQSIZE, ctr.getY()+SQSIZE);
points[2] = new EPoint(ctr.getX()+SQSIZE, ctr.getY()+SQSIZE);
points[3] = new EPoint(ctr.getX()+SQSIZE, ctr.getY()-SQSIZE);
poly = new Poly(points);
poly.setStyle(Poly.Type.CLOSED);
h.addPoly(poly, cell, col);
}
}
}
wnd.finishedHighlighting();
}
/**
* Method to generate unique colors.
* Uses this pattern
* R: 100 110 111 202 202 112 11 23 23 11 24 24
* G: 010 101 202 111 022 121 23 11 32 24 11 42
* B: 001 011 022 022 111 211 32 32 11 42 42 11
* Where:
* 0=off
* 1=the main color
* 2=halfway between 1 and 0
* 3=halfway between 1 and 2
* 4=halfway between 2 and 0
* @param numColors the number of colors to generate
* @return an array of colors.
*/
private static Color [] makeUniqueColors(int numColors)
{
int numRuns = (numColors+29) / 30;
Color [] colors = new Color[numColors];
int index = 0;
for(int i=0; i<numRuns; i++)
{
int c1 = 255 - 255/numRuns*i;
int c2 = c1 / 2;
int c3 = c2 / 2;
int c4 = (c1 + c2) / 2;
// combinations of color 1
if (index < numColors) colors[index++] = new Color(c1, 0, 0);
if (index < numColors) colors[index++] = new Color( 0, c1, 0);
if (index < numColors) colors[index++] = new Color( 0, 0, c1);
if (index < numColors) colors[index++] = new Color(c1, c1, 0);
if (index < numColors) colors[index++] = new Color( 0, c1, c1);
if (index < numColors) colors[index++] = new Color(c1, 0, c1);
// combinations of the colors 1 and 2
if (index < numColors) colors[index++] = new Color(c1, c2, 0);
if (index < numColors) colors[index++] = new Color(c1, 0, c2);
if (index < numColors) colors[index++] = new Color(c1, c2, c2);
if (index < numColors) colors[index++] = new Color(c2, c1, 0);
if (index < numColors) colors[index++] = new Color( 0, c1, c2);
if (index < numColors) colors[index++] = new Color(c2, c1, c2);
if (index < numColors) colors[index++] = new Color(c2, 0, c1);
if (index < numColors) colors[index++] = new Color( 0, c2, c1);
if (index < numColors) colors[index++] = new Color(c2, c2, c1);
// combinations of colors 1, 2, and 3
if (index < numColors) colors[index++] = new Color(c1, c2, c3);
if (index < numColors) colors[index++] = new Color(c1, c3, c2);
if (index < numColors) colors[index++] = new Color(c2, c1, c3);
if (index < numColors) colors[index++] = new Color(c3, c1, c2);
if (index < numColors) colors[index++] = new Color(c2, c3, c1);
if (index < numColors) colors[index++] = new Color(c3, c2, c1);
// combinations of colors 1, 2, and 4
if (index < numColors) colors[index++] = new Color(c1, c2, c4);
if (index < numColors) colors[index++] = new Color(c1, c4, c2);
if (index < numColors) colors[index++] = new Color(c2, c1, c4);
if (index < numColors) colors[index++] = new Color(c4, c1, c2);
if (index < numColors) colors[index++] = new Color(c2, c4, c1);
if (index < numColors) colors[index++] = new Color(c4, c2, c1);
}
return colors;
}
public static void listGeomsAllNetworksCommand() {
EditWindow wnd = EditWindow.needCurrent();
if (wnd == null) return;
Cell cell = wnd.getCell();
if (cell == null) return;
new ListGeomsAllNetworksJob(cell);
}
private static class ListGeomsAllNetworksJob extends Job {
private Cell cell;
public ListGeomsAllNetworksJob(Cell cell) {
super("ListGeomsAllNetworks", User.getUserTool(), Job.Type.EXAMINE, null, null, Job.Priority.USER);
this.cell = cell;
startJob();
}
public boolean doIt() throws JobException {
Netlist netlist = cell.getNetlist();
// Netlist netlist = cell.getNetlist(true);
List<Network> networks = new ArrayList<Network>();
for (Iterator<Network> it = netlist.getNetworks(); it.hasNext(); ) {
networks.add(it.next());
}
// sort list of networks by name
Collections.sort(networks, new TextUtils.NetworksByName());
for (Network net : networks) {
HashSet<Network> nets = new HashSet<Network>();
nets.add(net);
LayerCoverageTool.GeometryOnNetwork geoms = LayerCoverageTool.listGeometryOnNetworks(cell, nets,
false, GeometryHandler.GHMode.ALGO_SWEEP);
if (geoms.getTotalWireLength() == 0) continue;
System.out.println("Network "+net+" has wire length "+geoms.getTotalWireLength());
}
return true;
}
}
public static void showPowerAndGround()
{
Cell cell = WindowFrame.needCurCell();
if (cell == null) return;
EditWindow wnd = EditWindow.needCurrent();
if (wnd == null) return;
Highlighter highlighter = wnd.getHighlighter();
// Netlist netlist = cell.getUserNetlist();
Netlist netlist = cell.acquireUserNetlist();
if (netlist == null)
{
System.out.println("Sorry, a deadlock aborted query (network information unavailable). Please try again");
return;
}
HashSet<Network> pAndG = new HashSet<Network>();
for(Iterator<PortProto> it = cell.getPorts(); it.hasNext(); )
{
Export pp = (Export)it.next();
if (pp.isPower() || pp.isGround())
{
int width = netlist.getBusWidth(pp);
for(int i=0; i<width; i++)
{
Network net = netlist.getNetwork(pp, i);
pAndG.add(net);
}
}
}
for(Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = it.next();
PrimitiveNode.Function fun = ni.getFunction();
if (fun != PrimitiveNode.Function.CONPOWER && fun != PrimitiveNode.Function.CONGROUND)
continue;
for(Iterator<Connection> cIt = ni.getConnections(); cIt.hasNext(); )
{
Connection con = cIt.next();
ArcInst ai = con.getArc();
int width = netlist.getBusWidth(ai);
for(int i=0; i<width; i++)
{
Network net = netlist.getNetwork(ai, i);
pAndG.add(net);
}
}
}
highlighter.clear();
for(Network net : pAndG)
{
highlighter.addNetwork(net, cell);
}
highlighter.finished();
if (pAndG.size() == 0)
System.out.println("This cell has no Power or Ground networks");
}
private static class RepairPowerAndGround extends Job
{
protected RepairPowerAndGround()
{
super("Repair Power and Ground", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER);
startJob();
}
public boolean doIt() throws JobException
{
validatePowerAndGround(true);
return true;
}
}
public static void validatePowerAndGround(boolean repair)
{
if (repair) System.out.println("Repairing power and ground exports"); else
System.out.println("Validating power and ground exports");
int total = 0;
for(Iterator<Library> lIt = Library.getLibraries(); lIt.hasNext(); )
{
Library lib = lIt.next();
for(Iterator<Cell> cIt = lib.getCells(); cIt.hasNext(); )
{
Cell cell = cIt.next();
for(Iterator<PortProto> pIt = cell.getPorts(); pIt.hasNext(); )
{
Export pp = (Export)pIt.next();
if (pp.isNamedGround() && pp.getCharacteristic() != PortCharacteristic.GND)
{
System.out.println("Cell " + cell.describe(true) + ", export " + pp.getName() +
": does not have 'GROUND' characteristic");
if (repair) pp.setCharacteristic(PortCharacteristic.GND);
total++;
}
if (pp.isNamedPower() && pp.getCharacteristic() != PortCharacteristic.PWR)
{
System.out.println("Cell " + cell.describe(true) + ", export " + pp.getName() +
": does not have 'POWER' characteristic");
if (repair) pp.setCharacteristic(PortCharacteristic.PWR);
total++;
}
}
}
}
if (total == 0) System.out.println("No problems found"); else
{
if (repair) System.out.println("Fixed " + total + " export problems"); else
System.out.println("Found " + total + " export problems");
}
}
/**
* Method to add a "M" multiplier factor to the currently selected node.
*/
public static void addMultiplierCommand()
{
EditWindow wnd = EditWindow.needCurrent();
if (wnd == null) return;
Highlighter highlighter = wnd.getHighlighter();
NodeInst ni = (NodeInst)highlighter.getOneElectricObject(NodeInst.class);
if (ni == null) return;
new AddMultiplier(ni);
}
private static class AddMultiplier extends Job
{
private NodeInst ni;
protected AddMultiplier(NodeInst ni)
{
super("Add Spice Multiplier", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER);
this.ni = ni;
startJob();
}
public boolean doIt() throws JobException
{
TextDescriptor td = TextDescriptor.getNodeTextDescriptor().withDispPart(TextDescriptor.DispPos.NAMEVALUE).withOff(-1.5, -1);
ni.newVar(Simulation.M_FACTOR_KEY, new Double(1.0), td);
return true;
}
}
/**
* Method to create a new template in the current cell.
* Templates can be for SPICE or Verilog, depending on the Variable name.
* @param templateKey the name of the variable to create.
*/
public static void makeTemplate(Variable.Key templateKey)
{
new MakeTemplate(templateKey);
}
/**
* Method to create a new template on the target cell.
* Templates can be for SPICE or Verilog, depending on the Variable name.
* @param templateKey the name of the variable to create.
*/
public static void makeTemplate(Variable.Key templateKey, Cell tgtCell)
{
new MakeTemplate(templateKey, tgtCell);
}
/**
* Method to create a new template on the target cell, with a predefined String or String [].
* Templates can be for SPICE or Verilog, depending on the Variable name.
* @param templateKey the name of the variable to create.
*/
public static void makeTemplate(Variable.Key templateKey, Cell tgtCell, Object value)
{
new MakeTemplate(templateKey, tgtCell, value);
}
private static class MakeTemplate extends Job
{
private Variable.Key templateKey;
private Cell tgtCell;
private Object value;
protected MakeTemplate(Variable.Key templateKey)
{
super("Make template", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER);
this.templateKey = templateKey;
startJob();
}
protected MakeTemplate(Variable.Key templateKey, Cell tgtCell)
{
super("Make template", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER);
this.templateKey = templateKey;
this.tgtCell = tgtCell;
startJob();
}
protected MakeTemplate(Variable.Key templateKey, Cell tgtCell, Object value)
{
super("Make template", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER);
this.templateKey = templateKey;
this.tgtCell = tgtCell;
this.value = value;
startJob();
}
public boolean doIt() throws JobException
{
Cell cell;
if (tgtCell != null) cell = tgtCell; else
cell = WindowFrame.needCurCell();
if (cell == null) return false;
Variable templateVar = cell.getVar(templateKey);
if (templateVar != null)
{
System.out.println("This cell already has a template");
return false;
}
Point2D offset = cell.newVarOffset();
TextDescriptor td = TextDescriptor.getCellTextDescriptor().withInterior(true).
withDispPart(TextDescriptor.DispPos.NAMEVALUE).withOff(offset.getX(), offset.getY());
if (value == null) {
cell.newVar(templateKey, "*Undefined", td);
} else
{
cell.newVar(templateKey, value, td);
}
return true;
}
}
public static void getUnroutedArcCommand()
{
User.getUserTool().setCurrentArcProto(Generic.tech().unrouted_arc);
}
public static void padFrameGeneratorCommand()
{
String fileName = OpenFile.chooseInputFile(FileType.PADARR, null);
if (fileName != null)
{
PadGenerator.makePadFrame(Library.getCurrent(), fileName);
}
}
public static void listToolsCommand()
{
System.out.println("Tools in Electric:");
for(Iterator<Tool> it = Tool.getTools(); it.hasNext(); )
{
Tool tool = it.next();
StringBuffer infstr = new StringBuffer();
if (tool.isOn()) infstr.append("On"); else
infstr.append("Off");
if (tool.isBackground()) infstr.append(", Background");
if (tool.isFixErrors()) infstr.append(", Correcting");
if (tool.isIncremental()) infstr.append(", Incremental");
if (tool.isAnalysis()) infstr.append(", Analysis");
if (tool.isSynthesis()) infstr.append(", Synthesis");
System.out.println(tool.getName() + ": " + infstr.toString());
}
}
public static void javaBshScriptCommand()
{
String fileName = OpenFile.chooseInputFile(FileType.JAVA, null);
if (fileName != null)
{
// start a job to run the script
EvalJavaBsh.runScript(fileName);
}
}
private static final int CONVERT_TO_VHDL = 1;
private static final int COMPILE_VHDL_FOR_SC = 2;
private static final int PLACE_AND_ROUTE = 4;
private static final int SHOW_CELL = 8;
/**
* Method to handle the menu command to convert a cell to layout.
* Reads the cell library if necessary;
* Converts a schematic to VHDL if necessary;
* Compiles a VHDL cell to a netlist if necessary;
* Reads the netlist from the cell;
* does placement and routing;
* Generates Electric layout;
* Displays the resulting layout.
* @param cell the cell to compile.
* @param doItNow if the job must executed now
*/
public static void doSiliconCompilation(Cell cell, boolean doItNow)
{
if (cell == null) return;
int activities = PLACE_AND_ROUTE | SHOW_CELL;
// see if the current cell needs to be compiled
if (cell.getView() != View.NETLISTQUISC)
{
if (cell.isSchematic())
{
// current cell is Schematic. See if there is a more recent netlist or VHDL
Cell vhdlCell = cell.otherView(View.VHDL);
if (vhdlCell != null && vhdlCell.getRevisionDate().after(cell.getRevisionDate())) cell = vhdlCell; else
activities |= CONVERT_TO_VHDL | COMPILE_VHDL_FOR_SC;
}
if (cell.getView() == View.VHDL)
{
// current cell is VHDL. See if there is a more recent netlist
Cell netListCell = cell.otherView(View.NETLISTQUISC);
if (netListCell != null && netListCell.getRevisionDate().after(cell.getRevisionDate())) cell = netListCell; else
activities |= COMPILE_VHDL_FOR_SC;
}
}
if (Library.findLibrary(SilComp.SCLIBNAME) == null)
{
if (doItNow)
ReadSCLibraryJob.performTaskNoJob();
else
new ReadSCLibraryJob();
}
// do the silicon compilation task
doSilCompActivityNoJob(cell, activities, doItNow);
}
/**
* Method to handle the menu command to compile a VHDL cell.
* Compiles the VHDL in the current cell and displays the netlist.
*/
public static void compileVHDL()
{
Cell cell = WindowFrame.needCurCell();
if (cell == null) return;
if (cell.getView() != View.VHDL)
{
System.out.println("Must be editing a VHDL cell before compiling it");
return;
}
// do the VHDL compilation task
new DoSilCompActivity(cell, COMPILE_VHDL_FOR_SC | SHOW_CELL);
}
/**
* Method to handle the menu command to make a VHDL cell.
* Converts the schematic in the current cell to VHDL and displays it.
*/
public static void makeVHDL()
{
Cell cell = WindowFrame.needCurCell();
if (cell == null) return;
new DoSilCompActivity(cell, CONVERT_TO_VHDL | SHOW_CELL);
}
/**
* Class to read the Silicon Compiler support library in a new job.
*/
private static class ReadSCLibraryJob extends Job
{
private ReadSCLibraryJob()
{
super("Read Silicon Compiler Library", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER);
startJob();
}
public static boolean performTaskNoJob()
{
// read standard cell library
System.out.println("Reading Standard Cell Library '" + SilComp.SCLIBNAME + "'");
URL fileURL = LibFile.getLibFile(SilComp.SCLIBNAME + ".jelib");
LibraryFiles.readLibrary(fileURL, null, FileType.JELIB, true);
return true;
}
public boolean doIt() throws JobException
{
return performTaskNoJob();
}
}
public static boolean doSilCompActivityNoJob(Cell cell, int activities, boolean doItNow)
{
if (doItNow)
{
List<Cell> textCellsToRedraw = new ArrayList<Cell>();
try
{
DoSilCompActivity.performTaskNoJob(cell, textCellsToRedraw, activities);
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
}
else
new DoSilCompActivity(cell, activities);
return true;
}
/**
* Class to do the next silicon-compilation activity in a Job.
*/
private static class DoSilCompActivity extends Job
{
private Cell cell;
private int activities;
private List<Cell> textCellsToRedraw;
private DoSilCompActivity(Cell cell, int activities)
{
super("Silicon-Compiler activity", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER);
this.cell = cell;
this.activities = activities;
startJob();
}
public static Cell performTaskNoJob(Cell cell, List<Cell> textCellsToRedraw, int activities) throws JobException
{
Library destLib = cell.getLibrary();
textCellsToRedraw = new ArrayList<Cell>();
if ((activities&CONVERT_TO_VHDL) != 0)
{
// convert Schematic to VHDL
System.out.print("Generating VHDL from " + cell + " ...");
List<String> vhdlStrings = GenerateVHDL.convertCell(cell);
if (vhdlStrings == null)
throw new JobException("No VHDL produced");
String cellName = cell.getName() + "{vhdl}";
Cell vhdlCell = cell.getLibrary().findNodeProto(cellName);
if (vhdlCell == null)
{
vhdlCell = Cell.makeInstance(cell.getLibrary(), cellName);
if (vhdlCell == null) return null;
}
String [] array = new String[vhdlStrings.size()];
for(int i=0; i<vhdlStrings.size(); i++) array[i] = vhdlStrings.get(i);
vhdlCell.setTextViewContents(array);
textCellsToRedraw.add(vhdlCell);
System.out.println(" Done, created " + vhdlCell);
cell = vhdlCell;
}
if ((activities&COMPILE_VHDL_FOR_SC) != 0)
{
// compile the VHDL to a netlist
System.out.print("Compiling VHDL in " + cell + " ...");
CompileVHDL c = new CompileVHDL(cell);
if (c.hasErrors())
throw new JobException("ERRORS during compilation, no netlist produced");
List<String> netlistStrings = c.getQUISCNetlist(destLib);
if (netlistStrings == null)
throw new JobException("No netlist produced");
// store the QUISC netlist
String cellName = cell.getName() + "{net.quisc}";
Cell netlistCell = cell.getLibrary().findNodeProto(cellName);
if (netlistCell == null)
{
netlistCell = Cell.makeInstance(cell.getLibrary(), cellName);
if (netlistCell == null) return null;
}
String [] array = new String[netlistStrings.size()];
for(int i=0; i<netlistStrings.size(); i++) array[i] = netlistStrings.get(i);
netlistCell.setTextViewContents(array);
textCellsToRedraw.add(netlistCell);
System.out.println(" Done, created " + netlistCell);
cell = netlistCell;
}
if ((activities&PLACE_AND_ROUTE) != 0)
{
// first grab the information in the netlist
System.out.println("Reading netlist in " + cell);
GetNetlist gnl = new GetNetlist();
if (gnl.readNetCurCell(cell))
throw new JobException("Error compiling netlist");
// do the placement
System.out.println("Placing cells");
Place place = new Place();
String err = place.placeCells(gnl);
if (err != null)
throw new JobException(err);
// do the routing
System.out.println("Routing cells");
Route route = new Route();
err = route.routeCells(gnl);
if (err != null)
throw new JobException(err);
// generate the results
System.out.println("Generating layout");
Maker maker = new Maker();
Object result = maker.makeLayout(destLib, gnl);
if (result instanceof String)
{
System.out.println((String)result);
if (Technology.getCurrent() == Schematics.tech())
throw new JobException("Should switch to a layout technology first (currently in Schematics)");
}
if (!(result instanceof Cell)) return null;
cell = (Cell)result;
System.out.println("Created " + cell);
}
return cell;
}
public boolean doIt() throws JobException
{
fieldVariableChanged("cell");
textCellsToRedraw = new ArrayList<Cell>();
fieldVariableChanged("textCellsToRedraw");
cell = performTaskNoJob(cell, textCellsToRedraw, activities);
return true;
}
public void terminateOK()
{
for(Cell cell : textCellsToRedraw) {
TextWindow.updateText(cell);
}
if ((activities&SHOW_CELL) != 0) {
// show the cell
WindowFrame.createEditWindow(cell);
}
}
}
/****************** Parasitic Tool ********************/
public static void parasiticCommand()
{
EditWindow wnd = EditWindow.needCurrent();
if (wnd == null) return;
Cell cell = wnd.getCell();
Highlighter highlighter = wnd.getHighlighter();
Set<Network> nets = highlighter.getHighlightedNetworks();
for (Network net : nets)
{
ParasiticTool.getParasiticTool().netwokParasitic(net, cell);
}
}
public static void importAssuraDrcErrors() {
String fileName = OpenFile.chooseInputFile(FileType.ERR, null);
if (fileName == null) return;
EditWindow wnd = EditWindow.needCurrent();
if (wnd == null) return;
Cell cell = wnd.getCell();
if (cell == null) return;
HashMap<Cell,String> mangledNames = new HashMap<Cell,String>();
com.sun.electric.tool.io.output.GDS.buildUniqueNames(cell, mangledNames);
AssuraDrcErrors.importErrors(fileName, mangledNames, "DRC");
}
public static void importCalibreDrcErrors() {
String fileName = OpenFile.chooseInputFile(FileType.DB, null);
if (fileName == null) return;
EditWindow wnd = EditWindow.needCurrent();
if (wnd == null) return;
Cell cell = wnd.getCell();
HashMap<Cell,String> mangledNames = new HashMap<Cell,String>();
com.sun.electric.tool.io.output.GDS.buildUniqueNames(cell, mangledNames);
CalibreDrcErrors.importErrors(fileName, mangledNames, "DRC");
}
public static void exportDRCDeck() {
String fileName = OpenFile.chooseOutputFile(FileType.XML,
"Save XML DRC deck for foundry '" + Technology.getCurrent().getSelectedFoundry() + "'", null);
if (fileName == null) return;
DRCTemplate.exportDRCDecks(fileName, Technology.getCurrent());
}
public static void importDRCDeck() {
String fileName = OpenFile.chooseInputFile(FileType.XML, "Open XML DRC deck", false);
if (fileName == null) return;
Technology tech = Technology.getCurrent();
DRCTemplate.DRCXMLParser parser = DRCTemplate.importDRCDeck(TextUtils.makeURLToFile(fileName), true);
String message = "Deck file '" + fileName + "' loaded ";
message += (parser.isParseOK()) ? "without errors." : " with errors. No rules loaded.";
JOptionPane.showMessageDialog(TopLevel.getCurrentJFrame(), message,
"Import DRC Deck", (parser.isParseOK()) ? JOptionPane.WARNING_MESSAGE : JOptionPane.ERROR_MESSAGE);
if (!parser.isParseOK()) return; // errors in the file
new ImportDRCDeckJob(parser.getRules(), tech);
// for (DRCTemplate.DRCXMLBucket bucket : parser.getRules())
// {
// boolean done = false;
//
// // set the new rules under the foundry imported
// for (Iterator<Foundry> itF = tech.getFoundries(); itF.hasNext();)
// {
// Foundry f = itF.next();
// if (f.getType().name().equalsIgnoreCase(bucket.foundry))
// {
// f.setRules(bucket.drcRules);
// System.out.println("New DRC rules for foundry '" + f.getType().name() + "' were loaded in '" +
// tech.getTechName() + "'");
// // Need to clean cells using this foundry because the rules might have changed.
// DRC.cleanCellsDueToFoundryChanges(tech, f);
// // Only when the rules belong to the selected foundry, then reload the rules
// if (f == tech.getSelectedFoundry())
// tech.setState(true);
// done = true;
// break;
// }
// }
// if (!done)
// {
// JOptionPane.showMessageDialog(TopLevel.getCurrentJFrame(),
// "'" + bucket.foundry + "' is not a valid foundry in '" + tech.getTechName() + "'",
// "Importing DRC Deck", JOptionPane.ERROR_MESSAGE);
// }
// }
}
private static class ImportDRCDeckJob extends Job {
private List<DRCTemplate.DRCXMLBucket> rules;
private Technology tech;
public ImportDRCDeckJob(List<DRCTemplate.DRCXMLBucket> rules, Technology tech) {
super("ImportDRCDeck", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER);
this.rules = rules;
this.tech = tech;
startJob();
}
public boolean doIt() {
for (DRCTemplate.DRCXMLBucket bucket : rules) {
boolean done = false;
// set the new rules under the foundry imported
for (Iterator<Foundry> itF = tech.getFoundries(); itF.hasNext();) {
Foundry f = itF.next();
if (f.getType().getName().equalsIgnoreCase(bucket.foundry)) {
f.setRules(bucket.drcRules);
System.out.println("New DRC rules for foundry '" + f.getType().getName() + "' were loaded in '" +
tech.getTechName() + "'");
// Need to clean cells using this foundry because the rules might have changed.
DRC.cleanCellsDueToFoundryChanges(tech, f);
// Only when the rules belong to the selected foundry, then reload the rules
if (f == tech.getSelectedFoundry())
tech.setState();
done = true;
break;
}
}
if (!done) {
Job.getUserInterface().showErrorMessage(
"'" + bucket.foundry + "' is not a valid foundry in '" + tech.getTechName() + "'",
"Importing DRC Deck");
}
}
return true;
}
}
public static void runNccSchematicCrossProbing() {
EditWindow wnd = EditWindow.needCurrent();
if (wnd == null) return;
Cell cell = wnd.getCell();
if (cell == null) return;
NccCrossProbing.runNccSchematicCrossProbing(cell, wnd.getVarContext());
}
// private static void newAutoFill(boolean hierarchy, boolean binary)
// {
// Cell cell = WindowFrame.getCurrentCell();
// if (cell == null) return;
//
// FillGeneratorTool.generateAutoFill(cell, hierarchy, binary, false);
// }
}
| false | true | static EMenu makeMenu() {
/****************************** THE TOOL MENU ******************************/
// mnemonic keys available: B F H JK PQ XYZ
return new EMenu("_Tool",
//------------------- DRC
// mnemonic keys available: B EFG IJK MNOPQR UVWXYZ
new EMenu("_DRC",
new EMenuItem("Check _Hierarchically", KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0))
{ public void run() {
if (DRC.isMultiThreaded())
{
new MTDRCLayoutTool(Job.getUserInterface().needCurrentCell(), true, null).startJob();
}
else
{
DRC.checkDRCHierarchically(Job.getUserInterface().needCurrentCell(), null, GeometryHandler.GHMode.ALGO_SWEEP, false);
}
}},
new EMenuItem("Check _Selection Area Hierarchically") { public void run() {
EditWindow_ wnd = Job.getUserInterface().getCurrentEditWindow_();
if (wnd == null) return;
DRC.checkDRCHierarchically(wnd.getCell(), wnd.getHighlightedArea(), GeometryHandler.GHMode.ALGO_SWEEP, false); }},
new EMenuItem("Check Area _Coverage") { public void run() {
LayerCoverageTool.layerCoverageCommand(WindowFrame.needCurCell(), GeometryHandler.GHMode.ALGO_SWEEP, true); }},
new EMenuItem("_List Layer Coverage on Cell") { public void run() {
layerCoverageCommand(LayerCoverageTool.LCMode.AREA, GeometryHandler.GHMode.ALGO_SWEEP); }},
SEPARATOR,
new EMenuItem("Import _Assura DRC Errors for Current Cell...") { public void run() {
importAssuraDrcErrors(); }},
new EMenuItem("Import Calibre _DRC Errors for Current Cell...") { public void run() {
importCalibreDrcErrors(); }},
SEPARATOR,
new EMenuItem("Export DRC Deck...") { public void run() {
exportDRCDeck(); }},
new EMenuItem("Import DRC Deck...") { public void run() {
importDRCDeck(); }}),
//------------------- Simulation (Built-in)
// mnemonic keys available: B JK N PQ XYZ
new EMenu("Simulation (Built-in)",
Simulation.hasIRSIM() ? new EMenuItem("IRSI_M: Simulate Current Cell") { public void run() {
Simulation.startSimulation(Simulation.IRSIM_ENGINE, false, null, null); }} : null,
Simulation.hasIRSIM() ? new EMenuItem("IRSIM: _Write Deck...") { public void run() {
FileMenu.exportCommand(FileType.IRSIM, true); }} : null,
Simulation.hasIRSIM() ? new EMenuItem("_IRSIM: Simulate Deck...") { public void run() {
Simulation.startSimulation(Simulation.IRSIM_ENGINE, true, null, null); }} : null,
Simulation.hasIRSIM() ? SEPARATOR : null,
new EMenuItem("_ALS: Simulate Current Cell") { public void run() {
Simulation.startSimulation(Simulation.ALS_ENGINE, false, null, null); }},
Simulation.hasFLEET() ? SEPARATOR : null,
Simulation.hasFLEET() ? Simulation.FLEETMenu() : null,
SEPARATOR,
new EMenuItem("Set Signal _High at Main Time", KeyStroke.getKeyStroke('V', 0)) { public void run() {
Simulation.setSignalHigh(); }},
new EMenuItem("Set Signal _Low at Main Time", KeyStroke.getKeyStroke('G', 0)) { public void run() {
Simulation.setSignalLow(); }},
new EMenuItem("Set Signal Un_defined at Main Time", KeyStroke.getKeyStroke('X', 0)) { public void run() {
Simulation.setSignalX(); }},
new EMenuItem("Set Clock on Selected Signal...") { public void run() {
Simulation.setClock(); }},
SEPARATOR,
new EMenuItem("_Update Simulation Window") { public void run() {
Simulation.update(); }},
new EMenuItem("_Get Information about Selected Signals") { public void run() {
Simulation.showSignalInfo(); }},
SEPARATOR,
new EMenuItem("_Clear Selected Stimuli") { public void run() {
Simulation.removeSelectedStimuli(); }},
new EMenuItem("Clear All Stimuli _on Selected Signals") { public void run() {
Simulation.removeStimuliFromSignal(); }},
new EMenuItem("Clear All S_timuli") { public void run() {
Simulation.removeAllStimuli(); }},
SEPARATOR,
new EMenuItem("_Save Stimuli to Disk...") { public void run() {
Simulation.saveStimuli(); }},
new EMenuItem("_Restore Stimuli from Disk...") { public void run() {
Simulation.restoreStimuli(); }}),
//------------------- Simulation (SPICE)
// mnemonic keys available: AB IJK NO QR VWXYZ
new EMenu("Simulation (_Spice)",
new EMenuItem("Write Spice _Deck...") { public void run() {
FileMenu.exportCommand(FileType.SPICE, true); }},
new EMenuItem("Write _CDL Deck...") { public void run() {
FileMenu.exportCommand(FileType.CDL, true); }},
new EMenuItem("Plot Spice _Listing...") { public void run() {
Simulate.plotSpiceResults(); }},
new EMenuItem("Plot Spice _for This Cell") { public void run() {
Simulate.plotSpiceResultsThisCell(); }},
new EMenuItem("Set Spice _Model...") { public void run() {
Simulation.setSpiceModel(); }},
new EMenuItem("Add M_ultiplier") { public void run() {
addMultiplierCommand(); }},
new EMenuItem("Add Flat Cod_e") { public void run() {
makeTemplate(Spice.SPICE_CODE_FLAT_KEY); }},
SEPARATOR,
new EMenuItem("Set Generic Spice _Template") { public void run() {
makeTemplate(Spice.SPICE_TEMPLATE_KEY); }},
new EMenuItem("Set Spice _2 Template") { public void run() {
makeTemplate(Spice.SPICE_2_TEMPLATE_KEY); }},
new EMenuItem("Set Spice _3 Template") { public void run() {
makeTemplate(Spice.SPICE_3_TEMPLATE_KEY); }},
new EMenuItem("Set _HSpice Template") { public void run() {
makeTemplate(Spice.SPICE_H_TEMPLATE_KEY); }},
new EMenuItem("Set _PSpice Template") { public void run() {
makeTemplate(Spice.SPICE_P_TEMPLATE_KEY); }},
new EMenuItem("Set _GnuCap Template") { public void run() {
makeTemplate(Spice.SPICE_GC_TEMPLATE_KEY); }},
new EMenuItem("Set _SmartSpice Template") { public void run() {
makeTemplate(Spice.SPICE_SM_TEMPLATE_KEY); }},
new EMenuItem("Set Assura CDL Template") { public void run() {
makeTemplate(Spice.SPICE_A_TEMPLATE_KEY); }},
new EMenuItem("Set Calibre Spice Template") { public void run() {
makeTemplate(Spice.SPICE_C_TEMPLATE_KEY); }},
new EMenuItem("Set Netlist Cell From File") { public void run() {
makeTemplate(Spice.SPICE_NETLIST_FILE_KEY); }}),
//------------------- Simulation (Verilog)
// mnemonic keys available: AB EFGHIJKLMNO QRS U WXYZ
new EMenu("Simulation (_Verilog)",
new EMenuItem("Write _Verilog Deck...") { public void run() {
Simulation.setVerilogStopAtStandardCells(false);
FileMenu.exportCommand(FileType.VERILOG, true); }},
new EMenuItem("Plot Verilog VCD _Dump...") { public void run() {
Simulate.plotVerilogResults(); }},
new EMenuItem("Plot Verilog for This _Cell") { public void run() {
Simulate.plotVerilogResultsThisCell(); }},
SEPARATOR,
new EMenuItem("Set Verilog _Template") { public void run() {
makeTemplate(Verilog.VERILOG_TEMPLATE_KEY); }},
new EMenuItem("Set Verilog Default _Parameter") { public void run() {
makeTemplate(Verilog.VERILOG_DEFPARAM_KEY); }},
SEPARATOR,
// mnemonic keys available: ABC EFGHIJKLMNOPQRS UV XYZ
new EMenu("Set Verilog _Wire",
new EMenuItem("_Wire") { public void run() {
Simulation.setVerilogWireCommand(0); }},
new EMenuItem("_Trireg") { public void run() {
Simulation.setVerilogWireCommand(1); }},
new EMenuItem("_Default") { public void run() {
Simulation.setVerilogWireCommand(2); }}),
// mnemonic keys available: ABCDEFGHIJKLM OPQRSTUV XYZ
new EMenu("_Transistor Strength",
new EMenuItem("_Weak") { public void run() {
Simulation.setTransistorStrengthCommand(true); }},
new EMenuItem("_Normal") { public void run() {
Simulation.setTransistorStrengthCommand(false); }})),
//------------------- Simulation (others)
// mnemonic keys available: B D G KL N Q UVWXYZ
new EMenu("Simulation (_Others)",
new EMenuItem("Write _Maxwell Deck...") { public void run() {
FileMenu.exportCommand(FileType.MAXWELL, true); }},
new EMenuItem("Write _Tegas Deck...") { public void run() {
FileMenu.exportCommand(FileType.TEGAS, true); }},
new EMenuItem("Write _SILOS Deck...") { public void run() {
FileMenu.exportCommand(FileType.SILOS, true); }},
new EMenuItem("Write _PAL Deck...") { public void run() {
FileMenu.exportCommand(FileType.PAL, true); }},
SEPARATOR,
!Simulation.hasIRSIM() ? new EMenuItem("Write _IRSIM Deck...") { public void run() {
FileMenu.exportCommand(FileType.IRSIM, true); }} : null,
new EMenuItem("Write _ESIM/RNL Deck...") { public void run() {
FileMenu.exportCommand(FileType.ESIM, true); }},
new EMenuItem("Write _RSIM Deck...") { public void run() {
FileMenu.exportCommand(FileType.RSIM, true); }},
new EMenuItem("Write _COSMOS Deck...") { public void run() {
FileMenu.exportCommand(FileType.COSMOS, true); }},
new EMenuItem("Write M_OSSIM Deck...") { public void run() {
FileMenu.exportCommand(FileType.MOSSIM, true); }},
SEPARATOR,
new EMenuItem("Write _FastHenry Deck...") { public void run() {
FileMenu.exportCommand(FileType.FASTHENRY, true); }},
new EMenuItem("Fast_Henry Arc Properties...") { public void run() {
FastHenryArc.showFastHenryArcDialog(); }},
SEPARATOR,
new EMenuItem("Write _ArchSim Deck...") { public void run() {
FileMenu.exportCommand(FileType.ARCHSIM, true); }},
new EMenuItem("Display ArchSim _Journal...") { public void run() {
Simulate.plotArchSimResults(); }}),
//------------------- ERC
// mnemonic keys available: BCDEFGHIJKLMNOPQRSTUV XYZ
new EMenu("_ERC",
new EMenuItem("Check _Wells") { public void run() {
ERCWellCheck.analyzeCurCell(GeometryHandler.GHMode.ALGO_SWEEP); }},
new EMenuItem("_Antenna Check") { public void run() {
ERCAntenna.doAntennaCheck(); }}),
// ------------------- NCC
// mnemonic keys available: AB DEFGHIJKLMNOPQRS UVWXYZ
new EMenu("_NCC",
new EMenuItem("Schematic and Layout Views of Cell in _Current Window") { public void run() {
new NccJob(1); }},
new EMenuItem("Cells from _Two Windows") { public void run() {
new NccJob(2); }},
SEPARATOR,
new EMenuItem("Copy Schematic _User Names to Layout") { public void run() {
new SchemNamesToLay.RenameJob(); }},
new EMenuItem("Copy All Schematic _Names to Layout") { public void run() {
new AllSchemNamesToLay.RenameJob(); }},
new EMenuItem("Highlight _Equivalent") { public void run() {
HighlightEquivalent.highlight(); }},
new EMenuItem("Run NCC for Schematic Cross-Probing") { public void run() {
runNccSchematicCrossProbing(); }},
new EMenu("Add NCC _Annotation to Cell",
new EMenuItem("Exports Connected by Parent _vdd") { public void run() {
NccCellAnnotations.makeNCCAnnotationMenuCommand("exportsConnectedByParent vdd /vdd_[0-9]+/"); }},
new EMenuItem("Exports Connected By Parent _gnd") { public void run() {
NccCellAnnotations.makeNCCAnnotationMenuCommand("exportsConnectedByParent gnd /gnd_[0-9]+/"); }},
new EMenuItem("_Skip NCC") { public void run() {
NccCellAnnotations.makeNCCAnnotationMenuCommand("skipNCC <comment explaining why>"); }},
new EMenuItem("_Not a Subcircuit") { public void run() {
NccCellAnnotations.makeNCCAnnotationMenuCommand("notSubcircuit <comment explaining why>"); }},
new EMenuItem("_Flatten Instances") { public void run() {
NccCellAnnotations.makeNCCAnnotationMenuCommand("flattenInstances <list of instance names>"); }},
new EMenuItem("_Join Group") { public void run() {
NccCellAnnotations.makeNCCAnnotationMenuCommand("joinGroup <cell name>"); }},
new EMenuItem("_Transistor Type") { public void run() {
NccCellAnnotations.makeNCCAnnotationMenuCommand("transistorType <typeName>"); }},
new EMenuItem("_Resistor Type") { public void run() {
NccCellAnnotations.makeNCCAnnotationMenuCommand("resistorType <typeName>"); }},
new EMenuItem("Force _Part Match") { public void run() {
NccCellAnnotations.makeNCCAnnotationMenuCommand("forcePartMatch <Part name shared by schematic and layout>"); }},
new EMenuItem("Force _Wire Match") { public void run() {
NccCellAnnotations.makeNCCAnnotationMenuCommand("forceWireMatch <Wire name shared by schematic and layout>"); }},
new EMenuItem("_Black Box") { public void run() {
NccCellAnnotations.makeNCCAnnotationMenuCommand("blackBox <comment explaining why>"); }})),
// ------------------- PIE
// If Pie package is installed then add menu entries to call it
Pie.hasPie() ? new EMenu("_PIE",
new EMenuItem("PIE Schematic and Layout Views of Cell in Current Window") { public void run() {
Pie.invokePieNcc(1); }},
new EMenuItem("Cells from _Two Windows") { public void run() {
Pie.invokePieNcc(2); }}) : null,
// ------------------- Architecture Generator
// // If ArchGen package is installed then add menu entries to call it
// ArchGenPlugin.hasArchGen() ? ArchGenPlugin.getEMenu() : null,
//------------------- Network
// mnemonic keys available: D F IJK M O Q S W YZ
new EMenu("Net_work",
new EMenuItem("Show _Network", 'K') { public void run() {
showNetworkCommand(); }},
new EMenuItem("_List Networks") { public void run() {
listNetworksCommand(); }},
new EMenuItem("List _Connections on Network") { public void run() {
listConnectionsOnNetworkCommand(); }},
new EMenuItem("List _Exports on Network") { public void run() {
listExportsOnNetworkCommand(); }},
new EMenuItem("List Exports _below Network") { public void run() {
listExportsBelowNetworkCommand(); }},
new EMenuItem("List _Geometry on Network") { public void run() {
listGeometryOnNetworkCommand(GeometryHandler.GHMode.ALGO_SWEEP); }},
new EMenuItem("Show _All Networks") { public void run() {
showAllNetworksCommand(); }},
new EMenuItem("List _Total Wire Lengths on All Networks") { public void run() {
listGeomsAllNetworksCommand(); }},
SEPARATOR,
new EMenuItem("E_xtract Current Cell") { public void run() {
Connectivity.extractCurCell(false); }},
new EMenuItem("Extract Current _Hierarchy") { public void run() {
Connectivity.extractCurCell(true); }},
SEPARATOR,
new EMenuItem("Show _Power and Ground") { public void run() {
showPowerAndGround(); }},
new EMenuItem("_Validate Power and Ground") { public void run() {
validatePowerAndGround(false); }},
new EMenuItem("_Repair Power and Ground") { public void run() {
new RepairPowerAndGround(); }},
new EMenuItem("Redo Network N_umbering") { public void run() {
NetworkTool.renumberNetlists(); }}),
//------------------- Logical Effort
// mnemonic keys available: D FGH JK M PQRSTUVWXYZ
new EMenu("_Logical Effort",
new EMenuItem("_Optimize for Equal Gate Delays") { public void run() {
optimizeEqualGateDelaysCommand(true); }},
new EMenuItem("Optimize for Equal Gate Delays (no _caching)") { public void run() {
optimizeEqualGateDelaysCommand(false); }},
new EMenuItem("List _Info for Selected Node") { public void run() {
printLEInfoCommand(); }},
new EMenuItem("_Back Annotate Wire Lengths for Current Cell") { public void run() {
backAnnotateCommand(); }},
new EMenuItem("Clear Sizes on Selected _Node(s)") { public void run() {
clearSizesNodableCommand(); }},
new EMenuItem("Clear Sizes in _all Libraries") { public void run() {
clearSizesCommand(); }},
new EMenuItem("_Estimate Delays") { public void run() {
estimateDelaysCommand(); }},
new EMenuItem("Add LE Attribute to Selected Export") { public void run() {
addLEAttribute(); }},
SEPARATOR,
new EMenuItem("_Load Logical Effort Libraries (Purple, Red, and Orange)") { public void run() {
loadLogicalEffortLibraries(); }}),
//------------------- Routing
// mnemonic keys available: B D F IJK OPQ V XY
new EMenu("_Routing",
new EMenuItem.CheckBox("Enable _Auto-Stitching") {
public boolean isSelected() { return Routing.isAutoStitchOn(); }
public void setSelected(boolean b) {
Routing.setAutoStitchOn(b);
System.out.println("Auto-stitching " + (b ? "enabled" : "disabled"));
}
},
new EMenuItem("Auto-_Stitch Now") { public void run() {
AutoStitch.autoStitch(false, true); }},
new EMenuItem("Auto-Stitch _Highlighted Now", KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0)) { public void run() {
AutoStitch.autoStitch(true, true); }},
SEPARATOR,
new EMenuItem.CheckBox("Enable _Mimic-Stitching") {
public boolean isSelected() { return Routing.isMimicStitchOn(); }
public void setSelected(boolean b) {
Routing.setMimicStitchOn(b);
System.out.println("Mimic-stitching " + (b ? "enabled" : "disabled"));
}
},
new EMenuItem("Mimic-Stitch _Now", KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0)) { public void run() {
MimicStitch.mimicStitch(true); }},
new EMenuItem("Mimic S_elected") { public void run() {
Routing.getRoutingTool().mimicSelected(); }},
SEPARATOR,
new EMenuItem("Ma_ze Route") { public void run() {
Maze.mazeRoute(); }},
SEPARATOR,
new EMenuItem("_River-Route") { public void run() {
River.riverRoute(); }},
SEPARATOR,
new EMenuItem("Sea-Of-_Gates Route") { public void run() {
SeaOfGates.seaOfGatesRoute(); }},
Routing.hasSunRouter() ? SEPARATOR : null,
Routing.hasSunRouter() ? new EMenuItem("Sun _Lava Router") { public void run() {
Routing.sunRouteCurrentCell(); }} : null,
SEPARATOR,
new EMenuItem("_Unroute") { public void run() {
Routing.unrouteCurrent(); }},
new EMenuItem("Get Unrouted _Wire") { public void run() {
getUnroutedArcCommand(); }},
new EMenuItem("_Copy Routing Topology") { public void run() {
Routing.copyRoutingTopology(); }},
new EMenuItem("Pas_te Routing Topology") { public void run() {
Routing.pasteRoutingTopology(); }}),
//------------------- Generation
// mnemonic keys available: AB DE GH JK N Q TUVWXYZ
new EMenu("_Generation",
new EMenuItem("_Coverage Implants Generator") { public void run() {
layerCoverageCommand(LayerCoverageTool.LCMode.IMPLANT, GeometryHandler.GHMode.ALGO_SWEEP); }},
new EMenuItem("_Pad Frame Generator...") { public void run() {
padFrameGeneratorCommand(); }},
new EMenuItem("_ROM Generator...") { public void run() {
ROMGenerator.generateROM(); }},
new EMenuItem("MOSIS CMOS P_LA Generator...") { public void run() {
PLA.generate(); }},
new EMenuItem("_Fill (MoCMOS)...") { public void run() {
FillGenDialog.openFillGeneratorDialog(Technology.getMocmosTechnology()); }},
Technology.getTSMC180Technology() != null ? new EMenuItem("Fi_ll (TSMC180)...") { public void run() {
FillGenDialog.openFillGeneratorDialog(Technology.getTSMC180Technology()); }} : null,
Technology.getCMOS90Technology() != null ? new EMenuItem("F_ill (CMOS90)...") { public void run() {
FillGenDialog.openFillGeneratorDialog(Technology.getCMOS90Technology()); }} : null,
new EMenuItem("Generate gate layouts (_MoCMOS)") { public void run() {
GateLayoutGenerator.generateFromSchematicsJob(TechType.TechTypeEnum.MOCMOS); }},
Technology.getTSMC180Technology() != null ? new EMenuItem("Generate gate layouts (T_SMC180)") { public void run() {
GateLayoutGenerator.generateFromSchematicsJob(TechType.TechTypeEnum.TSMC180); }} : null,
Technology.getCMOS90Technology() != null ? new EMenuItem("Generate gate layouts (CM_OS90)") { public void run() {
GateLayoutGenerator.generateFromSchematicsJob(TechType.TechTypeEnum.CMOS90); }} : null),
//------------------- Silicon Compiler
// mnemonic keys available: AB DEFGHIJKLM OPQRSTUVWXYZ
new EMenu("Silicon Co_mpiler",
new EMenuItem("_Convert Current Cell to Layout") { public void run() {
doSiliconCompilation(WindowFrame.needCurCell(), false); }},
SEPARATOR,
new EMenuItem("Compile VHDL to _Netlist View") { public void run() {
compileVHDL(); }}),
//------------------- Compaction
// mnemonic keys available: AB DEFGHIJKLMNOPQRSTUVWXYZ
new EMenu("_Compaction",
new EMenuItem("Do _Compaction") { public void run() {
Compaction.compactNow(); }}),
//------------------- Others
SEPARATOR,
new EMenuItem("List _Tools") { public void run() {
listToolsCommand(); }},
// mnemonic keys available: ABCDEFGHIJKLMNOPQ STUVWXYZ
new EMenu("Lang_uages",
new EMenuItem("_Run Java Bean Shell Script") { public void run() {
javaBshScriptCommand(); }}));
}
| static EMenu makeMenu() {
/****************************** THE TOOL MENU ******************************/
// mnemonic keys available: B F H JK PQ XYZ
return new EMenu("_Tool",
//------------------- DRC
// mnemonic keys available: B EFG IJK MNOPQR UVWXYZ
new EMenu("_DRC",
new EMenuItem("Check _Hierarchically", KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0))
{ public void run() {
Cell cell = Job.getUserInterface().needCurrentCell();
// Multi-threaded code is only available for layout
if (DRC.isMultiThreaded() && cell.isLayout())
{
new MTDRCLayoutTool(cell, true, null).startJob();
}
else
{
DRC.checkDRCHierarchically(cell, null, GeometryHandler.GHMode.ALGO_SWEEP, false);
}
}},
new EMenuItem("Check _Selection Area Hierarchically") { public void run() {
EditWindow_ wnd = Job.getUserInterface().getCurrentEditWindow_();
if (wnd == null) return;
DRC.checkDRCHierarchically(wnd.getCell(), wnd.getHighlightedArea(), GeometryHandler.GHMode.ALGO_SWEEP, false); }},
new EMenuItem("Check Area _Coverage") { public void run() {
LayerCoverageTool.layerCoverageCommand(WindowFrame.needCurCell(), GeometryHandler.GHMode.ALGO_SWEEP, true); }},
new EMenuItem("_List Layer Coverage on Cell") { public void run() {
layerCoverageCommand(LayerCoverageTool.LCMode.AREA, GeometryHandler.GHMode.ALGO_SWEEP); }},
SEPARATOR,
new EMenuItem("Import _Assura DRC Errors for Current Cell...") { public void run() {
importAssuraDrcErrors(); }},
new EMenuItem("Import Calibre _DRC Errors for Current Cell...") { public void run() {
importCalibreDrcErrors(); }},
SEPARATOR,
new EMenuItem("Export DRC Deck...") { public void run() {
exportDRCDeck(); }},
new EMenuItem("Import DRC Deck...") { public void run() {
importDRCDeck(); }}),
//------------------- Simulation (Built-in)
// mnemonic keys available: B JK N PQ XYZ
new EMenu("Simulation (Built-in)",
Simulation.hasIRSIM() ? new EMenuItem("IRSI_M: Simulate Current Cell") { public void run() {
Simulation.startSimulation(Simulation.IRSIM_ENGINE, false, null, null); }} : null,
Simulation.hasIRSIM() ? new EMenuItem("IRSIM: _Write Deck...") { public void run() {
FileMenu.exportCommand(FileType.IRSIM, true); }} : null,
Simulation.hasIRSIM() ? new EMenuItem("_IRSIM: Simulate Deck...") { public void run() {
Simulation.startSimulation(Simulation.IRSIM_ENGINE, true, null, null); }} : null,
Simulation.hasIRSIM() ? SEPARATOR : null,
new EMenuItem("_ALS: Simulate Current Cell") { public void run() {
Simulation.startSimulation(Simulation.ALS_ENGINE, false, null, null); }},
Simulation.hasFLEET() ? SEPARATOR : null,
Simulation.hasFLEET() ? Simulation.FLEETMenu() : null,
SEPARATOR,
new EMenuItem("Set Signal _High at Main Time", KeyStroke.getKeyStroke('V', 0)) { public void run() {
Simulation.setSignalHigh(); }},
new EMenuItem("Set Signal _Low at Main Time", KeyStroke.getKeyStroke('G', 0)) { public void run() {
Simulation.setSignalLow(); }},
new EMenuItem("Set Signal Un_defined at Main Time", KeyStroke.getKeyStroke('X', 0)) { public void run() {
Simulation.setSignalX(); }},
new EMenuItem("Set Clock on Selected Signal...") { public void run() {
Simulation.setClock(); }},
SEPARATOR,
new EMenuItem("_Update Simulation Window") { public void run() {
Simulation.update(); }},
new EMenuItem("_Get Information about Selected Signals") { public void run() {
Simulation.showSignalInfo(); }},
SEPARATOR,
new EMenuItem("_Clear Selected Stimuli") { public void run() {
Simulation.removeSelectedStimuli(); }},
new EMenuItem("Clear All Stimuli _on Selected Signals") { public void run() {
Simulation.removeStimuliFromSignal(); }},
new EMenuItem("Clear All S_timuli") { public void run() {
Simulation.removeAllStimuli(); }},
SEPARATOR,
new EMenuItem("_Save Stimuli to Disk...") { public void run() {
Simulation.saveStimuli(); }},
new EMenuItem("_Restore Stimuli from Disk...") { public void run() {
Simulation.restoreStimuli(); }}),
//------------------- Simulation (SPICE)
// mnemonic keys available: AB IJK NO QR VWXYZ
new EMenu("Simulation (_Spice)",
new EMenuItem("Write Spice _Deck...") { public void run() {
FileMenu.exportCommand(FileType.SPICE, true); }},
new EMenuItem("Write _CDL Deck...") { public void run() {
FileMenu.exportCommand(FileType.CDL, true); }},
new EMenuItem("Plot Spice _Listing...") { public void run() {
Simulate.plotSpiceResults(); }},
new EMenuItem("Plot Spice _for This Cell") { public void run() {
Simulate.plotSpiceResultsThisCell(); }},
new EMenuItem("Set Spice _Model...") { public void run() {
Simulation.setSpiceModel(); }},
new EMenuItem("Add M_ultiplier") { public void run() {
addMultiplierCommand(); }},
new EMenuItem("Add Flat Cod_e") { public void run() {
makeTemplate(Spice.SPICE_CODE_FLAT_KEY); }},
SEPARATOR,
new EMenuItem("Set Generic Spice _Template") { public void run() {
makeTemplate(Spice.SPICE_TEMPLATE_KEY); }},
new EMenuItem("Set Spice _2 Template") { public void run() {
makeTemplate(Spice.SPICE_2_TEMPLATE_KEY); }},
new EMenuItem("Set Spice _3 Template") { public void run() {
makeTemplate(Spice.SPICE_3_TEMPLATE_KEY); }},
new EMenuItem("Set _HSpice Template") { public void run() {
makeTemplate(Spice.SPICE_H_TEMPLATE_KEY); }},
new EMenuItem("Set _PSpice Template") { public void run() {
makeTemplate(Spice.SPICE_P_TEMPLATE_KEY); }},
new EMenuItem("Set _GnuCap Template") { public void run() {
makeTemplate(Spice.SPICE_GC_TEMPLATE_KEY); }},
new EMenuItem("Set _SmartSpice Template") { public void run() {
makeTemplate(Spice.SPICE_SM_TEMPLATE_KEY); }},
new EMenuItem("Set Assura CDL Template") { public void run() {
makeTemplate(Spice.SPICE_A_TEMPLATE_KEY); }},
new EMenuItem("Set Calibre Spice Template") { public void run() {
makeTemplate(Spice.SPICE_C_TEMPLATE_KEY); }},
new EMenuItem("Set Netlist Cell From File") { public void run() {
makeTemplate(Spice.SPICE_NETLIST_FILE_KEY); }}),
//------------------- Simulation (Verilog)
// mnemonic keys available: AB EFGHIJKLMNO QRS U WXYZ
new EMenu("Simulation (_Verilog)",
new EMenuItem("Write _Verilog Deck...") { public void run() {
Simulation.setVerilogStopAtStandardCells(false);
FileMenu.exportCommand(FileType.VERILOG, true); }},
new EMenuItem("Plot Verilog VCD _Dump...") { public void run() {
Simulate.plotVerilogResults(); }},
new EMenuItem("Plot Verilog for This _Cell") { public void run() {
Simulate.plotVerilogResultsThisCell(); }},
SEPARATOR,
new EMenuItem("Set Verilog _Template") { public void run() {
makeTemplate(Verilog.VERILOG_TEMPLATE_KEY); }},
new EMenuItem("Set Verilog Default _Parameter") { public void run() {
makeTemplate(Verilog.VERILOG_DEFPARAM_KEY); }},
SEPARATOR,
// mnemonic keys available: ABC EFGHIJKLMNOPQRS UV XYZ
new EMenu("Set Verilog _Wire",
new EMenuItem("_Wire") { public void run() {
Simulation.setVerilogWireCommand(0); }},
new EMenuItem("_Trireg") { public void run() {
Simulation.setVerilogWireCommand(1); }},
new EMenuItem("_Default") { public void run() {
Simulation.setVerilogWireCommand(2); }}),
// mnemonic keys available: ABCDEFGHIJKLM OPQRSTUV XYZ
new EMenu("_Transistor Strength",
new EMenuItem("_Weak") { public void run() {
Simulation.setTransistorStrengthCommand(true); }},
new EMenuItem("_Normal") { public void run() {
Simulation.setTransistorStrengthCommand(false); }})),
//------------------- Simulation (others)
// mnemonic keys available: B D G KL N Q UVWXYZ
new EMenu("Simulation (_Others)",
new EMenuItem("Write _Maxwell Deck...") { public void run() {
FileMenu.exportCommand(FileType.MAXWELL, true); }},
new EMenuItem("Write _Tegas Deck...") { public void run() {
FileMenu.exportCommand(FileType.TEGAS, true); }},
new EMenuItem("Write _SILOS Deck...") { public void run() {
FileMenu.exportCommand(FileType.SILOS, true); }},
new EMenuItem("Write _PAL Deck...") { public void run() {
FileMenu.exportCommand(FileType.PAL, true); }},
SEPARATOR,
!Simulation.hasIRSIM() ? new EMenuItem("Write _IRSIM Deck...") { public void run() {
FileMenu.exportCommand(FileType.IRSIM, true); }} : null,
new EMenuItem("Write _ESIM/RNL Deck...") { public void run() {
FileMenu.exportCommand(FileType.ESIM, true); }},
new EMenuItem("Write _RSIM Deck...") { public void run() {
FileMenu.exportCommand(FileType.RSIM, true); }},
new EMenuItem("Write _COSMOS Deck...") { public void run() {
FileMenu.exportCommand(FileType.COSMOS, true); }},
new EMenuItem("Write M_OSSIM Deck...") { public void run() {
FileMenu.exportCommand(FileType.MOSSIM, true); }},
SEPARATOR,
new EMenuItem("Write _FastHenry Deck...") { public void run() {
FileMenu.exportCommand(FileType.FASTHENRY, true); }},
new EMenuItem("Fast_Henry Arc Properties...") { public void run() {
FastHenryArc.showFastHenryArcDialog(); }},
SEPARATOR,
new EMenuItem("Write _ArchSim Deck...") { public void run() {
FileMenu.exportCommand(FileType.ARCHSIM, true); }},
new EMenuItem("Display ArchSim _Journal...") { public void run() {
Simulate.plotArchSimResults(); }}),
//------------------- ERC
// mnemonic keys available: BCDEFGHIJKLMNOPQRSTUV XYZ
new EMenu("_ERC",
new EMenuItem("Check _Wells") { public void run() {
ERCWellCheck.analyzeCurCell(GeometryHandler.GHMode.ALGO_SWEEP); }},
new EMenuItem("_Antenna Check") { public void run() {
ERCAntenna.doAntennaCheck(); }}),
// ------------------- NCC
// mnemonic keys available: AB DEFGHIJKLMNOPQRS UVWXYZ
new EMenu("_NCC",
new EMenuItem("Schematic and Layout Views of Cell in _Current Window") { public void run() {
new NccJob(1); }},
new EMenuItem("Cells from _Two Windows") { public void run() {
new NccJob(2); }},
SEPARATOR,
new EMenuItem("Copy Schematic _User Names to Layout") { public void run() {
new SchemNamesToLay.RenameJob(); }},
new EMenuItem("Copy All Schematic _Names to Layout") { public void run() {
new AllSchemNamesToLay.RenameJob(); }},
new EMenuItem("Highlight _Equivalent") { public void run() {
HighlightEquivalent.highlight(); }},
new EMenuItem("Run NCC for Schematic Cross-Probing") { public void run() {
runNccSchematicCrossProbing(); }},
new EMenu("Add NCC _Annotation to Cell",
new EMenuItem("Exports Connected by Parent _vdd") { public void run() {
NccCellAnnotations.makeNCCAnnotationMenuCommand("exportsConnectedByParent vdd /vdd_[0-9]+/"); }},
new EMenuItem("Exports Connected By Parent _gnd") { public void run() {
NccCellAnnotations.makeNCCAnnotationMenuCommand("exportsConnectedByParent gnd /gnd_[0-9]+/"); }},
new EMenuItem("_Skip NCC") { public void run() {
NccCellAnnotations.makeNCCAnnotationMenuCommand("skipNCC <comment explaining why>"); }},
new EMenuItem("_Not a Subcircuit") { public void run() {
NccCellAnnotations.makeNCCAnnotationMenuCommand("notSubcircuit <comment explaining why>"); }},
new EMenuItem("_Flatten Instances") { public void run() {
NccCellAnnotations.makeNCCAnnotationMenuCommand("flattenInstances <list of instance names>"); }},
new EMenuItem("_Join Group") { public void run() {
NccCellAnnotations.makeNCCAnnotationMenuCommand("joinGroup <cell name>"); }},
new EMenuItem("_Transistor Type") { public void run() {
NccCellAnnotations.makeNCCAnnotationMenuCommand("transistorType <typeName>"); }},
new EMenuItem("_Resistor Type") { public void run() {
NccCellAnnotations.makeNCCAnnotationMenuCommand("resistorType <typeName>"); }},
new EMenuItem("Force _Part Match") { public void run() {
NccCellAnnotations.makeNCCAnnotationMenuCommand("forcePartMatch <Part name shared by schematic and layout>"); }},
new EMenuItem("Force _Wire Match") { public void run() {
NccCellAnnotations.makeNCCAnnotationMenuCommand("forceWireMatch <Wire name shared by schematic and layout>"); }},
new EMenuItem("_Black Box") { public void run() {
NccCellAnnotations.makeNCCAnnotationMenuCommand("blackBox <comment explaining why>"); }})),
// ------------------- PIE
// If Pie package is installed then add menu entries to call it
Pie.hasPie() ? new EMenu("_PIE",
new EMenuItem("PIE Schematic and Layout Views of Cell in Current Window") { public void run() {
Pie.invokePieNcc(1); }},
new EMenuItem("Cells from _Two Windows") { public void run() {
Pie.invokePieNcc(2); }}) : null,
// ------------------- Architecture Generator
// // If ArchGen package is installed then add menu entries to call it
// ArchGenPlugin.hasArchGen() ? ArchGenPlugin.getEMenu() : null,
//------------------- Network
// mnemonic keys available: D F IJK M O Q S W YZ
new EMenu("Net_work",
new EMenuItem("Show _Network", 'K') { public void run() {
showNetworkCommand(); }},
new EMenuItem("_List Networks") { public void run() {
listNetworksCommand(); }},
new EMenuItem("List _Connections on Network") { public void run() {
listConnectionsOnNetworkCommand(); }},
new EMenuItem("List _Exports on Network") { public void run() {
listExportsOnNetworkCommand(); }},
new EMenuItem("List Exports _below Network") { public void run() {
listExportsBelowNetworkCommand(); }},
new EMenuItem("List _Geometry on Network") { public void run() {
listGeometryOnNetworkCommand(GeometryHandler.GHMode.ALGO_SWEEP); }},
new EMenuItem("Show _All Networks") { public void run() {
showAllNetworksCommand(); }},
new EMenuItem("List _Total Wire Lengths on All Networks") { public void run() {
listGeomsAllNetworksCommand(); }},
SEPARATOR,
new EMenuItem("E_xtract Current Cell") { public void run() {
Connectivity.extractCurCell(false); }},
new EMenuItem("Extract Current _Hierarchy") { public void run() {
Connectivity.extractCurCell(true); }},
SEPARATOR,
new EMenuItem("Show _Power and Ground") { public void run() {
showPowerAndGround(); }},
new EMenuItem("_Validate Power and Ground") { public void run() {
validatePowerAndGround(false); }},
new EMenuItem("_Repair Power and Ground") { public void run() {
new RepairPowerAndGround(); }},
new EMenuItem("Redo Network N_umbering") { public void run() {
NetworkTool.renumberNetlists(); }}),
//------------------- Logical Effort
// mnemonic keys available: D FGH JK M PQRSTUVWXYZ
new EMenu("_Logical Effort",
new EMenuItem("_Optimize for Equal Gate Delays") { public void run() {
optimizeEqualGateDelaysCommand(true); }},
new EMenuItem("Optimize for Equal Gate Delays (no _caching)") { public void run() {
optimizeEqualGateDelaysCommand(false); }},
new EMenuItem("List _Info for Selected Node") { public void run() {
printLEInfoCommand(); }},
new EMenuItem("_Back Annotate Wire Lengths for Current Cell") { public void run() {
backAnnotateCommand(); }},
new EMenuItem("Clear Sizes on Selected _Node(s)") { public void run() {
clearSizesNodableCommand(); }},
new EMenuItem("Clear Sizes in _all Libraries") { public void run() {
clearSizesCommand(); }},
new EMenuItem("_Estimate Delays") { public void run() {
estimateDelaysCommand(); }},
new EMenuItem("Add LE Attribute to Selected Export") { public void run() {
addLEAttribute(); }},
SEPARATOR,
new EMenuItem("_Load Logical Effort Libraries (Purple, Red, and Orange)") { public void run() {
loadLogicalEffortLibraries(); }}),
//------------------- Routing
// mnemonic keys available: B D F IJK OPQ V XY
new EMenu("_Routing",
new EMenuItem.CheckBox("Enable _Auto-Stitching") {
public boolean isSelected() { return Routing.isAutoStitchOn(); }
public void setSelected(boolean b) {
Routing.setAutoStitchOn(b);
System.out.println("Auto-stitching " + (b ? "enabled" : "disabled"));
}
},
new EMenuItem("Auto-_Stitch Now") { public void run() {
AutoStitch.autoStitch(false, true); }},
new EMenuItem("Auto-Stitch _Highlighted Now", KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0)) { public void run() {
AutoStitch.autoStitch(true, true); }},
SEPARATOR,
new EMenuItem.CheckBox("Enable _Mimic-Stitching") {
public boolean isSelected() { return Routing.isMimicStitchOn(); }
public void setSelected(boolean b) {
Routing.setMimicStitchOn(b);
System.out.println("Mimic-stitching " + (b ? "enabled" : "disabled"));
}
},
new EMenuItem("Mimic-Stitch _Now", KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0)) { public void run() {
MimicStitch.mimicStitch(true); }},
new EMenuItem("Mimic S_elected") { public void run() {
Routing.getRoutingTool().mimicSelected(); }},
SEPARATOR,
new EMenuItem("Ma_ze Route") { public void run() {
Maze.mazeRoute(); }},
SEPARATOR,
new EMenuItem("_River-Route") { public void run() {
River.riverRoute(); }},
SEPARATOR,
new EMenuItem("Sea-Of-_Gates Route") { public void run() {
SeaOfGates.seaOfGatesRoute(); }},
Routing.hasSunRouter() ? SEPARATOR : null,
Routing.hasSunRouter() ? new EMenuItem("Sun _Lava Router") { public void run() {
Routing.sunRouteCurrentCell(); }} : null,
SEPARATOR,
new EMenuItem("_Unroute") { public void run() {
Routing.unrouteCurrent(); }},
new EMenuItem("Get Unrouted _Wire") { public void run() {
getUnroutedArcCommand(); }},
new EMenuItem("_Copy Routing Topology") { public void run() {
Routing.copyRoutingTopology(); }},
new EMenuItem("Pas_te Routing Topology") { public void run() {
Routing.pasteRoutingTopology(); }}),
//------------------- Generation
// mnemonic keys available: AB DE GH JK N Q TUVWXYZ
new EMenu("_Generation",
new EMenuItem("_Coverage Implants Generator") { public void run() {
layerCoverageCommand(LayerCoverageTool.LCMode.IMPLANT, GeometryHandler.GHMode.ALGO_SWEEP); }},
new EMenuItem("_Pad Frame Generator...") { public void run() {
padFrameGeneratorCommand(); }},
new EMenuItem("_ROM Generator...") { public void run() {
ROMGenerator.generateROM(); }},
new EMenuItem("MOSIS CMOS P_LA Generator...") { public void run() {
PLA.generate(); }},
new EMenuItem("_Fill (MoCMOS)...") { public void run() {
FillGenDialog.openFillGeneratorDialog(Technology.getMocmosTechnology()); }},
Technology.getTSMC180Technology() != null ? new EMenuItem("Fi_ll (TSMC180)...") { public void run() {
FillGenDialog.openFillGeneratorDialog(Technology.getTSMC180Technology()); }} : null,
Technology.getCMOS90Technology() != null ? new EMenuItem("F_ill (CMOS90)...") { public void run() {
FillGenDialog.openFillGeneratorDialog(Technology.getCMOS90Technology()); }} : null,
new EMenuItem("Generate gate layouts (_MoCMOS)") { public void run() {
GateLayoutGenerator.generateFromSchematicsJob(TechType.TechTypeEnum.MOCMOS); }},
Technology.getTSMC180Technology() != null ? new EMenuItem("Generate gate layouts (T_SMC180)") { public void run() {
GateLayoutGenerator.generateFromSchematicsJob(TechType.TechTypeEnum.TSMC180); }} : null,
Technology.getCMOS90Technology() != null ? new EMenuItem("Generate gate layouts (CM_OS90)") { public void run() {
GateLayoutGenerator.generateFromSchematicsJob(TechType.TechTypeEnum.CMOS90); }} : null),
//------------------- Silicon Compiler
// mnemonic keys available: AB DEFGHIJKLM OPQRSTUVWXYZ
new EMenu("Silicon Co_mpiler",
new EMenuItem("_Convert Current Cell to Layout") { public void run() {
doSiliconCompilation(WindowFrame.needCurCell(), false); }},
SEPARATOR,
new EMenuItem("Compile VHDL to _Netlist View") { public void run() {
compileVHDL(); }}),
//------------------- Compaction
// mnemonic keys available: AB DEFGHIJKLMNOPQRSTUVWXYZ
new EMenu("_Compaction",
new EMenuItem("Do _Compaction") { public void run() {
Compaction.compactNow(); }}),
//------------------- Others
SEPARATOR,
new EMenuItem("List _Tools") { public void run() {
listToolsCommand(); }},
// mnemonic keys available: ABCDEFGHIJKLMNOPQ STUVWXYZ
new EMenu("Lang_uages",
new EMenuItem("_Run Java Bean Shell Script") { public void run() {
javaBshScriptCommand(); }}));
}
|
diff --git a/src/com/android/email/ControllerResultUiThreadWrapper.java b/src/com/android/email/ControllerResultUiThreadWrapper.java
index 8c9d855c..e196059a 100644
--- a/src/com/android/email/ControllerResultUiThreadWrapper.java
+++ b/src/com/android/email/ControllerResultUiThreadWrapper.java
@@ -1,139 +1,139 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.email;
import com.android.email.Controller.Result;
import com.android.email.mail.MessagingException;
import android.os.Handler;
/**
* A {@link Result} that wraps another {@link Result} and makes sure methods gets called back
* on the UI thread.
*
* <p>Optionally it supports the "synchronous" mode, if you pass null for the {@code handler}
* parameter, which allows unit tests to run synchronously.
*/
public class ControllerResultUiThreadWrapper<T extends Result> extends Result {
private final Handler mHandler;
private final T mWrappee;
public ControllerResultUiThreadWrapper(Handler handler, T wrappee) {
mHandler = handler;
mWrappee = wrappee;
}
public T getWrappee() {
return mWrappee;
}
@Override
protected void setRegistered(boolean registered) {
super.setRegistered(registered);
mWrappee.setRegistered(registered);
}
private void run(Runnable runnable) {
if (mHandler == null) {
runnable.run();
} else {
mHandler.post(runnable);
}
}
@Override
- public void loadAttachmentCallback(final MessagingException result, final long messageId,
- final long accountId, final long attachmentId, final int progress) {
+ public void loadAttachmentCallback(final MessagingException result, final long accountId,
+ final long messageId, final long attachmentId, final int progress) {
run(new Runnable() {
public void run() {
/* It's possible this callback is unregistered after this Runnable was posted and
* sitting in the handler queue, so we always need to check if it's still registered
* on the UI thread.
*/
if (!isRegistered()) return;
mWrappee.loadAttachmentCallback(result, accountId, messageId, attachmentId,
progress);
}
});
}
@Override
public void loadMessageForViewCallback(final MessagingException result, final long accountId,
final long messageId, final int progress) {
run(new Runnable() {
public void run() {
if (!isRegistered()) return;
mWrappee.loadMessageForViewCallback(result, accountId, messageId, progress);
}
});
}
@Override
public void sendMailCallback(final MessagingException result, final long accountId,
final long messageId, final int progress) {
run(new Runnable() {
public void run() {
if (!isRegistered()) return;
mWrappee.sendMailCallback(result, accountId, messageId, progress);
}
});
}
@Override
public void serviceCheckMailCallback(final MessagingException result, final long accountId,
final long mailboxId, final int progress, final long tag) {
run(new Runnable() {
public void run() {
if (!isRegistered()) return;
mWrappee.serviceCheckMailCallback(result, accountId, mailboxId, progress, tag);
}
});
}
@Override
public void updateMailboxCallback(final MessagingException result, final long accountId,
final long mailboxId, final int progress, final int numNewMessages) {
run(new Runnable() {
public void run() {
if (!isRegistered()) return;
mWrappee.updateMailboxCallback(result, accountId, mailboxId, progress,
numNewMessages);
}
});
}
@Override
public void updateMailboxListCallback(final MessagingException result, final long accountId,
final int progress) {
run(new Runnable() {
public void run() {
if (!isRegistered()) return;
mWrappee.updateMailboxListCallback(result, accountId, progress);
}
});
}
@Override
public void deleteAccountCallback(final long accountId) {
run(new Runnable() {
public void run() {
if (!isRegistered()) return;
mWrappee.deleteAccountCallback(accountId);
}
});
}
}
| true | true | public void loadAttachmentCallback(final MessagingException result, final long messageId,
final long accountId, final long attachmentId, final int progress) {
run(new Runnable() {
public void run() {
/* It's possible this callback is unregistered after this Runnable was posted and
* sitting in the handler queue, so we always need to check if it's still registered
* on the UI thread.
*/
if (!isRegistered()) return;
mWrappee.loadAttachmentCallback(result, accountId, messageId, attachmentId,
progress);
}
});
}
| public void loadAttachmentCallback(final MessagingException result, final long accountId,
final long messageId, final long attachmentId, final int progress) {
run(new Runnable() {
public void run() {
/* It's possible this callback is unregistered after this Runnable was posted and
* sitting in the handler queue, so we always need to check if it's still registered
* on the UI thread.
*/
if (!isRegistered()) return;
mWrappee.loadAttachmentCallback(result, accountId, messageId, attachmentId,
progress);
}
});
}
|
diff --git a/update/org.eclipse.update.core/src/org/eclipse/update/internal/core/SiteFilePluginContentConsumer.java b/update/org.eclipse.update.core/src/org/eclipse/update/internal/core/SiteFilePluginContentConsumer.java
index d635f9cce..6a58144b0 100644
--- a/update/org.eclipse.update.core/src/org/eclipse/update/internal/core/SiteFilePluginContentConsumer.java
+++ b/update/org.eclipse.update.core/src/org/eclipse/update/internal/core/SiteFilePluginContentConsumer.java
@@ -1,179 +1,179 @@
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.update.internal.core;
import java.io.*;
import java.net.*;
import java.util.*;
import org.eclipse.core.runtime.*;
import org.eclipse.update.core.*;
/**
* Plugin Content Consumer on a Site
*/
public class SiteFilePluginContentConsumer extends ContentConsumer {
private IPluginEntry pluginEntry;
private ISite site;
private boolean closed = false;
// recovery
private String oldPath;
private String newPath;
// for abort
private List /*of path as String */
installedFiles;
/*
* Constructor
*/
public SiteFilePluginContentConsumer(IPluginEntry pluginEntry, ISite site) {
this.pluginEntry = pluginEntry;
this.site = site;
installedFiles = new ArrayList();
}
/*
* @see ISiteContentConsumer#store(ContentReference, IProgressMonitor)
*/
public void store(ContentReference contentReference, IProgressMonitor monitor) throws CoreException {
InputStream inStream = null;
String pluginPath = null;
if (closed) {
UpdateCore.warn("Attempt to store in a closed SiteFilePluginContentConsumer", new Exception());
return;
}
try {
URL newURL = new URL(site.getURL(), Site.DEFAULT_PLUGIN_PATH + pluginEntry.getVersionedIdentifier().toString());
pluginPath = newURL.getFile();
String contentKey = contentReference.getIdentifier();
inStream = contentReference.getInputStream();
pluginPath += pluginPath.endsWith(File.separator) ? contentKey : File.separator + contentKey;
// error recovery
- if (pluginPath.endsWith("\\plugin.xml") || pluginPath.endsWith("/plugin.xml")) {
+ if ("plugin.xml".equals(contentKey)) {
oldPath = pluginPath.replace(File.separatorChar, '/');
File localFile = new File(oldPath);
if (localFile.exists()) {
throw Utilities.newCoreException(Policy.bind("UpdateManagerUtils.FileAlreadyExists", new Object[] { localFile }), null);
}
pluginPath = ErrorRecoveryLog.getLocalRandomIdentifier(pluginPath);
newPath = pluginPath;
ErrorRecoveryLog.getLog().appendPath(ErrorRecoveryLog.PLUGIN_ENTRY, pluginPath);
}
- if (pluginPath.endsWith("\\fragment.xml") || pluginPath.endsWith("/fragment.xml")) {
+ if ("fragment.xml".equals(contentKey)) {
oldPath = pluginPath.replace(File.separatorChar, '/');
File localFile = new File(oldPath);
if (localFile.exists()) {
throw Utilities.newCoreException(Policy.bind("UpdateManagerUtils.FileAlreadyExists", new Object[] { localFile }), null);
}
pluginPath = ErrorRecoveryLog.getLocalRandomIdentifier(pluginPath);
newPath = pluginPath;
ErrorRecoveryLog.getLog().appendPath(ErrorRecoveryLog.FRAGMENT_ENTRY, pluginPath);
}
UpdateManagerUtils.copyToLocal(inStream, pluginPath, null);
UpdateManagerUtils.checkPermissions(contentReference, pluginPath); // 20305
installedFiles.add(pluginPath);
} catch (IOException e) {
throw Utilities.newCoreException(Policy.bind("GlobalConsumer.ErrorCreatingFile", pluginPath), e);
//$NON-NLS-1$
} finally {
if (inStream != null) {
try {
// close stream
inStream.close();
} catch (IOException e) {
}
}
}
}
/*
* @see ISiteContentConsumer#close()
*/
public void close() throws CoreException {
if (closed) {
UpdateCore.warn("Attempt to close a closed SiteFilePluginContentConsumer", new Exception());
return;
}
if (newPath != null) {
// rename file
ErrorRecoveryLog.getLog().appendPath(ErrorRecoveryLog.RENAME_ENTRY, newPath);
File fileToRename = new File(newPath);
boolean sucess = false;
if (fileToRename.exists()) {
File renamedFile = new File(oldPath);
sucess = fileToRename.renameTo(renamedFile);
}
if (!sucess) {
String msg = Policy.bind("ContentConsumer.UnableToRename", newPath, oldPath);
throw Utilities.newCoreException(msg, new Exception(msg));
}
}
if (site instanceof SiteFile)
((SiteFile) site).addPluginEntry(pluginEntry);
closed = true;
}
/*
*
*/
public void abort() throws CoreException {
if (closed) {
UpdateCore.warn("Attempt to abort a closed SiteFilePluginContentConsumer", new Exception());
return;
}
boolean sucess = true;
// delete plugin.xml first
if (oldPath != null) {
ErrorRecoveryLog.getLog().appendPath(ErrorRecoveryLog.DELETE_ENTRY, oldPath);
File fileToRemove = new File(oldPath);
if (fileToRemove.exists()) {
sucess = fileToRemove.delete();
}
}
if (!sucess) {
String msg = Policy.bind("Unable to delete", oldPath);
UpdateCore.log(msg, null);
} else {
// remove the plugin files;
Iterator iter = installedFiles.iterator();
File featureFile = null;
while (iter.hasNext()) {
String path = (String) iter.next();
featureFile = new File(path);
UpdateManagerUtils.removeFromFileSystem(featureFile);
}
// remove the plugin directory if empty
try {
URL newURL = new URL(site.getURL(), Site.DEFAULT_PLUGIN_PATH + pluginEntry.getVersionedIdentifier().toString());
String pluginPath = newURL.getFile();
UpdateManagerUtils.removeEmptyDirectoriesFromFileSystem(new File(pluginPath));
} catch (MalformedURLException e) {
throw Utilities.newCoreException(e.getMessage(), e);
}
}
closed = true;
}
}
| false | true | public void store(ContentReference contentReference, IProgressMonitor monitor) throws CoreException {
InputStream inStream = null;
String pluginPath = null;
if (closed) {
UpdateCore.warn("Attempt to store in a closed SiteFilePluginContentConsumer", new Exception());
return;
}
try {
URL newURL = new URL(site.getURL(), Site.DEFAULT_PLUGIN_PATH + pluginEntry.getVersionedIdentifier().toString());
pluginPath = newURL.getFile();
String contentKey = contentReference.getIdentifier();
inStream = contentReference.getInputStream();
pluginPath += pluginPath.endsWith(File.separator) ? contentKey : File.separator + contentKey;
// error recovery
if (pluginPath.endsWith("\\plugin.xml") || pluginPath.endsWith("/plugin.xml")) {
oldPath = pluginPath.replace(File.separatorChar, '/');
File localFile = new File(oldPath);
if (localFile.exists()) {
throw Utilities.newCoreException(Policy.bind("UpdateManagerUtils.FileAlreadyExists", new Object[] { localFile }), null);
}
pluginPath = ErrorRecoveryLog.getLocalRandomIdentifier(pluginPath);
newPath = pluginPath;
ErrorRecoveryLog.getLog().appendPath(ErrorRecoveryLog.PLUGIN_ENTRY, pluginPath);
}
if (pluginPath.endsWith("\\fragment.xml") || pluginPath.endsWith("/fragment.xml")) {
oldPath = pluginPath.replace(File.separatorChar, '/');
File localFile = new File(oldPath);
if (localFile.exists()) {
throw Utilities.newCoreException(Policy.bind("UpdateManagerUtils.FileAlreadyExists", new Object[] { localFile }), null);
}
pluginPath = ErrorRecoveryLog.getLocalRandomIdentifier(pluginPath);
newPath = pluginPath;
ErrorRecoveryLog.getLog().appendPath(ErrorRecoveryLog.FRAGMENT_ENTRY, pluginPath);
}
UpdateManagerUtils.copyToLocal(inStream, pluginPath, null);
UpdateManagerUtils.checkPermissions(contentReference, pluginPath); // 20305
installedFiles.add(pluginPath);
} catch (IOException e) {
throw Utilities.newCoreException(Policy.bind("GlobalConsumer.ErrorCreatingFile", pluginPath), e);
//$NON-NLS-1$
} finally {
if (inStream != null) {
try {
// close stream
inStream.close();
} catch (IOException e) {
}
}
}
}
| public void store(ContentReference contentReference, IProgressMonitor monitor) throws CoreException {
InputStream inStream = null;
String pluginPath = null;
if (closed) {
UpdateCore.warn("Attempt to store in a closed SiteFilePluginContentConsumer", new Exception());
return;
}
try {
URL newURL = new URL(site.getURL(), Site.DEFAULT_PLUGIN_PATH + pluginEntry.getVersionedIdentifier().toString());
pluginPath = newURL.getFile();
String contentKey = contentReference.getIdentifier();
inStream = contentReference.getInputStream();
pluginPath += pluginPath.endsWith(File.separator) ? contentKey : File.separator + contentKey;
// error recovery
if ("plugin.xml".equals(contentKey)) {
oldPath = pluginPath.replace(File.separatorChar, '/');
File localFile = new File(oldPath);
if (localFile.exists()) {
throw Utilities.newCoreException(Policy.bind("UpdateManagerUtils.FileAlreadyExists", new Object[] { localFile }), null);
}
pluginPath = ErrorRecoveryLog.getLocalRandomIdentifier(pluginPath);
newPath = pluginPath;
ErrorRecoveryLog.getLog().appendPath(ErrorRecoveryLog.PLUGIN_ENTRY, pluginPath);
}
if ("fragment.xml".equals(contentKey)) {
oldPath = pluginPath.replace(File.separatorChar, '/');
File localFile = new File(oldPath);
if (localFile.exists()) {
throw Utilities.newCoreException(Policy.bind("UpdateManagerUtils.FileAlreadyExists", new Object[] { localFile }), null);
}
pluginPath = ErrorRecoveryLog.getLocalRandomIdentifier(pluginPath);
newPath = pluginPath;
ErrorRecoveryLog.getLog().appendPath(ErrorRecoveryLog.FRAGMENT_ENTRY, pluginPath);
}
UpdateManagerUtils.copyToLocal(inStream, pluginPath, null);
UpdateManagerUtils.checkPermissions(contentReference, pluginPath); // 20305
installedFiles.add(pluginPath);
} catch (IOException e) {
throw Utilities.newCoreException(Policy.bind("GlobalConsumer.ErrorCreatingFile", pluginPath), e);
//$NON-NLS-1$
} finally {
if (inStream != null) {
try {
// close stream
inStream.close();
} catch (IOException e) {
}
}
}
}
|
diff --git a/util/plugins/eu.esdihumboldt.util/src/eu/esdihumboldt/util/validator/DigitCountValidator.java b/util/plugins/eu.esdihumboldt.util/src/eu/esdihumboldt/util/validator/DigitCountValidator.java
index 4dd6145ed..205ff65ee 100644
--- a/util/plugins/eu.esdihumboldt.util/src/eu/esdihumboldt/util/validator/DigitCountValidator.java
+++ b/util/plugins/eu.esdihumboldt.util/src/eu/esdihumboldt/util/validator/DigitCountValidator.java
@@ -1,139 +1,139 @@
/*
* Copyright (c) 2012 Data Harmonisation Panel
*
* All rights reserved. This program and the accompanying materials are made
* available 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.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution. If not, see <http://www.gnu.org/licenses/>.
*
* Contributors:
* HUMBOLDT EU Integrated Project #030962
* Data Harmonisation Panel <http://www.dhpanel.eu>
*/
package eu.esdihumboldt.util.validator;
import java.math.BigDecimal;
import org.springframework.core.convert.ConversionException;
/**
* Validator for digit counts. As in
* (http://www.w3.org/TR/xmlschema-2/#rf-totalDigits and
* http://www.w3.org/TR/xmlschema-2/#rf-fractionDigits)
*
* @author Kai Schwierczek
*/
public class DigitCountValidator extends AbstractValidator {
private Type type;
private int length;
/**
* Construct a validator that checks the digit count of the input to match
* the given type and value.
*
* @param type the digits to check for
* @param length the length to check for
*/
public DigitCountValidator(Type type, int length) {
this.type = type;
this.length = length;
}
/**
* @see eu.esdihumboldt.util.validator.Validator#validate(Object)
*/
@Override
public String validate(Object value) {
BigDecimal decimal;
try {
decimal = getObjectAs(value, BigDecimal.class);
if (decimal == null)
return "Input must be a number.";
} catch (ConversionException ce) {
return "Input must be a number.";
}
switch (type) {
case FRACTIONDIGITS:
boolean ok = true;
try {
// try lowering the scale if it is too large without rounding
// -> cut off ending zeros if possible
if (decimal.scale() > length)
decimal.setScale(length); // throws exception if scaling is
// not possible
} catch (ArithmeticException ae) {
ok = false; // scaling failed
}
if (ok)
return null;
else
return "Input must have at most " + length + " fraction digits but has "
+ decimal.scale() + ".";
case TOTALDIGITS:
// single zero in front of decimal point and ending zeros don't
// count
// here BigDecimal doesn't help, do string work.
String numberString = decimal.abs().toPlainString();
int indexOfDot = numberString.indexOf('.');
if (indexOfDot != -1) {
StringBuilder buf = new StringBuilder(numberString);
// remove ending zeros
while (buf.charAt(buf.length() - 1) == '0')
buf.deleteCharAt(buf.length() - 1);
// remove dot and maybe single zero in front of dot
if (indexOfDot == 1 && buf.charAt(0) == '0')
buf.delete(0, 2); // delete leading zero and .
else
buf.deleteCharAt(indexOfDot); // only delete point
numberString = buf.toString();
}
else if (numberString.equals("0"))
numberString = "";
if (numberString.length() <= length)
return null;
else
return "Input must have at most " + length + " total digits but has "
- + decimal.scale() + ".";
+ + numberString.length() + ".";
default:
return null; // all types checked, doesn't happen
}
}
/**
* @see eu.esdihumboldt.util.validator.Validator#getDescription()
*/
@Override
public String getDescription() {
switch (type) {
case FRACTIONDIGITS:
return "Input must be a number and must have at most " + length + " fraction digits.";
case TOTALDIGITS:
return "Input must be a number and must have at most " + length + " total digits.";
default:
return ""; // all types checked, doesn't happen
}
}
/**
* Type specifies what DigitCountValidator should check.
*/
public enum Type {
/**
* Check for fraction digit count.
*/
FRACTIONDIGITS,
/**
* Check for total digit count.
*/
TOTALDIGITS;
}
}
| true | true | public String validate(Object value) {
BigDecimal decimal;
try {
decimal = getObjectAs(value, BigDecimal.class);
if (decimal == null)
return "Input must be a number.";
} catch (ConversionException ce) {
return "Input must be a number.";
}
switch (type) {
case FRACTIONDIGITS:
boolean ok = true;
try {
// try lowering the scale if it is too large without rounding
// -> cut off ending zeros if possible
if (decimal.scale() > length)
decimal.setScale(length); // throws exception if scaling is
// not possible
} catch (ArithmeticException ae) {
ok = false; // scaling failed
}
if (ok)
return null;
else
return "Input must have at most " + length + " fraction digits but has "
+ decimal.scale() + ".";
case TOTALDIGITS:
// single zero in front of decimal point and ending zeros don't
// count
// here BigDecimal doesn't help, do string work.
String numberString = decimal.abs().toPlainString();
int indexOfDot = numberString.indexOf('.');
if (indexOfDot != -1) {
StringBuilder buf = new StringBuilder(numberString);
// remove ending zeros
while (buf.charAt(buf.length() - 1) == '0')
buf.deleteCharAt(buf.length() - 1);
// remove dot and maybe single zero in front of dot
if (indexOfDot == 1 && buf.charAt(0) == '0')
buf.delete(0, 2); // delete leading zero and .
else
buf.deleteCharAt(indexOfDot); // only delete point
numberString = buf.toString();
}
else if (numberString.equals("0"))
numberString = "";
if (numberString.length() <= length)
return null;
else
return "Input must have at most " + length + " total digits but has "
+ decimal.scale() + ".";
default:
return null; // all types checked, doesn't happen
}
}
| public String validate(Object value) {
BigDecimal decimal;
try {
decimal = getObjectAs(value, BigDecimal.class);
if (decimal == null)
return "Input must be a number.";
} catch (ConversionException ce) {
return "Input must be a number.";
}
switch (type) {
case FRACTIONDIGITS:
boolean ok = true;
try {
// try lowering the scale if it is too large without rounding
// -> cut off ending zeros if possible
if (decimal.scale() > length)
decimal.setScale(length); // throws exception if scaling is
// not possible
} catch (ArithmeticException ae) {
ok = false; // scaling failed
}
if (ok)
return null;
else
return "Input must have at most " + length + " fraction digits but has "
+ decimal.scale() + ".";
case TOTALDIGITS:
// single zero in front of decimal point and ending zeros don't
// count
// here BigDecimal doesn't help, do string work.
String numberString = decimal.abs().toPlainString();
int indexOfDot = numberString.indexOf('.');
if (indexOfDot != -1) {
StringBuilder buf = new StringBuilder(numberString);
// remove ending zeros
while (buf.charAt(buf.length() - 1) == '0')
buf.deleteCharAt(buf.length() - 1);
// remove dot and maybe single zero in front of dot
if (indexOfDot == 1 && buf.charAt(0) == '0')
buf.delete(0, 2); // delete leading zero and .
else
buf.deleteCharAt(indexOfDot); // only delete point
numberString = buf.toString();
}
else if (numberString.equals("0"))
numberString = "";
if (numberString.length() <= length)
return null;
else
return "Input must have at most " + length + " total digits but has "
+ numberString.length() + ".";
default:
return null; // all types checked, doesn't happen
}
}
|
diff --git a/paul/src/main/java/au/edu/uq/cmm/paul/status/FacilityStatusManager.java b/paul/src/main/java/au/edu/uq/cmm/paul/status/FacilityStatusManager.java
index 843ef6c..3ed787f 100644
--- a/paul/src/main/java/au/edu/uq/cmm/paul/status/FacilityStatusManager.java
+++ b/paul/src/main/java/au/edu/uq/cmm/paul/status/FacilityStatusManager.java
@@ -1,321 +1,321 @@
/*
* Copyright 2012, CMM, University of Queensland.
*
* This file is part of Paul.
*
* Paul is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Paul 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Paul. If not, see <http://www.gnu.org/licenses/>.
*/
package au.edu.uq.cmm.paul.status;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.NoResultException;
import javax.persistence.TypedQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import au.edu.uq.cmm.aclslib.proxy.AclsAuthenticationException;
import au.edu.uq.cmm.aclslib.proxy.AclsHelper;
import au.edu.uq.cmm.aclslib.proxy.AclsInUseException;
import au.edu.uq.cmm.eccles.FacilitySession;
import au.edu.uq.cmm.paul.Paul;
import au.edu.uq.cmm.paul.PaulException;
import au.edu.uq.cmm.paul.grabber.FileGrabber;
/**
* This class represents the session state of the facilities as
* captured by the ACLS proxy.
*
* @author scrawley
*/
public class FacilityStatusManager {
public enum Status {
ON, DISABLED, OFF
}
public static class FacilityStatus {
private final Long facilityId;
private Status status;
private String message;
private File localDirectory;
private FileGrabber fileGrabber;
public FacilityStatus(Long facilityId, Status status, String message) {
super();
this.facilityId = facilityId;
this.status = status;
this.message = message;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Long getFacilityId() {
return facilityId;
}
public FileGrabber getFileGrabber() {
return this.fileGrabber;
}
public void setFileGrabber(FileGrabber fileGrabber) {
this.fileGrabber = fileGrabber;
}
public File getLocalDirectory() {
return localDirectory;
}
public void setLocalDirectory(File localDirectory) {
this.localDirectory = localDirectory;
}
@Override
public String toString() {
return "FacilityStatus [facilityId=" + facilityId + ", status="
+ status + ", message=" + message + "]";
}
}
private static final Logger LOG = LoggerFactory.getLogger(FileGrabber.class);
// FIXME - the facility statuses need to be persisted.
private EntityManagerFactory emf;
private AclsHelper aclsHelper;
private Map<Long, FacilityStatus> facilityStatuses =
new HashMap<Long, FacilityStatus>();
public FacilityStatusManager(Paul services) {
this.emf = services.getEntityManagerFactory();
this.aclsHelper = services.getAclsHelper();
}
private Facility getFacility(EntityManager em, String facilityName) {
TypedQuery<Facility> query = em.createQuery(
"from Facility f where f.facilityName = :facilityName", Facility.class);
query.setParameter("facilityName", facilityName);
List<Facility> res = query.getResultList();
if (res.size() == 0) {
return null;
} else if (res.size() == 1) {
return res.get(0);
} else {
throw new PaulException("Duplicate facility entries");
}
}
public List<FacilitySession> sessionsForFacility(String facilityName) {
EntityManager em = emf.createEntityManager();
try {
TypedQuery<FacilitySession> query = em.createQuery(
"from FacilitySession s where s.facilityName = :facilityName " +
"order by s.loginTime desc", FacilitySession.class);
query.setParameter("facilityName", facilityName);
return query.getResultList();
} finally {
em.close();
}
}
public FacilityStatus getStatus(Facility facility) {
FacilityStatus status = facilityStatuses.get(facility.getId());
if (status == null) {
status = new FacilityStatus(facility.getId(),
facility.isDisabled() ? Status.DISABLED : Status.OFF, "");
facilityStatuses.put(facility.getId(), status);
}
return status;
}
public void attachStatus(Facility facility) {
FacilityStatus status = getStatus(facility);
if (status.getStatus() == Status.OFF && facility.isDisabled()) {
status.setStatus(Status.DISABLED);
} else if (status.getStatus() == Status.DISABLED && !facility.isDisabled()) {
status.setStatus(Status.OFF);
}
facility.setStatus(status);
}
public List<FacilitySession> getLatestSessions() {
EntityManager em = emf.createEntityManager();
try {
em.getTransaction().begin();
TypedQuery<String> query0 = em.createQuery(
"select f.facilityName from Facility f order by f.facilityName", String.class);
List<String> facilityNames = query0.getResultList();
List<FacilitySession> sessions = new ArrayList<FacilitySession>(facilityNames.size());
for (String facilityName : facilityNames) {
FacilitySession session = latestSession(em, facilityName);
if (session == null) {
session = new FacilitySession(facilityName);
}
sessions.add(session);
}
em.getTransaction().rollback();
return sessions;
} finally {
em.close();
}
}
public FacilitySession getLoginDetails(String facilityName, long timestamp) {
EntityManager em = emf.createEntityManager();
try {
// First, we select the sessions that potentially contain this timestamp.
// These start at or before the timestamp and either end after it, or don't end.
// We want the last of these ... so sort descending on start time.
TypedQuery<FacilitySession> query = em.createQuery(
"from FacilitySession s where s.facilityName = :facilityName " +
"and s.loginTime <= :timestamp " +
"and (s.logoutTime is null or s.logoutTime >= :timestamp) " +
"order by s.loginTime desc", FacilitySession.class);
query.setParameter("facilityName", facilityName);
query.setParameter("timestamp", new Date(timestamp));
query.setMaxResults(1);
List<FacilitySession> list = query.getResultList();
if (list.size() == 0) {
LOG.debug("No session on '" + facilityName + "' matches timestamp " + timestamp);
return null;
}
FacilitySession session = list.get(0);
if (session.getLogoutTime() == null) {
// If we have a session with no definite end, we need to infer an
// end point from the start of the next session, if any.
LOG.debug("Inferring session end ...");
TypedQuery<FacilitySession> query2 = em.createQuery(
"from FacilitySession s where s.facilityName = :facilityName " +
"and s.loginTime > :timestamp " +
"order by s.loginTime asc", FacilitySession.class);
query2.setParameter("facilityName", facilityName);
query2.setParameter("timestamp", session.getLoginTime());
query2.setMaxResults(1);
list = query2.getResultList();
if (list.size() > 0) {
FacilitySession session2 = list.get(0);
if (session2.getLoginTime().getTime() < timestamp) {
LOG.debug("No session on '" + facilityName +
"' matches timestamp " + timestamp + " (2)");
return null;
}
}
}
LOG.debug("Session for timestamp " + timestamp + " is " + session);
- return list.get(0);
+ return session;
} finally {
em.close();
}
}
public void logoutSession(String sessionUuid) throws AclsAuthenticationException {
EntityManager em = emf.createEntityManager();
try {
em.getTransaction().begin();
TypedQuery<FacilitySession> query = em.createQuery(
"from FacilitySession s where s.sessionUuid = :uuid",
FacilitySession.class);
query.setParameter("uuid", sessionUuid);
FacilitySession session = query.getSingleResult();
if (session.getLogoutTime() == null) {
session.setLogoutTime(new Date());
}
aclsHelper.logout(getFacility(em, session.getFacilityName()), session.getUserName(),
session.getAccount());
em.getTransaction().commit();
} catch (NoResultException ex) {
LOG.debug("session doesn't exist", ex);
} finally {
em.close();
}
}
public void logoutFacility(String facilityName) throws AclsAuthenticationException {
EntityManager em = emf.createEntityManager();
try {
em.getTransaction().begin();
FacilitySession session = latestSession(em, facilityName);
if (session != null) {
aclsHelper.logout(getFacility(em, facilityName),
session.getUserName(), session.getAccount());
em.getTransaction().commit();
} else {
em.getTransaction().rollback();
}
} finally {
em.close();
}
}
private FacilitySession latestSession(EntityManager em, String facilityName) {
TypedQuery<FacilitySession> query = em.createQuery(
"from FacilitySession s where s.facilityName = :facilityName " +
"order by s.loginTime desc", FacilitySession.class);
query.setParameter("facilityName", facilityName);
query.setMaxResults(1);
List<FacilitySession> results = query.getResultList();
return (results.isEmpty()) ? null : results.get(0);
}
public List<String> login(String facilityName, String userName, String password)
throws AclsAuthenticationException, AclsInUseException {
Facility facility = lookupIdleFacility(facilityName);
return aclsHelper.login(facility, userName, password);
}
public void selectAccount (String facilityName, String userName, String account)
throws AclsAuthenticationException, AclsInUseException {
Facility facility = lookupIdleFacility(facilityName);
aclsHelper.selectAccount(facility, userName, account);
}
private Facility lookupIdleFacility(String facilityName)
throws AclsAuthenticationException, AclsInUseException {
Facility facility;
EntityManager em = emf.createEntityManager();
try {
FacilitySession session = latestSession(em, facilityName);
if (session != null && session.getLogoutTime() == null) {
throw new AclsInUseException(facilityName, session.getUserName());
}
facility = getFacility(em, facilityName);
if (facility == null) {
throw new AclsAuthenticationException("Unknown facility " + facilityName);
}
return facility;
} finally {
em.close();
}
}
}
| true | true | public FacilitySession getLoginDetails(String facilityName, long timestamp) {
EntityManager em = emf.createEntityManager();
try {
// First, we select the sessions that potentially contain this timestamp.
// These start at or before the timestamp and either end after it, or don't end.
// We want the last of these ... so sort descending on start time.
TypedQuery<FacilitySession> query = em.createQuery(
"from FacilitySession s where s.facilityName = :facilityName " +
"and s.loginTime <= :timestamp " +
"and (s.logoutTime is null or s.logoutTime >= :timestamp) " +
"order by s.loginTime desc", FacilitySession.class);
query.setParameter("facilityName", facilityName);
query.setParameter("timestamp", new Date(timestamp));
query.setMaxResults(1);
List<FacilitySession> list = query.getResultList();
if (list.size() == 0) {
LOG.debug("No session on '" + facilityName + "' matches timestamp " + timestamp);
return null;
}
FacilitySession session = list.get(0);
if (session.getLogoutTime() == null) {
// If we have a session with no definite end, we need to infer an
// end point from the start of the next session, if any.
LOG.debug("Inferring session end ...");
TypedQuery<FacilitySession> query2 = em.createQuery(
"from FacilitySession s where s.facilityName = :facilityName " +
"and s.loginTime > :timestamp " +
"order by s.loginTime asc", FacilitySession.class);
query2.setParameter("facilityName", facilityName);
query2.setParameter("timestamp", session.getLoginTime());
query2.setMaxResults(1);
list = query2.getResultList();
if (list.size() > 0) {
FacilitySession session2 = list.get(0);
if (session2.getLoginTime().getTime() < timestamp) {
LOG.debug("No session on '" + facilityName +
"' matches timestamp " + timestamp + " (2)");
return null;
}
}
}
LOG.debug("Session for timestamp " + timestamp + " is " + session);
return list.get(0);
} finally {
em.close();
}
}
| public FacilitySession getLoginDetails(String facilityName, long timestamp) {
EntityManager em = emf.createEntityManager();
try {
// First, we select the sessions that potentially contain this timestamp.
// These start at or before the timestamp and either end after it, or don't end.
// We want the last of these ... so sort descending on start time.
TypedQuery<FacilitySession> query = em.createQuery(
"from FacilitySession s where s.facilityName = :facilityName " +
"and s.loginTime <= :timestamp " +
"and (s.logoutTime is null or s.logoutTime >= :timestamp) " +
"order by s.loginTime desc", FacilitySession.class);
query.setParameter("facilityName", facilityName);
query.setParameter("timestamp", new Date(timestamp));
query.setMaxResults(1);
List<FacilitySession> list = query.getResultList();
if (list.size() == 0) {
LOG.debug("No session on '" + facilityName + "' matches timestamp " + timestamp);
return null;
}
FacilitySession session = list.get(0);
if (session.getLogoutTime() == null) {
// If we have a session with no definite end, we need to infer an
// end point from the start of the next session, if any.
LOG.debug("Inferring session end ...");
TypedQuery<FacilitySession> query2 = em.createQuery(
"from FacilitySession s where s.facilityName = :facilityName " +
"and s.loginTime > :timestamp " +
"order by s.loginTime asc", FacilitySession.class);
query2.setParameter("facilityName", facilityName);
query2.setParameter("timestamp", session.getLoginTime());
query2.setMaxResults(1);
list = query2.getResultList();
if (list.size() > 0) {
FacilitySession session2 = list.get(0);
if (session2.getLoginTime().getTime() < timestamp) {
LOG.debug("No session on '" + facilityName +
"' matches timestamp " + timestamp + " (2)");
return null;
}
}
}
LOG.debug("Session for timestamp " + timestamp + " is " + session);
return session;
} finally {
em.close();
}
}
|
diff --git a/src/vooga/rts/state/GameState.java b/src/vooga/rts/state/GameState.java
index db45c896..25030a6e 100644
--- a/src/vooga/rts/state/GameState.java
+++ b/src/vooga/rts/state/GameState.java
@@ -1,273 +1,273 @@
package vooga.rts.state;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Observer;
import vooga.rts.action.InteractiveAction;
import vooga.rts.commands.Command;
import vooga.rts.commands.DragCommand;
import vooga.rts.controller.Controller;
import vooga.rts.gamedesign.sprite.gamesprites.Projectile;
import vooga.rts.gamedesign.sprite.gamesprites.Resource;
import vooga.rts.gamedesign.sprite.gamesprites.interactive.InteractiveEntity;
import vooga.rts.gamedesign.sprite.gamesprites.interactive.buildings.Building;
import vooga.rts.gamedesign.sprite.gamesprites.interactive.buildings.Garrison;
import vooga.rts.gamedesign.sprite.gamesprites.interactive.units.Soldier;
import vooga.rts.gamedesign.sprite.gamesprites.interactive.units.Unit;
import vooga.rts.gamedesign.sprite.gamesprites.interactive.units.Worker;
import vooga.rts.gamedesign.state.DetectableState;
import vooga.rts.gamedesign.strategy.production.CanProduce;
import vooga.rts.gamedesign.weapon.Weapon;
import vooga.rts.gui.menus.GameMenu;
import vooga.rts.map.GameMap;
import vooga.rts.player.HumanPlayer;
import vooga.rts.player.Player;
import vooga.rts.player.Team;
import vooga.rts.resourcemanager.ResourceManager;
import vooga.rts.util.Camera;
import vooga.rts.util.DelayedTask;
import vooga.rts.util.FrameCounter;
import vooga.rts.util.Information;
import vooga.rts.util.Location;
import vooga.rts.util.Location3D;
import vooga.rts.util.Pixmap;
import vooga.rts.util.PointTester;
/**
* The main model of the game. This keeps track of all the players, the
* humanplayer associated with the local game, plus the map.
*
* @author Challen Herzberg-Brovold
*
*/
public class GameState extends SubState implements Controller {
private final static int DEFAULT_NODE_SIZE = 8;
private Map<Integer, Team> myTeams;
private static GameMap myMap;
private HumanPlayer myHumanPlayer;
private List<Player> myPlayers;
// private Resource r;
// private Building building;
// private UpgradeBuilding upgradeBuilding;
private PointTester pt;
private FrameCounter myFrames;
private Rectangle2D myDrag;
private Resource r;
public GameState(Observer observer) {
super(observer);
myTeams = new HashMap<Integer, Team>();
myPlayers = new ArrayList<Player>();
// myMap = new GameMap(8, new Dimension(512, 512));
pt = new PointTester();
myFrames = new FrameCounter(new Location(100, 20));
setupGame();
}
@Override
public void update(double elapsedTime) {
myMap.update(elapsedTime);
for (Player p : myPlayers) {
p.update(elapsedTime);
}
yuckyUnitUpdate(elapsedTime);
myFrames.update(elapsedTime);
}
@Override
public void paint(Graphics2D pen) {
pen.setBackground(Color.BLACK);
myMap.paint(pen);
r.paint(pen);
// a bit odd, but we need to paint the other players before we paint
// HumanPlayer because
// HumanPlayer contains the gameMenu
for (Player p : myPlayers) {
if (!(p instanceof HumanPlayer)) {
p.paint(pen);
}
}
myHumanPlayer.paint(pen);
if (myDrag != null) {
pen.draw(myDrag);
// pen.draw(worldShape);
}
Camera.instance().paint(pen);
myFrames.paint(pen);
}
@Override
public void receiveCommand(Command command) {
// If it's a drag, we need to do some extra checking.
if (command instanceof DragCommand) {
myDrag = ((DragCommand) command).getScreenRectangle();
if (myDrag == null) {
return;
}
}
sendCommand(command);
}
@Override
public void sendCommand(Command command) {
myHumanPlayer.sendCommand(command);
}
/**
* Adds a player to the game
*
* @param player
* to add
* @param teamID
* of the player.
*/
public void addPlayer(Player player, int teamID) {
myPlayers.add(player);
if (myTeams.get(teamID) == null) {
addTeam(teamID);
}
myTeams.get(teamID).addPlayer(player);
}
public void addTeam(int teamID) {
myTeams.put(teamID, new Team(teamID));
}
public void addPlayer(int teamID) {
Player result;
if (myPlayers.size() == 0) {
myHumanPlayer = new HumanPlayer(teamID);
result = myHumanPlayer;
} else {
result = new Player(teamID);
}
addPlayer(result, teamID);
}
private DelayedTask test;
private DelayedTask occupyPukingTest;
public void setupGame() {
addPlayer(1);
Unit worker = new Worker(new Pixmap(ResourceManager.getInstance()
.<BufferedImage> getFile("images/scv.gif", BufferedImage.class)),
new Location3D(100, 100, 0), new Dimension(75, 75), null, 1,
200, 40, 5);
Information i1 = new Information("Worker", "I am a worker. I am sent down from Denethor, son of Ecthelion ", null, "images/scv.png");
worker.setInfo(i1);
myHumanPlayer.add(worker);
Unit a = new Soldier();
Projectile proj = new Projectile(new Pixmap(ResourceManager
.getInstance().<BufferedImage> getFile("images/bullet.png",
BufferedImage.class)), a.getWorldLocation(),
new Dimension(30, 30), 2, 10, 6);
a.getAttackStrategy().addWeapons(
new Weapon(proj, 400, a.getWorldLocation(), 1));
Information i2 = new Information("Marine", "I am a soldier of Nunu.", null, "buttons/marine.png");
- worker.setInfo(i1);
+ a.setInfo(i2);
myHumanPlayer.add(a);
addPlayer(2);
Unit c = new Soldier(new Location3D(1200, 500, 0), 2);
c.setHealth(150);
// myHumanPlayer.add(c);
myPlayers.get(1).add(c);
Building b = new Building(new Pixmap(ResourceManager.getInstance()
.<BufferedImage> getFile("images/factory.png", BufferedImage.class)),
new Location3D(700, 700, 0), new Dimension(100, 100), null, 1,
300, InteractiveEntity.DEFAULT_BUILD_TIME);
b.setProductionStrategy(new CanProduce());
((CanProduce) b.getProductionStrategy()).addProducable(new Soldier());
((CanProduce) b.getProductionStrategy()).createProductionActions(b);
((CanProduce) b.getProductionStrategy()).setRallyPoint(new Location3D(
600, 500, 0));
- Information i = new Information("Barracks", "This is a barracks that can make awesome pies", null, "images/barracks.png");
+ Information i = new Information("Barracks", "This is a barracks that can make awesome pies", null, "buttons/marine.png");
b.setInfo(i);
System.out.println(b.getInfo().getName());
myHumanPlayer.add(b);
Garrison garrison = new Garrison(new Pixmap(ResourceManager
.getInstance().<BufferedImage> getFile("images/barracks.jpeg",
BufferedImage.class)), new Location3D(300, 300, 0),
new Dimension(100, 100), null, 1, 300,
InteractiveEntity.DEFAULT_BUILD_TIME);
garrison.getOccupyStrategy().addValidClassType(new Soldier());
garrison.getOccupyStrategy().createOccupyActions(garrison);
myHumanPlayer.add(garrison);
myMap = new GameMap(8, new Dimension(512, 512));
r = new Resource(new Pixmap(ResourceManager.getInstance()
.<BufferedImage> getFile("images/mineral.gif", BufferedImage.class)),
new Location3D(200, 300, 0), new Dimension(50, 50), 0, 200,
"mineral");
final Building f = b;
test = new DelayedTask(3, new Runnable() {
@Override
public void run() {
f.getAction((new Command("I am a pony"))).apply();
test.restart();
}
});
final Garrison testGarrison = garrison;
occupyPukingTest = new DelayedTask(10, new Runnable() {
@Override
public void run() {
if (testGarrison.getOccupyStrategy().getOccupiers().size() > 0) {
System.out.println("will puke!");
testGarrison.getAction(new Command("deoccupy")).apply();
}
occupyPukingTest.restart();
}
});
}
private void yuckyUnitUpdate(double elapsedTime) {
List<InteractiveEntity> p1 = myTeams.get(1).getUnits();
List<InteractiveEntity> p2 = myTeams.get(2).getUnits();
for (InteractiveEntity u1 : p1) {
if (u1 instanceof Worker && r != null) {
((Worker) u1).gather(r);
}
for (InteractiveEntity u2 : p2) {
u2.getAttacked(u1);
u1.getAttacked(u2);
}
}
r.update(elapsedTime);
// }
test.update(elapsedTime);
// now even yuckier
for (int i = 0; i < p1.size(); ++i) {
if (p1.get(i) instanceof Unit) {
for (int j = i + 1; j < p1.size(); ++j) {
((Unit) p1.get(i)).occupy(p1.get(j));
}
}
}
occupyPukingTest.update(elapsedTime);
}
public static GameMap getMap() {
return myMap;
}
}
| false | true | public void setupGame() {
addPlayer(1);
Unit worker = new Worker(new Pixmap(ResourceManager.getInstance()
.<BufferedImage> getFile("images/scv.gif", BufferedImage.class)),
new Location3D(100, 100, 0), new Dimension(75, 75), null, 1,
200, 40, 5);
Information i1 = new Information("Worker", "I am a worker. I am sent down from Denethor, son of Ecthelion ", null, "images/scv.png");
worker.setInfo(i1);
myHumanPlayer.add(worker);
Unit a = new Soldier();
Projectile proj = new Projectile(new Pixmap(ResourceManager
.getInstance().<BufferedImage> getFile("images/bullet.png",
BufferedImage.class)), a.getWorldLocation(),
new Dimension(30, 30), 2, 10, 6);
a.getAttackStrategy().addWeapons(
new Weapon(proj, 400, a.getWorldLocation(), 1));
Information i2 = new Information("Marine", "I am a soldier of Nunu.", null, "buttons/marine.png");
worker.setInfo(i1);
myHumanPlayer.add(a);
addPlayer(2);
Unit c = new Soldier(new Location3D(1200, 500, 0), 2);
c.setHealth(150);
// myHumanPlayer.add(c);
myPlayers.get(1).add(c);
Building b = new Building(new Pixmap(ResourceManager.getInstance()
.<BufferedImage> getFile("images/factory.png", BufferedImage.class)),
new Location3D(700, 700, 0), new Dimension(100, 100), null, 1,
300, InteractiveEntity.DEFAULT_BUILD_TIME);
b.setProductionStrategy(new CanProduce());
((CanProduce) b.getProductionStrategy()).addProducable(new Soldier());
((CanProduce) b.getProductionStrategy()).createProductionActions(b);
((CanProduce) b.getProductionStrategy()).setRallyPoint(new Location3D(
600, 500, 0));
Information i = new Information("Barracks", "This is a barracks that can make awesome pies", null, "images/barracks.png");
b.setInfo(i);
System.out.println(b.getInfo().getName());
myHumanPlayer.add(b);
Garrison garrison = new Garrison(new Pixmap(ResourceManager
.getInstance().<BufferedImage> getFile("images/barracks.jpeg",
BufferedImage.class)), new Location3D(300, 300, 0),
new Dimension(100, 100), null, 1, 300,
InteractiveEntity.DEFAULT_BUILD_TIME);
garrison.getOccupyStrategy().addValidClassType(new Soldier());
garrison.getOccupyStrategy().createOccupyActions(garrison);
myHumanPlayer.add(garrison);
myMap = new GameMap(8, new Dimension(512, 512));
r = new Resource(new Pixmap(ResourceManager.getInstance()
.<BufferedImage> getFile("images/mineral.gif", BufferedImage.class)),
new Location3D(200, 300, 0), new Dimension(50, 50), 0, 200,
"mineral");
final Building f = b;
test = new DelayedTask(3, new Runnable() {
@Override
public void run() {
f.getAction((new Command("I am a pony"))).apply();
test.restart();
}
});
final Garrison testGarrison = garrison;
occupyPukingTest = new DelayedTask(10, new Runnable() {
@Override
public void run() {
if (testGarrison.getOccupyStrategy().getOccupiers().size() > 0) {
System.out.println("will puke!");
testGarrison.getAction(new Command("deoccupy")).apply();
}
occupyPukingTest.restart();
}
});
}
| public void setupGame() {
addPlayer(1);
Unit worker = new Worker(new Pixmap(ResourceManager.getInstance()
.<BufferedImage> getFile("images/scv.gif", BufferedImage.class)),
new Location3D(100, 100, 0), new Dimension(75, 75), null, 1,
200, 40, 5);
Information i1 = new Information("Worker", "I am a worker. I am sent down from Denethor, son of Ecthelion ", null, "images/scv.png");
worker.setInfo(i1);
myHumanPlayer.add(worker);
Unit a = new Soldier();
Projectile proj = new Projectile(new Pixmap(ResourceManager
.getInstance().<BufferedImage> getFile("images/bullet.png",
BufferedImage.class)), a.getWorldLocation(),
new Dimension(30, 30), 2, 10, 6);
a.getAttackStrategy().addWeapons(
new Weapon(proj, 400, a.getWorldLocation(), 1));
Information i2 = new Information("Marine", "I am a soldier of Nunu.", null, "buttons/marine.png");
a.setInfo(i2);
myHumanPlayer.add(a);
addPlayer(2);
Unit c = new Soldier(new Location3D(1200, 500, 0), 2);
c.setHealth(150);
// myHumanPlayer.add(c);
myPlayers.get(1).add(c);
Building b = new Building(new Pixmap(ResourceManager.getInstance()
.<BufferedImage> getFile("images/factory.png", BufferedImage.class)),
new Location3D(700, 700, 0), new Dimension(100, 100), null, 1,
300, InteractiveEntity.DEFAULT_BUILD_TIME);
b.setProductionStrategy(new CanProduce());
((CanProduce) b.getProductionStrategy()).addProducable(new Soldier());
((CanProduce) b.getProductionStrategy()).createProductionActions(b);
((CanProduce) b.getProductionStrategy()).setRallyPoint(new Location3D(
600, 500, 0));
Information i = new Information("Barracks", "This is a barracks that can make awesome pies", null, "buttons/marine.png");
b.setInfo(i);
System.out.println(b.getInfo().getName());
myHumanPlayer.add(b);
Garrison garrison = new Garrison(new Pixmap(ResourceManager
.getInstance().<BufferedImage> getFile("images/barracks.jpeg",
BufferedImage.class)), new Location3D(300, 300, 0),
new Dimension(100, 100), null, 1, 300,
InteractiveEntity.DEFAULT_BUILD_TIME);
garrison.getOccupyStrategy().addValidClassType(new Soldier());
garrison.getOccupyStrategy().createOccupyActions(garrison);
myHumanPlayer.add(garrison);
myMap = new GameMap(8, new Dimension(512, 512));
r = new Resource(new Pixmap(ResourceManager.getInstance()
.<BufferedImage> getFile("images/mineral.gif", BufferedImage.class)),
new Location3D(200, 300, 0), new Dimension(50, 50), 0, 200,
"mineral");
final Building f = b;
test = new DelayedTask(3, new Runnable() {
@Override
public void run() {
f.getAction((new Command("I am a pony"))).apply();
test.restart();
}
});
final Garrison testGarrison = garrison;
occupyPukingTest = new DelayedTask(10, new Runnable() {
@Override
public void run() {
if (testGarrison.getOccupyStrategy().getOccupiers().size() > 0) {
System.out.println("will puke!");
testGarrison.getAction(new Command("deoccupy")).apply();
}
occupyPukingTest.restart();
}
});
}
|
diff --git a/flexodesktop/GUI/flexo/src/main/java/org/openflexo/FlexoProperties.java b/flexodesktop/GUI/flexo/src/main/java/org/openflexo/FlexoProperties.java
index 78062e3f0..832a5cd29 100644
--- a/flexodesktop/GUI/flexo/src/main/java/org/openflexo/FlexoProperties.java
+++ b/flexodesktop/GUI/flexo/src/main/java/org/openflexo/FlexoProperties.java
@@ -1,206 +1,206 @@
/*
* (c) Copyright 2010-2011 AgileBirds
*
* This file is part of OpenFlexo.
*
* OpenFlexo is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenFlexo 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenFlexo. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.openflexo;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;
import org.openflexo.toolbox.FileResource;
import org.openflexo.view.controller.FlexoController;
import org.openflexo.view.controller.ScenarioRecorder;
/**
* This class is intended to model preferences of OpenFlexo application<br>
* To be accessed through all the application, all methods are statically defined.
*
* @author sguerin
*/
public class FlexoProperties {
public static final String ALLOWSDOCSUBMISSION = "allowsDocSubmission";
public static final String LOGCOUNT = "logCount";
public static final String KEEPLOGTRACE = "keepLogTrace";
public static final String DEFAULT_LOG_LEVEL = "default.logging.level";
public static final String CUSTOM_LOG_CONFIG_FILE = "logging.file.name";
public static final String FLEXO_SERVER_INSTANCE_URL = "flexoserver_instance_url";
public static final String BUG_REPORT_USER = "bug_report_user";
public static final String BUG_REPORT_PASWORD = "bug_report_password";
private static FlexoProperties _instance;
private Properties applicationProperties = null;
protected FlexoProperties(File preferencesFile) {
super();
applicationProperties = new Properties();
try {
applicationProperties.load(new FileInputStream(preferencesFile));
} catch (FileNotFoundException e) {
FlexoController.showError("Cannot find configuration file : " + preferencesFile.getAbsolutePath());
System.exit(0);
} catch (IOException e) {
FlexoController.showError("Cannot read configuration file : " + preferencesFile.getAbsolutePath());
System.exit(0);
}
ScenarioRecorder.ENABLE = "true".equals(applicationProperties.getProperty("record"));
setIsLoggingTrace(isLoggingTrace());
setMaxLogCount(getMaxLogCount());
setDefaultLoggingLevel(getDefaultLoggingLevel());
System.setProperty("java.util.logging.config.file", new FileResource("Config/logging.properties").getAbsolutePath());
if (applicationProperties.getProperty(DEFAULT_LOG_LEVEL) != null) {
System.setProperty("java.util.logging.config.file",
new FileResource("Config/logging_" + applicationProperties.getProperty(DEFAULT_LOG_LEVEL) + ".properties")
.getAbsolutePath());
}
if (applicationProperties.getProperty(CUSTOM_LOG_CONFIG_FILE) != null) {
System.setProperty("java.util.logging.config.file",
new File(applicationProperties.getProperty(CUSTOM_LOG_CONFIG_FILE)).getAbsolutePath());
}
}
public String getApplicationProperty(String property) {
return applicationProperties.getProperty(property);
}
public void setApplicationProperty(String property, String value) {
applicationProperties.setProperty(property, value);
}
public boolean isLoggingTrace() {
return "true".equals(applicationProperties.getProperty(KEEPLOGTRACE));
}
public String getLoggingFileName() {
return applicationProperties.getProperty(CUSTOM_LOG_CONFIG_FILE);
}
public void setLoggingFileName(String loggingFileName) {
if (loggingFileName != null) {
applicationProperties.setProperty(CUSTOM_LOG_CONFIG_FILE, loggingFileName);
} else {
applicationProperties.remove(CUSTOM_LOG_CONFIG_FILE);
}
}
public File getCustomLoggingFile() {
if (getLoggingFileName() == null) {
return null;
}
return new File(getLoggingFileName());
}
public Level getDefaultLoggingLevel() {
String returned = applicationProperties.getProperty(DEFAULT_LOG_LEVEL);
if (returned == null) {
return null;
} else if (returned.equals("SEVERE")) {
return Level.SEVERE;
} else if (returned.equals("WARNING")) {
return Level.WARNING;
} else if (returned.equals("INFO")) {
return Level.INFO;
} else if (returned.equals("FINE")) {
return Level.FINE;
} else if (returned.equals("FINER")) {
return Level.FINER;
} else if (returned.equals("FINEST")) {
return Level.FINEST;
}
return null;
}
public void setDefaultLoggingLevel(Level l) {
applicationProperties.setProperty(DEFAULT_LOG_LEVEL, l.getName());
}
public boolean getIsLoggingTrace() {
return applicationProperties.getProperty(KEEPLOGTRACE).equalsIgnoreCase("true");
}
public void setIsLoggingTrace(boolean b) {
applicationProperties.setProperty(KEEPLOGTRACE, b ? "true" : "false");
}
public int getMaxLogCount() {
return applicationProperties.getProperty(LOGCOUNT) == null ? 0 : Integer.valueOf(applicationProperties.getProperty(LOGCOUNT));
}
public void setMaxLogCount(int c) {
applicationProperties.setProperty(LOGCOUNT, String.valueOf(c));
}
public boolean getAllowsDocSubmission() {
return "true".equals(applicationProperties.getProperty(ALLOWSDOCSUBMISSION));
}
public void setAllowsDocSubmission(boolean b) {
applicationProperties.setProperty(ALLOWSDOCSUBMISSION, String.valueOf(b));
}
public String getBugReportPassword() {
return applicationProperties.getProperty(BUG_REPORT_PASWORD);
}
public String getBugReportUser() {
return applicationProperties.getProperty(BUG_REPORT_USER);
}
public String getFlexoServerInstanceURL() {
return applicationProperties.getProperty(FLEXO_SERVER_INSTANCE_URL);
}
public static FlexoProperties load() {
return instance();
}
public static FlexoProperties instance() {
if (_instance == null) {
_instance = new FlexoProperties(new FileResource("Config/Flexo.properties"));
if (!AdvancedPrefs.getPreferenceOverrideFromFlexoPropertiesDone()) {
boolean overrideDone = false;
if (_instance.getFlexoServerInstanceURL() != null) {
AdvancedPrefs.setFlexoServerInstanceURL(_instance.getFlexoServerInstanceURL());
overrideDone = true;
String webServiceUrl = _instance.applicationProperties.getProperty("webServiceUrl");
if (webServiceUrl != null) {
AdvancedPrefs.setWebServiceUrl(webServiceUrl);
}
}
if (_instance.getBugReportUser() != null) {
AdvancedPrefs.setBugReportUser(_instance.getBugReportUser());
overrideDone = true;
}
if (_instance.getBugReportPassword() != null) {
- AdvancedPrefs.setBugReportPassword(_instance.getBugReportPassword());
+ AdvancedPrefs.getPreferences().setProperty(AdvancedPrefs.BUG_REPORT_PASWORD, _instance.getBugReportPassword());
overrideDone = true;
}
if (overrideDone) {
AdvancedPrefs.setPreferenceOverrideFromFlexoPropertiesDone(true);
AdvancedPrefs.save();
}
}
}
return _instance;
}
}
| true | true | public static FlexoProperties instance() {
if (_instance == null) {
_instance = new FlexoProperties(new FileResource("Config/Flexo.properties"));
if (!AdvancedPrefs.getPreferenceOverrideFromFlexoPropertiesDone()) {
boolean overrideDone = false;
if (_instance.getFlexoServerInstanceURL() != null) {
AdvancedPrefs.setFlexoServerInstanceURL(_instance.getFlexoServerInstanceURL());
overrideDone = true;
String webServiceUrl = _instance.applicationProperties.getProperty("webServiceUrl");
if (webServiceUrl != null) {
AdvancedPrefs.setWebServiceUrl(webServiceUrl);
}
}
if (_instance.getBugReportUser() != null) {
AdvancedPrefs.setBugReportUser(_instance.getBugReportUser());
overrideDone = true;
}
if (_instance.getBugReportPassword() != null) {
AdvancedPrefs.setBugReportPassword(_instance.getBugReportPassword());
overrideDone = true;
}
if (overrideDone) {
AdvancedPrefs.setPreferenceOverrideFromFlexoPropertiesDone(true);
AdvancedPrefs.save();
}
}
}
return _instance;
}
| public static FlexoProperties instance() {
if (_instance == null) {
_instance = new FlexoProperties(new FileResource("Config/Flexo.properties"));
if (!AdvancedPrefs.getPreferenceOverrideFromFlexoPropertiesDone()) {
boolean overrideDone = false;
if (_instance.getFlexoServerInstanceURL() != null) {
AdvancedPrefs.setFlexoServerInstanceURL(_instance.getFlexoServerInstanceURL());
overrideDone = true;
String webServiceUrl = _instance.applicationProperties.getProperty("webServiceUrl");
if (webServiceUrl != null) {
AdvancedPrefs.setWebServiceUrl(webServiceUrl);
}
}
if (_instance.getBugReportUser() != null) {
AdvancedPrefs.setBugReportUser(_instance.getBugReportUser());
overrideDone = true;
}
if (_instance.getBugReportPassword() != null) {
AdvancedPrefs.getPreferences().setProperty(AdvancedPrefs.BUG_REPORT_PASWORD, _instance.getBugReportPassword());
overrideDone = true;
}
if (overrideDone) {
AdvancedPrefs.setPreferenceOverrideFromFlexoPropertiesDone(true);
AdvancedPrefs.save();
}
}
}
return _instance;
}
|
diff --git a/iwsn/csv2config/src/main/java/de/uniluebeck/itm/tr/iwsn/csv2config/CSV2Config.java b/iwsn/csv2config/src/main/java/de/uniluebeck/itm/tr/iwsn/csv2config/CSV2Config.java
index 49ec334c..638d7a2f 100644
--- a/iwsn/csv2config/src/main/java/de/uniluebeck/itm/tr/iwsn/csv2config/CSV2Config.java
+++ b/iwsn/csv2config/src/main/java/de/uniluebeck/itm/tr/iwsn/csv2config/CSV2Config.java
@@ -1,594 +1,598 @@
package de.uniluebeck.itm.tr.iwsn.csv2config;
import au.com.bytecode.opencsv.CSVReader;
import com.google.common.base.Preconditions;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import de.uniluebeck.itm.tr.runtime.portalapp.PortalServerFactory;
import de.uniluebeck.itm.tr.runtime.portalapp.xml.Portalapp;
import de.uniluebeck.itm.tr.runtime.portalapp.xml.WebService;
import de.uniluebeck.itm.tr.runtime.wsnapp.WSNDeviceAppFactory;
import de.uniluebeck.itm.tr.runtime.wsnapp.xml.WsnDevice;
import de.uniluebeck.itm.tr.runtime.wsnapp.xml.Wsnapp;
import de.uniluebeck.itm.tr.xml.*;
import eu.wisebed.ns.wiseml._1.*;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.PosixParser;
import org.apache.log4j.*;
import org.slf4j.LoggerFactory;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.*;
import java.util.*;
public class CSV2Config {
public static final String HOSTNAME = "hostname";
public static final String NODE_ID = "node.id";
public static final String NODE_PORT = "node.port";
public static final String NODE_REFERENCE = "node.reference";
public static final String NODE_TYPE = "node.type";
public static final String NODE_GATEWAY = "node.gateway";
public static final String NODE_DESCRIPTION = "node.description";
public static final String URN_TESTBED_PREFIX = "urn.testbed.prefix";
public static final String NODE_POSITION_X = "node.position.x";
public static final String NODE_POSITION_Y = "node.position.y";
public static final String NODE_POSITION_Z = "node.position.z";
public static final String META_ROOM_NAME = "meta.room.name";
public static final String META_ROOM_NUMBER = "meta.room.number";
public static final String META_NODE_CAPABILITY_PREFIX = "node.capability.";
public static final String META_NODE_CAPABILITY_SUFFIX_URN = ".urn";
public static final String META_NODE_CAPABILITY_SUFFIX_DATATYPE = ".datatype";
public static final String META_NODE_CAPABILITY_SUFFIX_UNIT = ".unit";
public static final String META_NODE_CAPABILITY_SUFFIX_DEFAULT = ".default";
private void createWiseMLFile() throws JAXBException, IOException {
// ====== create WiseML file ======
Wiseml wiseml = new Wiseml();
wiseml.setVersion("1.0");
Setup setup = new Setup();
wiseml.setSetup(setup);
// TODO fill out default values
//setup.setCoordinateType(coordinateType);
//setup.setDefaults(defaults);
//setup.setDescription(description);
//setup.setInterpolation(interpolation);
//setup.setOrigin(origin);
//setup.setTimeinfo(timeInfo);
List<Setup.Node> nodes = setup.getNode();
CSVReader reader = new CSVReader(
new FileReader(cmdLineParameters.csvFile),
CSVReader.DEFAULT_SEPARATOR,
CSVReader.DEFAULT_QUOTE_CHARACTER,
0
);
String[] nextLine;
// detect column by looking for property names in the first line
BiMap<Integer, String> columnMap = HashBiMap.create();
if ((nextLine = reader.readNext()) != null) {
for (int column = 0; column < nextLine.length; column++) {
columnMap.put(column, nextLine[column]);
}
Preconditions.checkNotNull(columnMap.containsValue(HOSTNAME));
Preconditions.checkNotNull(columnMap.containsValue(NODE_ID));
Preconditions.checkNotNull(columnMap.containsValue(NODE_REFERENCE));
Preconditions.checkNotNull(columnMap.containsValue(NODE_PORT));
Preconditions.checkNotNull(columnMap.containsValue(NODE_TYPE));
Preconditions.checkNotNull(columnMap.containsValue(URN_TESTBED_PREFIX));
} else {
throw new RuntimeException(
"CSV file must have at least one file containing one line that defines property names for the columns"
);
}
Setup.Node node;
BiMap<String, Integer> columns = columnMap.inverse();
while ((nextLine = reader.readNext()) != null) {
node = new Setup.Node();
nodes.add(node);
node.setId(cmdLineParameters.testbedPrefix + nextLine[columns.get(NODE_ID)]);
node.setDescription(nextLine[columns.get(NODE_DESCRIPTION)]);
node.setGateway(Boolean.parseBoolean(nextLine[columns.get(NODE_GATEWAY)].toLowerCase()));
node.setNodeType(nextLine[columns.get(NODE_TYPE)]);
Coordinate position = new Coordinate();
// TODO set something sensible here
//position.setPhi(phi);
//position.setTheta(theta);
position.setX(Double.parseDouble(nextLine[columns.get(NODE_POSITION_X)].replace(',', '.')));
position.setY(Double.parseDouble(nextLine[columns.get(NODE_POSITION_Y)].replace(',', '.')));
position.setZ(Double.parseDouble(nextLine[columns.get(NODE_POSITION_Z)].replace(',', '.')));
node.setPosition(position);
Set<String> columnSet = columns.keySet();
Map<Integer, Capability> capabilityMap = new HashMap<Integer, Capability>();
for (String column : columnSet) {
if (column.startsWith(META_NODE_CAPABILITY_PREFIX)) {
int capabilityNum = Integer.parseInt(
column.substring(
META_NODE_CAPABILITY_PREFIX.length(),
column.indexOf(".", META_NODE_CAPABILITY_PREFIX.length()
)
));
Capability capability = capabilityMap.get(capabilityNum);
boolean hadData = false;
if (capability == null) {
capability = new Capability();
}
if (column.endsWith(META_NODE_CAPABILITY_SUFFIX_URN)) {
String value = nextLine[columns.get(column)];
if (value != null && !"".equals(value)) {
capability.setName(nextLine[columns.get(column)]);
hadData = true;
}
} else if (column.endsWith(META_NODE_CAPABILITY_SUFFIX_DATATYPE)) {
String value = nextLine[columns.get(column)];
if (value != null && !"".equals(value)) {
capability.setDatatype(Dtypes.fromValue(value));
hadData = true;
}
} else if (column.endsWith(META_NODE_CAPABILITY_SUFFIX_DEFAULT)) {
String value = nextLine[columns.get(column)];
if (value != null && !"".equals(value)) {
capability.setDefault(value);
hadData = true;
}
} else if (column.endsWith(META_NODE_CAPABILITY_SUFFIX_UNIT)) {
String value = nextLine[columns.get(column)];
if (value != null && !"".equals(value)) {
capability.setUnit(Units.fromValue(value));
hadData = true;
}
}
if (hadData) {
capabilityMap.put(capabilityNum, capability);
}
}
}
for (Capability capability : capabilityMap.values()) {
node.getCapability().add(capability);
}
}
JAXBContext jc = JAXBContext.newInstance(Wiseml.class);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
FileWriter writer = new FileWriter(cmdLineParameters.wisemlOutputFile.getAbsolutePath());
marshaller.marshal(wiseml, writer);
}
private PosixParser cmdLineParser;
private org.slf4j.Logger log;
private Options cmdLineOptions;
private class CmdLineParameters {
public File csvFile = null;
public String testbedPrefix = null;
public File outputFile = null;
public File wisemlOutputFile = null;
public String portalInternalAddress = null;
public String sessionmanagementendpointurl = null;
public String wsninstancebaseurl = null;
public String wisemlfilename = null;
public String portalHostname = null;
public boolean useHexValues = false;
public boolean useAutodetection = false;
public String reservationSystemEndpointURL;
}
private CmdLineParameters cmdLineParameters = new CmdLineParameters();
public static void main(String[] args) throws IOException, JAXBException {
CSV2Config csv2Config = new CSV2Config();
csv2Config.configureLoggingDefaults();
csv2Config.setUpCmdLineParameters();
csv2Config.parseCmdLineParameters(args);
csv2Config.createTRConfig();
csv2Config.createWiseMLFile();
}
private void createTRConfig() throws IOException, JAXBException {
// ====== parse CSV file ======
CSVReader reader = new CSVReader(
new FileReader(cmdLineParameters.csvFile),
CSVReader.DEFAULT_SEPARATOR,
CSVReader.DEFAULT_QUOTE_CHARACTER,
0
);
String[] nextLine;
// detect column by looking for property names in the first line
BiMap<Integer, String> columnMap = HashBiMap.create();
if ((nextLine = reader.readNext()) != null) {
for (int column = 0; column < nextLine.length; column++) {
columnMap.put(column, nextLine[column]);
}
Preconditions.checkNotNull(columnMap.containsValue(HOSTNAME));
Preconditions.checkNotNull(columnMap.containsValue(NODE_ID));
Preconditions.checkNotNull(columnMap.containsValue(NODE_REFERENCE));
Preconditions.checkNotNull(columnMap.containsValue(NODE_PORT));
Preconditions.checkNotNull(columnMap.containsValue(NODE_TYPE));
Preconditions.checkNotNull(columnMap.containsValue(URN_TESTBED_PREFIX));
} else {
throw new RuntimeException(
"CSV file must have at least one file containing one line that defines property names for the columns"
);
}
Testbed testbed = new Testbed();
// ====== create configuration for portal server ======
Node portalNode = new Node();
portalNode.setId(cmdLineParameters.portalHostname);
NodeNames portalNodeNames = new NodeNames();
NodeName portalNodeName = new NodeName();
portalNodeName.setName(cmdLineParameters.portalHostname);
portalNodeNames.getNodename().add(portalNodeName);
portalNode.setNames(portalNodeNames);
ServerConnections portalServerConnections = new ServerConnections();
ServerConnection portalServerConnection = new ServerConnection();
portalServerConnection.setAddress(cmdLineParameters.portalInternalAddress);
portalServerConnection.setType("tcp");
portalServerConnections.getServerconnection().add(portalServerConnection);
portalNode.setServerconnections(portalServerConnections);
Applications portalApplications = new Applications();
Application portalApplication = new Application();
portalApplication.setName("Portal");
portalApplication.setFactoryclass(PortalServerFactory.class.getCanonicalName());
Portalapp portalapp = new Portalapp();
WebService webservice = new WebService();
webservice.setReservationendpointurl(cmdLineParameters.reservationSystemEndpointURL);
webservice.setSessionmanagementendpointurl(cmdLineParameters.sessionmanagementendpointurl);
webservice.setUrnprefix(cmdLineParameters.testbedPrefix);
webservice.setWisemlfilename(cmdLineParameters.wisemlfilename);
webservice.setWsninstancebaseurl(cmdLineParameters.wsninstancebaseurl);
portalapp.setWebservice(webservice);
portalApplication.setAny(portalapp);
portalApplications.getApplication().add(portalApplication);
portalNode.setApplications(portalApplications);
testbed.getNodes().add(portalNode);
// ====== create configuration for overlay nodeMap ======
Map<String, Node> nodeMap = new HashMap<String, Node>();
Map<String, Application> applicationMap = new HashMap<String, Application>();
BiMap<String, Integer> columns = columnMap.inverse();
while ((nextLine = reader.readNext()) != null) {
// add overlay node name if not yet existing
String hostname = nextLine[columns.get(HOSTNAME)];
Node node = nodeMap.get(hostname);
if (node == null) {
node = new Node();
node.setId(hostname);
nodeMap.put(hostname, node);
ServerConnection serverConnection = new ServerConnection();
serverConnection.setType("tcp");
serverConnection.setAddress(hostname + ":8880");
ServerConnections serverConnections = new ServerConnections();
serverConnections.getServerconnection().add(serverConnection);
node.setServerconnections(serverConnections);
testbed.getNodes().add(node);
}
// add device urn as node name to overlay node
+ String currentNodeName = nextLine[columns.get(URN_TESTBED_PREFIX)] + nextLine[columns.get(NODE_ID)];
+ NodeNames nodeNames = node.getNames();
+ if (nodeNames == null) {
+ nodeNames = new NodeNames();
+ node.setNames(nodeNames);
+ }
NodeName nodeName = new NodeName();
- nodeName.setName(nextLine[columns.get(URN_TESTBED_PREFIX)] + nextLine[columns.get(NODE_ID)]);
- NodeNames nodeNames = new NodeNames();
+ nodeName.setName(currentNodeName);
nodeNames.getNodename().add(nodeName);
- node.setNames(nodeNames);
// add WSN application if not yet existing
Application application = applicationMap.get(hostname);
if (application == null) {
application = new Application();
application.setName("WSNDeviceApp");
application.setFactoryclass(WSNDeviceAppFactory.class.getCanonicalName());
application.setAny(new Wsnapp());
Applications applications = new Applications();
applications.getApplication().add(application);
node.setApplications(applications);
applicationMap.put(hostname, application);
}
// add WSN device (current row of CSV)
WsnDevice wsnDevice = new WsnDevice();
wsnDevice.setType(nextLine[columns.get(NODE_TYPE)]);
wsnDevice.setUrn(nextLine[columns.get(URN_TESTBED_PREFIX)] + nextLine[columns.get(NODE_ID)]);
String nodePort = nextLine[columns.get(NODE_PORT)];
if (nodePort != null && !"".equals(nodePort)) {
wsnDevice.setSerialinterface(nodePort);
}
String nodeReference = nextLine[columns.get(NODE_REFERENCE)];
if (nodeReference != null && !"".equals(nodeReference)) {
wsnDevice.setUsbchipid(nodeReference);
}
Wsnapp wsnApp = (Wsnapp) application.getAny();
wsnApp.getDevice().add(wsnDevice);
}
// ====== write configuration file ======
JAXBContext jc = JAXBContext.newInstance(
Testbed.class,
Portalapp.class,
Wsnapp.class
);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
FileWriter writer = new FileWriter(cmdLineParameters.outputFile.getAbsolutePath());
marshaller.marshal(testbed, writer);
}
private void parseCmdLineParameters(String[] args) {
// ====== parse command line parameters ======
Properties properties = new Properties();
try {
CommandLine line = cmdLineParser.parse(cmdLineOptions, args);
if (line.hasOption('c')) {
String xmlFilename = line.getOptionValue('c');
cmdLineParameters.csvFile = new File(xmlFilename);
if (!cmdLineParameters.csvFile.exists()) {
throw new Exception(
"The given file name " + cmdLineParameters.csvFile.getAbsolutePath() + " does not exist!"
);
}
if (!cmdLineParameters.csvFile.canRead()) {
throw new Exception(
"The given file " + cmdLineParameters.csvFile.getAbsolutePath() + " is not readable!"
);
}
} else {
throw new Exception("Please supply -c");
}
if (line.hasOption('p')) {
properties.load(new FileInputStream(line.getOptionValue('p')));
if (properties.getProperty("urnprefix") != null) {
cmdLineParameters.testbedPrefix = properties.getProperty("urnprefix");
} else {
throw new Exception("Property file is missing the urnprefix property");
}
if (properties.getProperty("portal.hostname") != null) {
cmdLineParameters.portalHostname = properties.getProperty("portal.hostname");
cmdLineParameters.portalInternalAddress =
properties.getProperty("portal.hostname") + ":" + properties
.getProperty("portal.overlayport", "8880");
} else {
throw new Exception("Property file is missing the portal.hostname property");
}
if (properties.getProperty("portal.sessionmanagementurl") != null) {
cmdLineParameters.sessionmanagementendpointurl =
properties.getProperty("portal.sessionmanagementurl");
} else {
cmdLineParameters.sessionmanagementendpointurl =
"http://" + properties.getProperty("portal.hostname") + ":8888/sessions";
}
if (properties.getProperty("portal.wsninstancebaseurl") != null) {
cmdLineParameters.wsninstancebaseurl = properties.getProperty("portal.wsninstancebaseurl");
} else {
cmdLineParameters.wsninstancebaseurl =
"http://" + properties.getProperty("portal.hostname") + ":8888/wsn/";
}
if (properties.getProperty("portal.wisemlpath") != null) {
cmdLineParameters.wisemlfilename = properties.getProperty("portal.wisemlpath");
} else {
throw new Exception("Property file is missing the portal.wisemlpath property");
}
cmdLineParameters.useAutodetection =
Boolean.parseBoolean(properties.getProperty("mac-autodetection", "true"));
cmdLineParameters.useHexValues = Boolean.parseBoolean(properties.getProperty("hex", "true"));
cmdLineParameters.reservationSystemEndpointURL = properties.getProperty("portal.reservationsystem");
} else {
throw new Exception("Please supply -p");
}
if (line.hasOption('v')) {
Logger.getRootLogger().setLevel(Level.DEBUG);
Logger.getLogger("de.uniluebeck.itm").setLevel(Level.DEBUG);
}
if (line.hasOption('l')) {
Level level = Level.toLevel(line.getOptionValue('l'));
Logger.getRootLogger().setLevel(level);
Logger.getLogger("de.uniluebeck.itm").setLevel(level);
}
if (line.hasOption('h')) {
usage(cmdLineOptions);
}
if (line.hasOption('o')) {
String configFilename = line.getOptionValue('o');
cmdLineParameters.outputFile = new File(configFilename).getAbsoluteFile();
if (!cmdLineParameters.outputFile.exists()) {
cmdLineParameters.outputFile.getParentFile().mkdirs();
cmdLineParameters.outputFile.createNewFile();
}
if (!cmdLineParameters.outputFile.canWrite()) {
throw new Exception(
"The given file " + cmdLineParameters.outputFile.getAbsolutePath() + " is not writable!"
);
}
log.info("Using output file: {}", cmdLineParameters.outputFile.getAbsolutePath());
} else {
throw new Exception("Please supply -o");
}
if (line.hasOption('w')) {
String wisemlOutputFilename = line.getOptionValue('w');
cmdLineParameters.wisemlOutputFile = new File(wisemlOutputFilename).getAbsoluteFile();
if (!cmdLineParameters.wisemlOutputFile.exists()) {
cmdLineParameters.wisemlOutputFile.getParentFile().mkdirs();
cmdLineParameters.wisemlOutputFile.createNewFile();
}
if (!cmdLineParameters.wisemlOutputFile.canWrite()) {
throw new Exception("The given file " + cmdLineParameters.wisemlOutputFile
.getAbsolutePath() + " is not writable!"
);
}
log.info("Using WiseML output file: {}", cmdLineParameters.wisemlOutputFile.getAbsolutePath());
} else {
throw new Exception("Please supply -w");
}
} catch (Exception e) {
log.error("Invalid command line: " + e, e);
usage(cmdLineOptions);
}
}
private void configureLoggingDefaults() {
// ====== configure logging defaults ======
{
Appender appender = new ConsoleAppender(new PatternLayout("%-4r [%t] %-5p %c %x - %m%n"));
Logger itmLogger = Logger.getLogger("de.uniluebeck.itm");
if (!itmLogger.getAllAppenders().hasMoreElements()) {
itmLogger.addAppender(appender);
itmLogger.setLevel(Level.INFO);
}
}
log = LoggerFactory.getLogger(CSV2Config.class);
}
private void setUpCmdLineParameters() {
// ====== set up command line parameters ======
cmdLineParser = new PosixParser();
cmdLineOptions = new Options();
cmdLineOptions.addOption("c", "csv", true, "CSV nodes file");
cmdLineOptions.addOption("p", "properties", true, "Properties file");
cmdLineOptions.addOption("o", "output", true, "Testbed Runtime config file to be generated");
cmdLineOptions.addOption("w", "wisemloutput", true, "WiseML file to be generated");
cmdLineOptions.addOption("v", "verbose", false, "Verbose logging output (equal to -l DEBUG)");
cmdLineOptions.addOption("l", "logging", true,
"Set logging level (one of [" + Level.TRACE + "," + Level.DEBUG + "," + Level.INFO + "," + Level.WARN + "," + Level.ERROR + "]), optional"
);
cmdLineOptions.addOption("h", "help", false, "Display this help output, optional");
}
private static void usage(Options options) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp(CSV2Config.class.getCanonicalName(), options);
System.exit(1);
}
}
| false | true | private void createTRConfig() throws IOException, JAXBException {
// ====== parse CSV file ======
CSVReader reader = new CSVReader(
new FileReader(cmdLineParameters.csvFile),
CSVReader.DEFAULT_SEPARATOR,
CSVReader.DEFAULT_QUOTE_CHARACTER,
0
);
String[] nextLine;
// detect column by looking for property names in the first line
BiMap<Integer, String> columnMap = HashBiMap.create();
if ((nextLine = reader.readNext()) != null) {
for (int column = 0; column < nextLine.length; column++) {
columnMap.put(column, nextLine[column]);
}
Preconditions.checkNotNull(columnMap.containsValue(HOSTNAME));
Preconditions.checkNotNull(columnMap.containsValue(NODE_ID));
Preconditions.checkNotNull(columnMap.containsValue(NODE_REFERENCE));
Preconditions.checkNotNull(columnMap.containsValue(NODE_PORT));
Preconditions.checkNotNull(columnMap.containsValue(NODE_TYPE));
Preconditions.checkNotNull(columnMap.containsValue(URN_TESTBED_PREFIX));
} else {
throw new RuntimeException(
"CSV file must have at least one file containing one line that defines property names for the columns"
);
}
Testbed testbed = new Testbed();
// ====== create configuration for portal server ======
Node portalNode = new Node();
portalNode.setId(cmdLineParameters.portalHostname);
NodeNames portalNodeNames = new NodeNames();
NodeName portalNodeName = new NodeName();
portalNodeName.setName(cmdLineParameters.portalHostname);
portalNodeNames.getNodename().add(portalNodeName);
portalNode.setNames(portalNodeNames);
ServerConnections portalServerConnections = new ServerConnections();
ServerConnection portalServerConnection = new ServerConnection();
portalServerConnection.setAddress(cmdLineParameters.portalInternalAddress);
portalServerConnection.setType("tcp");
portalServerConnections.getServerconnection().add(portalServerConnection);
portalNode.setServerconnections(portalServerConnections);
Applications portalApplications = new Applications();
Application portalApplication = new Application();
portalApplication.setName("Portal");
portalApplication.setFactoryclass(PortalServerFactory.class.getCanonicalName());
Portalapp portalapp = new Portalapp();
WebService webservice = new WebService();
webservice.setReservationendpointurl(cmdLineParameters.reservationSystemEndpointURL);
webservice.setSessionmanagementendpointurl(cmdLineParameters.sessionmanagementendpointurl);
webservice.setUrnprefix(cmdLineParameters.testbedPrefix);
webservice.setWisemlfilename(cmdLineParameters.wisemlfilename);
webservice.setWsninstancebaseurl(cmdLineParameters.wsninstancebaseurl);
portalapp.setWebservice(webservice);
portalApplication.setAny(portalapp);
portalApplications.getApplication().add(portalApplication);
portalNode.setApplications(portalApplications);
testbed.getNodes().add(portalNode);
// ====== create configuration for overlay nodeMap ======
Map<String, Node> nodeMap = new HashMap<String, Node>();
Map<String, Application> applicationMap = new HashMap<String, Application>();
BiMap<String, Integer> columns = columnMap.inverse();
while ((nextLine = reader.readNext()) != null) {
// add overlay node name if not yet existing
String hostname = nextLine[columns.get(HOSTNAME)];
Node node = nodeMap.get(hostname);
if (node == null) {
node = new Node();
node.setId(hostname);
nodeMap.put(hostname, node);
ServerConnection serverConnection = new ServerConnection();
serverConnection.setType("tcp");
serverConnection.setAddress(hostname + ":8880");
ServerConnections serverConnections = new ServerConnections();
serverConnections.getServerconnection().add(serverConnection);
node.setServerconnections(serverConnections);
testbed.getNodes().add(node);
}
// add device urn as node name to overlay node
NodeName nodeName = new NodeName();
nodeName.setName(nextLine[columns.get(URN_TESTBED_PREFIX)] + nextLine[columns.get(NODE_ID)]);
NodeNames nodeNames = new NodeNames();
nodeNames.getNodename().add(nodeName);
node.setNames(nodeNames);
// add WSN application if not yet existing
Application application = applicationMap.get(hostname);
if (application == null) {
application = new Application();
application.setName("WSNDeviceApp");
application.setFactoryclass(WSNDeviceAppFactory.class.getCanonicalName());
application.setAny(new Wsnapp());
Applications applications = new Applications();
applications.getApplication().add(application);
node.setApplications(applications);
applicationMap.put(hostname, application);
}
// add WSN device (current row of CSV)
WsnDevice wsnDevice = new WsnDevice();
wsnDevice.setType(nextLine[columns.get(NODE_TYPE)]);
wsnDevice.setUrn(nextLine[columns.get(URN_TESTBED_PREFIX)] + nextLine[columns.get(NODE_ID)]);
String nodePort = nextLine[columns.get(NODE_PORT)];
if (nodePort != null && !"".equals(nodePort)) {
wsnDevice.setSerialinterface(nodePort);
}
String nodeReference = nextLine[columns.get(NODE_REFERENCE)];
if (nodeReference != null && !"".equals(nodeReference)) {
wsnDevice.setUsbchipid(nodeReference);
}
Wsnapp wsnApp = (Wsnapp) application.getAny();
wsnApp.getDevice().add(wsnDevice);
}
// ====== write configuration file ======
JAXBContext jc = JAXBContext.newInstance(
Testbed.class,
Portalapp.class,
Wsnapp.class
);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
FileWriter writer = new FileWriter(cmdLineParameters.outputFile.getAbsolutePath());
marshaller.marshal(testbed, writer);
}
| private void createTRConfig() throws IOException, JAXBException {
// ====== parse CSV file ======
CSVReader reader = new CSVReader(
new FileReader(cmdLineParameters.csvFile),
CSVReader.DEFAULT_SEPARATOR,
CSVReader.DEFAULT_QUOTE_CHARACTER,
0
);
String[] nextLine;
// detect column by looking for property names in the first line
BiMap<Integer, String> columnMap = HashBiMap.create();
if ((nextLine = reader.readNext()) != null) {
for (int column = 0; column < nextLine.length; column++) {
columnMap.put(column, nextLine[column]);
}
Preconditions.checkNotNull(columnMap.containsValue(HOSTNAME));
Preconditions.checkNotNull(columnMap.containsValue(NODE_ID));
Preconditions.checkNotNull(columnMap.containsValue(NODE_REFERENCE));
Preconditions.checkNotNull(columnMap.containsValue(NODE_PORT));
Preconditions.checkNotNull(columnMap.containsValue(NODE_TYPE));
Preconditions.checkNotNull(columnMap.containsValue(URN_TESTBED_PREFIX));
} else {
throw new RuntimeException(
"CSV file must have at least one file containing one line that defines property names for the columns"
);
}
Testbed testbed = new Testbed();
// ====== create configuration for portal server ======
Node portalNode = new Node();
portalNode.setId(cmdLineParameters.portalHostname);
NodeNames portalNodeNames = new NodeNames();
NodeName portalNodeName = new NodeName();
portalNodeName.setName(cmdLineParameters.portalHostname);
portalNodeNames.getNodename().add(portalNodeName);
portalNode.setNames(portalNodeNames);
ServerConnections portalServerConnections = new ServerConnections();
ServerConnection portalServerConnection = new ServerConnection();
portalServerConnection.setAddress(cmdLineParameters.portalInternalAddress);
portalServerConnection.setType("tcp");
portalServerConnections.getServerconnection().add(portalServerConnection);
portalNode.setServerconnections(portalServerConnections);
Applications portalApplications = new Applications();
Application portalApplication = new Application();
portalApplication.setName("Portal");
portalApplication.setFactoryclass(PortalServerFactory.class.getCanonicalName());
Portalapp portalapp = new Portalapp();
WebService webservice = new WebService();
webservice.setReservationendpointurl(cmdLineParameters.reservationSystemEndpointURL);
webservice.setSessionmanagementendpointurl(cmdLineParameters.sessionmanagementendpointurl);
webservice.setUrnprefix(cmdLineParameters.testbedPrefix);
webservice.setWisemlfilename(cmdLineParameters.wisemlfilename);
webservice.setWsninstancebaseurl(cmdLineParameters.wsninstancebaseurl);
portalapp.setWebservice(webservice);
portalApplication.setAny(portalapp);
portalApplications.getApplication().add(portalApplication);
portalNode.setApplications(portalApplications);
testbed.getNodes().add(portalNode);
// ====== create configuration for overlay nodeMap ======
Map<String, Node> nodeMap = new HashMap<String, Node>();
Map<String, Application> applicationMap = new HashMap<String, Application>();
BiMap<String, Integer> columns = columnMap.inverse();
while ((nextLine = reader.readNext()) != null) {
// add overlay node name if not yet existing
String hostname = nextLine[columns.get(HOSTNAME)];
Node node = nodeMap.get(hostname);
if (node == null) {
node = new Node();
node.setId(hostname);
nodeMap.put(hostname, node);
ServerConnection serverConnection = new ServerConnection();
serverConnection.setType("tcp");
serverConnection.setAddress(hostname + ":8880");
ServerConnections serverConnections = new ServerConnections();
serverConnections.getServerconnection().add(serverConnection);
node.setServerconnections(serverConnections);
testbed.getNodes().add(node);
}
// add device urn as node name to overlay node
String currentNodeName = nextLine[columns.get(URN_TESTBED_PREFIX)] + nextLine[columns.get(NODE_ID)];
NodeNames nodeNames = node.getNames();
if (nodeNames == null) {
nodeNames = new NodeNames();
node.setNames(nodeNames);
}
NodeName nodeName = new NodeName();
nodeName.setName(currentNodeName);
nodeNames.getNodename().add(nodeName);
// add WSN application if not yet existing
Application application = applicationMap.get(hostname);
if (application == null) {
application = new Application();
application.setName("WSNDeviceApp");
application.setFactoryclass(WSNDeviceAppFactory.class.getCanonicalName());
application.setAny(new Wsnapp());
Applications applications = new Applications();
applications.getApplication().add(application);
node.setApplications(applications);
applicationMap.put(hostname, application);
}
// add WSN device (current row of CSV)
WsnDevice wsnDevice = new WsnDevice();
wsnDevice.setType(nextLine[columns.get(NODE_TYPE)]);
wsnDevice.setUrn(nextLine[columns.get(URN_TESTBED_PREFIX)] + nextLine[columns.get(NODE_ID)]);
String nodePort = nextLine[columns.get(NODE_PORT)];
if (nodePort != null && !"".equals(nodePort)) {
wsnDevice.setSerialinterface(nodePort);
}
String nodeReference = nextLine[columns.get(NODE_REFERENCE)];
if (nodeReference != null && !"".equals(nodeReference)) {
wsnDevice.setUsbchipid(nodeReference);
}
Wsnapp wsnApp = (Wsnapp) application.getAny();
wsnApp.getDevice().add(wsnDevice);
}
// ====== write configuration file ======
JAXBContext jc = JAXBContext.newInstance(
Testbed.class,
Portalapp.class,
Wsnapp.class
);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
FileWriter writer = new FileWriter(cmdLineParameters.outputFile.getAbsolutePath());
marshaller.marshal(testbed, writer);
}
|
diff --git a/bi-platform-v2-plugin/src/org/pentaho/cdf/CdfFileInfoGenerator.java b/bi-platform-v2-plugin/src/org/pentaho/cdf/CdfFileInfoGenerator.java
index 8e057a6e..7afb41a2 100755
--- a/bi-platform-v2-plugin/src/org/pentaho/cdf/CdfFileInfoGenerator.java
+++ b/bi-platform-v2-plugin/src/org/pentaho/cdf/CdfFileInfoGenerator.java
@@ -1,57 +1,57 @@
package org.pentaho.cdf;
import java.io.InputStream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.pentaho.platform.api.engine.IFileInfo;
import org.pentaho.platform.api.engine.ISolutionFile;
import org.pentaho.platform.api.engine.SolutionFileMetaAdapter;
import org.pentaho.platform.engine.core.solution.FileInfo;
import org.pentaho.platform.util.xml.dom4j.XmlDom4JHelper;
/**
* Parses a Dom4J document and creates an IFileInfo object containing the
* xcdf info.
*
* @author Will Gorman ([email protected])
*/
public class CdfFileInfoGenerator extends SolutionFileMetaAdapter {
private Log logger = LogFactory.getLog(CdfFileInfoGenerator.class);
public CdfFileInfoGenerator() {
}
@Override
public IFileInfo getFileInfo(ISolutionFile solutionFile, InputStream in) {
- // TODO Auto-generated method stub
+ // TODO Auto-generated method stubT
Document doc = null;
try {
doc = XmlDom4JHelper.getDocFromStream(in);
} catch (Exception e) {
logger.error(Messages.getErrorString("CdfFileInfoGenerator.ERROR_0001_PARSING_XCDF"), e); //$NON-NLS-1$
return null;
}
if (doc == null) {
logger.error(Messages.getErrorString("CdfFileInfoGenerator.ERROR_0001_PARSING_XCDF")); //$NON-NLS-1$
return null;
}
String result = "dashboard"; //$NON-NLS-1$
String author = XmlDom4JHelper.getNodeText("/cdf/author", doc, ""); //$NON-NLS-1$ //$NON-NLS-2$
String description = XmlDom4JHelper.getNodeText("/cdf/description", doc, ""); //$NON-NLS-1$ //$NON-NLS-2$
String icon = XmlDom4JHelper.getNodeText("/cdf/icon", doc, ""); //$NON-NLS-1$ //$NON-NLS-2$
String title = XmlDom4JHelper.getNodeText("/cdf/title", doc, ""); //$NON-NLS-1$ //$NON-NLS-2$
IFileInfo info = new FileInfo();
info.setAuthor(author);
info.setDescription(description);
info.setDisplayType(result);
info.setIcon(icon);
info.setTitle(title);
return info;
}
}
| true | true | public IFileInfo getFileInfo(ISolutionFile solutionFile, InputStream in) {
// TODO Auto-generated method stub
Document doc = null;
try {
doc = XmlDom4JHelper.getDocFromStream(in);
} catch (Exception e) {
logger.error(Messages.getErrorString("CdfFileInfoGenerator.ERROR_0001_PARSING_XCDF"), e); //$NON-NLS-1$
return null;
}
if (doc == null) {
logger.error(Messages.getErrorString("CdfFileInfoGenerator.ERROR_0001_PARSING_XCDF")); //$NON-NLS-1$
return null;
}
String result = "dashboard"; //$NON-NLS-1$
String author = XmlDom4JHelper.getNodeText("/cdf/author", doc, ""); //$NON-NLS-1$ //$NON-NLS-2$
String description = XmlDom4JHelper.getNodeText("/cdf/description", doc, ""); //$NON-NLS-1$ //$NON-NLS-2$
String icon = XmlDom4JHelper.getNodeText("/cdf/icon", doc, ""); //$NON-NLS-1$ //$NON-NLS-2$
String title = XmlDom4JHelper.getNodeText("/cdf/title", doc, ""); //$NON-NLS-1$ //$NON-NLS-2$
IFileInfo info = new FileInfo();
info.setAuthor(author);
info.setDescription(description);
info.setDisplayType(result);
info.setIcon(icon);
info.setTitle(title);
return info;
}
| public IFileInfo getFileInfo(ISolutionFile solutionFile, InputStream in) {
// TODO Auto-generated method stubT
Document doc = null;
try {
doc = XmlDom4JHelper.getDocFromStream(in);
} catch (Exception e) {
logger.error(Messages.getErrorString("CdfFileInfoGenerator.ERROR_0001_PARSING_XCDF"), e); //$NON-NLS-1$
return null;
}
if (doc == null) {
logger.error(Messages.getErrorString("CdfFileInfoGenerator.ERROR_0001_PARSING_XCDF")); //$NON-NLS-1$
return null;
}
String result = "dashboard"; //$NON-NLS-1$
String author = XmlDom4JHelper.getNodeText("/cdf/author", doc, ""); //$NON-NLS-1$ //$NON-NLS-2$
String description = XmlDom4JHelper.getNodeText("/cdf/description", doc, ""); //$NON-NLS-1$ //$NON-NLS-2$
String icon = XmlDom4JHelper.getNodeText("/cdf/icon", doc, ""); //$NON-NLS-1$ //$NON-NLS-2$
String title = XmlDom4JHelper.getNodeText("/cdf/title", doc, ""); //$NON-NLS-1$ //$NON-NLS-2$
IFileInfo info = new FileInfo();
info.setAuthor(author);
info.setDescription(description);
info.setDisplayType(result);
info.setIcon(icon);
info.setTitle(title);
return info;
}
|
diff --git a/examples/org.eclipse.ocl.examples.xtext.essentialocl/src/org/eclipse/ocl/examples/xtext/essentialocl/attributes/NavigationOperatorCSAttribution.java b/examples/org.eclipse.ocl.examples.xtext.essentialocl/src/org/eclipse/ocl/examples/xtext/essentialocl/attributes/NavigationOperatorCSAttribution.java
index 0e419fe7d2..c5f705d3f8 100644
--- a/examples/org.eclipse.ocl.examples.xtext.essentialocl/src/org/eclipse/ocl/examples/xtext/essentialocl/attributes/NavigationOperatorCSAttribution.java
+++ b/examples/org.eclipse.ocl.examples.xtext.essentialocl/src/org/eclipse/ocl/examples/xtext/essentialocl/attributes/NavigationOperatorCSAttribution.java
@@ -1,92 +1,92 @@
/**
* <copyright>
*
* Copyright (c) 2010,2011 E.D.Willink and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* E.D.Willink - initial API and implementation
*
* </copyright>
*
* $Id: NavigationOperatorCSAttribution.java,v 1.13 2011/05/05 17:52:54 ewillink Exp $
*/
package org.eclipse.ocl.examples.xtext.essentialocl.attributes;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.ocl.examples.pivot.CollectionType;
import org.eclipse.ocl.examples.pivot.OCLExpression;
import org.eclipse.ocl.examples.pivot.PivotConstants;
import org.eclipse.ocl.examples.pivot.PivotPackage;
import org.eclipse.ocl.examples.pivot.Type;
import org.eclipse.ocl.examples.pivot.manager.MetaModelManager;
import org.eclipse.ocl.examples.pivot.scoping.AbstractAttribution;
import org.eclipse.ocl.examples.pivot.scoping.EnvironmentView;
import org.eclipse.ocl.examples.pivot.scoping.ScopeView;
import org.eclipse.ocl.examples.pivot.utilities.PivotUtil;
import org.eclipse.ocl.examples.xtext.base.baseCST.ElementCS;
import org.eclipse.ocl.examples.xtext.base.scoping.BaseScopeView;
import org.eclipse.ocl.examples.xtext.essentialocl.essentialOCLCST.NavigationOperatorCS;
public class NavigationOperatorCSAttribution extends AbstractAttribution
{
public static final NavigationOperatorCSAttribution INSTANCE = new NavigationOperatorCSAttribution();
@Override
public ScopeView computeLookup(EObject target, EnvironmentView environmentView, ScopeView scopeView) {
NavigationOperatorCS targetElement = (NavigationOperatorCS)target;
EObject child = scopeView.getChild();
if (child == targetElement.getArgument()) {
OCLExpression source = PivotUtil.getPivot(OCLExpression.class, targetElement.getSource());
if (source != null) {
Type type = source.getType();
if (!targetElement.getName().equals(PivotConstants.COLLECTION_NAVIGATION_OPERATOR)) {
if (type instanceof CollectionType) { // collection->implicit-collect(object-operation)
Type elementType = ((CollectionType)type).getElementType();
while (elementType instanceof CollectionType) {
elementType = ((CollectionType)elementType).getElementType(); // implicit-collect flattens
}
environmentView.addElementsOfScope(elementType, scopeView);
}
- else { // object.object-operation
+ else if (type != null) { // object.object-operation
environmentView.addElementsOfScope(type, scopeView);
environmentView.addElementsOfScope(type.getPackage(), scopeView);
}
}
else if (scopeView.getContainmentFeature() != PivotPackage.Literals.OPERATION_CALL_EXP__ARGUMENT){
if (type instanceof CollectionType) { // collection->collection-operation
environmentView.addElementsOfScope(type, scopeView);
}
else { // object.oclAsSet()->collection-operation
MetaModelManager metaModelManager = environmentView.getMetaModelManager();
Type setType = metaModelManager.getSetType(type);
environmentView.addElementsOfScope(setType, scopeView);
}
}
else {
if (type instanceof CollectionType) { // collection->iteration-operation(iterator-feature)
if (InvocationExpCSAttribution.isIteration(environmentView.getMetaModelManager(), targetElement.getArgument(), type)) {
environmentView.addElementsOfScope(((CollectionType)type).getElementType(), scopeView);
}
else {
return scopeView.getParent();
}
}
else { // object.oclAsSet()->iteration-operation(iterator-feature)
environmentView.addElementsOfScope(type, scopeView); // FIXME Only if iteration
}
}
}
return scopeView.getParent();
}
else {
ElementCS parent = targetElement.getLogicalParent();
BaseScopeView.computeLookups(environmentView, parent, target, PivotPackage.Literals.CALL_EXP__SOURCE, null);
return null;
}
}
}
| true | true | public ScopeView computeLookup(EObject target, EnvironmentView environmentView, ScopeView scopeView) {
NavigationOperatorCS targetElement = (NavigationOperatorCS)target;
EObject child = scopeView.getChild();
if (child == targetElement.getArgument()) {
OCLExpression source = PivotUtil.getPivot(OCLExpression.class, targetElement.getSource());
if (source != null) {
Type type = source.getType();
if (!targetElement.getName().equals(PivotConstants.COLLECTION_NAVIGATION_OPERATOR)) {
if (type instanceof CollectionType) { // collection->implicit-collect(object-operation)
Type elementType = ((CollectionType)type).getElementType();
while (elementType instanceof CollectionType) {
elementType = ((CollectionType)elementType).getElementType(); // implicit-collect flattens
}
environmentView.addElementsOfScope(elementType, scopeView);
}
else { // object.object-operation
environmentView.addElementsOfScope(type, scopeView);
environmentView.addElementsOfScope(type.getPackage(), scopeView);
}
}
else if (scopeView.getContainmentFeature() != PivotPackage.Literals.OPERATION_CALL_EXP__ARGUMENT){
if (type instanceof CollectionType) { // collection->collection-operation
environmentView.addElementsOfScope(type, scopeView);
}
else { // object.oclAsSet()->collection-operation
MetaModelManager metaModelManager = environmentView.getMetaModelManager();
Type setType = metaModelManager.getSetType(type);
environmentView.addElementsOfScope(setType, scopeView);
}
}
else {
if (type instanceof CollectionType) { // collection->iteration-operation(iterator-feature)
if (InvocationExpCSAttribution.isIteration(environmentView.getMetaModelManager(), targetElement.getArgument(), type)) {
environmentView.addElementsOfScope(((CollectionType)type).getElementType(), scopeView);
}
else {
return scopeView.getParent();
}
}
else { // object.oclAsSet()->iteration-operation(iterator-feature)
environmentView.addElementsOfScope(type, scopeView); // FIXME Only if iteration
}
}
}
return scopeView.getParent();
}
else {
ElementCS parent = targetElement.getLogicalParent();
BaseScopeView.computeLookups(environmentView, parent, target, PivotPackage.Literals.CALL_EXP__SOURCE, null);
return null;
}
}
| public ScopeView computeLookup(EObject target, EnvironmentView environmentView, ScopeView scopeView) {
NavigationOperatorCS targetElement = (NavigationOperatorCS)target;
EObject child = scopeView.getChild();
if (child == targetElement.getArgument()) {
OCLExpression source = PivotUtil.getPivot(OCLExpression.class, targetElement.getSource());
if (source != null) {
Type type = source.getType();
if (!targetElement.getName().equals(PivotConstants.COLLECTION_NAVIGATION_OPERATOR)) {
if (type instanceof CollectionType) { // collection->implicit-collect(object-operation)
Type elementType = ((CollectionType)type).getElementType();
while (elementType instanceof CollectionType) {
elementType = ((CollectionType)elementType).getElementType(); // implicit-collect flattens
}
environmentView.addElementsOfScope(elementType, scopeView);
}
else if (type != null) { // object.object-operation
environmentView.addElementsOfScope(type, scopeView);
environmentView.addElementsOfScope(type.getPackage(), scopeView);
}
}
else if (scopeView.getContainmentFeature() != PivotPackage.Literals.OPERATION_CALL_EXP__ARGUMENT){
if (type instanceof CollectionType) { // collection->collection-operation
environmentView.addElementsOfScope(type, scopeView);
}
else { // object.oclAsSet()->collection-operation
MetaModelManager metaModelManager = environmentView.getMetaModelManager();
Type setType = metaModelManager.getSetType(type);
environmentView.addElementsOfScope(setType, scopeView);
}
}
else {
if (type instanceof CollectionType) { // collection->iteration-operation(iterator-feature)
if (InvocationExpCSAttribution.isIteration(environmentView.getMetaModelManager(), targetElement.getArgument(), type)) {
environmentView.addElementsOfScope(((CollectionType)type).getElementType(), scopeView);
}
else {
return scopeView.getParent();
}
}
else { // object.oclAsSet()->iteration-operation(iterator-feature)
environmentView.addElementsOfScope(type, scopeView); // FIXME Only if iteration
}
}
}
return scopeView.getParent();
}
else {
ElementCS parent = targetElement.getLogicalParent();
BaseScopeView.computeLookups(environmentView, parent, target, PivotPackage.Literals.CALL_EXP__SOURCE, null);
return null;
}
}
|
diff --git a/src/SPL.java b/src/SPL.java
index d50eb73..d84bc36 100644
--- a/src/SPL.java
+++ b/src/SPL.java
@@ -1,61 +1,62 @@
/* Copyright (c) 2006, Sun Microsystems, Inc.
* 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 Sun Microsystems, Inc. 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.
*/
/**
* Stupid Programming Language parser.
*/
public class SPL {
/** Main entry point. */
public static void main(String args[]) {
lexar parser;
if (args.length == 1) {
System.out.println("Stupid Programming Language Interpreter Version 0.1: Reading from file " + args[0] + " . . .");
try {
parser = new lexar(new java.io.FileInputStream(args[0]));
} catch (java.io.FileNotFoundException e) {
System.out.println("Stupid Programming Language Interpreter Version 0.1: File " + args[0] + " not found.");
return;
}
} else {
System.out.println("Stupid Programming Language Interpreter Version 0.1: Usage :");
System.out.println(" java SPL inputfile");
return;
}
try {
- parser.Program();
+ SimpleNode tree = parser.Program();
+ tree.dump("");
//parser.jjtree.rootNode().interpret();
} catch (ParseException e) {
System.out.println("Stupid Programming Language Interpreter Version 0.1: Encountered errors during parse.");
e.printStackTrace();
} catch (Exception e1) {
System.out.println("Stupid Programming Language Interpreter Version 0.1: Encountered errors during interpretation/tree building.");
e1.printStackTrace();
}
}
}
| true | true | public static void main(String args[]) {
lexar parser;
if (args.length == 1) {
System.out.println("Stupid Programming Language Interpreter Version 0.1: Reading from file " + args[0] + " . . .");
try {
parser = new lexar(new java.io.FileInputStream(args[0]));
} catch (java.io.FileNotFoundException e) {
System.out.println("Stupid Programming Language Interpreter Version 0.1: File " + args[0] + " not found.");
return;
}
} else {
System.out.println("Stupid Programming Language Interpreter Version 0.1: Usage :");
System.out.println(" java SPL inputfile");
return;
}
try {
parser.Program();
//parser.jjtree.rootNode().interpret();
} catch (ParseException e) {
System.out.println("Stupid Programming Language Interpreter Version 0.1: Encountered errors during parse.");
e.printStackTrace();
} catch (Exception e1) {
System.out.println("Stupid Programming Language Interpreter Version 0.1: Encountered errors during interpretation/tree building.");
e1.printStackTrace();
}
}
| public static void main(String args[]) {
lexar parser;
if (args.length == 1) {
System.out.println("Stupid Programming Language Interpreter Version 0.1: Reading from file " + args[0] + " . . .");
try {
parser = new lexar(new java.io.FileInputStream(args[0]));
} catch (java.io.FileNotFoundException e) {
System.out.println("Stupid Programming Language Interpreter Version 0.1: File " + args[0] + " not found.");
return;
}
} else {
System.out.println("Stupid Programming Language Interpreter Version 0.1: Usage :");
System.out.println(" java SPL inputfile");
return;
}
try {
SimpleNode tree = parser.Program();
tree.dump("");
//parser.jjtree.rootNode().interpret();
} catch (ParseException e) {
System.out.println("Stupid Programming Language Interpreter Version 0.1: Encountered errors during parse.");
e.printStackTrace();
} catch (Exception e1) {
System.out.println("Stupid Programming Language Interpreter Version 0.1: Encountered errors during interpretation/tree building.");
e1.printStackTrace();
}
}
|
diff --git a/src/main/java/org/amplafi/flow/utils/AdminTool.java b/src/main/java/org/amplafi/flow/utils/AdminTool.java
index 6e38c7f..112dd40 100644
--- a/src/main/java/org/amplafi/flow/utils/AdminTool.java
+++ b/src/main/java/org/amplafi/flow/utils/AdminTool.java
@@ -1,359 +1,359 @@
package org.amplafi.flow.utils;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Properties;
import org.apache.commons.cli.ParseException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import static org.amplafi.flow.utils.AdminToolCommandLineOptions.*;
import org.amplafi.dsl.ScriptRunner;
import org.amplafi.dsl.ScriptDescription;
import java.util.Map;
/**
* Command line interface for running scripts to communicate with the
* Farreach.es wire server. Please read AdminTool.md
* for more details
*/
public class AdminTool {
/** Standard location for admin scripts. */
public static final String DEFAULT_COMMAND_SCRIPT_PATH = "src/main/resources/commandScripts";
public static final String DEFAULT_CONFIG_FILE_NAME = "fareaches.fadmin.properties";
public static final String DEFAULT_HOST = "http://apiv1.farreach.es";
public static final String DEFAULT_PORT = "80";
public static final String DEFAULT_API_VERSION = "apiv1";
private Properties configProperties;
private String comandScriptPath;
private String configFileName;
private Log log;
/**
* Main entry point for tool.
* @param args
*/
public static void main(String[] args) {
AdminTool adminTool = new AdminTool();
for (String arg : args) {
adminTool.getLog().debug("arg: " + arg);
}
adminTool.processCommandLine(args);
}
/**
* Process command line.
* @param args
*/
public void processCommandLine(String[] args) {
// Process command line options.
AdminToolCommandLineOptions cmdOptions = null;
try {
cmdOptions = new AdminToolCommandLineOptions(args);
} catch (ParseException e) {
getLog().error("Could not parse passed arguments, message:", e);
return;
}
// Print help if there has no args.
- if (args.length == 0 || cmdOptions.hasOption(HELP)) {
+ if (args.length == 0) {
cmdOptions.printHelp();
return;
}
String list = cmdOptions.getOptionValue(LIST);
// Obtain a list of script descriptions from the script runner
// this will also check for basic script compilation errors or lack of
// description lines in script.
ScriptRunner runner = new ScriptRunner("");
Map<String, ScriptDescription> scriptLookup = runner
.processScriptsInFolder(getComandScriptPath());
if (cmdOptions.hasOption(LIST) || cmdOptions.hasOption(LISTDETAILED)) {
// If user has asked for a list of commands then list the good
// scripts with their
// descriptions.
for (ScriptDescription sd : runner.getGoodScripts()) {
if (cmdOptions.hasOption(LIST)) {
emitOutput(" " + sd.getName() + " - "
+ sd.getDescription());
} else {
emitOutput(" " + sd.getName() + " - "
+ sd.getDescription() + " - "
+ getRelativePath(sd.getPath()));
}
}
// List scripts that have errors if there are any
if (!runner.getScriptsWithErrors().isEmpty()) {
emitOutput("The following scripts have errors: ");
}
for (ScriptDescription sd : runner.getScriptsWithErrors()) {
emitOutput(" " + getRelativePath(sd.getPath()) + " - "
+ sd.getErrorMesg());
}
} else if (cmdOptions.hasOption(HELP)) {
// TODO print usage if has option help
if (args.length == 1) {
cmdOptions.printHelp();
} else {
for (int i = 1; i < args.length; i++) {
String scriptName = args[i];
for (ScriptDescription sd : runner.getGoodScripts()) {
if (sd.getName().equals(scriptName)) {
if (sd.getUsage() != null && !sd.getUsage().equals("")) {
emitOutput("Script Usage: " + sd.getUsage());
} else {
emitOutput("Script " + scriptName +
" does not have usage information");
}
}
}
}
}
} else if (cmdOptions.hasOption(FILE_PATH)) {
// run an ad-hoc script from a file
String filePath = cmdOptions.getOptionValue(FILE_PATH);
runScript(filePath, scriptLookup, cmdOptions);
} else {
runScript(null, scriptLookup, cmdOptions);
}
// If the config properties were loaded, save them here.
saveProperties();
return;
}
/**
* Get the relative path by the absolute path.
* @param filePath is the full path to the script.
* @return relative path of the file
*/
private String getRelativePath(String filePath) {
String relativePath = filePath;
String currentPath = System.getProperty("user.dir");
if (filePath.contains(currentPath)) {
relativePath = filePath.substring(currentPath.length());
}
return relativePath;
}
/**
* Runs the named script.
* @param filePath is the full path to the script
* @param scriptLookup is the map of ScriptDescription
* @param cmdOptions is instance of AdminToolCommandLineOptions
*/
private void runScript(String filePath,
Map<String, ScriptDescription> scriptLookup,
AdminToolCommandLineOptions cmdOptions) {
List<String> remainder = cmdOptions.getRemainingOptions();
try {
// Get script options if needed
String host = getOption(cmdOptions, HOST, DEFAULT_HOST);
String port = getOption(cmdOptions, PORT, DEFAULT_PORT);
String apiVersion = getOption(cmdOptions, API_VERSION,
DEFAULT_API_VERSION);
String key = getOption(cmdOptions, API_KEY, "");
// Check if we are running and ad-hoc script
if (filePath == null) {
if (!remainder.isEmpty()) {
String scriptName = remainder.get(0);
if (scriptLookup.containsKey(scriptName)) {
ScriptDescription sd = scriptLookup.get(scriptName);
filePath = sd.getPath();
}
remainder.remove(0);
}
}
// Get the parameter for the script itself.
Map<String, String> parammap = getParamMap(remainder);
// Is verbose switched on?
boolean verbose = cmdOptions.hasOption(VERBOSE);
// run the script
ScriptRunner runner2 = new ScriptRunner(host, port, apiVersion,
key, parammap, verbose);
runner2.processScriptsInFolder(getComandScriptPath());
if (filePath != null) {
runner2.loadAndRunOneScript(filePath);
} else {
getLog().error("No script to run or not found.");
}
} catch (IOException ioe) {
getLog().error("Error : " + ioe);
}
}
/**
* Return the script parameters as a map of param name to param valye.
* @param remainderList is command arg list
* @return map of the user input params
*/
private Map<String, String> getParamMap(List<String> remainderList) {
Map<String, String> map = new HashMap<String, String>();
// On linux, options like param1=cat comes through as a single param
// On windows they come through as 2 params.
// To match options like param1=cat
String patternStr = "(\\w+)=(\\S+)";
Pattern p = Pattern.compile(patternStr);
for (int i = 0; i < remainderList.size(); i++) {
Matcher matcher = p.matcher(remainderList.get(i));
if (matcher.matches()) {
// If mathces then we are looking at param1=cat as a single
// param
map.put(matcher.group(1), matcher.group(2));
} else {
if (remainderList.size() > i + 1) {
map.put(remainderList.get(i), remainderList.get(i + 1));
}
i++;
}
}
return map;
}
/**
* Gets the program options, either from the command line, from the saved
* properties or asks the user.
* @param cmdOptions - Command line options
* @param key - name of property
* @param defaultVal - default value to suggest
* @return the option value.
* @throws IOException
*/
private String getOption(AdminToolCommandLineOptions cmdOptions,
String key, String defaultVal)
throws IOException {
Properties props = getProperties();
String value = null;
if (cmdOptions.hasOption(key)) {
// if option passed in on commandline then use that
value = cmdOptions.getOptionValue(key);
} else {
// if option is in properties then use that
String prefValue = props.getProperty(key, "");
if (cmdOptions.hasOption(NOCACHE) || prefValue.equals("")) {
// prompt the user for the option
System.out.print("Please, Enter : " + key
+ " ( Enter defaults to: " + defaultVal + ") ");
value = getUserInput(key);
if ("".equals(value)) {
value = defaultVal;
}
} else {
return prefValue;
}
}
props.setProperty(key, value);
return value;
}
/**
* Gets the configuration properties, loading it if hasn't been loaded.
* @return configuration properties.
*/
public Properties getProperties() {
if (configProperties == null) {
configProperties = new Properties();
try {
// load a properties file
configProperties.load(new FileInputStream(getConfigFileName()));
} catch (IOException ex) {
getLog().error("Error loading file " + getConfigFileName());
}
}
return configProperties;
}
/**
* Saves the configuration properties, loading it if hasn't been loaded.
*/
public void saveProperties() {
if (configProperties != null) {
try {
// load a properties file
configProperties.store(
new FileOutputStream(getConfigFileName()),
"Farreach.es Admin tool properties");
} catch (IOException ex) {
getLog().error("Error saving file " + getConfigFileName());
}
}
}
/**
* @param msg - message to emit
*/
public void emitOutput(String msg) {
getLog().info(msg);
}
/**
* Get the logger for this class.
*/
public Log getLog() {
if (this.log == null) {
this.log = LogFactory.getLog(this.getClass());
}
return this.log;
}
/**
* Gets the script path for the tool.
* @return path of the file commandScript
*/
String getComandScriptPath() {
if (comandScriptPath != null) {
return comandScriptPath;
} else {
comandScriptPath = DEFAULT_COMMAND_SCRIPT_PATH;
}
return comandScriptPath;
}
/**
* @param comandScriptPath the comandScriptPath to set
*/
public void setComandScriptPath(String comandScriptPath) {
this.comandScriptPath = comandScriptPath;
}
/**
* Gets the script path for the tool.
* @return the name of the config file
*/
public String getConfigFileName() {
if (configFileName != null) {
return configFileName;
} else {
configFileName = DEFAULT_CONFIG_FILE_NAME;
}
return configFileName;
}
/**
* @param configFileName the name of the config file
*/
public void setConfigFileName(String configFileName) {
this.configFileName = configFileName;
}
/**
* @param key is the key of user input
* @return the value of user input
*/
public String getUserInput(String key) {
BufferedReader consoleIn = new BufferedReader(new InputStreamReader(
System.in));
String value = "";
try {
value = consoleIn.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return value;
}
}
| true | true | public void processCommandLine(String[] args) {
// Process command line options.
AdminToolCommandLineOptions cmdOptions = null;
try {
cmdOptions = new AdminToolCommandLineOptions(args);
} catch (ParseException e) {
getLog().error("Could not parse passed arguments, message:", e);
return;
}
// Print help if there has no args.
if (args.length == 0 || cmdOptions.hasOption(HELP)) {
cmdOptions.printHelp();
return;
}
String list = cmdOptions.getOptionValue(LIST);
// Obtain a list of script descriptions from the script runner
// this will also check for basic script compilation errors or lack of
// description lines in script.
ScriptRunner runner = new ScriptRunner("");
Map<String, ScriptDescription> scriptLookup = runner
.processScriptsInFolder(getComandScriptPath());
if (cmdOptions.hasOption(LIST) || cmdOptions.hasOption(LISTDETAILED)) {
// If user has asked for a list of commands then list the good
// scripts with their
// descriptions.
for (ScriptDescription sd : runner.getGoodScripts()) {
if (cmdOptions.hasOption(LIST)) {
emitOutput(" " + sd.getName() + " - "
+ sd.getDescription());
} else {
emitOutput(" " + sd.getName() + " - "
+ sd.getDescription() + " - "
+ getRelativePath(sd.getPath()));
}
}
// List scripts that have errors if there are any
if (!runner.getScriptsWithErrors().isEmpty()) {
emitOutput("The following scripts have errors: ");
}
for (ScriptDescription sd : runner.getScriptsWithErrors()) {
emitOutput(" " + getRelativePath(sd.getPath()) + " - "
+ sd.getErrorMesg());
}
} else if (cmdOptions.hasOption(HELP)) {
// TODO print usage if has option help
if (args.length == 1) {
cmdOptions.printHelp();
} else {
for (int i = 1; i < args.length; i++) {
String scriptName = args[i];
for (ScriptDescription sd : runner.getGoodScripts()) {
if (sd.getName().equals(scriptName)) {
if (sd.getUsage() != null && !sd.getUsage().equals("")) {
emitOutput("Script Usage: " + sd.getUsage());
} else {
emitOutput("Script " + scriptName +
" does not have usage information");
}
}
}
}
}
} else if (cmdOptions.hasOption(FILE_PATH)) {
// run an ad-hoc script from a file
String filePath = cmdOptions.getOptionValue(FILE_PATH);
runScript(filePath, scriptLookup, cmdOptions);
} else {
runScript(null, scriptLookup, cmdOptions);
}
// If the config properties were loaded, save them here.
saveProperties();
return;
}
| public void processCommandLine(String[] args) {
// Process command line options.
AdminToolCommandLineOptions cmdOptions = null;
try {
cmdOptions = new AdminToolCommandLineOptions(args);
} catch (ParseException e) {
getLog().error("Could not parse passed arguments, message:", e);
return;
}
// Print help if there has no args.
if (args.length == 0) {
cmdOptions.printHelp();
return;
}
String list = cmdOptions.getOptionValue(LIST);
// Obtain a list of script descriptions from the script runner
// this will also check for basic script compilation errors or lack of
// description lines in script.
ScriptRunner runner = new ScriptRunner("");
Map<String, ScriptDescription> scriptLookup = runner
.processScriptsInFolder(getComandScriptPath());
if (cmdOptions.hasOption(LIST) || cmdOptions.hasOption(LISTDETAILED)) {
// If user has asked for a list of commands then list the good
// scripts with their
// descriptions.
for (ScriptDescription sd : runner.getGoodScripts()) {
if (cmdOptions.hasOption(LIST)) {
emitOutput(" " + sd.getName() + " - "
+ sd.getDescription());
} else {
emitOutput(" " + sd.getName() + " - "
+ sd.getDescription() + " - "
+ getRelativePath(sd.getPath()));
}
}
// List scripts that have errors if there are any
if (!runner.getScriptsWithErrors().isEmpty()) {
emitOutput("The following scripts have errors: ");
}
for (ScriptDescription sd : runner.getScriptsWithErrors()) {
emitOutput(" " + getRelativePath(sd.getPath()) + " - "
+ sd.getErrorMesg());
}
} else if (cmdOptions.hasOption(HELP)) {
// TODO print usage if has option help
if (args.length == 1) {
cmdOptions.printHelp();
} else {
for (int i = 1; i < args.length; i++) {
String scriptName = args[i];
for (ScriptDescription sd : runner.getGoodScripts()) {
if (sd.getName().equals(scriptName)) {
if (sd.getUsage() != null && !sd.getUsage().equals("")) {
emitOutput("Script Usage: " + sd.getUsage());
} else {
emitOutput("Script " + scriptName +
" does not have usage information");
}
}
}
}
}
} else if (cmdOptions.hasOption(FILE_PATH)) {
// run an ad-hoc script from a file
String filePath = cmdOptions.getOptionValue(FILE_PATH);
runScript(filePath, scriptLookup, cmdOptions);
} else {
runScript(null, scriptLookup, cmdOptions);
}
// If the config properties were loaded, save them here.
saveProperties();
return;
}
|
diff --git a/gnu/testlet/java/lang/Character/unicode.java b/gnu/testlet/java/lang/Character/unicode.java
index f815410b..ab5a6d08 100644
--- a/gnu/testlet/java/lang/Character/unicode.java
+++ b/gnu/testlet/java/lang/Character/unicode.java
@@ -1,664 +1,679 @@
// Tags: JDK1.1
// Uses: CharInfo
package gnu.testlet.java.lang.Character;
import java.io.*;
import gnu.testlet.Testlet;
import gnu.testlet.TestHarness;
import gnu.testlet.ResourceNotFoundException;
/*
MISSING:
Instance tests
( constructor, charValue, serialization): should be in other file
*/
public class unicode implements Testlet
{
public static boolean testDeprecated;
public static boolean verbose;
public static boolean benchmark;
public CharInfo[] chars = new CharInfo[0x10000];
public int failures;
public int tests;
TestHarness harness;
public unicode()
{
}
public unicode(TestHarness aHarness, String filename) throws IOException, ResourceNotFoundException
{
harness = aHarness;
Reader bir =
harness.getResourceReader ("gnu#testlet#java#lang#Character#"
+ filename);
harness.debug("Reading unicode database...");
while ( bir.ready() )
{
String str;
CharInfo ci = new CharInfo();
str = getNext(bir);
int code = (char)Integer.parseInt(str,16);
ci.name = getNext(bir);
ci.category = getNext(bir);
getNext(bir);
getNext(bir);
getNext(bir);
str = getNext(bir);
if ( !str.equals("") )
ci.digit = Integer.parseInt(str, 10 );
else
ci.digit = -1;
getNext(bir);
str = getNext(bir);
if ( str.equals("") )
{
ci.numericValue = -1;
}
else
{
try {
ci.numericValue = Integer.parseInt(str,10);
if ( ci.numericValue < 0 )
ci.numericValue = -2;
} catch ( NumberFormatException e )
{
ci.numericValue = -2;
}
}
getNext(bir);
getNext(bir);
getNext(bir);
str = getNext(bir);
if ( !str.equals("") )
ci.uppercase = (char)Integer.parseInt(str, 16);
str = getNext(bir);
if ( !str.equals("") )
ci.lowercase = (char)Integer.parseInt(str, 16);
str = getNext(bir);
if ( !str.equals("") )
ci.titlecase = (char)Integer.parseInt(str, 16);
chars[code] = ci;
}
CharInfo ch = new CharInfo();
ch.name = "CJK Ideograph";
ch.category = "Lo";
ch.digit = -1;
ch.numericValue = -1;
for ( int i = 0x4E01; i <= 0x9FA4; i++ )
{
chars[i] = ch;
}
ch = new CharInfo();
ch.name = "Hangul Syllable";
ch.category = "Lo";
ch.digit = -1;
ch.numericValue = -1;
for ( int i = 0xAC01; i <= 0xD7A2; i++ )
{
chars[i] = ch;
}
ch = new CharInfo();
ch.name = "CJK Compatibility Ideograph";
ch.category = "Lo";
ch.digit = -1;
ch.numericValue = -1;
for ( int i = 0xF901; i <= 0xFA2C; i++ )
{
chars[i] = ch;
}
ch = new CharInfo();
ch.name = "Surrogate";
ch.category= "Cs";
ch.digit = -1;
ch.numericValue = -1;
for ( int i = 0xD800; i <= 0xDFFFl; i++ )
{
chars[i] = ch;
}
ch = new CharInfo();
ch.name = "Private Use";
ch.category = "Co";
ch.digit = -1;
ch.numericValue = -1;
for ( int i = 0xE000; i <= 0xF8FF; i++ )
{
chars[i] = ch;
}
ch = new CharInfo();
ch.name = "UNDEFINED";
ch.category = "Cn";
ch.digit = -1;
ch.numericValue = -1;
for ( int i =0; i <= 0xFFFF; i++ )
{
if ( chars[i] == null )
chars[i] = ch;
}
/*
It is not stated that A-Z and a-z should
have getNumericValue() (as it is in digit())
*/
for ( int i = 'A'; i <= 'Z'; i++ )
{
chars[i].digit = i - 'A' + 10;
chars[i].numericValue = chars[i].digit; // ??
}
for ( int i = 'a'; i <= 'z'; i++ )
{
chars[i].digit = i - 'a' + 10;
chars[i].numericValue = chars[i].digit; // ??
}
/*
Following two ranges are not clearly stated in
spec, but they are reasonable;
*/
for ( int i = 0xFF21; i <= 0xFF3A; i++ )
{
chars[i].digit = i - 0xFF21 + 10;
chars[i].numericValue = chars[i].digit; // ??
}
for ( int i = 0xFF41; i <= 0xFF5A; i++ )
{
chars[i].digit = i - 0xFF41 + 10;
chars[i].numericValue = chars[i].digit; // ??
}
harness.debug("done");
}
private String getNext( Reader r ) throws IOException
{
StringBuffer sb = new StringBuffer();
while ( r.ready() )
{
char ch = (char)r.read();
if ( ch == '\r' )
{
continue;
}
else if (ch == ';' || ch == '\n' )
{
return sb.toString();
}
else
sb.append(ch);
}
return sb.toString();
}
public String stringChar(int ch )
{
return "Character " + Integer.toString(ch,16) + ":"
+ chars[ch].name;
}
private void reportError( String what )
{
harness.check(false,what);
}
private void reportError( int ch, String what )
{
harness.check(false,stringChar(ch) +" incorectly reported as " + what);
}
private void checkPassed()
{
harness.check(true);
}
public boolean range( int mid, int low, int high )
{
return (mid >= low && mid <= high);
}
public boolean ignorable(int i)
{
return (range(i,0x0000,0x0008) ||
range(i,0x000E,0x001B) ||
// According to JDK 1.2 docs, 7f-9f are ignorable.
range(i,0x007f,0x009f) ||
range(i,0x200C,0x200F) ||
range(i,0x202A,0x202E) ||
range(i,0x206A,0x206F) ||
i == 0xFEFF);
}
public void performTests()
{
for ( int x =0; x <= 0xffff; x++ )
{
// isLowerCase
char i = (char)x;
// NOTE: JLS doesn't say anything about `Ll'
// category. And Unicode 2.1.8 has some
// characters which might be considered
// lowercase by all the other rules, but which
// are not marked Ll -- e.g., 0x0345. So we
// don't check for this.
if ( ( // "Ll".equals(chars[i].category) &&
(i < 0x2000 || i > 0x2fff)
&& chars[i].lowercase == 0
&& (chars[i].uppercase != 0
|| (chars[i].name.indexOf("SMALL LETTER")
!= -1)
|| (chars[i].name.indexOf("SMALL LIGATURE")
!= -1)))
!= Character.isLowerCase((char)i) )
{
reportError(i,
(Character.isLowerCase((char)i) ? "lowercase" : "not-lowercase" ));
}
else checkPassed();
// isUpperCase
// NOTE: JLS doesn't say anything about `Lu'
// category. And Unicode 2.1.8 has some
// characters which might be considered
// uppercase by all the other rules, but which
// are not marked Lu -- e.g., 0x03d2. So we
// don't check for this.
if ( // "Lu".equals(chars[i].category)
( (i < 0x2000 || i > 0x2ffff)
&& chars[i].uppercase == 0
&& (chars[i].lowercase != 0
|| (chars[i].name.indexOf("CAPITAL LETTER")
!= -1)
|| (chars[i].name.indexOf("CAPITAL LIGATURE")
!= -1)))
!= Character.isUpperCase((char)i) )
{
reportError(i,
(Character.isUpperCase((char)i) ? "uppercase" : "not-uppercase" ) );
}
else checkPassed();
// isTitleCase
if ( "Lt".equals(chars[i].category) !=
Character.isTitleCase((char)i) )
{
reportError(i,
(Character.isTitleCase((char)i) ? "titlecase" : "not-titlecase" ) );
}
else checkPassed();
// isDigit
// if ( (chars[i].category.charAt(0) == 'N') !=
// Character.isDigit((char)i) )
- if ((
- (chars[i].name.indexOf("DIGIT") > -1) &&
- !range(i,0x2000,0x2FFF)
- ) !=Character.isDigit((char)i) )
+// if (( (chars[i].name.indexOf("DIGIT") > -1) &&
+// !range(i,0x2000,0x2FFF)
+ if ( (range (i, 0x0030, 0x0039)
+ || range (i, 0x0660, 0x0669)
+ || range (i, 0x6f0, 0x06f9)
+ || range (i, 0x0966, 0x096f)
+ || range (i, 0x09e6, 0x09ef)
+ || range (i, 0x0a66, 0x0a6f)
+ || range (i, 0x0ae6, 0x0aef)
+ || range (i, 0x0b66, 0x0b6f)
+ || range (i, 0x0be7, 0x0bef)
+ || range (i, 0x0c66, 0x0c6f)
+ || range (i, 0x0ce6, 0x0cef)
+ || range (i, 0x0d66, 0x0d6f)
+ || range (i, 0x0e50, 0x0e59)
+ || range (i, 0x0ed0, 0x0ed9)
+ || range (i, 0x0f20, 0x0f29)
+ || range (i, 0xff10, 0xff19)
+ ) !=Character.isDigit((char)i) )
{
reportError(i,
(Character.isDigit((char)i) ? "digit" : "not-digit" ) );
}
else checkPassed();
// isDefined
/* if ( ((chars[i] != null) ||
(i >= 0xD800 && i <= 0xFA2D ) )*/
if ( !chars[i].category.equals("Cn")
!= Character.isDefined((char)i) )
{
reportError(i,
(Character.isDefined((char)i) ? "defined" : "not-defined" ) );
}
else checkPassed();
// isLetter
if ( (
(chars[i].category.charAt(0) == 'L')) !=
Character.isLetter((char)i) )
{
reportError(i,
(Character.isLetter((char)i) ? "letter" : "not-letter" ) );
}
else checkPassed();
// isLetterOrDigit
if ( Character.isLetterOrDigit(i) !=
(Character.isLetter(i) || Character.isDigit(i)) )
{
reportError(i,
(Character.isLetterOrDigit(i) ? "letterordigit" : "not-letterordigit") );
}
else checkPassed();
// isSpaceChar
if ( (
(chars[i].category.charAt(0) == 'Z')) !=
Character.isSpaceChar(i) )
{
reportError(i,
(Character.isSpaceChar(i) ? "spacechar" : "not-spacechar" ) );
}
else checkPassed();
// isWhiteSpace
boolean t = false;
if ( chars[i].category.charAt(0) == 'Z' && i !=0x00a0
&& i != 0xFEFF )
t = true;
if ( range(i,0x0009,0x000D)|| range(i,0x001C,0x001F) )
t = true;
if ( t != Character.isWhitespace(i) )
{
reportError(i,
Character.isWhitespace(i) ? "whitespace" : "not-whitespace" );
}
else checkPassed();
// isISOControl
if ( ((i <= 0x001F)
|| range(i,0x007F,0x009F) ) !=
Character.isISOControl(i) )
{
reportError(i,
Character.isISOControl(i) ? "isocontrol" : "not-isocontrol");
}
else checkPassed();
int type = Character.getType(i);
String typeStr = null;
switch (type)
{
case Character.UNASSIGNED: typeStr = "Cn"; break;
case Character.UPPERCASE_LETTER: typeStr = "Lu"; break;
case Character.LOWERCASE_LETTER: typeStr = "Ll"; break;
case Character.TITLECASE_LETTER: typeStr = "Lt"; break;
case Character.MODIFIER_LETTER: typeStr = "Lm"; break;
case Character.OTHER_LETTER: typeStr = "Lo"; break;
case Character.NON_SPACING_MARK: typeStr = "Mn"; break;
case Character.ENCLOSING_MARK: typeStr = "Me"; break;
case Character.COMBINING_SPACING_MARK: typeStr = "Mc"; break;
case Character.DECIMAL_DIGIT_NUMBER: typeStr = "Nd"; break;
case Character.LETTER_NUMBER: typeStr = "Nl"; break;
case Character.OTHER_NUMBER: typeStr = "No"; break;
case Character.SPACE_SEPARATOR: typeStr = "Zs"; break;
case Character.LINE_SEPARATOR: typeStr = "Zl"; break;
case Character.PARAGRAPH_SEPARATOR: typeStr = "Zp"; break;
case Character.CONTROL: typeStr = "Cc"; break;
case Character.FORMAT: typeStr = "Cf"; break;
case Character.PRIVATE_USE: typeStr = "Co"; break;
case Character.SURROGATE: typeStr = "Cs"; break;
case Character.DASH_PUNCTUATION: typeStr = "Pd"; break;
case Character.START_PUNCTUATION: typeStr = "Ps"; break;
case Character.END_PUNCTUATION: typeStr = "Pe"; break;
case Character.CONNECTOR_PUNCTUATION: typeStr = "Pc"; break;
case Character.OTHER_PUNCTUATION: typeStr = "Po"; break;
case Character.MATH_SYMBOL: typeStr = "Sm"; break;
case Character.CURRENCY_SYMBOL: typeStr = "Sc"; break;
case Character.MODIFIER_SYMBOL: typeStr = "Sk"; break;
case Character.OTHER_SYMBOL: typeStr = "So"; break;
default: typeStr = "ERROR"; break;
}
if ( ! (chars[i].category.equals(typeStr)
|| (typeStr.equals("Ps")
&& chars[i].category.equals("Pi"))
|| (typeStr.equals("Pe")
&& chars[i].category.equals("Pf"))))
{
reportError(
stringChar(i) + " is reported to be type " + typeStr +
" instead of " + chars[i].category);
}
else checkPassed();
// isJavaIdentifierStart
if ( ( (chars[i].category.charAt(0) == 'L') ||
chars[i].category.equals("Sc") ||
chars[i].category.equals("Pc") ) !=
Character.isJavaIdentifierStart(i) )
{
reportError(i,
Character.isJavaIdentifierStart(i) ? "javaindetifierstart" : "not-javaidentfierstart");
}
else checkPassed();
// isJavaIdentifierPart
boolean shouldbe = false;
typeStr = chars[i].category;
if (
(
typeStr.charAt(0) == 'L' ||
typeStr.equals("Sc") ||
typeStr.equals("Pc") ||
typeStr.equals("Nd") ||
typeStr.equals("Nl") ||
typeStr.equals("Mc") ||
typeStr.equals("Mn") ||
typeStr.equals("Cf") ||
(typeStr.equals("Cc") && ignorable (i))
) != Character.isJavaIdentifierPart(i) )
{
reportError(i,
Character.isJavaIdentifierPart(i) ? "javaidentifierpart" : "not-javaidentifierpart" );
}
else checkPassed();
//isUnicodeIdentifierStart
if ( (chars[i].category.charAt(0) == 'L') !=
Character.isUnicodeIdentifierStart(i) )
{
reportError(i,
Character.isUnicodeIdentifierStart(i) ? "unicodeidentifierstart" : "not-unicodeidentifierstart" );
}
else checkPassed();
//isUnicodeIdentifierPart
shouldbe = false;
typeStr = chars[i].category;
if (
(
typeStr.charAt(0) == 'L' ||
typeStr.equals("Pc") ||
typeStr.equals("Nd") ||
typeStr.equals("Nl") ||
typeStr.equals("Mc") ||
typeStr.equals("Mn") ||
typeStr.equals("Cf") ||
(typeStr.equals("Cc") && ignorable (i))
) != Character.isUnicodeIdentifierPart(i) )
{
reportError(i,
Character.isUnicodeIdentifierPart(i) ? "unicodeidentifierpart" : "not-unicodeidentifierpart" );
}
else checkPassed();
//isIdentifierIgnorable
if (
(
ignorable (i)
) != Character.isIdentifierIgnorable(i) )
{
reportError(i,
Character.isIdentifierIgnorable(i)? "identifierignorable": "not-identifierignorable");
}
else checkPassed();
// toLowerCase
char cs = (chars[i].lowercase != 0 ? chars[i].lowercase : i);
if ( Character.toLowerCase(i) != cs )
{
reportError(stringChar(i) + " has wrong lowercase form of " +
stringChar(Character.toLowerCase(i)) +" instead of " +
stringChar(cs) );
}
else checkPassed();
// toUpperCase
cs =(chars[i].uppercase != 0 ? chars[i].uppercase : i);
if ( Character.toUpperCase(i) != cs )
{
reportError( stringChar(i) +
" has wrong uppercase form of " +
stringChar(Character.toUpperCase(i)) +
" instead of " +
stringChar(cs) );
}
else checkPassed();
// toTitleCase
cs = (chars[i].titlecase != 0 ? chars[i].titlecase :
chars[i].uppercase !=0 ? chars[i].uppercase : i);
if ( "Lt".equals(chars[i].category) )
{
cs = i;
}
if ( Character.toTitleCase(i) != cs )
{
reportError( stringChar(i) +
" has wrong titlecase form of " +
stringChar(Character.toTitleCase(i)) +
" instead of " +
stringChar(cs) );
}
else checkPassed();
// digit
int digit = chars[i].digit;
for ( int radix = Character.MIN_RADIX; radix <= Character.MAX_RADIX; radix++)
{
int sb = digit;
if ( (chars[i].name.indexOf("DIGIT") == -1)
|| range(i,0x2000,0x2FFF))
sb = -1;
if (i >= 'A' && i <= 'Z')
sb = i - 'A' + 10;
if (i >= 'a' && i <= 'z')
sb = i - 'a' + 10;
if (sb >= radix)
sb = -1;
if ( Character.digit(i,radix) != sb )
{
reportError( stringChar(i) + " has wrong digit form of "
+ Character.digit(i,radix) + " for radix " + radix + " instead of "
+ sb );
}
else checkPassed();
}
// getNumericValue
if ( chars[i].numericValue !=
Character.getNumericValue(i) )
{
reportError( stringChar(i) + " has wrong numeric value of " +
Character.getNumericValue(i) + " instead of " + chars[i].numericValue);
}
if ( testDeprecated )
{
// isJavaLetter
if ( (i == '$' || i == '_' || Character.isLetter(i)) !=
Character.isJavaLetter(i) )
{
reportError(i,
(Character.isJavaLetter(i)? "javaletter" : "not-javaletter"));
}
else checkPassed();
// isJavaLetterOrDigit
if ((Character.isJavaLetter(i) || Character.isDigit(i) ||
i == '$' || i == '_') !=
Character.isJavaLetterOrDigit(i)
)
{
reportError(i,
(Character.isJavaLetterOrDigit(i) ? "javaletterordigit" : "not-javaletterordigit") );
}
else checkPassed();
// isSpace
if (((i == ' ' || i == '\t' || i == '\n' || i == '\r' ||
i == '\f')) != Character.isSpace(i) )
{
reportError(i,
(Character.isSpace(i) ? "space" : "non-space" ) );
}
else checkPassed();
} // testDeprecated
} // for
// forDigit
for ( int r = -100; r < 100; r++ )
{
for ( int d = -100; d < 100; d++ )
{
char dch = Character.forDigit(d,r);
char wantch = 0;
if ( range(r, Character.MIN_RADIX, Character.MAX_RADIX) &&
range(d,0,r-1) )
{
if ( d < 10 )
{
wantch = (char)('0' + (char)d);
}
else if ( d < 36 )
{
wantch = (char)('a' + d - 10);
}
}
if ( dch != wantch )
{
reportError( "Error in forDigit(" + d +
"," + r + "), got " + dch + " wanted " +
wantch );
}
else checkPassed();
}
}
}
public void test(TestHarness harness)
{
try {
long start = System.currentTimeMillis();
unicode t = new unicode(harness, "UnicodeData.txt");
long midtime = System.currentTimeMillis();
t.performTests();
harness.debug("Bechmark : load:" + (midtime-start) +
"ms tests:" + (System.currentTimeMillis() - midtime) + "ms");
}
catch ( Exception e )
{
harness.debug(e);
harness.check(false);
}
}
}
| true | true | public void performTests()
{
for ( int x =0; x <= 0xffff; x++ )
{
// isLowerCase
char i = (char)x;
// NOTE: JLS doesn't say anything about `Ll'
// category. And Unicode 2.1.8 has some
// characters which might be considered
// lowercase by all the other rules, but which
// are not marked Ll -- e.g., 0x0345. So we
// don't check for this.
if ( ( // "Ll".equals(chars[i].category) &&
(i < 0x2000 || i > 0x2fff)
&& chars[i].lowercase == 0
&& (chars[i].uppercase != 0
|| (chars[i].name.indexOf("SMALL LETTER")
!= -1)
|| (chars[i].name.indexOf("SMALL LIGATURE")
!= -1)))
!= Character.isLowerCase((char)i) )
{
reportError(i,
(Character.isLowerCase((char)i) ? "lowercase" : "not-lowercase" ));
}
else checkPassed();
// isUpperCase
// NOTE: JLS doesn't say anything about `Lu'
// category. And Unicode 2.1.8 has some
// characters which might be considered
// uppercase by all the other rules, but which
// are not marked Lu -- e.g., 0x03d2. So we
// don't check for this.
if ( // "Lu".equals(chars[i].category)
( (i < 0x2000 || i > 0x2ffff)
&& chars[i].uppercase == 0
&& (chars[i].lowercase != 0
|| (chars[i].name.indexOf("CAPITAL LETTER")
!= -1)
|| (chars[i].name.indexOf("CAPITAL LIGATURE")
!= -1)))
!= Character.isUpperCase((char)i) )
{
reportError(i,
(Character.isUpperCase((char)i) ? "uppercase" : "not-uppercase" ) );
}
else checkPassed();
// isTitleCase
if ( "Lt".equals(chars[i].category) !=
Character.isTitleCase((char)i) )
{
reportError(i,
(Character.isTitleCase((char)i) ? "titlecase" : "not-titlecase" ) );
}
else checkPassed();
// isDigit
// if ( (chars[i].category.charAt(0) == 'N') !=
// Character.isDigit((char)i) )
if ((
(chars[i].name.indexOf("DIGIT") > -1) &&
!range(i,0x2000,0x2FFF)
) !=Character.isDigit((char)i) )
{
reportError(i,
(Character.isDigit((char)i) ? "digit" : "not-digit" ) );
}
else checkPassed();
// isDefined
/* if ( ((chars[i] != null) ||
(i >= 0xD800 && i <= 0xFA2D ) )*/
if ( !chars[i].category.equals("Cn")
!= Character.isDefined((char)i) )
{
reportError(i,
(Character.isDefined((char)i) ? "defined" : "not-defined" ) );
}
else checkPassed();
// isLetter
if ( (
(chars[i].category.charAt(0) == 'L')) !=
Character.isLetter((char)i) )
{
reportError(i,
(Character.isLetter((char)i) ? "letter" : "not-letter" ) );
}
else checkPassed();
// isLetterOrDigit
if ( Character.isLetterOrDigit(i) !=
(Character.isLetter(i) || Character.isDigit(i)) )
{
reportError(i,
(Character.isLetterOrDigit(i) ? "letterordigit" : "not-letterordigit") );
}
else checkPassed();
// isSpaceChar
if ( (
(chars[i].category.charAt(0) == 'Z')) !=
Character.isSpaceChar(i) )
{
reportError(i,
(Character.isSpaceChar(i) ? "spacechar" : "not-spacechar" ) );
}
else checkPassed();
// isWhiteSpace
boolean t = false;
if ( chars[i].category.charAt(0) == 'Z' && i !=0x00a0
&& i != 0xFEFF )
t = true;
if ( range(i,0x0009,0x000D)|| range(i,0x001C,0x001F) )
t = true;
if ( t != Character.isWhitespace(i) )
{
reportError(i,
Character.isWhitespace(i) ? "whitespace" : "not-whitespace" );
}
else checkPassed();
// isISOControl
if ( ((i <= 0x001F)
|| range(i,0x007F,0x009F) ) !=
Character.isISOControl(i) )
{
reportError(i,
Character.isISOControl(i) ? "isocontrol" : "not-isocontrol");
}
else checkPassed();
int type = Character.getType(i);
String typeStr = null;
switch (type)
{
case Character.UNASSIGNED: typeStr = "Cn"; break;
case Character.UPPERCASE_LETTER: typeStr = "Lu"; break;
case Character.LOWERCASE_LETTER: typeStr = "Ll"; break;
case Character.TITLECASE_LETTER: typeStr = "Lt"; break;
case Character.MODIFIER_LETTER: typeStr = "Lm"; break;
case Character.OTHER_LETTER: typeStr = "Lo"; break;
case Character.NON_SPACING_MARK: typeStr = "Mn"; break;
case Character.ENCLOSING_MARK: typeStr = "Me"; break;
case Character.COMBINING_SPACING_MARK: typeStr = "Mc"; break;
case Character.DECIMAL_DIGIT_NUMBER: typeStr = "Nd"; break;
case Character.LETTER_NUMBER: typeStr = "Nl"; break;
case Character.OTHER_NUMBER: typeStr = "No"; break;
case Character.SPACE_SEPARATOR: typeStr = "Zs"; break;
case Character.LINE_SEPARATOR: typeStr = "Zl"; break;
case Character.PARAGRAPH_SEPARATOR: typeStr = "Zp"; break;
case Character.CONTROL: typeStr = "Cc"; break;
case Character.FORMAT: typeStr = "Cf"; break;
case Character.PRIVATE_USE: typeStr = "Co"; break;
case Character.SURROGATE: typeStr = "Cs"; break;
case Character.DASH_PUNCTUATION: typeStr = "Pd"; break;
case Character.START_PUNCTUATION: typeStr = "Ps"; break;
case Character.END_PUNCTUATION: typeStr = "Pe"; break;
case Character.CONNECTOR_PUNCTUATION: typeStr = "Pc"; break;
case Character.OTHER_PUNCTUATION: typeStr = "Po"; break;
case Character.MATH_SYMBOL: typeStr = "Sm"; break;
case Character.CURRENCY_SYMBOL: typeStr = "Sc"; break;
case Character.MODIFIER_SYMBOL: typeStr = "Sk"; break;
case Character.OTHER_SYMBOL: typeStr = "So"; break;
default: typeStr = "ERROR"; break;
}
if ( ! (chars[i].category.equals(typeStr)
|| (typeStr.equals("Ps")
&& chars[i].category.equals("Pi"))
|| (typeStr.equals("Pe")
&& chars[i].category.equals("Pf"))))
{
reportError(
stringChar(i) + " is reported to be type " + typeStr +
" instead of " + chars[i].category);
}
else checkPassed();
// isJavaIdentifierStart
if ( ( (chars[i].category.charAt(0) == 'L') ||
chars[i].category.equals("Sc") ||
chars[i].category.equals("Pc") ) !=
Character.isJavaIdentifierStart(i) )
{
reportError(i,
Character.isJavaIdentifierStart(i) ? "javaindetifierstart" : "not-javaidentfierstart");
}
else checkPassed();
// isJavaIdentifierPart
boolean shouldbe = false;
typeStr = chars[i].category;
if (
(
typeStr.charAt(0) == 'L' ||
typeStr.equals("Sc") ||
typeStr.equals("Pc") ||
typeStr.equals("Nd") ||
typeStr.equals("Nl") ||
typeStr.equals("Mc") ||
typeStr.equals("Mn") ||
typeStr.equals("Cf") ||
(typeStr.equals("Cc") && ignorable (i))
) != Character.isJavaIdentifierPart(i) )
{
reportError(i,
Character.isJavaIdentifierPart(i) ? "javaidentifierpart" : "not-javaidentifierpart" );
}
else checkPassed();
//isUnicodeIdentifierStart
if ( (chars[i].category.charAt(0) == 'L') !=
Character.isUnicodeIdentifierStart(i) )
{
reportError(i,
Character.isUnicodeIdentifierStart(i) ? "unicodeidentifierstart" : "not-unicodeidentifierstart" );
}
else checkPassed();
//isUnicodeIdentifierPart
shouldbe = false;
typeStr = chars[i].category;
if (
(
typeStr.charAt(0) == 'L' ||
typeStr.equals("Pc") ||
typeStr.equals("Nd") ||
typeStr.equals("Nl") ||
typeStr.equals("Mc") ||
typeStr.equals("Mn") ||
typeStr.equals("Cf") ||
(typeStr.equals("Cc") && ignorable (i))
) != Character.isUnicodeIdentifierPart(i) )
{
reportError(i,
Character.isUnicodeIdentifierPart(i) ? "unicodeidentifierpart" : "not-unicodeidentifierpart" );
}
else checkPassed();
//isIdentifierIgnorable
if (
(
ignorable (i)
) != Character.isIdentifierIgnorable(i) )
{
reportError(i,
Character.isIdentifierIgnorable(i)? "identifierignorable": "not-identifierignorable");
}
else checkPassed();
// toLowerCase
char cs = (chars[i].lowercase != 0 ? chars[i].lowercase : i);
if ( Character.toLowerCase(i) != cs )
{
reportError(stringChar(i) + " has wrong lowercase form of " +
stringChar(Character.toLowerCase(i)) +" instead of " +
stringChar(cs) );
}
else checkPassed();
// toUpperCase
cs =(chars[i].uppercase != 0 ? chars[i].uppercase : i);
if ( Character.toUpperCase(i) != cs )
{
reportError( stringChar(i) +
" has wrong uppercase form of " +
stringChar(Character.toUpperCase(i)) +
" instead of " +
stringChar(cs) );
}
else checkPassed();
// toTitleCase
cs = (chars[i].titlecase != 0 ? chars[i].titlecase :
chars[i].uppercase !=0 ? chars[i].uppercase : i);
if ( "Lt".equals(chars[i].category) )
{
cs = i;
}
if ( Character.toTitleCase(i) != cs )
{
reportError( stringChar(i) +
" has wrong titlecase form of " +
stringChar(Character.toTitleCase(i)) +
" instead of " +
stringChar(cs) );
}
else checkPassed();
// digit
int digit = chars[i].digit;
for ( int radix = Character.MIN_RADIX; radix <= Character.MAX_RADIX; radix++)
{
int sb = digit;
if ( (chars[i].name.indexOf("DIGIT") == -1)
|| range(i,0x2000,0x2FFF))
sb = -1;
if (i >= 'A' && i <= 'Z')
sb = i - 'A' + 10;
if (i >= 'a' && i <= 'z')
sb = i - 'a' + 10;
if (sb >= radix)
sb = -1;
if ( Character.digit(i,radix) != sb )
{
reportError( stringChar(i) + " has wrong digit form of "
+ Character.digit(i,radix) + " for radix " + radix + " instead of "
+ sb );
}
else checkPassed();
}
// getNumericValue
if ( chars[i].numericValue !=
Character.getNumericValue(i) )
{
reportError( stringChar(i) + " has wrong numeric value of " +
Character.getNumericValue(i) + " instead of " + chars[i].numericValue);
}
if ( testDeprecated )
{
// isJavaLetter
if ( (i == '$' || i == '_' || Character.isLetter(i)) !=
Character.isJavaLetter(i) )
{
reportError(i,
(Character.isJavaLetter(i)? "javaletter" : "not-javaletter"));
}
else checkPassed();
// isJavaLetterOrDigit
if ((Character.isJavaLetter(i) || Character.isDigit(i) ||
i == '$' || i == '_') !=
Character.isJavaLetterOrDigit(i)
)
{
reportError(i,
(Character.isJavaLetterOrDigit(i) ? "javaletterordigit" : "not-javaletterordigit") );
}
else checkPassed();
// isSpace
if (((i == ' ' || i == '\t' || i == '\n' || i == '\r' ||
i == '\f')) != Character.isSpace(i) )
{
reportError(i,
(Character.isSpace(i) ? "space" : "non-space" ) );
}
else checkPassed();
} // testDeprecated
} // for
// forDigit
for ( int r = -100; r < 100; r++ )
{
for ( int d = -100; d < 100; d++ )
{
char dch = Character.forDigit(d,r);
char wantch = 0;
if ( range(r, Character.MIN_RADIX, Character.MAX_RADIX) &&
range(d,0,r-1) )
{
if ( d < 10 )
{
wantch = (char)('0' + (char)d);
}
else if ( d < 36 )
{
wantch = (char)('a' + d - 10);
}
}
if ( dch != wantch )
{
reportError( "Error in forDigit(" + d +
"," + r + "), got " + dch + " wanted " +
wantch );
}
else checkPassed();
}
}
}
| public void performTests()
{
for ( int x =0; x <= 0xffff; x++ )
{
// isLowerCase
char i = (char)x;
// NOTE: JLS doesn't say anything about `Ll'
// category. And Unicode 2.1.8 has some
// characters which might be considered
// lowercase by all the other rules, but which
// are not marked Ll -- e.g., 0x0345. So we
// don't check for this.
if ( ( // "Ll".equals(chars[i].category) &&
(i < 0x2000 || i > 0x2fff)
&& chars[i].lowercase == 0
&& (chars[i].uppercase != 0
|| (chars[i].name.indexOf("SMALL LETTER")
!= -1)
|| (chars[i].name.indexOf("SMALL LIGATURE")
!= -1)))
!= Character.isLowerCase((char)i) )
{
reportError(i,
(Character.isLowerCase((char)i) ? "lowercase" : "not-lowercase" ));
}
else checkPassed();
// isUpperCase
// NOTE: JLS doesn't say anything about `Lu'
// category. And Unicode 2.1.8 has some
// characters which might be considered
// uppercase by all the other rules, but which
// are not marked Lu -- e.g., 0x03d2. So we
// don't check for this.
if ( // "Lu".equals(chars[i].category)
( (i < 0x2000 || i > 0x2ffff)
&& chars[i].uppercase == 0
&& (chars[i].lowercase != 0
|| (chars[i].name.indexOf("CAPITAL LETTER")
!= -1)
|| (chars[i].name.indexOf("CAPITAL LIGATURE")
!= -1)))
!= Character.isUpperCase((char)i) )
{
reportError(i,
(Character.isUpperCase((char)i) ? "uppercase" : "not-uppercase" ) );
}
else checkPassed();
// isTitleCase
if ( "Lt".equals(chars[i].category) !=
Character.isTitleCase((char)i) )
{
reportError(i,
(Character.isTitleCase((char)i) ? "titlecase" : "not-titlecase" ) );
}
else checkPassed();
// isDigit
// if ( (chars[i].category.charAt(0) == 'N') !=
// Character.isDigit((char)i) )
// if (( (chars[i].name.indexOf("DIGIT") > -1) &&
// !range(i,0x2000,0x2FFF)
if ( (range (i, 0x0030, 0x0039)
|| range (i, 0x0660, 0x0669)
|| range (i, 0x6f0, 0x06f9)
|| range (i, 0x0966, 0x096f)
|| range (i, 0x09e6, 0x09ef)
|| range (i, 0x0a66, 0x0a6f)
|| range (i, 0x0ae6, 0x0aef)
|| range (i, 0x0b66, 0x0b6f)
|| range (i, 0x0be7, 0x0bef)
|| range (i, 0x0c66, 0x0c6f)
|| range (i, 0x0ce6, 0x0cef)
|| range (i, 0x0d66, 0x0d6f)
|| range (i, 0x0e50, 0x0e59)
|| range (i, 0x0ed0, 0x0ed9)
|| range (i, 0x0f20, 0x0f29)
|| range (i, 0xff10, 0xff19)
) !=Character.isDigit((char)i) )
{
reportError(i,
(Character.isDigit((char)i) ? "digit" : "not-digit" ) );
}
else checkPassed();
// isDefined
/* if ( ((chars[i] != null) ||
(i >= 0xD800 && i <= 0xFA2D ) )*/
if ( !chars[i].category.equals("Cn")
!= Character.isDefined((char)i) )
{
reportError(i,
(Character.isDefined((char)i) ? "defined" : "not-defined" ) );
}
else checkPassed();
// isLetter
if ( (
(chars[i].category.charAt(0) == 'L')) !=
Character.isLetter((char)i) )
{
reportError(i,
(Character.isLetter((char)i) ? "letter" : "not-letter" ) );
}
else checkPassed();
// isLetterOrDigit
if ( Character.isLetterOrDigit(i) !=
(Character.isLetter(i) || Character.isDigit(i)) )
{
reportError(i,
(Character.isLetterOrDigit(i) ? "letterordigit" : "not-letterordigit") );
}
else checkPassed();
// isSpaceChar
if ( (
(chars[i].category.charAt(0) == 'Z')) !=
Character.isSpaceChar(i) )
{
reportError(i,
(Character.isSpaceChar(i) ? "spacechar" : "not-spacechar" ) );
}
else checkPassed();
// isWhiteSpace
boolean t = false;
if ( chars[i].category.charAt(0) == 'Z' && i !=0x00a0
&& i != 0xFEFF )
t = true;
if ( range(i,0x0009,0x000D)|| range(i,0x001C,0x001F) )
t = true;
if ( t != Character.isWhitespace(i) )
{
reportError(i,
Character.isWhitespace(i) ? "whitespace" : "not-whitespace" );
}
else checkPassed();
// isISOControl
if ( ((i <= 0x001F)
|| range(i,0x007F,0x009F) ) !=
Character.isISOControl(i) )
{
reportError(i,
Character.isISOControl(i) ? "isocontrol" : "not-isocontrol");
}
else checkPassed();
int type = Character.getType(i);
String typeStr = null;
switch (type)
{
case Character.UNASSIGNED: typeStr = "Cn"; break;
case Character.UPPERCASE_LETTER: typeStr = "Lu"; break;
case Character.LOWERCASE_LETTER: typeStr = "Ll"; break;
case Character.TITLECASE_LETTER: typeStr = "Lt"; break;
case Character.MODIFIER_LETTER: typeStr = "Lm"; break;
case Character.OTHER_LETTER: typeStr = "Lo"; break;
case Character.NON_SPACING_MARK: typeStr = "Mn"; break;
case Character.ENCLOSING_MARK: typeStr = "Me"; break;
case Character.COMBINING_SPACING_MARK: typeStr = "Mc"; break;
case Character.DECIMAL_DIGIT_NUMBER: typeStr = "Nd"; break;
case Character.LETTER_NUMBER: typeStr = "Nl"; break;
case Character.OTHER_NUMBER: typeStr = "No"; break;
case Character.SPACE_SEPARATOR: typeStr = "Zs"; break;
case Character.LINE_SEPARATOR: typeStr = "Zl"; break;
case Character.PARAGRAPH_SEPARATOR: typeStr = "Zp"; break;
case Character.CONTROL: typeStr = "Cc"; break;
case Character.FORMAT: typeStr = "Cf"; break;
case Character.PRIVATE_USE: typeStr = "Co"; break;
case Character.SURROGATE: typeStr = "Cs"; break;
case Character.DASH_PUNCTUATION: typeStr = "Pd"; break;
case Character.START_PUNCTUATION: typeStr = "Ps"; break;
case Character.END_PUNCTUATION: typeStr = "Pe"; break;
case Character.CONNECTOR_PUNCTUATION: typeStr = "Pc"; break;
case Character.OTHER_PUNCTUATION: typeStr = "Po"; break;
case Character.MATH_SYMBOL: typeStr = "Sm"; break;
case Character.CURRENCY_SYMBOL: typeStr = "Sc"; break;
case Character.MODIFIER_SYMBOL: typeStr = "Sk"; break;
case Character.OTHER_SYMBOL: typeStr = "So"; break;
default: typeStr = "ERROR"; break;
}
if ( ! (chars[i].category.equals(typeStr)
|| (typeStr.equals("Ps")
&& chars[i].category.equals("Pi"))
|| (typeStr.equals("Pe")
&& chars[i].category.equals("Pf"))))
{
reportError(
stringChar(i) + " is reported to be type " + typeStr +
" instead of " + chars[i].category);
}
else checkPassed();
// isJavaIdentifierStart
if ( ( (chars[i].category.charAt(0) == 'L') ||
chars[i].category.equals("Sc") ||
chars[i].category.equals("Pc") ) !=
Character.isJavaIdentifierStart(i) )
{
reportError(i,
Character.isJavaIdentifierStart(i) ? "javaindetifierstart" : "not-javaidentfierstart");
}
else checkPassed();
// isJavaIdentifierPart
boolean shouldbe = false;
typeStr = chars[i].category;
if (
(
typeStr.charAt(0) == 'L' ||
typeStr.equals("Sc") ||
typeStr.equals("Pc") ||
typeStr.equals("Nd") ||
typeStr.equals("Nl") ||
typeStr.equals("Mc") ||
typeStr.equals("Mn") ||
typeStr.equals("Cf") ||
(typeStr.equals("Cc") && ignorable (i))
) != Character.isJavaIdentifierPart(i) )
{
reportError(i,
Character.isJavaIdentifierPart(i) ? "javaidentifierpart" : "not-javaidentifierpart" );
}
else checkPassed();
//isUnicodeIdentifierStart
if ( (chars[i].category.charAt(0) == 'L') !=
Character.isUnicodeIdentifierStart(i) )
{
reportError(i,
Character.isUnicodeIdentifierStart(i) ? "unicodeidentifierstart" : "not-unicodeidentifierstart" );
}
else checkPassed();
//isUnicodeIdentifierPart
shouldbe = false;
typeStr = chars[i].category;
if (
(
typeStr.charAt(0) == 'L' ||
typeStr.equals("Pc") ||
typeStr.equals("Nd") ||
typeStr.equals("Nl") ||
typeStr.equals("Mc") ||
typeStr.equals("Mn") ||
typeStr.equals("Cf") ||
(typeStr.equals("Cc") && ignorable (i))
) != Character.isUnicodeIdentifierPart(i) )
{
reportError(i,
Character.isUnicodeIdentifierPart(i) ? "unicodeidentifierpart" : "not-unicodeidentifierpart" );
}
else checkPassed();
//isIdentifierIgnorable
if (
(
ignorable (i)
) != Character.isIdentifierIgnorable(i) )
{
reportError(i,
Character.isIdentifierIgnorable(i)? "identifierignorable": "not-identifierignorable");
}
else checkPassed();
// toLowerCase
char cs = (chars[i].lowercase != 0 ? chars[i].lowercase : i);
if ( Character.toLowerCase(i) != cs )
{
reportError(stringChar(i) + " has wrong lowercase form of " +
stringChar(Character.toLowerCase(i)) +" instead of " +
stringChar(cs) );
}
else checkPassed();
// toUpperCase
cs =(chars[i].uppercase != 0 ? chars[i].uppercase : i);
if ( Character.toUpperCase(i) != cs )
{
reportError( stringChar(i) +
" has wrong uppercase form of " +
stringChar(Character.toUpperCase(i)) +
" instead of " +
stringChar(cs) );
}
else checkPassed();
// toTitleCase
cs = (chars[i].titlecase != 0 ? chars[i].titlecase :
chars[i].uppercase !=0 ? chars[i].uppercase : i);
if ( "Lt".equals(chars[i].category) )
{
cs = i;
}
if ( Character.toTitleCase(i) != cs )
{
reportError( stringChar(i) +
" has wrong titlecase form of " +
stringChar(Character.toTitleCase(i)) +
" instead of " +
stringChar(cs) );
}
else checkPassed();
// digit
int digit = chars[i].digit;
for ( int radix = Character.MIN_RADIX; radix <= Character.MAX_RADIX; radix++)
{
int sb = digit;
if ( (chars[i].name.indexOf("DIGIT") == -1)
|| range(i,0x2000,0x2FFF))
sb = -1;
if (i >= 'A' && i <= 'Z')
sb = i - 'A' + 10;
if (i >= 'a' && i <= 'z')
sb = i - 'a' + 10;
if (sb >= radix)
sb = -1;
if ( Character.digit(i,radix) != sb )
{
reportError( stringChar(i) + " has wrong digit form of "
+ Character.digit(i,radix) + " for radix " + radix + " instead of "
+ sb );
}
else checkPassed();
}
// getNumericValue
if ( chars[i].numericValue !=
Character.getNumericValue(i) )
{
reportError( stringChar(i) + " has wrong numeric value of " +
Character.getNumericValue(i) + " instead of " + chars[i].numericValue);
}
if ( testDeprecated )
{
// isJavaLetter
if ( (i == '$' || i == '_' || Character.isLetter(i)) !=
Character.isJavaLetter(i) )
{
reportError(i,
(Character.isJavaLetter(i)? "javaletter" : "not-javaletter"));
}
else checkPassed();
// isJavaLetterOrDigit
if ((Character.isJavaLetter(i) || Character.isDigit(i) ||
i == '$' || i == '_') !=
Character.isJavaLetterOrDigit(i)
)
{
reportError(i,
(Character.isJavaLetterOrDigit(i) ? "javaletterordigit" : "not-javaletterordigit") );
}
else checkPassed();
// isSpace
if (((i == ' ' || i == '\t' || i == '\n' || i == '\r' ||
i == '\f')) != Character.isSpace(i) )
{
reportError(i,
(Character.isSpace(i) ? "space" : "non-space" ) );
}
else checkPassed();
} // testDeprecated
} // for
// forDigit
for ( int r = -100; r < 100; r++ )
{
for ( int d = -100; d < 100; d++ )
{
char dch = Character.forDigit(d,r);
char wantch = 0;
if ( range(r, Character.MIN_RADIX, Character.MAX_RADIX) &&
range(d,0,r-1) )
{
if ( d < 10 )
{
wantch = (char)('0' + (char)d);
}
else if ( d < 36 )
{
wantch = (char)('a' + d - 10);
}
}
if ( dch != wantch )
{
reportError( "Error in forDigit(" + d +
"," + r + "), got " + dch + " wanted " +
wantch );
}
else checkPassed();
}
}
}
|
diff --git a/Interpreter/src/edu/tum/lua/stdlib/GetMetatable.java b/Interpreter/src/edu/tum/lua/stdlib/GetMetatable.java
index 5e4bf20..9360906 100644
--- a/Interpreter/src/edu/tum/lua/stdlib/GetMetatable.java
+++ b/Interpreter/src/edu/tum/lua/stdlib/GetMetatable.java
@@ -1,22 +1,22 @@
package edu.tum.lua.stdlib;
import static edu.tum.lua.Preconditions.checkArguments;
import java.util.Collections;
import java.util.List;
import edu.tum.lua.types.LuaFunctionNative;
import edu.tum.lua.types.LuaTable;
import edu.tum.lua.types.LuaType;
public class GetMetatable extends LuaFunctionNative {
private static final LuaType[][] types = { { LuaType.TABLE } };
@Override
public List<Object> apply(List<Object> arguments) {
checkArguments("getmetatable", arguments, types);
LuaTable table = (LuaTable) arguments.get(0);
- return Collections.singletonList(table.getMetatable());
+ return Collections.singletonList((Object) table.getMetatable());
}
}
| true | true | public List<Object> apply(List<Object> arguments) {
checkArguments("getmetatable", arguments, types);
LuaTable table = (LuaTable) arguments.get(0);
return Collections.singletonList(table.getMetatable());
}
| public List<Object> apply(List<Object> arguments) {
checkArguments("getmetatable", arguments, types);
LuaTable table = (LuaTable) arguments.get(0);
return Collections.singletonList((Object) table.getMetatable());
}
|
diff --git a/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/contentassist/AutoELContentAssistantProposal.java b/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/contentassist/AutoELContentAssistantProposal.java
index 692ca47e..9c9a3df2 100644
--- a/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/contentassist/AutoELContentAssistantProposal.java
+++ b/plugins/org.jboss.tools.jst.jsp/src/org/jboss/tools/jst/jsp/contentassist/AutoELContentAssistantProposal.java
@@ -1,210 +1,210 @@
/*******************************************************************************
* Copyright (c) 2010 Red Hat, Inc.
* Distributed under license by Red Hat, Inc. All rights reserved.
* This program is made available under the terms of the
* Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
******************************************************************************/
package org.jboss.tools.jst.jsp.contentassist;
import java.io.Reader;
import java.io.StringReader;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.text.javadoc.JavadocContentAccess2;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLinks;
import org.eclipse.jdt.ui.JavaElementLabels;
import org.eclipse.jface.internal.text.html.HTMLPrinter;
import org.eclipse.jface.text.contentassist.IContextInformation;
import org.eclipse.swt.graphics.Image;
/**
* Class to provide EL proposals to Content Assistant.
* The main purpose is to provide correct additional proposal information based on
* IJavaElement objects collected for the proposal.
*
* @author Victor Rubezhny
*/
@SuppressWarnings("restriction")
public class AutoELContentAssistantProposal extends AutoContentAssistantProposal {
private IJavaElement[] fJavaElements;
private String fAdditionalProposalInfo;
/**
* Constructs the proposal object
*
* @param replacementString
* @param replacementOffset
* @param replacementLength
* @param cursorPosition
* @param image
* @param displayString
* @param contextInformation
* @param elements
* @param relevance
*/
public AutoELContentAssistantProposal(String replacementString, int replacementOffset, int replacementLength, int cursorPosition, Image image, String displayString, IContextInformation contextInformation, IJavaElement[] elements, int relevance) {
super(replacementString, replacementOffset, replacementLength, cursorPosition, image, displayString, contextInformation, null, relevance);
this.fJavaElements = elements;
}
/*
* (non-Javadoc)
* @see org.eclipse.wst.sse.ui.internal.contentassist.CustomCompletionProposal#getAdditionalProposalInfo()
*/
public String getAdditionalProposalInfo() {
if (fAdditionalProposalInfo == null) {
if (this.fJavaElements != null && this.fJavaElements.length > 0) {
this.fAdditionalProposalInfo = extractProposalContextInfo(fJavaElements);
}
}
return fAdditionalProposalInfo;
}
/*
* Extracts the additional proposal information based on Javadoc for the stored IJavaElement objects
*/
private String extractProposalContextInfo(IJavaElement[] elements) {
int nResults= elements.length;
StringBuffer buffer= new StringBuffer();
boolean hasContents= false;
IJavaElement element= null;
if (nResults > 1) {
for (int i= 0; i < elements.length; i++) {
if (elements[i] == null) continue;
if (elements[i] instanceof IMember ||
elements[i].getElementType() == IJavaElement.LOCAL_VARIABLE ||
elements[i].getElementType() == IJavaElement.TYPE_PARAMETER) {
- buffer.append('�').append(' ').append(getInfoText(elements[i]));
+ buffer.append('\uE467').append(' ').append(getInfoText(elements[i]));
hasContents= true;
}
buffer.append("<br/>"); //$NON-NLS-1$
}
for (int i=0; i < elements.length; i++) {
if (elements[i] == null) continue;
if (elements[i] instanceof IMember ||
elements[i].getElementType() == IJavaElement.LOCAL_VARIABLE ||
elements[i].getElementType() == IJavaElement.TYPE_PARAMETER) {
buffer.append("<br/>"); //$NON-NLS-1$
addFullInfo(buffer, elements[i]);
hasContents = true;
}
}
} else {
element= elements[0];
if (element instanceof IMember ||
element.getElementType() == IJavaElement.LOCAL_VARIABLE ||
element.getElementType() == IJavaElement.TYPE_PARAMETER) {
addFullInfo(buffer, element);
hasContents= true;
}
}
if (!hasContents)
return null;
if (buffer.length() > 0) {
HTMLPrinter.insertPageProlog(buffer, 0, (String)null);
HTMLPrinter.addPageEpilog(buffer);
return buffer.toString();
}
return null;
}
private static final long LABEL_FLAGS= JavaElementLabels.ALL_FULLY_QUALIFIED
| JavaElementLabels.M_PRE_RETURNTYPE | JavaElementLabels.M_PARAMETER_TYPES | JavaElementLabels.M_PARAMETER_NAMES | JavaElementLabels.M_EXCEPTIONS
| JavaElementLabels.F_PRE_TYPE_SIGNATURE | JavaElementLabels.M_PRE_TYPE_PARAMETERS | JavaElementLabels.T_TYPE_PARAMETERS
| JavaElementLabels.USE_RESOLVED;
private static final long LOCAL_VARIABLE_FLAGS= LABEL_FLAGS & ~JavaElementLabels.F_FULLY_QUALIFIED | JavaElementLabels.F_POST_QUALIFIED;
private static final long TYPE_PARAMETER_FLAGS= LABEL_FLAGS | JavaElementLabels.TP_POST_QUALIFIED;
/*
* Returns the label for the IJavaElement objects
*/
private String getInfoText(IJavaElement element) {
long flags;
switch (element.getElementType()) {
case IJavaElement.LOCAL_VARIABLE:
flags= LOCAL_VARIABLE_FLAGS;
break;
case IJavaElement.TYPE_PARAMETER:
flags= TYPE_PARAMETER_FLAGS;
break;
default:
flags= LABEL_FLAGS;
break;
}
StringBuffer label= new StringBuffer(JavaElementLinks.getElementLabel(element, flags));
StringBuffer buf= new StringBuffer();
buf.append("<span style='word-wrap:break-word;'>"); //$NON-NLS-1$
buf.append(label);
buf.append("</span>"); //$NON-NLS-1$
return buf.toString();
}
/*
* Adds full information to the additional proposal information
*
* @param buffer
* @param element
* @return
*/
private void addFullInfo(StringBuffer buffer, IJavaElement element) {
if (element instanceof IMember) {
IMember member= (IMember) element;
HTMLPrinter.addSmallHeader(buffer, getInfoText(member));
Reader reader = null;
try {
String content= JavadocContentAccess2.getHTMLContent(member, true);
reader= content == null ? null : new StringReader(content);
} catch (JavaModelException ex) {
JavaPlugin.log(ex);
}
if (reader == null) {
reader = new StringReader(Messages.NO_JAVADOC);
}
if (reader != null) {
HTMLPrinter.addParagraph(buffer, reader);
}
} else if (element.getElementType() == IJavaElement.LOCAL_VARIABLE || element.getElementType() == IJavaElement.TYPE_PARAMETER) {
HTMLPrinter.addSmallHeader(buffer, getInfoText(element));
}
}
/**
* Return cursor position of proposal replacement string.
*
* Method is added because of JBIDE-7168
*/
public int getCursorPosition() {
int cursorPosition = -1;
int openingQuoteInReplacement = getReplacementString().indexOf('(');
int closingQuoteInReplacement = getReplacementString().indexOf(')');
int openingQuoteInDisplay = getDisplayString().indexOf('(');
int closingQuoteInDisplay = getDisplayString().indexOf(')');
if (openingQuoteInReplacement != -1 && closingQuoteInReplacement != -1 &&
openingQuoteInDisplay != -1 && closingQuoteInDisplay != -1 &&
(closingQuoteInReplacement - openingQuoteInReplacement) !=
(closingQuoteInDisplay - openingQuoteInDisplay)) {
cursorPosition = openingQuoteInReplacement + 1;
}
return cursorPosition>-1?cursorPosition:super.getCursorPosition();
}
}
| true | true | private String extractProposalContextInfo(IJavaElement[] elements) {
int nResults= elements.length;
StringBuffer buffer= new StringBuffer();
boolean hasContents= false;
IJavaElement element= null;
if (nResults > 1) {
for (int i= 0; i < elements.length; i++) {
if (elements[i] == null) continue;
if (elements[i] instanceof IMember ||
elements[i].getElementType() == IJavaElement.LOCAL_VARIABLE ||
elements[i].getElementType() == IJavaElement.TYPE_PARAMETER) {
buffer.append('�').append(' ').append(getInfoText(elements[i]));
hasContents= true;
}
buffer.append("<br/>"); //$NON-NLS-1$
}
for (int i=0; i < elements.length; i++) {
if (elements[i] == null) continue;
if (elements[i] instanceof IMember ||
elements[i].getElementType() == IJavaElement.LOCAL_VARIABLE ||
elements[i].getElementType() == IJavaElement.TYPE_PARAMETER) {
buffer.append("<br/>"); //$NON-NLS-1$
addFullInfo(buffer, elements[i]);
hasContents = true;
}
}
} else {
element= elements[0];
if (element instanceof IMember ||
element.getElementType() == IJavaElement.LOCAL_VARIABLE ||
element.getElementType() == IJavaElement.TYPE_PARAMETER) {
addFullInfo(buffer, element);
hasContents= true;
}
}
if (!hasContents)
return null;
if (buffer.length() > 0) {
HTMLPrinter.insertPageProlog(buffer, 0, (String)null);
HTMLPrinter.addPageEpilog(buffer);
return buffer.toString();
}
return null;
}
| private String extractProposalContextInfo(IJavaElement[] elements) {
int nResults= elements.length;
StringBuffer buffer= new StringBuffer();
boolean hasContents= false;
IJavaElement element= null;
if (nResults > 1) {
for (int i= 0; i < elements.length; i++) {
if (elements[i] == null) continue;
if (elements[i] instanceof IMember ||
elements[i].getElementType() == IJavaElement.LOCAL_VARIABLE ||
elements[i].getElementType() == IJavaElement.TYPE_PARAMETER) {
buffer.append('\uE467').append(' ').append(getInfoText(elements[i]));
hasContents= true;
}
buffer.append("<br/>"); //$NON-NLS-1$
}
for (int i=0; i < elements.length; i++) {
if (elements[i] == null) continue;
if (elements[i] instanceof IMember ||
elements[i].getElementType() == IJavaElement.LOCAL_VARIABLE ||
elements[i].getElementType() == IJavaElement.TYPE_PARAMETER) {
buffer.append("<br/>"); //$NON-NLS-1$
addFullInfo(buffer, elements[i]);
hasContents = true;
}
}
} else {
element= elements[0];
if (element instanceof IMember ||
element.getElementType() == IJavaElement.LOCAL_VARIABLE ||
element.getElementType() == IJavaElement.TYPE_PARAMETER) {
addFullInfo(buffer, element);
hasContents= true;
}
}
if (!hasContents)
return null;
if (buffer.length() > 0) {
HTMLPrinter.insertPageProlog(buffer, 0, (String)null);
HTMLPrinter.addPageEpilog(buffer);
return buffer.toString();
}
return null;
}
|
diff --git a/src/main/java/edu/sc/seis/sod/source/seismogram/DataSelectWebService.java b/src/main/java/edu/sc/seis/sod/source/seismogram/DataSelectWebService.java
index 1a5d370b4..4518f1cff 100644
--- a/src/main/java/edu/sc/seis/sod/source/seismogram/DataSelectWebService.java
+++ b/src/main/java/edu/sc/seis/sod/source/seismogram/DataSelectWebService.java
@@ -1,109 +1,115 @@
package edu.sc.seis.sod.source.seismogram;
import java.io.IOException;
import java.net.Authenticator;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.TimeZone;
import org.w3c.dom.Element;
import edu.iris.Fissures.FissuresException;
import edu.iris.Fissures.IfSeismogramDC.RequestFilter;
import edu.iris.Fissures.model.MicroSecondDate;
import edu.iris.Fissures.model.UnitImpl;
import edu.iris.Fissures.network.ChannelImpl;
import edu.iris.Fissures.seismogramDC.LocalSeismogramImpl;
import edu.sc.seis.fissuresUtil.cache.CacheEvent;
import edu.sc.seis.fissuresUtil.chooser.ThreadSafeSimpleDateFormat;
import edu.sc.seis.fissuresUtil.exceptionHandler.GlobalExceptionHandler;
import edu.sc.seis.fissuresUtil.mseed.FissuresConvert;
import edu.sc.seis.fissuresUtil.time.MicroSecondTimeRange;
import edu.sc.seis.fissuresUtil.time.RangeTool;
import edu.sc.seis.seisFile.MSeedQueryReader;
import edu.sc.seis.seisFile.SeisFileException;
import edu.sc.seis.seisFile.dataSelectWS.DataSelectException;
import edu.sc.seis.seisFile.dataSelectWS.DataSelectReader;
import edu.sc.seis.seisFile.mseed.DataRecord;
import edu.sc.seis.seisFile.mseed.SeedFormatException;
import edu.sc.seis.sod.CookieJar;
import edu.sc.seis.sod.SodUtil;
public class DataSelectWebService implements SeismogramSourceLocator {
public DataSelectWebService(Element config) throws MalformedURLException {
this(config, DEFAULT_WS_URL);
}
public DataSelectWebService(Element config, String defaultURL) throws MalformedURLException {
baseUrl = SodUtil.loadText(config, "url", defaultURL);
String user = SodUtil.loadText(config, "user", "");
String password = SodUtil.loadText(config, "password", "");
if (user.length() != 0 && password.length() != 0) {
Authenticator.setDefault(new MyAuthenticator(user, password));
}
}
public SeismogramSource getSeismogramSource(CacheEvent event,
ChannelImpl channel,
RequestFilter[] infilters,
CookieJar cookieJar) throws Exception {
return new SeismogramSource() {
public List<RequestFilter> available_data(List<RequestFilter> request) {
// bad fix this...
return request;
}
public List<LocalSeismogramImpl> retrieveData(List<RequestFilter> request) throws FissuresException {
try {
List<LocalSeismogramImpl> out = new ArrayList<LocalSeismogramImpl>();
MSeedQueryReader dsReader = new DataSelectReader(baseUrl);
for (RequestFilter rf : request) {
MicroSecondDate start = new MicroSecondDate(rf.start_time);
List<DataRecord> records = dsReader.read(rf.channel_id.network_id.network_code,
rf.channel_id.station_code,
rf.channel_id.site_code,
rf.channel_id.channel_code,
start,
new MicroSecondDate(rf.end_time));
- out.addAll(FissuresConvert.toFissures(records));
+ List<LocalSeismogramImpl> perRFList = FissuresConvert.toFissures(records);
+ for (LocalSeismogramImpl seis : perRFList) {
+ // the DataRecords know nothing about channel or network begin times, so use the request
+ seis.channel_id.begin_time = rf.channel_id.begin_time;
+ seis.channel_id.network_id.begin_time = rf.channel_id.network_id.begin_time;
+ }
+ out.addAll(perRFList);
}
return out;
} catch(IOException e) {
GlobalExceptionHandler.handle(e);
throw new FissuresException(e.getMessage(), new edu.iris.Fissures.Error(1, "IOException"));
} catch(SeedFormatException e) {
GlobalExceptionHandler.handle(e);
throw new FissuresException(e.getMessage(), new edu.iris.Fissures.Error(1, "SeedFormatException"));
} catch(SeisFileException e) {
GlobalExceptionHandler.handle(e);
throw new FissuresException(e.getMessage(), new edu.iris.Fissures.Error(1, "DataSelectException"));
}
}
};
}
protected String baseUrl;
public static final String DEFAULT_WS_URL = "http://www.iris.edu/ws/dataselect/query";
public static ThreadSafeSimpleDateFormat longFormat = new ThreadSafeSimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", TimeZone.getTimeZone("GMT"));
private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(DataSelectWebService.class);
}
class MyAuthenticator extends Authenticator {
String user;
String password;
public MyAuthenticator(String user, String password) {
this.user = user;
this.password = password;
}
public PasswordAuthentication getPasswordAuthentication () {
return new PasswordAuthentication (user, password.toCharArray());
}
}
| true | true | public SeismogramSource getSeismogramSource(CacheEvent event,
ChannelImpl channel,
RequestFilter[] infilters,
CookieJar cookieJar) throws Exception {
return new SeismogramSource() {
public List<RequestFilter> available_data(List<RequestFilter> request) {
// bad fix this...
return request;
}
public List<LocalSeismogramImpl> retrieveData(List<RequestFilter> request) throws FissuresException {
try {
List<LocalSeismogramImpl> out = new ArrayList<LocalSeismogramImpl>();
MSeedQueryReader dsReader = new DataSelectReader(baseUrl);
for (RequestFilter rf : request) {
MicroSecondDate start = new MicroSecondDate(rf.start_time);
List<DataRecord> records = dsReader.read(rf.channel_id.network_id.network_code,
rf.channel_id.station_code,
rf.channel_id.site_code,
rf.channel_id.channel_code,
start,
new MicroSecondDate(rf.end_time));
out.addAll(FissuresConvert.toFissures(records));
}
return out;
} catch(IOException e) {
GlobalExceptionHandler.handle(e);
throw new FissuresException(e.getMessage(), new edu.iris.Fissures.Error(1, "IOException"));
} catch(SeedFormatException e) {
GlobalExceptionHandler.handle(e);
throw new FissuresException(e.getMessage(), new edu.iris.Fissures.Error(1, "SeedFormatException"));
} catch(SeisFileException e) {
GlobalExceptionHandler.handle(e);
throw new FissuresException(e.getMessage(), new edu.iris.Fissures.Error(1, "DataSelectException"));
}
}
};
}
| public SeismogramSource getSeismogramSource(CacheEvent event,
ChannelImpl channel,
RequestFilter[] infilters,
CookieJar cookieJar) throws Exception {
return new SeismogramSource() {
public List<RequestFilter> available_data(List<RequestFilter> request) {
// bad fix this...
return request;
}
public List<LocalSeismogramImpl> retrieveData(List<RequestFilter> request) throws FissuresException {
try {
List<LocalSeismogramImpl> out = new ArrayList<LocalSeismogramImpl>();
MSeedQueryReader dsReader = new DataSelectReader(baseUrl);
for (RequestFilter rf : request) {
MicroSecondDate start = new MicroSecondDate(rf.start_time);
List<DataRecord> records = dsReader.read(rf.channel_id.network_id.network_code,
rf.channel_id.station_code,
rf.channel_id.site_code,
rf.channel_id.channel_code,
start,
new MicroSecondDate(rf.end_time));
List<LocalSeismogramImpl> perRFList = FissuresConvert.toFissures(records);
for (LocalSeismogramImpl seis : perRFList) {
// the DataRecords know nothing about channel or network begin times, so use the request
seis.channel_id.begin_time = rf.channel_id.begin_time;
seis.channel_id.network_id.begin_time = rf.channel_id.network_id.begin_time;
}
out.addAll(perRFList);
}
return out;
} catch(IOException e) {
GlobalExceptionHandler.handle(e);
throw new FissuresException(e.getMessage(), new edu.iris.Fissures.Error(1, "IOException"));
} catch(SeedFormatException e) {
GlobalExceptionHandler.handle(e);
throw new FissuresException(e.getMessage(), new edu.iris.Fissures.Error(1, "SeedFormatException"));
} catch(SeisFileException e) {
GlobalExceptionHandler.handle(e);
throw new FissuresException(e.getMessage(), new edu.iris.Fissures.Error(1, "DataSelectException"));
}
}
};
}
|
diff --git a/java-demo/src/test/java/org/codehaus/gpars/javademo/DataflowTaskTest.java b/java-demo/src/test/java/org/codehaus/gpars/javademo/DataflowTaskTest.java
index 375b1f92..842d3b68 100644
--- a/java-demo/src/test/java/org/codehaus/gpars/javademo/DataflowTaskTest.java
+++ b/java-demo/src/test/java/org/codehaus/gpars/javademo/DataflowTaskTest.java
@@ -1,77 +1,77 @@
// GPars - Groovy Parallel Systems
//
// Copyright © 2008-2012 The original author or authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.codehaus.gpars.javademo;
import groovyx.gpars.MessagingRunnable;
import groovyx.gpars.dataflow.DataflowVariable;
import groovyx.gpars.dataflow.Promise;
import groovyx.gpars.group.DefaultPGroup;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import static org.junit.Assert.assertEquals;
@SuppressWarnings({"MagicNumber"})
public class DataflowTaskTest {
@Test
- public void testDataflowVariable() throws InterruptedException {
+ public void testDataflowVariable() throws Throwable {
final List<String> logMessages = new ArrayList<String>();
final DefaultPGroup group = new DefaultPGroup(10);
// variable can be assigned once only, read allowed multiple times
final DataflowVariable<Integer> a = new DataflowVariable<Integer>();
// group.task will use thread from pool and uses it to execute value bind
group.task(new Runnable() {
public void run() {
// first thread binding value succeeds, other attempts would fail with IllegalStateException
logMessages.add("Value bound");
a.bind(10);
}
});
// group.task will use thread from pool and uses it to execute call method
final Promise<?> result = group.task(new Callable() {
public Object call() throws Exception {
// getVal will wait for the value to be assigned
final int result = a.getVal() + 10;
logMessages.add("Value calculated");
return result;
}
});
// Specify, what will happen when value is bound
result.whenBound(new MessagingRunnable<Integer>() {
@Override
protected void doRun(final Integer resultValue) {
logMessages.add("Result calculated");
assertEquals("Result value invalid", 20L, resultValue.intValue());
assertEquals("Wrong order of calls", Arrays.asList("Value bound", "Value calculated", "Result calculated"), logMessages);
}
});
- System.out.println("result = " + result.getVal());
+ System.out.println("result = " + result.get());
}
}
| false | true | public void testDataflowVariable() throws InterruptedException {
final List<String> logMessages = new ArrayList<String>();
final DefaultPGroup group = new DefaultPGroup(10);
// variable can be assigned once only, read allowed multiple times
final DataflowVariable<Integer> a = new DataflowVariable<Integer>();
// group.task will use thread from pool and uses it to execute value bind
group.task(new Runnable() {
public void run() {
// first thread binding value succeeds, other attempts would fail with IllegalStateException
logMessages.add("Value bound");
a.bind(10);
}
});
// group.task will use thread from pool and uses it to execute call method
final Promise<?> result = group.task(new Callable() {
public Object call() throws Exception {
// getVal will wait for the value to be assigned
final int result = a.getVal() + 10;
logMessages.add("Value calculated");
return result;
}
});
// Specify, what will happen when value is bound
result.whenBound(new MessagingRunnable<Integer>() {
@Override
protected void doRun(final Integer resultValue) {
logMessages.add("Result calculated");
assertEquals("Result value invalid", 20L, resultValue.intValue());
assertEquals("Wrong order of calls", Arrays.asList("Value bound", "Value calculated", "Result calculated"), logMessages);
}
});
System.out.println("result = " + result.getVal());
}
| public void testDataflowVariable() throws Throwable {
final List<String> logMessages = new ArrayList<String>();
final DefaultPGroup group = new DefaultPGroup(10);
// variable can be assigned once only, read allowed multiple times
final DataflowVariable<Integer> a = new DataflowVariable<Integer>();
// group.task will use thread from pool and uses it to execute value bind
group.task(new Runnable() {
public void run() {
// first thread binding value succeeds, other attempts would fail with IllegalStateException
logMessages.add("Value bound");
a.bind(10);
}
});
// group.task will use thread from pool and uses it to execute call method
final Promise<?> result = group.task(new Callable() {
public Object call() throws Exception {
// getVal will wait for the value to be assigned
final int result = a.getVal() + 10;
logMessages.add("Value calculated");
return result;
}
});
// Specify, what will happen when value is bound
result.whenBound(new MessagingRunnable<Integer>() {
@Override
protected void doRun(final Integer resultValue) {
logMessages.add("Result calculated");
assertEquals("Result value invalid", 20L, resultValue.intValue());
assertEquals("Wrong order of calls", Arrays.asList("Value bound", "Value calculated", "Result calculated"), logMessages);
}
});
System.out.println("result = " + result.get());
}
|
diff --git a/src/UI/PlaceHoldDialog.java b/src/UI/PlaceHoldDialog.java
index 7141690..7abd254 100644
--- a/src/UI/PlaceHoldDialog.java
+++ b/src/UI/PlaceHoldDialog.java
@@ -1,121 +1,121 @@
package UI;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import Transactions.Transactions;
public class PlaceHoldDialog extends JFrame implements ActionListener{
JTextField callNo = new JTextField();
// JTextField author = new JTextField();
// JTextField subject = new JTextField();
static String returnToUserDialogString = "Return to User Dialog";
static String placeHold = "Place hold";
static String bid;
public static final int VALIDATIONERROR = 2;
public PlaceHoldDialog(String name)
{
super (name);
}
private void addComponentsToPane(final Container pane)
{
JPanel panel = new JPanel();
- panel.setLayout(new GridLayout(5, 2));
+ panel.setLayout(new GridLayout(3, 2));
panel.add(new Label("Place Hold"));
panel.add(new Label(""));
panel.add(new Label("Call number"));
panel.add(callNo);
// provide option to search ?
JButton returnToUserDialog = new JButton(returnToUserDialogString);
returnToUserDialog.setActionCommand(returnToUserDialogString);
returnToUserDialog.addActionListener(this);
JButton placeHoldButton = new JButton(placeHold);
placeHoldButton.setActionCommand(placeHold);
placeHoldButton.addActionListener(this);
panel.add(returnToUserDialog);
panel.add(placeHoldButton);
pane.add(panel);
}
public static void createAndShowGUI(String borrowerID) {
//Create and set up the window.
PlaceHoldDialog frame = new PlaceHoldDialog("Search Dialog");
// frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up the content pane.
frame.addComponentsToPane(frame.getContentPane());
//Display the window.
frame.pack();
frame.setVisible(true);
bid = borrowerID;
}
@Override
public void actionPerformed(ActionEvent arg0) {
if (returnToUserDialogString.equals(arg0.getActionCommand()))
{
this.dispose();
}
else if (placeHold.equals(arg0.getActionCommand()))
{
if (placeHold() != VALIDATIONERROR) {
callNo.setText("");
}
else {
JOptionPane.showMessageDialog(this, "Invalid Input", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
private int placeHold() {
String callNum = callNo.getText().trim();
if (callNum.length() != 0) {
DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yy");
Date date = new Date();
String currDate = dateFormat.format(date);
System.out.println(currDate);
Transactions trans = new Transactions();
// trans.placeHold(bid, callNum, currDate);
return 0;
}
return VALIDATIONERROR;
}
}
| true | true | private void addComponentsToPane(final Container pane)
{
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(5, 2));
panel.add(new Label("Place Hold"));
panel.add(new Label(""));
panel.add(new Label("Call number"));
panel.add(callNo);
// provide option to search ?
JButton returnToUserDialog = new JButton(returnToUserDialogString);
returnToUserDialog.setActionCommand(returnToUserDialogString);
returnToUserDialog.addActionListener(this);
JButton placeHoldButton = new JButton(placeHold);
placeHoldButton.setActionCommand(placeHold);
placeHoldButton.addActionListener(this);
panel.add(returnToUserDialog);
panel.add(placeHoldButton);
pane.add(panel);
}
| private void addComponentsToPane(final Container pane)
{
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3, 2));
panel.add(new Label("Place Hold"));
panel.add(new Label(""));
panel.add(new Label("Call number"));
panel.add(callNo);
// provide option to search ?
JButton returnToUserDialog = new JButton(returnToUserDialogString);
returnToUserDialog.setActionCommand(returnToUserDialogString);
returnToUserDialog.addActionListener(this);
JButton placeHoldButton = new JButton(placeHold);
placeHoldButton.setActionCommand(placeHold);
placeHoldButton.addActionListener(this);
panel.add(returnToUserDialog);
panel.add(placeHoldButton);
pane.add(panel);
}
|
diff --git a/labs/smartos-ssh/src/main/java/org/jclouds/smartos/compute/domain/VM.java b/labs/smartos-ssh/src/main/java/org/jclouds/smartos/compute/domain/VM.java
index 988fd230dd..3dac30de0e 100644
--- a/labs/smartos-ssh/src/main/java/org/jclouds/smartos/compute/domain/VM.java
+++ b/labs/smartos-ssh/src/main/java/org/jclouds/smartos/compute/domain/VM.java
@@ -1,205 +1,205 @@
package org.jclouds.smartos.compute.domain;
import java.util.Map;
import java.util.UUID;
import com.google.common.base.Objects;
import com.google.common.base.Optional;
/**
* Representing a Virtual Machine (Zone / KVM )
**/
public class VM {
public enum State {
RUNNING, STOPPED, INCOMPLETE
}
public static Builder builder() {
return new Builder();
}
public Builder toBuilder() {
return builder().fromVM(this);
}
public static class Builder {
protected SmartOSHost host;
protected UUID uuid;
protected String type;
protected String ram;
protected State state = State.STOPPED;
protected String alias;
public Builder uuid(UUID uuid) {
this.uuid = uuid;
return this;
}
public Builder uuid(String uuid) {
this.uuid = UUID.fromString(uuid);
return this;
}
public Builder host(SmartOSHost host) {
this.host = host;
return this;
}
public Builder type(String type) {
this.type = type;
return this;
}
public Builder ram(String ram) {
this.ram = ram;
return this;
}
public Builder state(String state) {
this.state = State.valueOf(state.toUpperCase());
return this;
}
public Builder state(State state) {
this.state = state;
return this;
}
public Builder alias(String alias) {
this.alias = alias;
return this;
}
public Builder fromVmadmString(String string) {
String[] sections = string.split(":");
uuid(sections[0]);
type(sections[1]);
ram(sections[2]);
state(sections[3]);
if (sections.length > 4)
alias(sections[4]);
return this;
}
public VM build() {
return new VM(host, uuid, type, ram, state, alias);
}
public Builder fromVM(VM in) {
return host(in.getHost()).uuid(in.getUuid()).type(in.getType()).ram(in.getRam()).state(in.getState())
.alias(in.getAlias());
}
}
protected SmartOSHost host;
protected final UUID uuid;
protected String type;
protected String ram;
protected State state;
protected String alias;
public VM(SmartOSHost host, UUID uuid, String type, String ram, State state, String alias) {
this.host = host;
this.uuid = uuid;
this.type = type;
this.ram = ram;
this.state = state;
this.alias = alias;
}
public State getState() {
return state;
}
public void destroy() {
host.destroyHost(uuid);
}
public void reboot() {
host.rebootHost(uuid);
}
public void stop() {
host.stopHost(uuid);
}
public void start() {
host.startHost(uuid);
}
public Optional<String> getPublicAddress() throws InterruptedException {
Map<String, String> ipAddresses;
for (int i = 0; i < 30; i++) {
ipAddresses = host.getVMIpAddresses(uuid);
- if (ipAddresses.isEmpty()) {
+ if (!ipAddresses.isEmpty()) {
// Got some
String ip = ipAddresses.get("net0");
if (ip != null && !ip.equals("0.0.0.0"))
return Optional.of(ip);
}
Thread.sleep(1000);
}
return Optional.absent();
}
public SmartOSHost getHost() {
return host;
}
public UUID getUuid() {
return uuid;
}
public String getType() {
return type;
}
public String getRam() {
return ram;
}
public String getAlias() {
return alias;
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
// UUID is primary key
return uuid.hashCode();
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
return uuid.equals(((DataSet) obj).getUuid());
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return Objects.toStringHelper(this).omitNullValues().add("uuid", uuid).add("type", type).add("ram", ram)
.add("alias", alias).toString();
}
}
| true | true | public Optional<String> getPublicAddress() throws InterruptedException {
Map<String, String> ipAddresses;
for (int i = 0; i < 30; i++) {
ipAddresses = host.getVMIpAddresses(uuid);
if (ipAddresses.isEmpty()) {
// Got some
String ip = ipAddresses.get("net0");
if (ip != null && !ip.equals("0.0.0.0"))
return Optional.of(ip);
}
Thread.sleep(1000);
}
return Optional.absent();
}
| public Optional<String> getPublicAddress() throws InterruptedException {
Map<String, String> ipAddresses;
for (int i = 0; i < 30; i++) {
ipAddresses = host.getVMIpAddresses(uuid);
if (!ipAddresses.isEmpty()) {
// Got some
String ip = ipAddresses.get("net0");
if (ip != null && !ip.equals("0.0.0.0"))
return Optional.of(ip);
}
Thread.sleep(1000);
}
return Optional.absent();
}
|
diff --git a/src/de/jandavid/asxcel/model/Enterprise.java b/src/de/jandavid/asxcel/model/Enterprise.java
index 75b7523..aa78cf0 100644
--- a/src/de/jandavid/asxcel/model/Enterprise.java
+++ b/src/de/jandavid/asxcel/model/Enterprise.java
@@ -1,232 +1,232 @@
/**
* This file is part of ASxcel.
*
* ASxcel is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ASxcel 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ASxcel. If not, see <http://www.gnu.org/licenses/>.
*/
package de.jandavid.asxcel.model;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
/**
* This application has the purpose to help the user manage
* his enterprise by providing him with a new way to collect
* and view data. This class is responsible for collecting
* all information the user enters about his enterprise.
*
* @author jdno
*/
public class Enterprise {
/**
* This is the enterprise's ID in the database.
*/
private int id;
/**
* Where the enterprise's main office is located.
*/
private Airport mainHub;
/**
* The model is needed to access the database.
*/
private Model model;
/**
* This is the name the user gave his enterprise.
*/
private String name;
/**
* This is a list of routes a user has established or
* is planning to introduce.
*/
private ArrayList<Route> routes = new ArrayList<Route>();
/**
* An enterprise is the logical collection of the user's
* information. It is identified by its name.
* @param name The (unique) name of the enterprise.
* @throws SQLException If an SQL error occurs this gets thrown.
*/
public Enterprise(Model model, String name) throws SQLException, Exception {
this.model = model;
this.name = name;
syncWithDb();
}
/**
* This method creates a new route and adds it to the list of routes.
* @param origin The airport where the route starts.
* @param destination The airport where the route ends.
* @return The newly created route.
* @throws SQLException If a SQL error occurs this gets thrown.
*/
public Route createRoute(Airport origin, Airport destination) throws SQLException {
for(Route r: routes) {
if(r.getOrigin().compareTo(origin) == 0) {
if(r.getDestination().compareTo(destination) == 0) {
return r;
}
}
}
Route r = new Route(model, origin, destination);
routes.add(r);
return r;
}
/**
* This method checks if routes exist for a given airport. This is
* useful when deleting an airport.
* @param airport The airport to check for routes.
* @return True of routes exists to or from the given airport, false otherwise.
*/
public boolean doRoutesExistFor(Airport airport) {
for(Route r: routes) {
if(r.getOrigin().equals(airport) || r.getDestination().equals(airport)) {
return true;
}
}
return false;
}
/**
* Delete a specific route, based on its position in the list.
* @param route The position of the route to delete.
* @throws SQLException If a SQL error occurs this gets thrown.
*/
public void deleteRoute(int route) throws SQLException {
Route r = routes.get(route);
String query = "DELETE FROM `routes` WHERE `id` = '" + r.getId() + "'";
model.getDatabase().executeUpdate(query, new ArrayList<Object>(0));
routes.remove(route);
}
/**
* This method retrieves all destinations for a given airport.
* @param origin The airport where the routes start.
* @return A list of all airports to which routes go.
*/
public ArrayList<Airport> getDestinations(Airport origin) {
ArrayList<Airport> airports = new ArrayList<Airport>();
for(Route r: routes) {
if(r.getOrigin().compareTo(origin) == 0) {
airports.add(r.getDestination());
}
}
Collections.sort(airports);
return airports;
}
/**
* This method loads all routes belonging to the current enterprise
* from the database.
* @throws SQLException If a SQL error occurs this gets thrown.
*/
public void loadRoutes() throws SQLException {
String query = "SELECT `a1`.`name` AS `origin`, `a2`.`name` AS `destination` FROM `routes` AS `r` " +
"INNER JOIN `airports` AS `a1` ON `r`.`origin` = `a1`.`id` " +
"INNER JOIN `airports` AS `a2` ON `r`.`destination` = `a2`.`id` " +
"WHERE `r`.`enterprise` = '" + id + "'";
DatabaseResult dr = model.getDatabase().executeQuery(query);
while(dr.next()) {
- Airport origin = new Airport(model, dr.getString(0));
- Airport destination = new Airport(model, dr.getString(1));
+ Airport origin = model.getAirport(dr.getString(0));
+ Airport destination = model.getAirport(dr.getString(1));
Route r = new Route(model, origin, destination);
routes.add(r);
}
Collections.sort(routes);
}
/**
* This method synchronizes an enterprise with the database, assuming
* the enterprise has been created already. If this is the case this
* instance of Enterprise gets filled with its data, else a new enterprise
* gets added to the database with the given name.
* @throws SQLException If an SQL error occurs this gets thrown.
*/
private void syncWithDb() throws SQLException, Exception {
String query = "SELECT `e`.`id`, `e`.`name`, `a`.`name` FROM `enterprises` AS `e` " +
"INNER JOIN `airports` AS `a` ON `e`.`airport` = `a`.`id` " +
"WHERE `e`.`name` = ? LIMIT 1";
ArrayList<Object> params = new ArrayList<Object>(1);
params.add(name);
DatabaseResult dr = model.getDatabase().executeQuery(query, params);
if(dr.next()) {
id = dr.getInt(0);
name = dr.getString(1);
mainHub = new Airport(model, dr.getString(2));
loadRoutes();
} else {
throw new Exception("Enterprise was not found");
}
}
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @return the mainHub
*/
public Airport getMainHub() {
return mainHub;
}
/**
* @return the model
*/
public Model getModel() {
return model;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @return the routes
*/
public ArrayList<Route> getRoutes() {
return routes;
}
}
| true | true | public void loadRoutes() throws SQLException {
String query = "SELECT `a1`.`name` AS `origin`, `a2`.`name` AS `destination` FROM `routes` AS `r` " +
"INNER JOIN `airports` AS `a1` ON `r`.`origin` = `a1`.`id` " +
"INNER JOIN `airports` AS `a2` ON `r`.`destination` = `a2`.`id` " +
"WHERE `r`.`enterprise` = '" + id + "'";
DatabaseResult dr = model.getDatabase().executeQuery(query);
while(dr.next()) {
Airport origin = new Airport(model, dr.getString(0));
Airport destination = new Airport(model, dr.getString(1));
Route r = new Route(model, origin, destination);
routes.add(r);
}
Collections.sort(routes);
}
| public void loadRoutes() throws SQLException {
String query = "SELECT `a1`.`name` AS `origin`, `a2`.`name` AS `destination` FROM `routes` AS `r` " +
"INNER JOIN `airports` AS `a1` ON `r`.`origin` = `a1`.`id` " +
"INNER JOIN `airports` AS `a2` ON `r`.`destination` = `a2`.`id` " +
"WHERE `r`.`enterprise` = '" + id + "'";
DatabaseResult dr = model.getDatabase().executeQuery(query);
while(dr.next()) {
Airport origin = model.getAirport(dr.getString(0));
Airport destination = model.getAirport(dr.getString(1));
Route r = new Route(model, origin, destination);
routes.add(r);
}
Collections.sort(routes);
}
|
diff --git a/Meteorolog-a-AguasCalientes/src/java/org/meteorologaaguascalientes/presentation/History.java b/Meteorolog-a-AguasCalientes/src/java/org/meteorologaaguascalientes/presentation/History.java
index 57751d6..71c37ca 100644
--- a/Meteorolog-a-AguasCalientes/src/java/org/meteorologaaguascalientes/presentation/History.java
+++ b/Meteorolog-a-AguasCalientes/src/java/org/meteorologaaguascalientes/presentation/History.java
@@ -1,102 +1,102 @@
package org.meteorologaaguascalientes.presentation;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.meteorologaaguascalientes.businesslogic.facade.ServiceFacade;
import org.meteorologaaguascalientes.control.forecast.ForecastsFactory;
@WebServlet(name = "History", urlPatterns = {"/history"})
public class History extends HttpServlet {
/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Properties prop = new Properties();
prop.load(getServletContext().getResourceAsStream("/WEB-INF/config.properties"));
response.setContentType("text/csv;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String variableName = request.getParameter("variable");
if (variableName != null) {
List<SortedMap<Date, Double>> dataList;
SortedMap<Date, Double> data;
ServiceFacade serviceFacade = new ServiceFacade();
dataList = serviceFacade.getData(variableName, ForecastsFactory.DEFAULT);
- out.println(prop.getProperty("date") + "," + prop.getProperty("dao." + variableName) + "," + prop.getProperty("forecast"));
+ out.println(prop.getProperty("date") + "," + prop.getProperty( variableName) + "," + prop.getProperty("forecast"));
data = dataList.get(0);
for (Map.Entry<Date, Double> e : data.entrySet()) {
out.println(formatter.format(e.getKey())
+ "," + e.getValue() + ",");
}
if (!data.isEmpty()) {
out.println(formatter.format(data.lastKey()) + ",," + data.get(data.lastKey()) + ",");
}
data = dataList.get(1);
for (Map.Entry<Date, Double> e : data.entrySet()) {
out.println(formatter.format(e.getKey())
+ ",," + e.getValue());
}
}
} finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP
* <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP
* <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| true | true | protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Properties prop = new Properties();
prop.load(getServletContext().getResourceAsStream("/WEB-INF/config.properties"));
response.setContentType("text/csv;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String variableName = request.getParameter("variable");
if (variableName != null) {
List<SortedMap<Date, Double>> dataList;
SortedMap<Date, Double> data;
ServiceFacade serviceFacade = new ServiceFacade();
dataList = serviceFacade.getData(variableName, ForecastsFactory.DEFAULT);
out.println(prop.getProperty("date") + "," + prop.getProperty("dao." + variableName) + "," + prop.getProperty("forecast"));
data = dataList.get(0);
for (Map.Entry<Date, Double> e : data.entrySet()) {
out.println(formatter.format(e.getKey())
+ "," + e.getValue() + ",");
}
if (!data.isEmpty()) {
out.println(formatter.format(data.lastKey()) + ",," + data.get(data.lastKey()) + ",");
}
data = dataList.get(1);
for (Map.Entry<Date, Double> e : data.entrySet()) {
out.println(formatter.format(e.getKey())
+ ",," + e.getValue());
}
}
} finally {
out.close();
}
}
| protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Properties prop = new Properties();
prop.load(getServletContext().getResourceAsStream("/WEB-INF/config.properties"));
response.setContentType("text/csv;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String variableName = request.getParameter("variable");
if (variableName != null) {
List<SortedMap<Date, Double>> dataList;
SortedMap<Date, Double> data;
ServiceFacade serviceFacade = new ServiceFacade();
dataList = serviceFacade.getData(variableName, ForecastsFactory.DEFAULT);
out.println(prop.getProperty("date") + "," + prop.getProperty( variableName) + "," + prop.getProperty("forecast"));
data = dataList.get(0);
for (Map.Entry<Date, Double> e : data.entrySet()) {
out.println(formatter.format(e.getKey())
+ "," + e.getValue() + ",");
}
if (!data.isEmpty()) {
out.println(formatter.format(data.lastKey()) + ",," + data.get(data.lastKey()) + ",");
}
data = dataList.get(1);
for (Map.Entry<Date, Double> e : data.entrySet()) {
out.println(formatter.format(e.getKey())
+ ",," + e.getValue());
}
}
} finally {
out.close();
}
}
|
diff --git a/src/main/java/pl/softwaremill/demo/tools/StartNewInstance.java b/src/main/java/pl/softwaremill/demo/tools/StartNewInstance.java
index 89feafc..49ec0a2 100644
--- a/src/main/java/pl/softwaremill/demo/tools/StartNewInstance.java
+++ b/src/main/java/pl/softwaremill/demo/tools/StartNewInstance.java
@@ -1,62 +1,62 @@
package pl.softwaremill.demo.tools;
import com.xerox.amazonws.ec2.*;
import pl.softwaremill.demo.impl.sdb.AwsAccessKeys;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author Adam Warski (adam at warski dot org)
*/
public class StartNewInstance {
private final AwsAccessKeys awsAccessKeys;
public StartNewInstance(AwsAccessKeys awsAccessKeys) {
this.awsAccessKeys = awsAccessKeys;
}
public void start() throws EC2Exception, LoadBalancingException {
Jec2 ec2 = createJec2();
List<String> instanceIds = startInstance(ec2);
registerWithElb(instanceIds);
}
private Jec2 createJec2() {
return new Jec2(awsAccessKeys.getAccessKeyId(), awsAccessKeys.getSecretAccessKey(),
true, "ec2.eu-west-1.amazonaws.com");
}
public List<String> startInstance(Jec2 ec2) throws EC2Exception {
- LaunchConfiguration launchConfiguration = new LaunchConfiguration("ami-e287b196");
+ LaunchConfiguration launchConfiguration = new LaunchConfiguration("ami-6d477b19");
launchConfiguration.setSecurityGroup(Arrays.asList("SoftDevCon"));
launchConfiguration.setKeyName("confitura");
launchConfiguration.setAvailabilityZone("eu-west-1c");
ReservationDescription reservationDescription = ec2.runInstances(launchConfiguration);
List<String> instanceIds = new ArrayList<String>();
for (ReservationDescription.Instance instance : reservationDescription.getInstances()) {
System.out.println("Started instance " + instance);
instanceIds.add(instance.getInstanceId());
}
return instanceIds;
}
public void registerWithElb(List<String> instanceIds) throws LoadBalancingException {
LoadBalancing loadBalancing = createLoadBalancing();
loadBalancing.registerInstancesWithLoadBalancer("SoftDevConLB", instanceIds);
System.out.println("Registered " + instanceIds + " with the load balancer.");
}
private LoadBalancing createLoadBalancing() {
return new LoadBalancing(awsAccessKeys.getAccessKeyId(),
awsAccessKeys.getSecretAccessKey(), true, "elasticloadbalancing.eu-west-1.amazonaws.com");
}
public static void main(String[] args) throws IOException, LoadBalancingException, EC2Exception {
new StartNewInstance(AwsAccessKeys.createFromResources()).start();
}
}
| true | true | public List<String> startInstance(Jec2 ec2) throws EC2Exception {
LaunchConfiguration launchConfiguration = new LaunchConfiguration("ami-e287b196");
launchConfiguration.setSecurityGroup(Arrays.asList("SoftDevCon"));
launchConfiguration.setKeyName("confitura");
launchConfiguration.setAvailabilityZone("eu-west-1c");
ReservationDescription reservationDescription = ec2.runInstances(launchConfiguration);
List<String> instanceIds = new ArrayList<String>();
for (ReservationDescription.Instance instance : reservationDescription.getInstances()) {
System.out.println("Started instance " + instance);
instanceIds.add(instance.getInstanceId());
}
return instanceIds;
}
| public List<String> startInstance(Jec2 ec2) throws EC2Exception {
LaunchConfiguration launchConfiguration = new LaunchConfiguration("ami-6d477b19");
launchConfiguration.setSecurityGroup(Arrays.asList("SoftDevCon"));
launchConfiguration.setKeyName("confitura");
launchConfiguration.setAvailabilityZone("eu-west-1c");
ReservationDescription reservationDescription = ec2.runInstances(launchConfiguration);
List<String> instanceIds = new ArrayList<String>();
for (ReservationDescription.Instance instance : reservationDescription.getInstances()) {
System.out.println("Started instance " + instance);
instanceIds.add(instance.getInstanceId());
}
return instanceIds;
}
|
diff --git a/app/src/iic3686/rocketscience/GameThread.java b/app/src/iic3686/rocketscience/GameThread.java
index 7fb61c2..ff32ec2 100644
--- a/app/src/iic3686/rocketscience/GameThread.java
+++ b/app/src/iic3686/rocketscience/GameThread.java
@@ -1,228 +1,228 @@
package iic3686.rocketscience;
import org.andengine.entity.IEntity;
import org.andengine.entity.primitive.Rectangle;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.sprite.Sprite;
import org.andengine.entity.text.Text;
import org.andengine.opengl.texture.TextureOptions;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.andengine.opengl.texture.region.ITextureRegion;
public class GameThread extends Thread{
private Scene currentScene;
private GameManager gm;
//Game Logic Variables
boolean gameIsRunning;
int levelCounter;
Rectangle orderRectangle;
Rectangle timeRectangle;
//Time counter
int timeCounter;
int errorCounter;
float colorValue;
Sprite loseSplash;
Sprite victorySplash;
private TagHandler th;
//
public GameThread(Scene startScene, GameManager gm, Rectangle orderRectangle, Sprite loseSplash, Sprite victorySplash)
{
this.currentScene = startScene;
this.gm = gm;
this.gameIsRunning = true;
this.levelCounter = 1;
this.orderRectangle = orderRectangle;
this.timeCounter = 0;
this.errorCounter = 0;
this.loseSplash = loseSplash;
this.victorySplash = victorySplash;
this.th = TagHandler.getInstance();
this.timeRectangle = (Rectangle)currentScene.getChildByTag(th.getTag("timeRectangle"));
}
public void run() {
while(gameIsRunning)
{
timeCounter = 0;
errorCounter = 0;
while(!this.gm.isRoundOver())
{
//Level crap
if(this.gm.currentLevel == 1)
{
//Display Nav and Comm
//Bring the black and white ones, move the originals
Sprite armoryOff = (Sprite)currentScene.getChildByTag(th.getTag("armoryOff"));
Sprite armoryOn = (Sprite)currentScene.getChildByTag(th.getTag("armory"));
Sprite kitchenOff = (Sprite)currentScene.getChildByTag(th.getTag("kitchenOff"));
Sprite kitchenOn = (Sprite)currentScene.getChildByTag(th.getTag("kitchen"));
armoryOn.setPosition(2000, 2000);
kitchenOn.setPosition(2000, 2000);
kitchenOff.setPosition(0, 260);
armoryOff.setPosition(0, 140);
}
else if(this.gm.currentLevel == 2)
{
//Display Nav, Comm and Armory
Sprite armoryOff = (Sprite)currentScene.getChildByTag(th.getTag("armoryOff"));
Sprite armoryOn = (Sprite)currentScene.getChildByTag(th.getTag("armory"));
Sprite kitchenOff = (Sprite)currentScene.getChildByTag(th.getTag("kitchenOff"));
Sprite kitchenOn = (Sprite)currentScene.getChildByTag(th.getTag("kitchen"));
armoryOff.setPosition(2000, 2000);
kitchenOn.setPosition(2000, 2000);
kitchenOff.setPosition(0, 260);
armoryOn.setPosition(0, 140);
}
else
{
//Display everything
Sprite armoryOff = (Sprite)currentScene.getChildByTag(th.getTag("armoryOff"));
Sprite armoryOn = (Sprite)currentScene.getChildByTag(th.getTag("armory"));
Sprite kitchenOff = (Sprite)currentScene.getChildByTag(th.getTag("kitchenOff"));
Sprite kitchenOn = (Sprite)currentScene.getChildByTag(th.getTag("kitchen"));
armoryOff.setPosition(2000, 2000);
kitchenOff.setPosition(2000, 2000);
kitchenOn.setPosition(0, 260);
armoryOn.setPosition(0, 140);
}
//GAME LOOP EL LUP LUP
if(this.gm.currentOrder == null)
this.gm.getNewOrder();
//Create new round
/*if(this.gm.isRoundOver())
{
//Start new round
this.gm.newRound();
}*/
//ERROR CHECK
if(errorCounter > 10)
{
loseSplash.setPosition(0,200);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
loseSplash.setPosition(2000,2000);
this.gm.resetGame();
errorCounter = 0;
levelCounter = 1;
Text orderTextLabel= (Text)currentScene.getChildByTag(th.getTag("orderText"));
orderTextLabel.setText("Get ready for Level "+levelCounter+"!");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//Check to see if the order has changed recently
if(this.gm.hasBeenChangedRecently())
timeCounter = 0;
//Change the text of the buttons if needed
//currentScene
//Change the text of the instruction and check the status
//Background progressive change
//if(timeCounter < 5000)
if(timeCounter < this.gm.timeLimit)
{
//colorValue = (float)0.8+(timeCounter/5000);
//this.orderRectangle.setColor((float)colorValue, 0, 0);
//timeRectangle.setWidth((float) (480.0 / 5000)*(5000 - timeCounter));
timeRectangle.setWidth((float) (480.0 / this.gm.timeLimit)*(this.gm.timeLimit - timeCounter));
timeCounter++;
}
else
{
//5 seconds have passed, change mission, increase errorCounter
this.gm.getNewOrder();
errorCounter++;
this.orderRectangle.setColor(1, 1, 1);
timeCounter = 0;
}
Text orderTextLabel= (Text)currentScene.getChildByTag(th.getTag("orderText"));
orderTextLabel.setText(this.gm.getCurrentOrderText());
//IEntity boton1 = currentScene.getChildByTag(10);
//boton1.setVisible(!boton1.isVisible());
//IEntity boton2 = currentScene.getChildByTag(11);
//boton2.setVisible(!boton2.isVisible());
Sprite NaveChica = (Sprite)currentScene.getChildByTag(th.getTag("NaveChica"));
NaveChica.setX((gm.currentOrderNumber * 460)/gm.ordersRound);
try {
//this.orderRectangle.setColor(1, 1, 1);
- this.sleep(1);
+ Thread.sleep(1);
//this.orderRectangle.setColor(1, 0, 0);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//END OF ROUND
- Text orderTextLabel= (Text)currentScene.getChildByTag(1);
+ Text orderTextLabel= (Text)currentScene.getChildByTag(th.getTag("orderText"));
//orderTextLabel.setText("Level Complete!");
victorySplash.setPosition(0,200);
try {
- this.sleep(4000);
+ Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
levelCounter++;
victorySplash.setPosition(2000,2000);
if(this.gm.currentLevel == 1)
{
orderTextLabel.setText("You reached the atmosphere.");
try {
- this.sleep(2000);
+ Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
orderTextLabel.setText("Level 2: Reach the Moon");
}
else if(this.gm.currentLevel == 2)
{
orderTextLabel.setText("You reached the Moon.");
try {
- this.sleep(2000);
+ Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
orderTextLabel.setText("Level 3: Reach Mars");
}
else if(this.gm.currentLevel == 3)
{
orderTextLabel.setText("You reached Mars.");
try {
- this.sleep(2000);
+ Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
orderTextLabel.setText("Level 4: Explore space.");
}
else
{
orderTextLabel.setText("Get ready for Level "+levelCounter+"!");
}
try {
- this.sleep(2000);
+ Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.gm.newRound();
}
}
}
| false | true | public void run() {
while(gameIsRunning)
{
timeCounter = 0;
errorCounter = 0;
while(!this.gm.isRoundOver())
{
//Level crap
if(this.gm.currentLevel == 1)
{
//Display Nav and Comm
//Bring the black and white ones, move the originals
Sprite armoryOff = (Sprite)currentScene.getChildByTag(th.getTag("armoryOff"));
Sprite armoryOn = (Sprite)currentScene.getChildByTag(th.getTag("armory"));
Sprite kitchenOff = (Sprite)currentScene.getChildByTag(th.getTag("kitchenOff"));
Sprite kitchenOn = (Sprite)currentScene.getChildByTag(th.getTag("kitchen"));
armoryOn.setPosition(2000, 2000);
kitchenOn.setPosition(2000, 2000);
kitchenOff.setPosition(0, 260);
armoryOff.setPosition(0, 140);
}
else if(this.gm.currentLevel == 2)
{
//Display Nav, Comm and Armory
Sprite armoryOff = (Sprite)currentScene.getChildByTag(th.getTag("armoryOff"));
Sprite armoryOn = (Sprite)currentScene.getChildByTag(th.getTag("armory"));
Sprite kitchenOff = (Sprite)currentScene.getChildByTag(th.getTag("kitchenOff"));
Sprite kitchenOn = (Sprite)currentScene.getChildByTag(th.getTag("kitchen"));
armoryOff.setPosition(2000, 2000);
kitchenOn.setPosition(2000, 2000);
kitchenOff.setPosition(0, 260);
armoryOn.setPosition(0, 140);
}
else
{
//Display everything
Sprite armoryOff = (Sprite)currentScene.getChildByTag(th.getTag("armoryOff"));
Sprite armoryOn = (Sprite)currentScene.getChildByTag(th.getTag("armory"));
Sprite kitchenOff = (Sprite)currentScene.getChildByTag(th.getTag("kitchenOff"));
Sprite kitchenOn = (Sprite)currentScene.getChildByTag(th.getTag("kitchen"));
armoryOff.setPosition(2000, 2000);
kitchenOff.setPosition(2000, 2000);
kitchenOn.setPosition(0, 260);
armoryOn.setPosition(0, 140);
}
//GAME LOOP EL LUP LUP
if(this.gm.currentOrder == null)
this.gm.getNewOrder();
//Create new round
/*if(this.gm.isRoundOver())
{
//Start new round
this.gm.newRound();
}*/
//ERROR CHECK
if(errorCounter > 10)
{
loseSplash.setPosition(0,200);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
loseSplash.setPosition(2000,2000);
this.gm.resetGame();
errorCounter = 0;
levelCounter = 1;
Text orderTextLabel= (Text)currentScene.getChildByTag(th.getTag("orderText"));
orderTextLabel.setText("Get ready for Level "+levelCounter+"!");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//Check to see if the order has changed recently
if(this.gm.hasBeenChangedRecently())
timeCounter = 0;
//Change the text of the buttons if needed
//currentScene
//Change the text of the instruction and check the status
//Background progressive change
//if(timeCounter < 5000)
if(timeCounter < this.gm.timeLimit)
{
//colorValue = (float)0.8+(timeCounter/5000);
//this.orderRectangle.setColor((float)colorValue, 0, 0);
//timeRectangle.setWidth((float) (480.0 / 5000)*(5000 - timeCounter));
timeRectangle.setWidth((float) (480.0 / this.gm.timeLimit)*(this.gm.timeLimit - timeCounter));
timeCounter++;
}
else
{
//5 seconds have passed, change mission, increase errorCounter
this.gm.getNewOrder();
errorCounter++;
this.orderRectangle.setColor(1, 1, 1);
timeCounter = 0;
}
Text orderTextLabel= (Text)currentScene.getChildByTag(th.getTag("orderText"));
orderTextLabel.setText(this.gm.getCurrentOrderText());
//IEntity boton1 = currentScene.getChildByTag(10);
//boton1.setVisible(!boton1.isVisible());
//IEntity boton2 = currentScene.getChildByTag(11);
//boton2.setVisible(!boton2.isVisible());
Sprite NaveChica = (Sprite)currentScene.getChildByTag(th.getTag("NaveChica"));
NaveChica.setX((gm.currentOrderNumber * 460)/gm.ordersRound);
try {
//this.orderRectangle.setColor(1, 1, 1);
this.sleep(1);
//this.orderRectangle.setColor(1, 0, 0);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//END OF ROUND
Text orderTextLabel= (Text)currentScene.getChildByTag(1);
//orderTextLabel.setText("Level Complete!");
victorySplash.setPosition(0,200);
try {
this.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
levelCounter++;
victorySplash.setPosition(2000,2000);
if(this.gm.currentLevel == 1)
{
orderTextLabel.setText("You reached the atmosphere.");
try {
this.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
orderTextLabel.setText("Level 2: Reach the Moon");
}
else if(this.gm.currentLevel == 2)
{
orderTextLabel.setText("You reached the Moon.");
try {
this.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
orderTextLabel.setText("Level 3: Reach Mars");
}
else if(this.gm.currentLevel == 3)
{
orderTextLabel.setText("You reached Mars.");
try {
this.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
orderTextLabel.setText("Level 4: Explore space.");
}
else
{
orderTextLabel.setText("Get ready for Level "+levelCounter+"!");
}
try {
this.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.gm.newRound();
}
}
| public void run() {
while(gameIsRunning)
{
timeCounter = 0;
errorCounter = 0;
while(!this.gm.isRoundOver())
{
//Level crap
if(this.gm.currentLevel == 1)
{
//Display Nav and Comm
//Bring the black and white ones, move the originals
Sprite armoryOff = (Sprite)currentScene.getChildByTag(th.getTag("armoryOff"));
Sprite armoryOn = (Sprite)currentScene.getChildByTag(th.getTag("armory"));
Sprite kitchenOff = (Sprite)currentScene.getChildByTag(th.getTag("kitchenOff"));
Sprite kitchenOn = (Sprite)currentScene.getChildByTag(th.getTag("kitchen"));
armoryOn.setPosition(2000, 2000);
kitchenOn.setPosition(2000, 2000);
kitchenOff.setPosition(0, 260);
armoryOff.setPosition(0, 140);
}
else if(this.gm.currentLevel == 2)
{
//Display Nav, Comm and Armory
Sprite armoryOff = (Sprite)currentScene.getChildByTag(th.getTag("armoryOff"));
Sprite armoryOn = (Sprite)currentScene.getChildByTag(th.getTag("armory"));
Sprite kitchenOff = (Sprite)currentScene.getChildByTag(th.getTag("kitchenOff"));
Sprite kitchenOn = (Sprite)currentScene.getChildByTag(th.getTag("kitchen"));
armoryOff.setPosition(2000, 2000);
kitchenOn.setPosition(2000, 2000);
kitchenOff.setPosition(0, 260);
armoryOn.setPosition(0, 140);
}
else
{
//Display everything
Sprite armoryOff = (Sprite)currentScene.getChildByTag(th.getTag("armoryOff"));
Sprite armoryOn = (Sprite)currentScene.getChildByTag(th.getTag("armory"));
Sprite kitchenOff = (Sprite)currentScene.getChildByTag(th.getTag("kitchenOff"));
Sprite kitchenOn = (Sprite)currentScene.getChildByTag(th.getTag("kitchen"));
armoryOff.setPosition(2000, 2000);
kitchenOff.setPosition(2000, 2000);
kitchenOn.setPosition(0, 260);
armoryOn.setPosition(0, 140);
}
//GAME LOOP EL LUP LUP
if(this.gm.currentOrder == null)
this.gm.getNewOrder();
//Create new round
/*if(this.gm.isRoundOver())
{
//Start new round
this.gm.newRound();
}*/
//ERROR CHECK
if(errorCounter > 10)
{
loseSplash.setPosition(0,200);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
loseSplash.setPosition(2000,2000);
this.gm.resetGame();
errorCounter = 0;
levelCounter = 1;
Text orderTextLabel= (Text)currentScene.getChildByTag(th.getTag("orderText"));
orderTextLabel.setText("Get ready for Level "+levelCounter+"!");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//Check to see if the order has changed recently
if(this.gm.hasBeenChangedRecently())
timeCounter = 0;
//Change the text of the buttons if needed
//currentScene
//Change the text of the instruction and check the status
//Background progressive change
//if(timeCounter < 5000)
if(timeCounter < this.gm.timeLimit)
{
//colorValue = (float)0.8+(timeCounter/5000);
//this.orderRectangle.setColor((float)colorValue, 0, 0);
//timeRectangle.setWidth((float) (480.0 / 5000)*(5000 - timeCounter));
timeRectangle.setWidth((float) (480.0 / this.gm.timeLimit)*(this.gm.timeLimit - timeCounter));
timeCounter++;
}
else
{
//5 seconds have passed, change mission, increase errorCounter
this.gm.getNewOrder();
errorCounter++;
this.orderRectangle.setColor(1, 1, 1);
timeCounter = 0;
}
Text orderTextLabel= (Text)currentScene.getChildByTag(th.getTag("orderText"));
orderTextLabel.setText(this.gm.getCurrentOrderText());
//IEntity boton1 = currentScene.getChildByTag(10);
//boton1.setVisible(!boton1.isVisible());
//IEntity boton2 = currentScene.getChildByTag(11);
//boton2.setVisible(!boton2.isVisible());
Sprite NaveChica = (Sprite)currentScene.getChildByTag(th.getTag("NaveChica"));
NaveChica.setX((gm.currentOrderNumber * 460)/gm.ordersRound);
try {
//this.orderRectangle.setColor(1, 1, 1);
Thread.sleep(1);
//this.orderRectangle.setColor(1, 0, 0);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//END OF ROUND
Text orderTextLabel= (Text)currentScene.getChildByTag(th.getTag("orderText"));
//orderTextLabel.setText("Level Complete!");
victorySplash.setPosition(0,200);
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
levelCounter++;
victorySplash.setPosition(2000,2000);
if(this.gm.currentLevel == 1)
{
orderTextLabel.setText("You reached the atmosphere.");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
orderTextLabel.setText("Level 2: Reach the Moon");
}
else if(this.gm.currentLevel == 2)
{
orderTextLabel.setText("You reached the Moon.");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
orderTextLabel.setText("Level 3: Reach Mars");
}
else if(this.gm.currentLevel == 3)
{
orderTextLabel.setText("You reached Mars.");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
orderTextLabel.setText("Level 4: Explore space.");
}
else
{
orderTextLabel.setText("Get ready for Level "+levelCounter+"!");
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.gm.newRound();
}
}
|
diff --git a/src/main/java/com/thevoxelbox/voxelbar/VoxelBarCommands.java b/src/main/java/com/thevoxelbox/voxelbar/VoxelBarCommands.java
index d17bf9b..1076cf2 100644
--- a/src/main/java/com/thevoxelbox/voxelbar/VoxelBarCommands.java
+++ b/src/main/java/com/thevoxelbox/voxelbar/VoxelBarCommands.java
@@ -1,64 +1,64 @@
package com.thevoxelbox.voxelbar;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class VoxelBarCommands implements CommandExecutor {
private VoxelBar vb = new VoxelBar();
private VoxelBarToggleManager tm = vb.tm;
public boolean onCommand(CommandSender cs, Command cmnd, String label, String[] args) {
// Check if player is console.
if (!(cs instanceof Player)) {
cs.sendMessage("You cannot use VoxelBar from the console!");
return true;
}
// Initialize variables
Player player = (Player) cs;
String command;
// Check that the player has typed more than /vbar - If not send them a help message.
if (args.length == 0) {
player.sendMessage(helpMessage());
return true;
}
// Set command to the first arg of the command
command = args[0];
if (command.equalsIgnoreCase("enable") || command.equalsIgnoreCase("on") || command.equalsIgnoreCase("e")) { // Check if they're running the /vbar enable command
if (tm.isEnabled(player.getName())) {
player.sendMessage(ChatColor.GREEN + "VoxelBar already enabled for you! Type " + ChatColor.DARK_AQUA + "/vbar disable" + ChatColor.GREEN + " to disable VoxelBar!");
return true;
}
tm.setStatus(player.getName(), true);
player.sendMessage(ChatColor.GREEN + "VoxelBar enabled for you - " + ChatColor.DARK_AQUA + "/vbar disable" + ChatColor.GREEN + " to turn it off again!");
return true;
} else if (command.equalsIgnoreCase("disable") || command.equalsIgnoreCase("off") || command.equalsIgnoreCase("d")) { // Check if they're running the /vbar disable command
if (tm.isEnabled(player.getName())) {
tm.setStatus(player.getName(), false);
player.sendMessage(ChatColor.GREEN + "VoxelBar disabled for you - " + ChatColor.DARK_AQUA + "/vbar enable" + ChatColor.GREEN + " to turn it on again!");
return true;
}
- player.sendMessage(ChatColor.GREEN + "VoxelBar already enabled for you! Type " + ChatColor.DARK_AQUA + "/vbar disable" + ChatColor.GREEN + " to disable VoxelBar!");
+ player.sendMessage(ChatColor.GREEN + "VoxelBar already disabled for you! Type " + ChatColor.DARK_AQUA + "/vbar enable" + ChatColor.GREEN + " to enable VoxelBar!");
return true;
}
player.sendMessage(helpMessage());
return true;
}
public String helpMessage() {
String help = null;
help = ChatColor.GREEN + "==========[VoxelBar]==========\n";
help += ChatColor.GREEN + "/vbar \n";
help += ChatColor.GREEN + "/vbar enable \n";
help += ChatColor.GREEN + "/vbar disable \n";
help += ChatColor.GREEN + "==============================\n";
return help;
}
}
| true | true | public boolean onCommand(CommandSender cs, Command cmnd, String label, String[] args) {
// Check if player is console.
if (!(cs instanceof Player)) {
cs.sendMessage("You cannot use VoxelBar from the console!");
return true;
}
// Initialize variables
Player player = (Player) cs;
String command;
// Check that the player has typed more than /vbar - If not send them a help message.
if (args.length == 0) {
player.sendMessage(helpMessage());
return true;
}
// Set command to the first arg of the command
command = args[0];
if (command.equalsIgnoreCase("enable") || command.equalsIgnoreCase("on") || command.equalsIgnoreCase("e")) { // Check if they're running the /vbar enable command
if (tm.isEnabled(player.getName())) {
player.sendMessage(ChatColor.GREEN + "VoxelBar already enabled for you! Type " + ChatColor.DARK_AQUA + "/vbar disable" + ChatColor.GREEN + " to disable VoxelBar!");
return true;
}
tm.setStatus(player.getName(), true);
player.sendMessage(ChatColor.GREEN + "VoxelBar enabled for you - " + ChatColor.DARK_AQUA + "/vbar disable" + ChatColor.GREEN + " to turn it off again!");
return true;
} else if (command.equalsIgnoreCase("disable") || command.equalsIgnoreCase("off") || command.equalsIgnoreCase("d")) { // Check if they're running the /vbar disable command
if (tm.isEnabled(player.getName())) {
tm.setStatus(player.getName(), false);
player.sendMessage(ChatColor.GREEN + "VoxelBar disabled for you - " + ChatColor.DARK_AQUA + "/vbar enable" + ChatColor.GREEN + " to turn it on again!");
return true;
}
player.sendMessage(ChatColor.GREEN + "VoxelBar already enabled for you! Type " + ChatColor.DARK_AQUA + "/vbar disable" + ChatColor.GREEN + " to disable VoxelBar!");
return true;
}
player.sendMessage(helpMessage());
return true;
}
| public boolean onCommand(CommandSender cs, Command cmnd, String label, String[] args) {
// Check if player is console.
if (!(cs instanceof Player)) {
cs.sendMessage("You cannot use VoxelBar from the console!");
return true;
}
// Initialize variables
Player player = (Player) cs;
String command;
// Check that the player has typed more than /vbar - If not send them a help message.
if (args.length == 0) {
player.sendMessage(helpMessage());
return true;
}
// Set command to the first arg of the command
command = args[0];
if (command.equalsIgnoreCase("enable") || command.equalsIgnoreCase("on") || command.equalsIgnoreCase("e")) { // Check if they're running the /vbar enable command
if (tm.isEnabled(player.getName())) {
player.sendMessage(ChatColor.GREEN + "VoxelBar already enabled for you! Type " + ChatColor.DARK_AQUA + "/vbar disable" + ChatColor.GREEN + " to disable VoxelBar!");
return true;
}
tm.setStatus(player.getName(), true);
player.sendMessage(ChatColor.GREEN + "VoxelBar enabled for you - " + ChatColor.DARK_AQUA + "/vbar disable" + ChatColor.GREEN + " to turn it off again!");
return true;
} else if (command.equalsIgnoreCase("disable") || command.equalsIgnoreCase("off") || command.equalsIgnoreCase("d")) { // Check if they're running the /vbar disable command
if (tm.isEnabled(player.getName())) {
tm.setStatus(player.getName(), false);
player.sendMessage(ChatColor.GREEN + "VoxelBar disabled for you - " + ChatColor.DARK_AQUA + "/vbar enable" + ChatColor.GREEN + " to turn it on again!");
return true;
}
player.sendMessage(ChatColor.GREEN + "VoxelBar already disabled for you! Type " + ChatColor.DARK_AQUA + "/vbar enable" + ChatColor.GREEN + " to enable VoxelBar!");
return true;
}
player.sendMessage(helpMessage());
return true;
}
|
diff --git a/src/cli/Extractor.java b/src/cli/Extractor.java
index 2b6109d..6493037 100644
--- a/src/cli/Extractor.java
+++ b/src/cli/Extractor.java
@@ -1,244 +1,244 @@
package cli;
import java.io.*;
import java.util.*;
import tackbp.KbpConstants;
import sf.SFConstants;
import sf.SFEntity;
import sf.SFEntity.SingleAnswer;
import sf.eval.MistakeBreakdown;
import sf.eval.SFScore;
import sf.filler.Filler;
import sf.filler.regex.*;
import sf.filler.tree.*;
import sf.retriever.CorefEntity;
import sf.retriever.CorefIndex;
import sf.retriever.CorefMention;
import sf.retriever.CorefProvider;
import sf.retriever.ProcessedCorpus;
import util.FileUtil;
/**
* CSE 454 Assignment 1 main class. Java 7 required.
*
* In the main method, a pipeline is run as follows: 1) Read the queries. 2) For
* each query, retrieve relevant documents. In this assignment, only the
* documents containing an answer will be returned to save running time. In
* practice, a search-engine-style retriever will be used. Iterate through all
* the sentences returned and the slot filler will applied to extract answers.
* 3) Spit out answers and evaluate them against the labels.
*
* In this assignment, you only need to write a new class for the assigned slots
* implementing the <code>sf.filler.Filler</code> interface. An example class on
* birthdate is implemented in <code>sf.filler.RegexPerDateOfBirthFiller.java</code>.
*
* @author Xiao Ling
*/
public class Extractor {
// TODO: actually calculate number of sentences in a corpus.
protected static long ESTIMATED_SENTENCE_COUNT = 27350000;
protected static String formatTime(long nanoseconds) {
double seconds = nanoseconds / 1000000000.;
boolean negative = seconds < 0;
if ( negative ) seconds *= -1;
int minutes = (int)(seconds / 60);
seconds -= minutes * 60;
int hours = minutes / 60;
minutes -= hours * 60;
int days = hours / 24;
hours -= days * 24;
return String.format("%s%d:%02d:%02d:%02.3f", negative ? "-" : "",
days, hours, minutes, seconds);
}
public static void run(Args args) throws InstantiationException, IllegalAccessException {
// read the queries
sf.query.QueryReader queryReader = new sf.query.QueryReader();
queryReader.readFrom( new File( args.testSet, "queries.xml" )
.getPath() );
// Construct fillers
Filler[] fillers = new Filler[ args.fillers.size() ];
int i = 0;
for ( Class<? extends Filler> filler : args.fillers ) {
fillers[ i++ ] = filler.newInstance();
}
StringBuilder answersString = new StringBuilder();
String basePath = args.corpus.getPath();
// initialize the corpus
// FIXME replace the list by a generic class with an input of slot
// name and an output of all the relevant files from the answer file
long startTime = System.nanoTime();
ProcessedCorpus corpus = null;
CorefIndex corefIndex = null;
try {
corpus = new ProcessedCorpus( basePath );
corefIndex = new CorefIndex( basePath );
// Predict annotations
Map<String, String> annotations = null;
int c = 0;
while (corpus.hasNext()) {
// Get next annotation
annotations = corpus.next();
c++;
if ( c < args.skip ) {
if ( c % 100000 == 0 ) {
System.out.println("Skipped " + c + " sentences.");
}
continue;
}
// Report status
if (c % 1000 == 0) {
long elapsed = System.nanoTime() - startTime;
long estTime = (long)( elapsed *
- (double) ( ESTIMATED_SENTENCE_COUNT / c - 1 ));
+ (double) ( ESTIMATED_SENTENCE_COUNT / (double) c - 1 ));
System.out.println("===== Read " + c + " lines in " +
formatTime(elapsed) + ", remaining time " +
formatTime(estTime));
}
String[] sentenceArticle = annotations.get(
SFConstants.ARTICLE_IDS ).split("\t");
// Advance index to current document ID.
long desiredDocId = Long.parseLong( sentenceArticle[1] );
corefIndex.nextDoc( desiredDocId );
// Get a coreference provider for the current sentence.
long sentenceId = Long.parseLong( sentenceArticle[0] );
CorefProvider sentenceCoref =
corefIndex.getSentenceProvider( sentenceId );
// Report coreference information
if ( args.verbose && c % 1000 == 0 ) {
System.out.println("Sentence " + sentenceId + ": " +
annotations.get( SFConstants.TEXT ) );
System.out.println("Coreference mentions: " +
sentenceCoref.all());
Set<CorefEntity> entities = new HashSet<CorefEntity>();
for ( CorefMention mention : sentenceCoref.all() ) {
entities.add( mention.entity );
}
System.out.println("Coreference entities: " + entities);
}
// For each query and filler, attempt to fill the slot.
for (SFEntity query : queryReader.queryList) {
for ( Filler filler : fillers ) {
filler.predict(query, annotations, sentenceCoref);
}
}
// Exit if we have exceeded the limit.
if ( args.limit > 0 && c >= args.limit )
break;
}
// Collect answers
for (Filler filler : fillers) {
for (String slotName : filler.slotNames) {
// for each query, print out the answer, or NIL if nothing is found
for (SFEntity query : queryReader.queryList) {
if (query.answers.containsKey(slotName)) {
// The output file format
// Column 1: query id
// Column 2: the slot name
// Column 3: a unique run id for the submission
// Column 4: NIL, if the system believes no
// information is learnable for this slot. Or,
// a single docid which supports the slot value
// Column 5: a slot value
SingleAnswer ans = query.answers.get(slotName).get(0);
for (SingleAnswer a : query.answers.get(slotName)) {
if (a.count > ans.count) // choose answer with highest count
ans = a;
}
answersString.append(String.format(
"%s\t%s\t%s\t%s\t%s\n", query.queryId,
slotName, "MyRun", ans.doc,
ans.answer));
} else {
answersString.append(String.format(
"%s\t%s\t%s\t%s\t%s\n", query.queryId,
slotName, "MyRun", "NIL", ""));
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// TODO: handle errors more intelligently:
try {
if ( corpus != null ) corpus.close();
if ( corefIndex != null ) corefIndex.close();
} catch ( IOException e ) {
throw new RuntimeException(e);
}
}
FileUtil.writeTextToFile(answersString.toString(),
new File( args.testSet, "annotations.pred" ).getPath() );
}
public static void main(String[] argsList) throws Exception {
Args args = new Args(argsList, System.err);
System.out.println("Arguments:\n" + args);
// The slot filling pipeline
if (args.run)
run(args);
// Evaluate against the gold standard labels
// The label file format (11 fields):
// 1. NA
// 2. query id
// 3. NA
// 4. slot name
// 5. from which doc
// 6., 7., 8. NA
// 9. answer string
// 10. equiv. class for the answer in different strings
// 11. judgement. Correct ones are labeled as 1.
if (args.eval) {
String goldAnnotationPath =
new File( args.testSet, "annotations.gold" ).getPath();
String predictedAnnotationPath =
new File( args.testSet, "annotations.pred" ).getPath();
SFScore.main(new String[] { predictedAnnotationPath,
goldAnnotationPath,
"anydoc" });
}
if (args.breakdown) {
String goldAnnotationPath =
new File( args.testSet, "annotations.gold" ).getPath();
String predictedAnnotationPath =
new File( args.testSet, "annotations.pred" ).getPath();
String queryFilePath =
new File( args.testSet, "queries.xml" ).getPath();
String sentMetaPath =
new File( args.corpus, "sentences.meta" ).getPath();
String sentTextPath =
new File( args.corpus, "sentences.text" ).getPath();
MistakeBreakdown.main(new String[] { predictedAnnotationPath,
goldAnnotationPath,
queryFilePath,
sentMetaPath,
sentTextPath });
}
}
}
| true | true | public static void run(Args args) throws InstantiationException, IllegalAccessException {
// read the queries
sf.query.QueryReader queryReader = new sf.query.QueryReader();
queryReader.readFrom( new File( args.testSet, "queries.xml" )
.getPath() );
// Construct fillers
Filler[] fillers = new Filler[ args.fillers.size() ];
int i = 0;
for ( Class<? extends Filler> filler : args.fillers ) {
fillers[ i++ ] = filler.newInstance();
}
StringBuilder answersString = new StringBuilder();
String basePath = args.corpus.getPath();
// initialize the corpus
// FIXME replace the list by a generic class with an input of slot
// name and an output of all the relevant files from the answer file
long startTime = System.nanoTime();
ProcessedCorpus corpus = null;
CorefIndex corefIndex = null;
try {
corpus = new ProcessedCorpus( basePath );
corefIndex = new CorefIndex( basePath );
// Predict annotations
Map<String, String> annotations = null;
int c = 0;
while (corpus.hasNext()) {
// Get next annotation
annotations = corpus.next();
c++;
if ( c < args.skip ) {
if ( c % 100000 == 0 ) {
System.out.println("Skipped " + c + " sentences.");
}
continue;
}
// Report status
if (c % 1000 == 0) {
long elapsed = System.nanoTime() - startTime;
long estTime = (long)( elapsed *
(double) ( ESTIMATED_SENTENCE_COUNT / c - 1 ));
System.out.println("===== Read " + c + " lines in " +
formatTime(elapsed) + ", remaining time " +
formatTime(estTime));
}
String[] sentenceArticle = annotations.get(
SFConstants.ARTICLE_IDS ).split("\t");
// Advance index to current document ID.
long desiredDocId = Long.parseLong( sentenceArticle[1] );
corefIndex.nextDoc( desiredDocId );
// Get a coreference provider for the current sentence.
long sentenceId = Long.parseLong( sentenceArticle[0] );
CorefProvider sentenceCoref =
corefIndex.getSentenceProvider( sentenceId );
// Report coreference information
if ( args.verbose && c % 1000 == 0 ) {
System.out.println("Sentence " + sentenceId + ": " +
annotations.get( SFConstants.TEXT ) );
System.out.println("Coreference mentions: " +
sentenceCoref.all());
Set<CorefEntity> entities = new HashSet<CorefEntity>();
for ( CorefMention mention : sentenceCoref.all() ) {
entities.add( mention.entity );
}
System.out.println("Coreference entities: " + entities);
}
// For each query and filler, attempt to fill the slot.
for (SFEntity query : queryReader.queryList) {
for ( Filler filler : fillers ) {
filler.predict(query, annotations, sentenceCoref);
}
}
// Exit if we have exceeded the limit.
if ( args.limit > 0 && c >= args.limit )
break;
}
// Collect answers
for (Filler filler : fillers) {
for (String slotName : filler.slotNames) {
// for each query, print out the answer, or NIL if nothing is found
for (SFEntity query : queryReader.queryList) {
if (query.answers.containsKey(slotName)) {
// The output file format
// Column 1: query id
// Column 2: the slot name
// Column 3: a unique run id for the submission
// Column 4: NIL, if the system believes no
// information is learnable for this slot. Or,
// a single docid which supports the slot value
// Column 5: a slot value
SingleAnswer ans = query.answers.get(slotName).get(0);
for (SingleAnswer a : query.answers.get(slotName)) {
if (a.count > ans.count) // choose answer with highest count
ans = a;
}
answersString.append(String.format(
"%s\t%s\t%s\t%s\t%s\n", query.queryId,
slotName, "MyRun", ans.doc,
ans.answer));
} else {
answersString.append(String.format(
"%s\t%s\t%s\t%s\t%s\n", query.queryId,
slotName, "MyRun", "NIL", ""));
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// TODO: handle errors more intelligently:
try {
if ( corpus != null ) corpus.close();
if ( corefIndex != null ) corefIndex.close();
} catch ( IOException e ) {
throw new RuntimeException(e);
}
}
FileUtil.writeTextToFile(answersString.toString(),
new File( args.testSet, "annotations.pred" ).getPath() );
}
| public static void run(Args args) throws InstantiationException, IllegalAccessException {
// read the queries
sf.query.QueryReader queryReader = new sf.query.QueryReader();
queryReader.readFrom( new File( args.testSet, "queries.xml" )
.getPath() );
// Construct fillers
Filler[] fillers = new Filler[ args.fillers.size() ];
int i = 0;
for ( Class<? extends Filler> filler : args.fillers ) {
fillers[ i++ ] = filler.newInstance();
}
StringBuilder answersString = new StringBuilder();
String basePath = args.corpus.getPath();
// initialize the corpus
// FIXME replace the list by a generic class with an input of slot
// name and an output of all the relevant files from the answer file
long startTime = System.nanoTime();
ProcessedCorpus corpus = null;
CorefIndex corefIndex = null;
try {
corpus = new ProcessedCorpus( basePath );
corefIndex = new CorefIndex( basePath );
// Predict annotations
Map<String, String> annotations = null;
int c = 0;
while (corpus.hasNext()) {
// Get next annotation
annotations = corpus.next();
c++;
if ( c < args.skip ) {
if ( c % 100000 == 0 ) {
System.out.println("Skipped " + c + " sentences.");
}
continue;
}
// Report status
if (c % 1000 == 0) {
long elapsed = System.nanoTime() - startTime;
long estTime = (long)( elapsed *
(double) ( ESTIMATED_SENTENCE_COUNT / (double) c - 1 ));
System.out.println("===== Read " + c + " lines in " +
formatTime(elapsed) + ", remaining time " +
formatTime(estTime));
}
String[] sentenceArticle = annotations.get(
SFConstants.ARTICLE_IDS ).split("\t");
// Advance index to current document ID.
long desiredDocId = Long.parseLong( sentenceArticle[1] );
corefIndex.nextDoc( desiredDocId );
// Get a coreference provider for the current sentence.
long sentenceId = Long.parseLong( sentenceArticle[0] );
CorefProvider sentenceCoref =
corefIndex.getSentenceProvider( sentenceId );
// Report coreference information
if ( args.verbose && c % 1000 == 0 ) {
System.out.println("Sentence " + sentenceId + ": " +
annotations.get( SFConstants.TEXT ) );
System.out.println("Coreference mentions: " +
sentenceCoref.all());
Set<CorefEntity> entities = new HashSet<CorefEntity>();
for ( CorefMention mention : sentenceCoref.all() ) {
entities.add( mention.entity );
}
System.out.println("Coreference entities: " + entities);
}
// For each query and filler, attempt to fill the slot.
for (SFEntity query : queryReader.queryList) {
for ( Filler filler : fillers ) {
filler.predict(query, annotations, sentenceCoref);
}
}
// Exit if we have exceeded the limit.
if ( args.limit > 0 && c >= args.limit )
break;
}
// Collect answers
for (Filler filler : fillers) {
for (String slotName : filler.slotNames) {
// for each query, print out the answer, or NIL if nothing is found
for (SFEntity query : queryReader.queryList) {
if (query.answers.containsKey(slotName)) {
// The output file format
// Column 1: query id
// Column 2: the slot name
// Column 3: a unique run id for the submission
// Column 4: NIL, if the system believes no
// information is learnable for this slot. Or,
// a single docid which supports the slot value
// Column 5: a slot value
SingleAnswer ans = query.answers.get(slotName).get(0);
for (SingleAnswer a : query.answers.get(slotName)) {
if (a.count > ans.count) // choose answer with highest count
ans = a;
}
answersString.append(String.format(
"%s\t%s\t%s\t%s\t%s\n", query.queryId,
slotName, "MyRun", ans.doc,
ans.answer));
} else {
answersString.append(String.format(
"%s\t%s\t%s\t%s\t%s\n", query.queryId,
slotName, "MyRun", "NIL", ""));
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// TODO: handle errors more intelligently:
try {
if ( corpus != null ) corpus.close();
if ( corefIndex != null ) corefIndex.close();
} catch ( IOException e ) {
throw new RuntimeException(e);
}
}
FileUtil.writeTextToFile(answersString.toString(),
new File( args.testSet, "annotations.pred" ).getPath() );
}
|
diff --git a/api/src/test/java/bo/gotthardt/util/InMemoryEbeanServer.java b/api/src/test/java/bo/gotthardt/util/InMemoryEbeanServer.java
index 41e3a1f..f6df969 100644
--- a/api/src/test/java/bo/gotthardt/util/InMemoryEbeanServer.java
+++ b/api/src/test/java/bo/gotthardt/util/InMemoryEbeanServer.java
@@ -1,79 +1,79 @@
package bo.gotthardt.util;
import com.avaje.ebean.EbeanServer;
import com.avaje.ebean.EbeanServerFactory;
import com.avaje.ebean.config.ServerConfig;
import com.avaje.ebeaninternal.api.SpiEbeanServer;
import com.avaje.ebeaninternal.server.ddl.DdlGenerator;
import lombok.Delegate;
import org.fest.reflect.core.Reflection;
import javax.persistence.PersistenceException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
/**
* In-memory EbeanServer for use in unit/integration tests.
*
* @author Bo Gotthardt
*/
public class InMemoryEbeanServer implements EbeanServer {
private static final String SUBCLASSING_ERROR = "This configuration does not allow entity subclassing ";
@Delegate(types=EbeanServer.class)
private final EbeanServer server;
public InMemoryEbeanServer() {
// Load the in-memory database configuration.
ServerConfig config = new ServerConfig();
config.setName("h2");
config.loadFromProperties();
// We'd like to generate and run database creation queries before each test.
// But we'd also like to not have System.out spammed by Ebean's DdlGenerator class that performs this.
// If generation/run is enabled, it will do so as soon as we create the server, so turn it off, and do it manually later.
config.setDdlGenerate(false);
config.setDdlRun(false);
// Turn off SQL logging as it is rather spammy.
config.setDebugSql(false);
// Production uses enhancement, so turn off subclassing so we will get en error up front if a test run defaults to using it.
config.setAllowSubclassing(false);
// Set as default server in case anyone is using the Ebean singleton.
config.setDefaultServer(true);
try {
server = EbeanServerFactory.create(config);
} catch (PersistenceException e) {
// Ebean will throw this exception with a particular error message when subclassing is turned off but used anyway.
String message = e.getMessage();
if (message != null && message.contains(SUBCLASSING_ERROR)) {
// Rethrow as a more informative error.
throw new RuntimeException("A test involving Ebean has defaulted to using subclassing rather than enhancement.\n" +
" Is your IDE set up to run unit tests with the Ebean javaagent?\n" +
- " Or is " + message.substring(SUBCLASSING_ERROR.length()) + " located in the wrong package?");
+ " Or is " + message.substring(SUBCLASSING_ERROR.length()) + " located in a package that the ebean-maven-enhancement plugin is not configured for?");
} else {
throw e;
}
}
// Block DdlGenerator from spamming System.out by replacing its private "out" PrintStream with a dummy.
DdlGenerator ddl = ((SpiEbeanServer) server).getDdlGenerator();
PrintStream stream = new PrintStream(new OutputStream() {
@Override
public void write(int b) throws IOException {
// Do nothing.
}
});
Reflection.field("out").ofType(PrintStream.class).in(ddl).set(stream);
// And finally run the database creation queries.
ddl.runScript(false, ddl.generateDropDdl());
ddl.runScript(false, ddl.generateCreateDdl());
}
}
| true | true | public InMemoryEbeanServer() {
// Load the in-memory database configuration.
ServerConfig config = new ServerConfig();
config.setName("h2");
config.loadFromProperties();
// We'd like to generate and run database creation queries before each test.
// But we'd also like to not have System.out spammed by Ebean's DdlGenerator class that performs this.
// If generation/run is enabled, it will do so as soon as we create the server, so turn it off, and do it manually later.
config.setDdlGenerate(false);
config.setDdlRun(false);
// Turn off SQL logging as it is rather spammy.
config.setDebugSql(false);
// Production uses enhancement, so turn off subclassing so we will get en error up front if a test run defaults to using it.
config.setAllowSubclassing(false);
// Set as default server in case anyone is using the Ebean singleton.
config.setDefaultServer(true);
try {
server = EbeanServerFactory.create(config);
} catch (PersistenceException e) {
// Ebean will throw this exception with a particular error message when subclassing is turned off but used anyway.
String message = e.getMessage();
if (message != null && message.contains(SUBCLASSING_ERROR)) {
// Rethrow as a more informative error.
throw new RuntimeException("A test involving Ebean has defaulted to using subclassing rather than enhancement.\n" +
" Is your IDE set up to run unit tests with the Ebean javaagent?\n" +
" Or is " + message.substring(SUBCLASSING_ERROR.length()) + " located in the wrong package?");
} else {
throw e;
}
}
// Block DdlGenerator from spamming System.out by replacing its private "out" PrintStream with a dummy.
DdlGenerator ddl = ((SpiEbeanServer) server).getDdlGenerator();
PrintStream stream = new PrintStream(new OutputStream() {
@Override
public void write(int b) throws IOException {
// Do nothing.
}
});
Reflection.field("out").ofType(PrintStream.class).in(ddl).set(stream);
// And finally run the database creation queries.
ddl.runScript(false, ddl.generateDropDdl());
ddl.runScript(false, ddl.generateCreateDdl());
}
| public InMemoryEbeanServer() {
// Load the in-memory database configuration.
ServerConfig config = new ServerConfig();
config.setName("h2");
config.loadFromProperties();
// We'd like to generate and run database creation queries before each test.
// But we'd also like to not have System.out spammed by Ebean's DdlGenerator class that performs this.
// If generation/run is enabled, it will do so as soon as we create the server, so turn it off, and do it manually later.
config.setDdlGenerate(false);
config.setDdlRun(false);
// Turn off SQL logging as it is rather spammy.
config.setDebugSql(false);
// Production uses enhancement, so turn off subclassing so we will get en error up front if a test run defaults to using it.
config.setAllowSubclassing(false);
// Set as default server in case anyone is using the Ebean singleton.
config.setDefaultServer(true);
try {
server = EbeanServerFactory.create(config);
} catch (PersistenceException e) {
// Ebean will throw this exception with a particular error message when subclassing is turned off but used anyway.
String message = e.getMessage();
if (message != null && message.contains(SUBCLASSING_ERROR)) {
// Rethrow as a more informative error.
throw new RuntimeException("A test involving Ebean has defaulted to using subclassing rather than enhancement.\n" +
" Is your IDE set up to run unit tests with the Ebean javaagent?\n" +
" Or is " + message.substring(SUBCLASSING_ERROR.length()) + " located in a package that the ebean-maven-enhancement plugin is not configured for?");
} else {
throw e;
}
}
// Block DdlGenerator from spamming System.out by replacing its private "out" PrintStream with a dummy.
DdlGenerator ddl = ((SpiEbeanServer) server).getDdlGenerator();
PrintStream stream = new PrintStream(new OutputStream() {
@Override
public void write(int b) throws IOException {
// Do nothing.
}
});
Reflection.field("out").ofType(PrintStream.class).in(ddl).set(stream);
// And finally run the database creation queries.
ddl.runScript(false, ddl.generateDropDdl());
ddl.runScript(false, ddl.generateCreateDdl());
}
|
diff --git a/classpath/java/io/RandomAccessFile.java b/classpath/java/io/RandomAccessFile.java
index 18bacb99..da9a8356 100644
--- a/classpath/java/io/RandomAccessFile.java
+++ b/classpath/java/io/RandomAccessFile.java
@@ -1,132 +1,133 @@
/* Copyright (c) 2008-2011, Avian Contributors
Permission to use, copy, modify, and/or distribute this software
for any purpose with or without fee is hereby granted, provided
that the above copyright notice and this permission notice appear
in all copies.
There is NO WARRANTY for this software. See license.txt for
details. */
package java.io;
import java.lang.IllegalArgumentException;
public class RandomAccessFile {
private long peer;
private File file;
private long position = 0;
private long length;
public RandomAccessFile(String name, String mode)
throws FileNotFoundException
{
if (! mode.equals("r")) throw new IllegalArgumentException();
file = new File(name);
open();
}
private void open() throws FileNotFoundException {
long[] result = new long[2];
open(file.getPath(), result);
peer = result[0];
length = result[1];
}
private static native void open(String name, long[] result)
throws FileNotFoundException;
private void refresh() throws IOException {
if (file.length() != length) {
close();
open();
}
}
public long length() throws IOException {
refresh();
return length;
}
public long getFilePointer() throws IOException {
return position;
}
public void seek(long position) throws IOException {
if (position < 0 || position > length()) throw new IOException();
this.position = position;
}
public int skipBytes(int count) throws IOException {
if (position + count > length()) throw new IOException();
this.position = position + count;
return count;
}
public int read(byte b[], int off, int len) throws IOException {
if(b == null)
throw new IllegalArgumentException();
if (peer == 0)
throw new IOException();
if(len == 0)
return 0;
if (position + len > this.length)
throw new EOFException();
if (off < 0 || off + len > b.length)
throw new ArrayIndexOutOfBoundsException();
int bytesRead = readBytes(peer, position, b, off, len);
position += bytesRead;
return bytesRead;
}
public int read(byte b[]) throws IOException {
if(b == null)
throw new IllegalArgumentException();
if (peer == 0)
throw new IOException();
if(b.length == 0)
return 0;
if (position + b.length > this.length)
throw new EOFException();
int bytesRead = readBytes(peer, position, b, 0, b.length);
position += bytesRead;
return bytesRead;
}
public void readFully(byte b[], int off, int len) throws IOException {
if(b == null)
throw new IllegalArgumentException();
if (peer == 0)
throw new IOException();
if(len == 0)
return;
if (position + len > this.length)
throw new EOFException();
if (off < 0 || off + len > b.length)
throw new ArrayIndexOutOfBoundsException();
int n = 0;
do {
int count = readBytes(peer, position, b, off + n, len - n);
- if (count < 0)
+ position += count;
+ if (count == 0)
throw new EOFException();
n += count;
} while (n < len);
}
public void readFully(byte b[]) throws IOException {
readFully(b, 0, b.length);
}
private static native int readBytes(long peer, long position, byte[] buffer,
int offset, int length);
public void close() throws IOException {
if (peer != 0) {
close(peer);
peer = 0;
}
}
private static native void close(long peer);
}
| true | true | public void readFully(byte b[], int off, int len) throws IOException {
if(b == null)
throw new IllegalArgumentException();
if (peer == 0)
throw new IOException();
if(len == 0)
return;
if (position + len > this.length)
throw new EOFException();
if (off < 0 || off + len > b.length)
throw new ArrayIndexOutOfBoundsException();
int n = 0;
do {
int count = readBytes(peer, position, b, off + n, len - n);
if (count < 0)
throw new EOFException();
n += count;
} while (n < len);
}
| public void readFully(byte b[], int off, int len) throws IOException {
if(b == null)
throw new IllegalArgumentException();
if (peer == 0)
throw new IOException();
if(len == 0)
return;
if (position + len > this.length)
throw new EOFException();
if (off < 0 || off + len > b.length)
throw new ArrayIndexOutOfBoundsException();
int n = 0;
do {
int count = readBytes(peer, position, b, off + n, len - n);
position += count;
if (count == 0)
throw new EOFException();
n += count;
} while (n < len);
}
|
diff --git a/hudson-core/src/test/java/hudson/model/UpdateCenterTest.java b/hudson-core/src/test/java/hudson/model/UpdateCenterTest.java
index 7f4941b2..6f7e08cc 100644
--- a/hudson-core/src/test/java/hudson/model/UpdateCenterTest.java
+++ b/hudson-core/src/test/java/hudson/model/UpdateCenterTest.java
@@ -1,64 +1,64 @@
/*******************************************************************************
*
* Copyright (c) 2004-2011 Oracle Corporation.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
*
* Kohsuke Kawaguchi, Nikita Levyankov
*
*
*******************************************************************************/
package hudson.model;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import net.sf.json.JSONObject;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import static junit.framework.Assert.assertTrue;
/**
* Quick test for {@link UpdateCenter}.
*
* @author Kohsuke Kawaguchi
*/
public class UpdateCenterTest {
@Test
public void testData() throws IOException {
// check if we have the internet connectivity. See HUDSON-2095
try {
HttpURLConnection con = (HttpURLConnection) new URL("http://hudson-ci.org/").openConnection();
con.setRequestMethod("HEAD");
con.setConnectTimeout(10000); //set timeout to 10 seconds
if (con.getResponseCode() != HttpURLConnection.HTTP_OK) {
System.out.println("Skipping this test. Page doesn't exists");
return;
}
} catch (java.net.SocketTimeoutException e) {
System.out.println("Skipping this test. Timeout exception");
return;
} catch (IOException e) {
System.out.println("Skipping this test. No internet connectivity");
return;
}
URL url = new URL("http://hudson-ci.org/update-center3/update-center.json?version=build");
String jsonp = IOUtils.toString(url.openStream());
String json = jsonp.substring(jsonp.indexOf('(')+1,jsonp.lastIndexOf(')'));
UpdateSite us = new UpdateSite("default", url.toExternalForm());
UpdateSite.Data data = us.new Data(JSONObject.fromObject(json));
- assertTrue(data.core.url.startsWith("http://hudson-ci.org/") || data.core.url.startsWith("http://eclipse.org/"));
+ assertTrue(data.core.url.startsWith("http://hudson-ci.org/") || data.core.url.startsWith("http://download.eclipse.org/"));
assertTrue(data.plugins.containsKey("rake"));
System.out.println(data.core.url);
}
}
| true | true | public void testData() throws IOException {
// check if we have the internet connectivity. See HUDSON-2095
try {
HttpURLConnection con = (HttpURLConnection) new URL("http://hudson-ci.org/").openConnection();
con.setRequestMethod("HEAD");
con.setConnectTimeout(10000); //set timeout to 10 seconds
if (con.getResponseCode() != HttpURLConnection.HTTP_OK) {
System.out.println("Skipping this test. Page doesn't exists");
return;
}
} catch (java.net.SocketTimeoutException e) {
System.out.println("Skipping this test. Timeout exception");
return;
} catch (IOException e) {
System.out.println("Skipping this test. No internet connectivity");
return;
}
URL url = new URL("http://hudson-ci.org/update-center3/update-center.json?version=build");
String jsonp = IOUtils.toString(url.openStream());
String json = jsonp.substring(jsonp.indexOf('(')+1,jsonp.lastIndexOf(')'));
UpdateSite us = new UpdateSite("default", url.toExternalForm());
UpdateSite.Data data = us.new Data(JSONObject.fromObject(json));
assertTrue(data.core.url.startsWith("http://hudson-ci.org/") || data.core.url.startsWith("http://eclipse.org/"));
assertTrue(data.plugins.containsKey("rake"));
System.out.println(data.core.url);
}
| public void testData() throws IOException {
// check if we have the internet connectivity. See HUDSON-2095
try {
HttpURLConnection con = (HttpURLConnection) new URL("http://hudson-ci.org/").openConnection();
con.setRequestMethod("HEAD");
con.setConnectTimeout(10000); //set timeout to 10 seconds
if (con.getResponseCode() != HttpURLConnection.HTTP_OK) {
System.out.println("Skipping this test. Page doesn't exists");
return;
}
} catch (java.net.SocketTimeoutException e) {
System.out.println("Skipping this test. Timeout exception");
return;
} catch (IOException e) {
System.out.println("Skipping this test. No internet connectivity");
return;
}
URL url = new URL("http://hudson-ci.org/update-center3/update-center.json?version=build");
String jsonp = IOUtils.toString(url.openStream());
String json = jsonp.substring(jsonp.indexOf('(')+1,jsonp.lastIndexOf(')'));
UpdateSite us = new UpdateSite("default", url.toExternalForm());
UpdateSite.Data data = us.new Data(JSONObject.fromObject(json));
assertTrue(data.core.url.startsWith("http://hudson-ci.org/") || data.core.url.startsWith("http://download.eclipse.org/"));
assertTrue(data.plugins.containsKey("rake"));
System.out.println(data.core.url);
}
|
diff --git a/web/src/main/java/org/fao/geonet/services/publisher/GeoServerRest.java b/web/src/main/java/org/fao/geonet/services/publisher/GeoServerRest.java
index 6c97fa174c..7b74fcef2f 100644
--- a/web/src/main/java/org/fao/geonet/services/publisher/GeoServerRest.java
+++ b/web/src/main/java/org/fao/geonet/services/publisher/GeoServerRest.java
@@ -1,666 +1,666 @@
//=============================================================================
//=== Copyright (C) 2010 Food and Agriculture Organization of the
//=== United Nations (FAO-UN), United Nations World Food Programme (WFP)
//=== and United Nations Environment Programme (UNEP)
//===
//=== This program is free software; you can redistribute it and/or modify
//=== it under the terms of the GNU General Public License as published by
//=== the Free Software Foundation; either version 2 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
//=== General Public License for more details.
//===
//=== You should have received a copy of the GNU General Public License
//=== along with this program; if not, write to the Free Software
//=== Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
//===
//=== Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2,
//=== Rome - Italy. email: [email protected]
//==============================================================================
package org.fao.geonet.services.publisher;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import jeeves.utils.Log;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.fao.geonet.csw.common.util.Xml;
import org.jdom.Element;
/**
* This class uses GeoServer's management REST APIs for creating, updating and
* deleting data or coverage store.
* http://docs.geoserver.org/stable/en/user/extensions/rest/rest-config-api.html
*
*
* Similar development have been discovered at the end of that proposal patch:
* http://code.google.com/p/gsrcj/
* http://code.google.com/p/toolboxenvironment/source
* /browse/trunk/ArchivingServer
* /src/java/it/intecs/pisa/archivingserver/chain/commands
* /PublishToGeoServer.java
*
*/
public class GeoServerRest {
public final static String METHOD_POST = "POST";
public final static String METHOD_GET = "GET";
public final static String METHOD_PUT = "PUT";
public final static String METHOD_DELETE = "DELETE";
public final static String LOGGER_NAME = "geonetwork.GeoServerRest";
private String password;
private String username;
private String restUrl;
private String baseCatalogueUrl;
private String defaultWorkspace;
private String response;
private int status;
private HttpClientFactory httpClientFactory;
/**
* Create a GeoServerRest instance to communicate with a GeoServer node.
*
* @param baseCatalogueUrl
* TODO
*/
public GeoServerRest(String url, String username, String password,
String baseCatalogueUrl) {
init(url, username, password, baseCatalogueUrl);
}
/**
* Create a GeoServerRest instance to communicate with a GeoServer node and
* a default namespace
*
* @param url
* @param username
* @param password
* @param defaultns
* @param baseCatalogueUrl
* TODO
*/
public GeoServerRest(String url, String username, String password,
String defaultns, String baseCatalogueUrl) {
init(url, username, password, baseCatalogueUrl);
this.defaultWorkspace = defaultns;
}
private void init(String url, String username, String password,
String baseCatalogueUrl) {
this.restUrl = url;
this.username = username;
this.password = password;
this.baseCatalogueUrl = baseCatalogueUrl;
this.httpClientFactory = new HttpClientFactory(this.username,
this.password);
Log.createLogger(LOGGER_NAME);
}
/**
* @return Return last transaction response information if set.
*/
public String getResponse() {
return response;
}
/**
* @return Last status information
*/
public int getStatus() {
return status;
}
/**
* @return The default workspace used
*/
public String getDefaultWorkspace() {
return defaultWorkspace;
}
/**
* Retrieve layer (feature type or coverage) information. Use @see
* #getResponse() to get the message returned.
*
* TODO : Add format ?
*
* @param layer
* @return
* @throws IOException
*/
public boolean getLayer(String layer) throws IOException {
int status = sendREST(GeoServerRest.METHOD_GET, "/layers/" + layer
+ ".xml", null, null, null, true);
return status == 200;
}
public String getLayerInfo(String layer) throws IOException {
if (getLayer(layer))
return getResponse();
else
return null;
}
/**
* If the layer does not exist, return <code>false</code>
*
* @param layer
* Name of the layer to delete
* @return
* @throws IOException
*/
public boolean deleteLayer(String layer) throws IOException {
int status = sendREST(GeoServerRest.METHOD_DELETE, "/layers/" + layer,
null, null, null, true);
// TODO : add force to remove ft, ds
return status == 200;
}
/**
* Create a coverage from file
*
* @param ws
* Name of the workspace to add the coverage in
* @param cs
* Name of the coverage
* @param f
* A zip or a geotiff {@link File} to updload.
* @return
* @throws IOException
*/
public boolean createCoverage(String ws, String cs, File f, String metadataUuid, String metadataTitle)
throws IOException {
String contentType = "image/tiff";
if (f.getName().toLowerCase().endsWith(".zip")) {
contentType = "application/zip";
}
int status = sendREST(GeoServerRest.METHOD_PUT, "/workspaces/" + ws
+ "/coveragestores/" + cs + "/file.geotiff", null, f,
contentType, false);
createCoverageForStore(ws, cs, null, metadataUuid, metadataTitle);
return status == 201;
}
/**
* Create a coverage from an external file or URL.
*
* @param ws
* @param cs
* @param file
* @return
* @throws IOException
*/
public boolean createCoverage(String ws, String cs, String file, String metadataUuid, String metadataTitle)
throws IOException {
String contentType = "image/tiff";
String extension = "geotiff";
if (GeoFile.fileIsECW(file)) {
contentType = "image/ecw";
extension = "ecw";
}
String type = "file";
if (file.toLowerCase().endsWith(".zip")) {
contentType = "application/zip";
}
// String extension = file.substring(file.lastIndexOf('.'),
// file.length());
if (file.startsWith("http://")) {
type = "url";
} else if (file.startsWith("file://")) {
type = "external";
}
int status = sendREST(GeoServerRest.METHOD_PUT, "/workspaces/" + ws
+ "/coveragestores/" + cs + "/" + type + "." + extension, file,
null, contentType, false);
createCoverageForStore(ws, cs, file, metadataUuid, metadataTitle);
return status == 201;
}
private void createCoverageForStore(String ws, String cs, String file,
String metadataUuid, String metadataTitle)
throws IOException {
String xml = "<coverageStore><name>" + cs + "</name><title>"
+ (metadataTitle != null ? metadataTitle : cs)
+ "</title><enabled>true</enabled>"
+ (file != null ? "<file>" + file + "</file>" : "")
+ "<metadataLinks>"
+ "<metadataLink>"
+ "<type>text/xml</type>"
+ "<metadataType>ISO19115:2003</metadataType>"
+ "<content>"
+ this.baseCatalogueUrl + "?uuid=" + metadataUuid
+ "</content>"
+ "</metadataLink>"
+ "<metadataLink>"
+ "<type>text/xml</type>"
+ "<metadataType>TC211</metadataType>"
+ "<content>"
+ this.baseCatalogueUrl + "?uuid=" + metadataUuid
+ "</content>"
+ "</metadataLink>"
+ "</metadataLinks>"
+ "</coverageStore>";
int statusCoverage = sendREST(GeoServerRest.METHOD_PUT, "/workspaces/" + ws
+ "/coveragestores/" + cs + "/coverages/" + cs + ".xml", xml,
null, "text/xml", false);
}
/**
* Create a coverage from file in default workspace
*
* @param cs
* @param f
* @return
* @throws IOException
*/
public boolean createCoverage(String cs, File f, String metadataUuid, String metadataTitle) throws IOException {
// TODO : check default workspace is not null ?
return createCoverage(getDefaultWorkspace(), cs, f, metadataUuid, metadataTitle);
}
/**
* Create a coverage from external file or URL in default workspace
*
* @param cs
* @param f
* @param metadataUuid TODO
* @param metadataTitle TODO
* @return
* @throws IOException
*/
public boolean createCoverage(String cs, String f, String metadataUuid, String metadataTitle) throws IOException {
return createCoverage(getDefaultWorkspace(), cs, f, metadataUuid, metadataTitle);
}
/**
* @see #createCoverage(String, String, File)
* @param ws
* @param ds
* @param f
* @return
* @throws IOException
*/
public boolean updateCoverage(String ws, String ds, File f, String metadataUuid, String metadataTitle)
throws IOException {
return createCoverage(ws, ds, f, metadataUuid, metadataTitle);
}
/**
* @see #createCoverage(String, String, File)
* @param ds
* @param f
* @return
* @throws IOException
*/
public boolean updateCoverage(String ds, File f, String metadataUuid, String metadataTitle) throws IOException {
return createCoverage(getDefaultWorkspace(), ds, f, metadataUuid, metadataTitle);
}
/**
*
* @param ws
* Name of the workspace the coverage is in
* @param cs
* Name of the coverage store
* @param c
* Name of the coverage
* @return
* @throws IOException
*/
public boolean deleteCoverage(String ws, String cs, String c)
throws IOException {
int status = sendREST(GeoServerRest.METHOD_DELETE, "/workspaces/" + ws
+ "/coveragestores/" + cs + "/coverages/" + c, null, null,
null, true);
return status == 200;
}
/**
* Delete a coverage in default workspace
*
* @param cs
* @param c
* @return
* @throws IOException
*/
public boolean deleteCoverage(String cs, String c) throws IOException {
return deleteCoverage(getDefaultWorkspace(), cs, c);
}
/**
*
* @param ws
* Name of the workspace to put the datastore in
* @param ds
* Name of the datastore
* @param f
* Zip {@link File} to upload containing a shapefile
* @param createStyle
* True to create a default style @see
* {@link #createStyle(String)}
* @return
* @throws IOException
*/
public boolean createDatastore(String ws, String ds, File f,
boolean createStyle) throws IOException {
int status = sendREST(GeoServerRest.METHOD_PUT, "/workspaces/" + ws
+ "/datastores/" + ds + "/file.shp", null, f,
"application/zip", false);
if (createStyle) {
createStyle(ds);
}
return status == 201;
}
public boolean createDatastore(String ws, String ds, String file,
boolean createStyle) throws IOException {
String type = "";
String extension = file.substring(file.lastIndexOf('.'), file.length());
if (file.startsWith("http://")) {
type = "url";
} else if (file.startsWith("file://")) {
type = "external";
}
int status = sendREST(GeoServerRest.METHOD_PUT, "/workspaces/" + ws
+ "/datastores/" + ds + "/" + type + extension, file, null,
"text/plain", false);
if (createStyle) {
createStyle(ds);
}
return status == 201;
}
/**
* Create datastore in default workspace
*
* @param ds
* @param f
* @param createStyle
* @return
* @throws IOException
*/
public boolean createDatastore(String ds, File f, boolean createStyle)
throws IOException {
return createDatastore(getDefaultWorkspace(), ds, f, createStyle);
}
public boolean createDatastore(String ds, String file, boolean createStyle)
throws IOException {
return createDatastore(getDefaultWorkspace(), ds, file, createStyle);
}
/**
* Delete a datastore
*
* @param ws
* @param ds
* @return
* @throws IOException
*/
public boolean deleteDatastore(String ws, String ds) throws IOException {
int status = sendREST(GeoServerRest.METHOD_DELETE, "/workspaces/" + ws
+ "/datastores/" + ds, null, null, null, true);
return status == 200;
}
/**
* Delete a datastore in default workspace
*
* @param ds
* @return
* @throws IOException
*/
public boolean deleteDatastore(String ds) throws IOException {
return deleteDatastore(getDefaultWorkspace(), ds);
}
/**
* Delete a coverage store
*
* @param ws
* @param cs
* @return
* @throws IOException
*/
public boolean deleteCoverageStore(String ws, String cs) throws IOException {
int status = sendREST(GeoServerRest.METHOD_DELETE, "/workspaces/" + ws
+ "/coveragestores/" + cs, null, null, null, true);
return status == 200;
}
/**
* Delete a coverage store in default workspace @see {@link #deleteCoverageStore(String, String)
* @param ds
* @return
* @throws IOException
*/
public boolean deleteCoverageStore(String ds) throws IOException {
return deleteCoverageStore(getDefaultWorkspace(), ds);
}
public boolean deleteFeatureType(String ws, String ds, String ft)
throws IOException {
int status = sendREST(GeoServerRest.METHOD_DELETE, "/workspaces/" + ws
+ "/datastores/" + ds + "/featuretypes/" + ft, null, null,
null, true);
return status == 200;
}
public boolean deleteFeatureType(String ds, String ft) throws IOException {
return deleteFeatureType(getDefaultWorkspace(), ds, ft);
}
/**
* Create a default style for the layer named {layer}_style copied from the
* default style set by GeoServer (eg. polygon.sld for polygon).
*
* @param layer
* @return
*/
public int createStyle(String layer) {
try {
int status = sendREST(GeoServerRest.METHOD_GET, "/layers/" + layer
+ ".xml", null, null, null, true);
Element layerProperties = Xml.loadString(getResponse(), false);
String styleName = layerProperties.getChild("defaultStyle")
.getChild("name").getText();
status = sendREST(GeoServerRest.METHOD_GET, "/styles/" + styleName
+ ".sld", null, null, null, true);
String currentStyle = getResponse();
String body = "<style><name>" + layer + "_style</name><filename>"
+ layer + ".sld</filename></style>";
status = sendREST(GeoServerRest.METHOD_POST, "/styles", body, null,
"text/xml", true);
status = sendREST(GeoServerRest.METHOD_PUT, "/styles/" + layer
+ "_style", currentStyle, null,
"application/vnd.ogc.sld+xml", true);
body = "<layer><defaultStyle><name>"
+ layer
+ "_style</name></defaultStyle><enabled>true</enabled></layer>";
// Add the enable flag due to GeoServer bug
// http://jira.codehaus.org/browse/GEOS-3964
status = sendREST(GeoServerRest.METHOD_PUT, "/layers/" + layer,
body, null, "text/xml", true);
} catch (Exception e) {
if(Log.isDebugEnabled("GeoServerRest"))
Log.debug("GeoServerRest", "Failed to create style for layer: "
+ layer + ", error is: " + e.getMessage());
}
return status;
}
public boolean createDatabaseDatastore(String ds, String host, String port,
String db, String user, String pwd, String dbType, String ns)
throws IOException {
return createDatabaseDatastore(getDefaultWorkspace(), ds, host, port,
db, user, pwd, dbType, ns);
}
public boolean createDatabaseDatastore(String ws, String ds, String host,
String port, String db, String user, String pwd, String dbType,
String ns) throws IOException {
String xml = "<dataStore><name>" + ds
+ "</name><enabled>true</enabled><connectionParameters><host>"
+ host + "</host><port>" + port + "</port><database>" + db
+ "</database><user>" + user + "</user><passwd>" + pwd
+ "</passwd><dbtype>" + dbType + "</dbtype><namespace>" + ns
+ "</namespace></connectionParameters></dataStore>";
status = sendREST(GeoServerRest.METHOD_POST, "/workspaces/" + ws
+ "/datastores", xml, null, "text/xml", true);
return 201 == status;
}
public boolean createFeatureType(String ds, String ft, boolean createStyle,
String metadataUuid, String metadataTitle) throws IOException {
return createFeatureType(getDefaultWorkspace(), ds, ft, createStyle,
metadataUuid, metadataTitle);
}
public boolean createFeatureType(String ws, String ds, String ft,
boolean createStyle, String metadataUuid, String metadataTitle)
throws IOException {
String xml = "<featureType><name>" + ft + "</name><title>" + ft
+ "</title>" + "</featureType>";
status = sendREST(GeoServerRest.METHOD_POST, "/workspaces/" + ws
+ "/datastores/" + ds + "/featuretypes", xml, null, "text/xml",
true);
xml = "<featureType><title>"
+ (metadataTitle != null ? metadataTitle : ft)
+ "</title><enabled>true</enabled>"
+ "<metadataLinks>"
+ "<metadataLink>"
+ "<type>text/xml</type>"
+ "<metadataType>ISO19115:2003</metadataType>"
+ "<content>"
+ this.baseCatalogueUrl
+ "csw?SERVICE=CSW&VERSION=2.0.2&REQUEST=GetRecordById"
+ "&outputSchema=http://www.isotc211.org/2005/gmd"
+ // Geopublication only allowed for ISO19139* records. The
// outputSchema should always return a record.
"&ID=" + metadataUuid + "</content>"
+ "</metadataLink>"
+ "</metadataLinks>"
+ "</featureType>";
status = sendREST(GeoServerRest.METHOD_PUT, "/workspaces/" + ws
+ "/datastores/" + ds + "/featuretypes/" + ft, xml, null,
"text/xml", true);
// Create layer for feature type (require for MapServer REST API)
int s = sendREST(GeoServerRest.METHOD_PUT, "/layers/" + ft, null, null,
"text/xml", false);
if (createStyle) {
createStyle(ft);
}
return 201 == status;
}
/**
*
* @param method
* e.g. 'POST', 'GET', 'PUT' or 'DELETE'
* @param urlParams
* REST API parameter
* @param postData
* XML data
* @param file
* File to upload
* @param contentType
* type of content in case of post data or file updload.
* @param saveResponse
* @return
* @throws IOException
*/
public int sendREST(String method, String urlParams, String postData,
File file, String contentType, Boolean saveResponse)
throws IOException {
response = "";
final HttpClient c = httpClientFactory.newHttpClient();
String url = this.restUrl + urlParams;
if(Log.isDebugEnabled(LOGGER_NAME)) {
Log.debug(LOGGER_NAME, "url:" + url);
Log.debug(LOGGER_NAME, "method:" + method);
Log.debug(LOGGER_NAME, "postData:" + postData);
}
HttpMethod m;
if (method.equals(METHOD_PUT)) {
m = new PutMethod(url);
if (file != null) {
((PutMethod) m).setRequestEntity(new InputStreamRequestEntity(
new FileInputStream(file)));
}
if (postData != null) {
((PutMethod) m).setRequestEntity(new StringRequestEntity(
- postData));
+ postData, contentType, "UTF-8"));
}
} else if (method.equals(METHOD_DELETE)) {
m = new DeleteMethod(url);
} else if (method.equals(METHOD_POST)) {
m = new PostMethod(url);
if (postData != null) {
((PostMethod) m).setRequestEntity(new StringRequestEntity(
- postData));
+ postData, contentType, "UTF-8"));
}
} else {
m = new GetMethod(url);
}
if (contentType != null && !"".equals(contentType)) {
m.setRequestHeader("Content-type", contentType);
}
m.setDoAuthentication(true);
status = c.executeMethod(m);
if(Log.isDebugEnabled(LOGGER_NAME)) Log.debug(LOGGER_NAME, "status:" + status);
if (saveResponse)
this.response = m.getResponseBodyAsString();
return status;
}
}
| false | true | public int sendREST(String method, String urlParams, String postData,
File file, String contentType, Boolean saveResponse)
throws IOException {
response = "";
final HttpClient c = httpClientFactory.newHttpClient();
String url = this.restUrl + urlParams;
if(Log.isDebugEnabled(LOGGER_NAME)) {
Log.debug(LOGGER_NAME, "url:" + url);
Log.debug(LOGGER_NAME, "method:" + method);
Log.debug(LOGGER_NAME, "postData:" + postData);
}
HttpMethod m;
if (method.equals(METHOD_PUT)) {
m = new PutMethod(url);
if (file != null) {
((PutMethod) m).setRequestEntity(new InputStreamRequestEntity(
new FileInputStream(file)));
}
if (postData != null) {
((PutMethod) m).setRequestEntity(new StringRequestEntity(
postData));
}
} else if (method.equals(METHOD_DELETE)) {
m = new DeleteMethod(url);
} else if (method.equals(METHOD_POST)) {
m = new PostMethod(url);
if (postData != null) {
((PostMethod) m).setRequestEntity(new StringRequestEntity(
postData));
}
} else {
m = new GetMethod(url);
}
if (contentType != null && !"".equals(contentType)) {
m.setRequestHeader("Content-type", contentType);
}
m.setDoAuthentication(true);
status = c.executeMethod(m);
if(Log.isDebugEnabled(LOGGER_NAME)) Log.debug(LOGGER_NAME, "status:" + status);
if (saveResponse)
this.response = m.getResponseBodyAsString();
return status;
}
| public int sendREST(String method, String urlParams, String postData,
File file, String contentType, Boolean saveResponse)
throws IOException {
response = "";
final HttpClient c = httpClientFactory.newHttpClient();
String url = this.restUrl + urlParams;
if(Log.isDebugEnabled(LOGGER_NAME)) {
Log.debug(LOGGER_NAME, "url:" + url);
Log.debug(LOGGER_NAME, "method:" + method);
Log.debug(LOGGER_NAME, "postData:" + postData);
}
HttpMethod m;
if (method.equals(METHOD_PUT)) {
m = new PutMethod(url);
if (file != null) {
((PutMethod) m).setRequestEntity(new InputStreamRequestEntity(
new FileInputStream(file)));
}
if (postData != null) {
((PutMethod) m).setRequestEntity(new StringRequestEntity(
postData, contentType, "UTF-8"));
}
} else if (method.equals(METHOD_DELETE)) {
m = new DeleteMethod(url);
} else if (method.equals(METHOD_POST)) {
m = new PostMethod(url);
if (postData != null) {
((PostMethod) m).setRequestEntity(new StringRequestEntity(
postData, contentType, "UTF-8"));
}
} else {
m = new GetMethod(url);
}
if (contentType != null && !"".equals(contentType)) {
m.setRequestHeader("Content-type", contentType);
}
m.setDoAuthentication(true);
status = c.executeMethod(m);
if(Log.isDebugEnabled(LOGGER_NAME)) Log.debug(LOGGER_NAME, "status:" + status);
if (saveResponse)
this.response = m.getResponseBodyAsString();
return status;
}
|
diff --git a/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseFactory.java b/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseFactory.java
index 5271aff58..272f14c80 100644
--- a/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseFactory.java
+++ b/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/EclipseFactory.java
@@ -1,1124 +1,1128 @@
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* PARC initial implementation
* Mik Kersten 2004-07-26 extended to allow overloading of
* hierarchy builder
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.lookup;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.AstUtil;
import org.aspectj.ajdt.internal.core.builder.AjBuildManager;
import org.aspectj.bridge.ISourceLocation;
import org.aspectj.bridge.IMessage.Kind;
import org.aspectj.org.eclipse.jdt.core.Flags;
import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.ASTNode;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.EmptyStatement;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Wildcard;
import org.aspectj.org.eclipse.jdt.internal.compiler.impl.Constant;
import org.aspectj.org.eclipse.jdt.internal.compiler.impl.ReferenceContext;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ArrayBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.Binding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.FieldBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LocalTypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ParameterizedTypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.RawTypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.Scope;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SyntheticFieldBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeVariableBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.WildcardBinding;
import org.aspectj.weaver.BCException;
import org.aspectj.weaver.BoundedReferenceType;
import org.aspectj.weaver.ConcreteTypeMunger;
import org.aspectj.weaver.IHasPosition;
import org.aspectj.weaver.Member;
import org.aspectj.weaver.MemberKind;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.NewFieldTypeMunger;
import org.aspectj.weaver.NewMethodTypeMunger;
import org.aspectj.weaver.ReferenceType;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedMemberImpl;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.TypeFactory;
import org.aspectj.weaver.TypeVariable;
import org.aspectj.weaver.TypeVariableDeclaringElement;
import org.aspectj.weaver.TypeVariableReference;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.UnresolvedTypeVariableReferenceType;
import org.aspectj.weaver.WildcardedUnresolvedType;
import org.aspectj.weaver.World;
import org.aspectj.weaver.UnresolvedType.TypeKind;
/**
* @author Jim Hugunin
*/
public class EclipseFactory {
public static boolean DEBUG = false;
public static int debug_mungerCount = -1;
private AjBuildManager buildManager;
private LookupEnvironment lookupEnvironment;
private boolean xSerializableAspects;
private World world;
public Collection finishedTypeMungers = null;
// We can get clashes if we don't treat raw types differently - we end up looking
// up a raw and getting the generic type (pr115788)
private Map/*UnresolvedType, TypeBinding*/ typexToBinding = new HashMap();
private Map/*UnresolvedType, TypeBinding*/ rawTypeXToBinding = new HashMap();
//XXX currently unused
// private Map/*TypeBinding, ResolvedType*/ bindingToResolvedTypeX = new HashMap();
public static EclipseFactory fromLookupEnvironment(LookupEnvironment env) {
AjLookupEnvironment aenv = (AjLookupEnvironment)env;
return aenv.factory;
}
public static EclipseFactory fromScopeLookupEnvironment(Scope scope) {
return fromLookupEnvironment(AstUtil.getCompilationUnitScope(scope).environment);
}
public EclipseFactory(LookupEnvironment lookupEnvironment,AjBuildManager buildManager) {
this.lookupEnvironment = lookupEnvironment;
this.buildManager = buildManager;
this.world = buildManager.getWorld();
this.xSerializableAspects = buildManager.buildConfig.isXserializableAspects();
}
public EclipseFactory(LookupEnvironment lookupEnvironment, World world, boolean xSer) {
this.lookupEnvironment = lookupEnvironment;
this.world = world;
this.xSerializableAspects = xSer;
this.buildManager = null;
}
public World getWorld() {
return world;
}
public void showMessage(
Kind kind,
String message,
ISourceLocation loc1,
ISourceLocation loc2)
{
getWorld().showMessage(kind, message, loc1, loc2);
}
public ResolvedType fromEclipse(ReferenceBinding binding) {
if (binding == null) return ResolvedType.MISSING;
//??? this seems terribly inefficient
//System.err.println("resolving: " + binding.getClass() + ", name = " + getName(binding));
ResolvedType ret = getWorld().resolve(fromBinding(binding));
//System.err.println(" got: " + ret);
return ret;
}
public ResolvedType fromTypeBindingToRTX(TypeBinding tb) {
if (tb == null) return ResolvedType.MISSING;
ResolvedType ret = getWorld().resolve(fromBinding(tb));
return ret;
}
public ResolvedType[] fromEclipse(ReferenceBinding[] bindings) {
if (bindings == null) {
return ResolvedType.NONE;
}
int len = bindings.length;
ResolvedType[] ret = new ResolvedType[len];
for (int i=0; i < len; i++) {
ret[i] = fromEclipse(bindings[i]);
}
return ret;
}
public static String getName(TypeBinding binding) {
if (binding instanceof TypeVariableBinding) {
// The first bound may be null - so default to object?
TypeVariableBinding tvb = (TypeVariableBinding)binding;
if (tvb.firstBound!=null) {
return getName(tvb.firstBound);
} else {
return getName(tvb.superclass);
}
}
if (binding instanceof ReferenceBinding) {
return new String(
CharOperation.concatWith(((ReferenceBinding)binding).compoundName, '.'));
}
String packageName = new String(binding.qualifiedPackageName());
String className = new String(binding.qualifiedSourceName()).replace('.', '$');
if (packageName.length() > 0) {
className = packageName + "." + className;
}
//XXX doesn't handle arrays correctly (or primitives?)
return new String(className);
}
/**
* Some generics notes:
*
* Andy 6-May-05
* We were having trouble with parameterized types in a couple of places - due to TypeVariableBindings. When we
* see a TypeVariableBinding now we default to either the firstBound if it is specified or java.lang.Object. Not
* sure when/if this gets us unstuck? It does mean we forget that it is a type variable when going back
* the other way from the UnresolvedType and that would seem a bad thing - but I've yet to see the reason we need to
* remember the type variable.
* Adrian 10-July-05
* When we forget it's a type variable we come unstuck when getting the declared members of a parameterized
* type - since we don't know it's a type variable we can't replace it with the type parameter.
*/
//??? going back and forth between strings and bindings is a waste of cycles
public UnresolvedType fromBinding(TypeBinding binding) {
if (binding instanceof HelperInterfaceBinding) {
return ((HelperInterfaceBinding) binding).getTypeX();
}
if (binding == null || binding.qualifiedSourceName() == null) {
return ResolvedType.MISSING;
}
// first piece of generics support!
if (binding instanceof TypeVariableBinding) {
TypeVariableBinding tb = (TypeVariableBinding) binding;
UnresolvedTypeVariableReferenceType utvrt = (UnresolvedTypeVariableReferenceType) fromTypeVariableBinding(tb);
return utvrt;
}
// handle arrays since the component type may need special treatment too...
if (binding instanceof ArrayBinding) {
ArrayBinding aBinding = (ArrayBinding) binding;
UnresolvedType componentType = fromBinding(aBinding.leafComponentType);
return UnresolvedType.makeArray(componentType, aBinding.dimensions);
}
if (binding instanceof WildcardBinding) {
WildcardBinding eWB = (WildcardBinding) binding;
// Repair the bound
// e.g. If the bound for the wildcard is a typevariable, e.g. '? extends E' then
// the type variable in the unresolvedtype will be correct only in name. In that
// case let's set it correctly based on the one in the eclipse WildcardBinding
UnresolvedType theBound = null;
if (eWB.bound instanceof TypeVariableBinding) {
theBound = fromTypeVariableBinding((TypeVariableBinding)eWB.bound);
} else {
theBound = fromBinding(eWB.bound);
}
// if (eWB.boundKind == WildCard.SUPER) {
//
// }
WildcardedUnresolvedType theType = (WildcardedUnresolvedType) TypeFactory.createTypeFromSignature(CharOperation.charToString(eWB.genericTypeSignature()));
// if (theType.isGenericWildcard() && theType.isSuper()) theType.setLowerBound(theBound);
// if (theType.isGenericWildcard() && theType.isExtends()) theType.setUpperBound(theBound);
return theType;
}
if (binding instanceof ParameterizedTypeBinding) {
if (binding instanceof RawTypeBinding) {
// special case where no parameters are specified!
return UnresolvedType.forRawTypeName(getName(binding));
}
ParameterizedTypeBinding ptb = (ParameterizedTypeBinding) binding;
UnresolvedType[] arguments = null;
if (ptb.arguments!=null) { // null can mean this is an inner type of a Parameterized Type with no bounds of its own (pr100227)
arguments = new UnresolvedType[ptb.arguments.length];
for (int i = 0; i < arguments.length; i++) {
arguments[i] = fromBinding(ptb.arguments[i]);
}
}
String baseTypeSignature = null;
ResolvedType baseType = getWorld().resolve(UnresolvedType.forName(getName(binding)),true);
if (!baseType.isMissing()) {
// can legitimately be missing if a bound refers to a type we haven't added to the world yet...
// pr168044 - sometimes (whilst resolving types) we are working with 'half finished' types and so (for example) the underlying generic type for a raw type hasnt been set yet
//if (!baseType.isGenericType() && arguments!=null) baseType = baseType.getGenericType();
baseTypeSignature = baseType.getErasureSignature();
} else {
baseTypeSignature = UnresolvedType.forName(getName(binding)).getSignature();
}
// Create an unresolved parameterized type. We can't create a resolved one as the
// act of resolution here may cause recursion problems since the parameters may
// be type variables that we haven't fixed up yet.
if (arguments==null) arguments=new UnresolvedType[0];
- String parameterizedSig = ResolvedType.PARAMETERIZED_TYPE_IDENTIFIER+CharOperation.charToString(binding.genericTypeSignature()).substring(1);
- return TypeFactory.createUnresolvedParameterizedType(parameterizedSig,baseTypeSignature,arguments);
+// StringBuffer parameterizedSig = new StringBuffer();
+// parameterizedSig.append(ResolvedType.PARAMETERIZED_TYPE_IDENTIFIER);
+//
+//// String parameterizedSig = new StringBuffer().append(ResolvedType.PARAMETERIZED_TYPE_IDENTIFIER).append(CharOperation.charToString(binding.genericTypeSignature()).substring(1)).toString();
+// return TypeFactory.createUnresolvedParameterizedType(parameterizedSig,baseTypeSignature,arguments);
+ return TypeFactory.createUnresolvedParameterizedType(baseTypeSignature,arguments);
}
// Convert the source type binding for a generic type into a generic UnresolvedType
// notice we can easily determine the type variables from the eclipse object
// and we can recover the generic signature from it too - so we pass those
// to the forGenericType() method.
if (binding.isGenericType() &&
!binding.isParameterizedType() &&
!binding.isRawType()) {
TypeVariableBinding[] tvbs = binding.typeVariables();
TypeVariable[] tVars = new TypeVariable[tvbs.length];
for (int i = 0; i < tvbs.length; i++) {
TypeVariableBinding eclipseV = tvbs[i];
tVars[i] = ((TypeVariableReference)fromTypeVariableBinding(eclipseV)).getTypeVariable();
}
//TODO asc generics - temporary guard....
if (!(binding instanceof SourceTypeBinding))
throw new RuntimeException("Cant get the generic sig for "+binding.debugName());
return UnresolvedType.forGenericType(getName(binding),tVars,
CharOperation.charToString(((SourceTypeBinding)binding).genericSignature()));
}
// LocalTypeBinding have a name $Local$, we can get the real name by using the signature....
if (binding instanceof LocalTypeBinding) {
LocalTypeBinding ltb = (LocalTypeBinding) binding;
if (ltb.constantPoolName() != null && ltb.constantPoolName().length > 0) {
return UnresolvedType.forSignature(new String(binding.signature()));
} else {
// we're reporting a problem and don't have a resolved name for an
// anonymous local type yet, report the issue on the enclosing type
return UnresolvedType.forSignature(new String(ltb.enclosingType.signature()));
}
}
return UnresolvedType.forName(getName(binding));
}
/**
* Some type variables refer to themselves recursively, this enables us to avoid
* recursion problems.
*/
private static Map typeVariableBindingsInProgress = new HashMap();
/**
* Convert from the eclipse form of type variable (TypeVariableBinding) to the AspectJ
* form (TypeVariable).
*/
private UnresolvedType fromTypeVariableBinding(TypeVariableBinding aTypeVariableBinding) {
// first, check for recursive call to this method for the same tvBinding
if (typeVariableBindingsInProgress.containsKey(aTypeVariableBinding)) {
return (UnresolvedType) typeVariableBindingsInProgress.get(aTypeVariableBinding);
}
// Check if its a type variable binding that we need to recover to an alias...
if (typeVariablesForAliasRecovery!=null) {
String aliasname = (String)typeVariablesForAliasRecovery.get(aTypeVariableBinding);
if (aliasname!=null) {
UnresolvedTypeVariableReferenceType ret = new UnresolvedTypeVariableReferenceType();
ret.setTypeVariable(new TypeVariable(aliasname));
return ret;
}
}
if (typeVariablesForThisMember.containsKey(new String(aTypeVariableBinding.sourceName))) {
return (UnresolvedType)typeVariablesForThisMember.get(new String(aTypeVariableBinding.sourceName));
}
// Create the UnresolvedTypeVariableReferenceType for the type variable
String name = CharOperation.charToString(aTypeVariableBinding.sourceName());
UnresolvedTypeVariableReferenceType ret = new UnresolvedTypeVariableReferenceType();
typeVariableBindingsInProgress.put(aTypeVariableBinding,ret);
TypeVariable tv = new TypeVariable(name);
ret.setTypeVariable(tv);
// Dont set any bounds here, you'll get in a recursive mess
// TODO -- what about lower bounds??
UnresolvedType superclassType = fromBinding(aTypeVariableBinding.superclass());
UnresolvedType[] superinterfaces = new UnresolvedType[aTypeVariableBinding.superInterfaces.length];
for (int i = 0; i < superinterfaces.length; i++) {
superinterfaces[i] = fromBinding(aTypeVariableBinding.superInterfaces[i]);
}
tv.setUpperBound(superclassType);
tv.setAdditionalInterfaceBounds(superinterfaces);
tv.setRank(aTypeVariableBinding.rank);
if (aTypeVariableBinding.declaringElement instanceof MethodBinding) {
tv.setDeclaringElementKind(TypeVariable.METHOD);
// tv.setDeclaringElement(fromBinding((MethodBinding)aTypeVariableBinding.declaringElement);
} else {
tv.setDeclaringElementKind(TypeVariable.TYPE);
// // tv.setDeclaringElement(fromBinding(aTypeVariableBinding.declaringElement));
}
if (aTypeVariableBinding.declaringElement instanceof MethodBinding)
typeVariablesForThisMember.put(new String(aTypeVariableBinding.sourceName),ret);
typeVariableBindingsInProgress.remove(aTypeVariableBinding);
return ret;
}
public UnresolvedType[] fromBindings(TypeBinding[] bindings) {
if (bindings == null) return UnresolvedType.NONE;
int len = bindings.length;
UnresolvedType[] ret = new UnresolvedType[len];
for (int i=0; i<len; i++) {
ret[i] = fromBinding(bindings[i]);
}
return ret;
}
public static ASTNode astForLocation(IHasPosition location) {
return new EmptyStatement(location.getStart(), location.getEnd());
}
public Collection getDeclareParents() {
return getWorld().getDeclareParents();
}
public Collection getDeclareAnnotationOnTypes() {
return getWorld().getDeclareAnnotationOnTypes();
}
public Collection getDeclareAnnotationOnFields() {
return getWorld().getDeclareAnnotationOnFields();
}
public Collection getDeclareAnnotationOnMethods() {
return getWorld().getDeclareAnnotationOnMethods();
}
public boolean areTypeMungersFinished() {
return finishedTypeMungers != null;
}
public void finishTypeMungers() {
// make sure that type mungers are
Collection ret = new ArrayList();
Collection baseTypeMungers = getWorld().getCrosscuttingMembersSet().getTypeMungers();
// XXX by Andy: why do we mix up the mungers here? it means later we know about two sets
// and the late ones are a subset of the complete set? (see pr114436)
// XXX by Andy removed this line finally, see pr141956
// baseTypeMungers.addAll(getWorld().getCrosscuttingMembersSet().getLateTypeMungers());
debug_mungerCount=baseTypeMungers.size();
for (Iterator i = baseTypeMungers.iterator(); i.hasNext(); ) {
ConcreteTypeMunger munger = (ConcreteTypeMunger) i.next();
EclipseTypeMunger etm = makeEclipseTypeMunger(munger);
if (etm != null) ret.add(etm);
}
finishedTypeMungers = ret;
}
public EclipseTypeMunger makeEclipseTypeMunger(ConcreteTypeMunger concrete) {
//System.err.println("make munger: " + concrete);
//!!! can't do this if we want incremental to work right
//if (concrete instanceof EclipseTypeMunger) return (EclipseTypeMunger)concrete;
//System.err.println(" was not eclipse");
if (concrete.getMunger() != null && EclipseTypeMunger.supportsKind(concrete.getMunger().getKind())) {
AbstractMethodDeclaration method = null;
if (concrete instanceof EclipseTypeMunger) {
method = ((EclipseTypeMunger)concrete).getSourceMethod();
}
EclipseTypeMunger ret =
new EclipseTypeMunger(this, concrete.getMunger(), concrete.getAspectType(), method);
if (ret.getSourceLocation() == null) {
ret.setSourceLocation(concrete.getSourceLocation());
}
return ret;
} else {
return null;
}
}
public Collection getTypeMungers() {
//??? assert finishedTypeMungers != null
return finishedTypeMungers;
}
public ResolvedMember makeResolvedMember(MethodBinding binding) {
return makeResolvedMember(binding, binding.declaringClass);
}
public ResolvedMember makeResolvedMember(MethodBinding binding, Shadow.Kind shadowKind) {
MemberKind memberKind = binding.isConstructor() ? Member.CONSTRUCTOR : Member.METHOD;
if (shadowKind == Shadow.AdviceExecution) memberKind = Member.ADVICE;
return makeResolvedMember(binding,binding.declaringClass,memberKind);
}
/**
* Conversion from a methodbinding (eclipse) to a resolvedmember (aspectj) is now done
* in the scope of some type variables. Before converting the parts of a methodbinding
* (params, return type) we store the type variables in this structure, then should any
* component of the method binding refer to them, we grab them from the map.
*/
private Map typeVariablesForThisMember = new HashMap();
/**
* This is a map from typevariablebindings (eclipsey things) to the names the user
* originally specified in their ITD. For example if the target is 'interface I<N extends Number> {}'
* and the ITD was 'public void I<X>.m(List<X> lxs) {}' then this map would contain a pointer
* from the eclipse type 'N extends Number' to the letter 'X'.
*/
private Map typeVariablesForAliasRecovery;
/**
* Construct a resolvedmember from a methodbinding. The supplied map tells us about any
* typevariablebindings that replaced typevariables whilst the compiler was resolving types -
* this only happens if it is a generic itd that shares type variables with its target type.
*/
public ResolvedMember makeResolvedMemberForITD(MethodBinding binding,TypeBinding declaringType,
Map /*TypeVariableBinding > original alias name*/ recoveryAliases) {
ResolvedMember result = null;
try {
typeVariablesForAliasRecovery = recoveryAliases;
result = makeResolvedMember(binding,declaringType);
} finally {
typeVariablesForAliasRecovery = null;
}
return result;
}
public ResolvedMember makeResolvedMember(MethodBinding binding, TypeBinding declaringType) {
return makeResolvedMember(binding,declaringType,
binding.isConstructor() ? Member.CONSTRUCTOR : Member.METHOD);
}
public ResolvedMember makeResolvedMember(MethodBinding binding, TypeBinding declaringType, MemberKind memberKind) {
//System.err.println("member for: " + binding + ", " + new String(binding.declaringClass.sourceName));
// Convert the type variables and store them
UnresolvedType[] ajTypeRefs = null;
typeVariablesForThisMember.clear();
// This is the set of type variables available whilst building the resolved member...
if (binding.typeVariables!=null) {
ajTypeRefs = new UnresolvedType[binding.typeVariables.length];
for (int i = 0; i < binding.typeVariables.length; i++) {
ajTypeRefs[i] = fromBinding(binding.typeVariables[i]);
typeVariablesForThisMember.put(new String(binding.typeVariables[i].sourceName),/*new Integer(binding.typeVariables[i].rank),*/ajTypeRefs[i]);
}
}
// AMC these next two lines shouldn't be needed once we sort out generic types properly in the world map
ResolvedType realDeclaringType = world.resolve(fromBinding(declaringType));
if (realDeclaringType.isRawType()) realDeclaringType = realDeclaringType.getGenericType();
ResolvedMemberImpl ret = new EclipseResolvedMember(binding,
memberKind,
realDeclaringType,
binding.modifiers,
fromBinding(binding.returnType),
new String(binding.selector),
fromBindings(binding.parameters),
fromBindings(binding.thrownExceptions),this
);
if (binding.isVarargs()) {
ret.setVarargsMethod();
}
if (ajTypeRefs!=null) {
TypeVariable[] tVars = new TypeVariable[ajTypeRefs.length];
for (int i=0;i<ajTypeRefs.length;i++) {
tVars[i]=((TypeVariableReference)ajTypeRefs[i]).getTypeVariable();
}
ret.setTypeVariables(tVars);
}
typeVariablesForThisMember.clear();
ret.resolve(world);
return ret;
}
public ResolvedMember makeResolvedMember(FieldBinding binding) {
return makeResolvedMember(binding, binding.declaringClass);
}
public ResolvedMember makeResolvedMember(FieldBinding binding, TypeBinding receiverType) {
// AMC these next two lines shouldn't be needed once we sort out generic types properly in the world map
ResolvedType realDeclaringType = world.resolve(fromBinding(receiverType));
if (realDeclaringType.isRawType()) realDeclaringType = realDeclaringType.getGenericType();
ResolvedMemberImpl ret = new EclipseResolvedMember(binding,
Member.FIELD,
realDeclaringType,
binding.modifiers,
world.resolve(fromBinding(binding.type)),
new String(binding.name),
UnresolvedType.NONE);
return ret;
}
public TypeBinding makeTypeBinding(UnresolvedType typeX) {
TypeBinding ret = null;
// looking up type variables can get us into trouble
if (!typeX.isTypeVariableReference() && !isParameterizedWithTypeVariables(typeX)) {
if (typeX.isRawType()) {
ret = (TypeBinding)rawTypeXToBinding.get(typeX);
} else {
ret = (TypeBinding)typexToBinding.get(typeX);
}
}
if (ret == null) {
ret = makeTypeBinding1(typeX);
if (!(typeX instanceof BoundedReferenceType) &&
!(typeX instanceof UnresolvedTypeVariableReferenceType)
) {
if (typeX.isRawType()) {
rawTypeXToBinding.put(typeX,ret);
} else {
typexToBinding.put(typeX, ret);
}
}
}
if (ret == null) {
System.out.println("can't find: " + typeX);
}
return ret;
}
// return true if this is type variables are in the type arguments
private boolean isParameterizedWithTypeVariables(UnresolvedType typeX) {
if (!typeX.isParameterizedType()) return false;
UnresolvedType[] typeArguments = typeX.getTypeParameters();
if (typeArguments!=null) {
for (int i = 0; i < typeArguments.length; i++) {
if (typeArguments[i].isTypeVariableReference()) return true;
}
}
return false;
}
// When converting a parameterized type from our world to the eclipse world, these get set so that
// resolution of the type parameters may known in what context it is occurring (pr114744)
private ReferenceBinding baseTypeForParameterizedType;
private int indexOfTypeParameterBeingConverted;
private TypeBinding makeTypeBinding1(UnresolvedType typeX) {
if (typeX.isPrimitiveType()) {
if (typeX == ResolvedType.BOOLEAN) return TypeBinding.BOOLEAN;
if (typeX == ResolvedType.BYTE) return TypeBinding.BYTE;
if (typeX == ResolvedType.CHAR) return TypeBinding.CHAR;
if (typeX == ResolvedType.DOUBLE) return TypeBinding.DOUBLE;
if (typeX == ResolvedType.FLOAT) return TypeBinding.FLOAT;
if (typeX == ResolvedType.INT) return TypeBinding.INT;
if (typeX == ResolvedType.LONG) return TypeBinding.LONG;
if (typeX == ResolvedType.SHORT) return TypeBinding.SHORT;
if (typeX == ResolvedType.VOID) return TypeBinding.VOID;
throw new RuntimeException("weird primitive type " + typeX);
} else if (typeX.isArray()) {
int dim = 0;
while (typeX.isArray()) {
dim++;
typeX = typeX.getComponentType();
}
return lookupEnvironment.createArrayType(makeTypeBinding(typeX), dim);
} else if (typeX.isParameterizedType()) {
// Converting back to a binding from a UnresolvedType
UnresolvedType[] typeParameters = typeX.getTypeParameters();
ReferenceBinding baseTypeBinding = lookupBinding(typeX.getBaseName());
TypeBinding[] argumentBindings = new TypeBinding[typeParameters.length];
baseTypeForParameterizedType = baseTypeBinding;
for (int i = 0; i < argumentBindings.length; i++) {
indexOfTypeParameterBeingConverted = i;
argumentBindings[i] = makeTypeBinding(typeParameters[i]);
}
indexOfTypeParameterBeingConverted = 0;
baseTypeForParameterizedType = null;
ParameterizedTypeBinding ptb =
lookupEnvironment.createParameterizedType(baseTypeBinding,argumentBindings,baseTypeBinding.enclosingType());
return ptb;
} else if (typeX.isTypeVariableReference()) {
// return makeTypeVariableBinding((TypeVariableReference)typeX);
return makeTypeVariableBindingFromAJTypeVariable(((TypeVariableReference)typeX).getTypeVariable());
} else if (typeX.isRawType()) {
ReferenceBinding baseTypeBinding = lookupBinding(typeX.getBaseName());
RawTypeBinding rtb = lookupEnvironment.createRawType(baseTypeBinding,baseTypeBinding.enclosingType());
return rtb;
} else if (typeX.isGenericWildcard()) {
if (typeX instanceof WildcardedUnresolvedType) {
WildcardedUnresolvedType wut = (WildcardedUnresolvedType)typeX;
int boundkind = Wildcard.UNBOUND;
TypeBinding bound = null;
if (wut.isExtends()) {
boundkind = Wildcard.EXTENDS;
bound = makeTypeBinding(wut.getUpperBound());
} else if (wut.isSuper()) {
boundkind = Wildcard.SUPER;
bound = makeTypeBinding(wut.getLowerBound());
}
TypeBinding[] otherBounds = null;
// TODO 2 ought to support extra bounds for WildcardUnresolvedType
// if (wut.getAdditionalBounds()!=null && wut.getAdditionalBounds().length!=0) otherBounds = makeTypeBindings(wut.getAdditionalBounds());
WildcardBinding wb = lookupEnvironment.createWildcard(baseTypeForParameterizedType,indexOfTypeParameterBeingConverted,bound,otherBounds,boundkind);
return wb;
} else if (typeX instanceof BoundedReferenceType) {
// translate from boundedreferencetype to WildcardBinding
BoundedReferenceType brt = (BoundedReferenceType)typeX;
// Work out 'kind' for the WildcardBinding
int boundkind = Wildcard.UNBOUND;
TypeBinding bound = null;
if (brt.isExtends()) {
boundkind = Wildcard.EXTENDS;
bound = makeTypeBinding(brt.getUpperBound());
} else if (brt.isSuper()) {
boundkind = Wildcard.SUPER;
bound = makeTypeBinding(brt.getLowerBound());
}
TypeBinding[] otherBounds = null;
if (brt.getAdditionalBounds()!=null && brt.getAdditionalBounds().length!=0) otherBounds = makeTypeBindings(brt.getAdditionalBounds());
WildcardBinding wb = lookupEnvironment.createWildcard(baseTypeForParameterizedType,indexOfTypeParameterBeingConverted,bound,otherBounds,boundkind);
return wb;
} else {
throw new BCException("This type "+typeX+" (class "+typeX.getClass().getName()+") should not be claiming to be a wildcard!");
}
} else {
return lookupBinding(typeX.getName());
}
}
private ReferenceBinding lookupBinding(String sname) {
char[][] name = CharOperation.splitOn('.', sname.toCharArray());
ReferenceBinding rb = lookupEnvironment.getType(name);
return rb;
}
public TypeBinding[] makeTypeBindings(UnresolvedType[] types) {
int len = types.length;
TypeBinding[] ret = new TypeBinding[len];
for (int i = 0; i < len; i++) {
ret[i] = makeTypeBinding(types[i]);
}
return ret;
}
// just like the code above except it returns an array of ReferenceBindings
private ReferenceBinding[] makeReferenceBindings(UnresolvedType[] types) {
int len = types.length;
ReferenceBinding[] ret = new ReferenceBinding[len];
for (int i = 0; i < len; i++) {
ret[i] = (ReferenceBinding)makeTypeBinding(types[i]);
}
return ret;
}
// field related
public FieldBinding makeFieldBinding(NewFieldTypeMunger nftm) {
return internalMakeFieldBinding(nftm.getSignature(),nftm.getTypeVariableAliases());
}
/**
* Convert a resolvedmember into an eclipse field binding
*/
public FieldBinding makeFieldBinding(ResolvedMember member,List aliases) {
return internalMakeFieldBinding(member,aliases);
}
/**
* Convert a resolvedmember into an eclipse field binding
*/
public FieldBinding makeFieldBinding(ResolvedMember member) {
return internalMakeFieldBinding(member,null);
}
// OPTIMIZE tidy this up, must be able to optimize for the synthetic case, if we passed in the binding for the declaring type, that would make things easier
/**
* Build a new Eclipse SyntheticFieldBinding for an AspectJ ResolvedMember.
*/
public SyntheticFieldBinding createSyntheticFieldBinding(SourceTypeBinding owningType,ResolvedMember member) {
SyntheticFieldBinding sfb = new SyntheticFieldBinding(member.getName().toCharArray(),
makeTypeBinding(member.getReturnType()),
member.getModifiers() | Flags.AccSynthetic,
owningType,
Constant.NotAConstant,
-1); // index filled in later
owningType.addSyntheticField(sfb);
return sfb;
}
/**
* Take a normal AJ member and convert it into an eclipse fieldBinding.
* Taking into account any aliases that it may include due to being
* a generic itd. Any aliases are put into the typeVariableToBinding
* map so that they will be substituted as appropriate in the returned
* fieldbinding.
*/
public FieldBinding internalMakeFieldBinding(ResolvedMember member,List aliases) {
typeVariableToTypeBinding.clear();
TypeVariableBinding[] tvbs = null;
ReferenceBinding declaringType = (ReferenceBinding)makeTypeBinding(member.getDeclaringType());
// If there are aliases, place them in the map
if (aliases!=null && aliases.size()>0) {
int i =0;
for (Iterator iter = aliases.iterator(); iter.hasNext();) {
String element = (String) iter.next();
typeVariableToTypeBinding.put(element,declaringType.typeVariables()[i++]);
}
}
currentType = declaringType;
FieldBinding fb = null;
if (member.getName().startsWith(NameMangler.PREFIX)) {
fb = new SyntheticFieldBinding(member.getName().toCharArray(),
makeTypeBinding(member.getReturnType()),
member.getModifiers() | Flags.AccSynthetic,
currentType,
Constant.NotAConstant,-1); // index filled in later
} else {
fb = new FieldBinding(member.getName().toCharArray(),
makeTypeBinding(member.getReturnType()),
member.getModifiers(),
currentType,
Constant.NotAConstant);
}
typeVariableToTypeBinding.clear();
currentType = null;
if (member.getName().startsWith(NameMangler.PREFIX)) {
fb.modifiers |= Flags.AccSynthetic;
}
return fb;
}
private ReferenceBinding currentType = null;
// method binding related
public MethodBinding makeMethodBinding(NewMethodTypeMunger nmtm) {
return internalMakeMethodBinding(nmtm.getSignature(),nmtm.getTypeVariableAliases());
}
/**
* Convert a resolvedmember into an eclipse method binding.
*/
public MethodBinding makeMethodBinding(ResolvedMember member,List aliases) {
return internalMakeMethodBinding(member,aliases);
}
/**
* Creates a method binding for a resolvedmember taking into account type variable aliases -
* this variant can take an aliasTargetType and should be used when the alias target type
* cannot be retrieved from the resolvedmember.
*/
public MethodBinding makeMethodBinding(ResolvedMember member,List aliases,UnresolvedType aliasTargetType) {
return internalMakeMethodBinding(member,aliases,aliasTargetType);
}
/**
* Convert a resolvedmember into an eclipse method binding.
*/
public MethodBinding makeMethodBinding(ResolvedMember member) {
return internalMakeMethodBinding(member,null); // there are no aliases
}
public MethodBinding internalMakeMethodBinding(ResolvedMember member,List aliases) {
return internalMakeMethodBinding(member,aliases,member.getDeclaringType());
}
/**
* Take a normal AJ member and convert it into an eclipse methodBinding.
* Taking into account any aliases that it may include due to being a
* generic ITD. Any aliases are put into the typeVariableToBinding
* map so that they will be substituted as appropriate in the returned
* methodbinding
*/
public MethodBinding internalMakeMethodBinding(ResolvedMember member,List aliases,UnresolvedType aliasTargetType) {
typeVariableToTypeBinding.clear();
TypeVariableBinding[] tvbs = null;
if (member.getTypeVariables()!=null) {
if (member.getTypeVariables().length==0) {
tvbs = Binding.NO_TYPE_VARIABLES;
} else {
tvbs = makeTypeVariableBindingsFromAJTypeVariables(member.getTypeVariables());
// QQQ do we need to bother fixing up the declaring element here?
}
}
ReferenceBinding declaringType = (ReferenceBinding)makeTypeBinding(member.getDeclaringType());
// If there are aliases, place them in the map
if (aliases!=null && aliases.size()!=0) {
int i=0;
ReferenceBinding aliasTarget = (ReferenceBinding)makeTypeBinding(aliasTargetType);
if (aliasTarget.isRawType()) {
aliasTarget = ((RawTypeBinding) aliasTarget).genericType();
}
for (Iterator iter = aliases.iterator(); iter.hasNext();) {
String element = (String) iter.next();
typeVariableToTypeBinding.put(element,aliasTarget.typeVariables()[i++]);
}
}
currentType = declaringType;
MethodBinding mb = new MethodBinding(member.getModifiers(),
member.getName().toCharArray(),
makeTypeBinding(member.getReturnType()),
makeTypeBindings(member.getParameterTypes()),
makeReferenceBindings(member.getExceptions()),
declaringType);
if (tvbs!=null) mb.typeVariables = tvbs;
typeVariableToTypeBinding.clear();
currentType = null;
if (NameMangler.isSyntheticMethod(member.getName(), true)) {
mb.modifiers |= Flags.AccSynthetic;
}
return mb;
}
/**
* Convert a bunch of type variables in one go, from AspectJ form to Eclipse form.
*/
// private TypeVariableBinding[] makeTypeVariableBindings(UnresolvedType[] typeVariables) {
// int len = typeVariables.length;
// TypeVariableBinding[] ret = new TypeVariableBinding[len];
// for (int i = 0; i < len; i++) {
// ret[i] = makeTypeVariableBinding((TypeVariableReference)typeVariables[i]);
// }
// return ret;
// }
private TypeVariableBinding[] makeTypeVariableBindingsFromAJTypeVariables(TypeVariable[] typeVariables) {
int len = typeVariables.length;
TypeVariableBinding[] ret = new TypeVariableBinding[len];
for (int i = 0; i < len; i++) {
ret[i] = makeTypeVariableBindingFromAJTypeVariable(typeVariables[i]);
}
return ret;
}
// only accessed through private methods in this class. Ensures all type variables we encounter
// map back to the same type binding - this is important later when Eclipse code is processing
// a methodbinding trying to come up with possible bindings for the type variables.
// key is currently the name of the type variable...is that ok?
private Map typeVariableToTypeBinding = new HashMap();
/**
* Converts from an TypeVariableReference to a TypeVariableBinding. A TypeVariableReference
* in AspectJ world holds a TypeVariable and it is this type variable that is converted
* to the TypeVariableBinding.
*/
private TypeVariableBinding makeTypeVariableBinding(TypeVariableReference tvReference) {
TypeVariable tv = tvReference.getTypeVariable();
TypeVariableBinding tvBinding = (TypeVariableBinding)typeVariableToTypeBinding.get(tv.getName());
if (currentType!=null) {
TypeVariableBinding tvb = currentType.getTypeVariable(tv.getName().toCharArray());
if (tvb!=null) return tvb;
}
if (tvBinding==null) {
Binding declaringElement = null;
// this will cause an infinite loop or NPE... not required yet luckily.
// if (tVar.getDeclaringElement() instanceof Member) {
// declaringElement = makeMethodBinding((ResolvedMember)tVar.getDeclaringElement());
// } else {
// declaringElement = makeTypeBinding((UnresolvedType)tVar.getDeclaringElement());
// }
tvBinding = new TypeVariableBinding(tv.getName().toCharArray(),null,tv.getRank());
typeVariableToTypeBinding.put(tv.getName(),tvBinding);
tvBinding.superclass=(ReferenceBinding)makeTypeBinding(tv.getUpperBound());
tvBinding.firstBound=(ReferenceBinding)makeTypeBinding(tv.getFirstBound());
if (tv.getAdditionalInterfaceBounds()==null) {
tvBinding.superInterfaces=TypeVariableBinding.NO_SUPERINTERFACES;
} else {
TypeBinding tbs[] = makeTypeBindings(tv.getAdditionalInterfaceBounds());
ReferenceBinding[] rbs= new ReferenceBinding[tbs.length];
for (int i = 0; i < tbs.length; i++) {
rbs[i] = (ReferenceBinding)tbs[i];
}
tvBinding.superInterfaces=rbs;
}
}
return tvBinding;
}
private TypeVariableBinding makeTypeVariableBindingFromAJTypeVariable(TypeVariable tv) {
TypeVariableBinding tvBinding = (TypeVariableBinding)typeVariableToTypeBinding.get(tv.getName());
if (currentType!=null) {
TypeVariableBinding tvb = currentType.getTypeVariable(tv.getName().toCharArray());
if (tvb!=null) return tvb;
}
if (tvBinding==null) {
Binding declaringElement = null;
// this will cause an infinite loop or NPE... not required yet luckily.
// if (tVar.getDeclaringElement() instanceof Member) {
// declaringElement = makeMethodBinding((ResolvedMember)tVar.getDeclaringElement());
// } else {
// declaringElement = makeTypeBinding((UnresolvedType)tVar.getDeclaringElement());
// }
tvBinding = new TypeVariableBinding(tv.getName().toCharArray(),declaringElement,tv.getRank());
typeVariableToTypeBinding.put(tv.getName(),tvBinding);
tvBinding.superclass=(ReferenceBinding)makeTypeBinding(tv.getUpperBound());
tvBinding.firstBound=(ReferenceBinding)makeTypeBinding(tv.getFirstBound());
if (tv.getAdditionalInterfaceBounds()==null) {
tvBinding.superInterfaces=TypeVariableBinding.NO_SUPERINTERFACES;
} else {
TypeBinding tbs[] = makeTypeBindings(tv.getAdditionalInterfaceBounds());
ReferenceBinding[] rbs= new ReferenceBinding[tbs.length];
for (int i = 0; i < tbs.length; i++) {
rbs[i] = (ReferenceBinding)tbs[i];
}
tvBinding.superInterfaces=rbs;
}
}
return tvBinding;
}
public MethodBinding makeMethodBindingForCall(Member member) {
return new MethodBinding(member.getModifiers() & ~ Modifier.INTERFACE,
member.getName().toCharArray(),
makeTypeBinding(member.getReturnType()),
makeTypeBindings(member.getParameterTypes()),
new ReferenceBinding[0],
(ReferenceBinding)makeTypeBinding(member.getDeclaringType()));
}
public void finishedCompilationUnit(CompilationUnitDeclaration unit) {
if ((buildManager != null) && buildManager.doGenerateModel()) {
AjBuildManager.getAsmHierarchyBuilder().buildStructureForCompilationUnit(unit, buildManager.getStructureModel(), buildManager.buildConfig);
}
}
public void addTypeBinding(TypeBinding binding) {
typexToBinding.put(fromBinding(binding), binding);
}
public void addTypeBindingAndStoreInWorld(TypeBinding binding) {
UnresolvedType ut = fromBinding(binding);
typexToBinding.put(ut, binding);
world.lookupOrCreateName(ut);
}
public Shadow makeShadow(ASTNode location, ReferenceContext context) {
return EclipseShadow.makeShadow(this, location, context);
}
public Shadow makeShadow(ReferenceContext context) {
return EclipseShadow.makeShadow(this, (ASTNode) context, context);
}
public void addSourceTypeBinding(SourceTypeBinding binding, CompilationUnitDeclaration unit) {
TypeDeclaration decl = binding.scope.referenceContext;
// Deal with the raw/basic type to give us an entry in the world type map
UnresolvedType simpleTx = null;
if (binding.isGenericType()) {
simpleTx = UnresolvedType.forRawTypeName(getName(binding));
} else if (binding.isLocalType()) {
LocalTypeBinding ltb = (LocalTypeBinding) binding;
if (ltb.constantPoolName() != null && ltb.constantPoolName().length > 0) {
simpleTx = UnresolvedType.forSignature(new String(binding.signature()));
} else {
simpleTx = UnresolvedType.forName(getName(binding));
}
}else {
simpleTx = UnresolvedType.forName(getName(binding));
}
ReferenceType name = getWorld().lookupOrCreateName(simpleTx);
// A type can change from simple > generic > simple across a set of compiles. We need
// to ensure the entry in the typemap is promoted and demoted correctly. The call
// to setGenericType() below promotes a simple to a raw. This call demotes it back
// to simple
// pr125405
if (!binding.isRawType() && !binding.isGenericType() && name.getTypekind()==TypeKind.RAW) {
name.demoteToSimpleType();
}
EclipseSourceType t = new EclipseSourceType(name, this, binding, decl, unit);
// For generics, go a bit further - build a typex for the generic type
// give it the same delegate and link it to the raw type
if (binding.isGenericType()) {
UnresolvedType complexTx = fromBinding(binding); // fully aware of any generics info
ResolvedType cName = world.resolve(complexTx,true);
ReferenceType complexName = null;
if (!cName.isMissing()) {
complexName = (ReferenceType) cName;
complexName = (ReferenceType) complexName.getGenericType();
if (complexName == null) complexName = new ReferenceType(complexTx,world);
} else {
complexName = new ReferenceType(complexTx,world);
}
name.setGenericType(complexName);
complexName.setDelegate(t);
}
name.setDelegate(t);
if (decl instanceof AspectDeclaration) {
((AspectDeclaration)decl).typeX = name;
((AspectDeclaration)decl).concreteName = t;
}
ReferenceBinding[] memberTypes = binding.memberTypes;
for (int i = 0, length = memberTypes.length; i < length; i++) {
addSourceTypeBinding((SourceTypeBinding) memberTypes[i], unit);
}
}
// XXX this doesn't feel like it belongs here, but it breaks a hard dependency on
// exposing AjBuildManager (needed by AspectDeclaration).
public boolean isXSerializableAspects() {
return xSerializableAspects;
}
public ResolvedMember fromBinding(MethodBinding binding) {
return new ResolvedMemberImpl(Member.METHOD,fromBinding(binding.declaringClass),binding.modifiers,
fromBinding(binding.returnType),CharOperation.charToString(binding.selector),fromBindings(binding.parameters));
}
public TypeVariableDeclaringElement fromBinding(Binding declaringElement) {
if (declaringElement instanceof TypeBinding) {
return fromBinding(((TypeBinding)declaringElement));
} else {
return fromBinding((MethodBinding)declaringElement);
}
}
public void cleanup() {
this.typexToBinding.clear();
this.rawTypeXToBinding.clear();
this.finishedTypeMungers = null;
}
public void minicleanup() {
this.typexToBinding.clear();
this.rawTypeXToBinding.clear();
}
}
| true | true | public UnresolvedType fromBinding(TypeBinding binding) {
if (binding instanceof HelperInterfaceBinding) {
return ((HelperInterfaceBinding) binding).getTypeX();
}
if (binding == null || binding.qualifiedSourceName() == null) {
return ResolvedType.MISSING;
}
// first piece of generics support!
if (binding instanceof TypeVariableBinding) {
TypeVariableBinding tb = (TypeVariableBinding) binding;
UnresolvedTypeVariableReferenceType utvrt = (UnresolvedTypeVariableReferenceType) fromTypeVariableBinding(tb);
return utvrt;
}
// handle arrays since the component type may need special treatment too...
if (binding instanceof ArrayBinding) {
ArrayBinding aBinding = (ArrayBinding) binding;
UnresolvedType componentType = fromBinding(aBinding.leafComponentType);
return UnresolvedType.makeArray(componentType, aBinding.dimensions);
}
if (binding instanceof WildcardBinding) {
WildcardBinding eWB = (WildcardBinding) binding;
// Repair the bound
// e.g. If the bound for the wildcard is a typevariable, e.g. '? extends E' then
// the type variable in the unresolvedtype will be correct only in name. In that
// case let's set it correctly based on the one in the eclipse WildcardBinding
UnresolvedType theBound = null;
if (eWB.bound instanceof TypeVariableBinding) {
theBound = fromTypeVariableBinding((TypeVariableBinding)eWB.bound);
} else {
theBound = fromBinding(eWB.bound);
}
// if (eWB.boundKind == WildCard.SUPER) {
//
// }
WildcardedUnresolvedType theType = (WildcardedUnresolvedType) TypeFactory.createTypeFromSignature(CharOperation.charToString(eWB.genericTypeSignature()));
// if (theType.isGenericWildcard() && theType.isSuper()) theType.setLowerBound(theBound);
// if (theType.isGenericWildcard() && theType.isExtends()) theType.setUpperBound(theBound);
return theType;
}
if (binding instanceof ParameterizedTypeBinding) {
if (binding instanceof RawTypeBinding) {
// special case where no parameters are specified!
return UnresolvedType.forRawTypeName(getName(binding));
}
ParameterizedTypeBinding ptb = (ParameterizedTypeBinding) binding;
UnresolvedType[] arguments = null;
if (ptb.arguments!=null) { // null can mean this is an inner type of a Parameterized Type with no bounds of its own (pr100227)
arguments = new UnresolvedType[ptb.arguments.length];
for (int i = 0; i < arguments.length; i++) {
arguments[i] = fromBinding(ptb.arguments[i]);
}
}
String baseTypeSignature = null;
ResolvedType baseType = getWorld().resolve(UnresolvedType.forName(getName(binding)),true);
if (!baseType.isMissing()) {
// can legitimately be missing if a bound refers to a type we haven't added to the world yet...
// pr168044 - sometimes (whilst resolving types) we are working with 'half finished' types and so (for example) the underlying generic type for a raw type hasnt been set yet
//if (!baseType.isGenericType() && arguments!=null) baseType = baseType.getGenericType();
baseTypeSignature = baseType.getErasureSignature();
} else {
baseTypeSignature = UnresolvedType.forName(getName(binding)).getSignature();
}
// Create an unresolved parameterized type. We can't create a resolved one as the
// act of resolution here may cause recursion problems since the parameters may
// be type variables that we haven't fixed up yet.
if (arguments==null) arguments=new UnresolvedType[0];
String parameterizedSig = ResolvedType.PARAMETERIZED_TYPE_IDENTIFIER+CharOperation.charToString(binding.genericTypeSignature()).substring(1);
return TypeFactory.createUnresolvedParameterizedType(parameterizedSig,baseTypeSignature,arguments);
}
// Convert the source type binding for a generic type into a generic UnresolvedType
// notice we can easily determine the type variables from the eclipse object
// and we can recover the generic signature from it too - so we pass those
// to the forGenericType() method.
if (binding.isGenericType() &&
!binding.isParameterizedType() &&
!binding.isRawType()) {
TypeVariableBinding[] tvbs = binding.typeVariables();
TypeVariable[] tVars = new TypeVariable[tvbs.length];
for (int i = 0; i < tvbs.length; i++) {
TypeVariableBinding eclipseV = tvbs[i];
tVars[i] = ((TypeVariableReference)fromTypeVariableBinding(eclipseV)).getTypeVariable();
}
//TODO asc generics - temporary guard....
if (!(binding instanceof SourceTypeBinding))
throw new RuntimeException("Cant get the generic sig for "+binding.debugName());
return UnresolvedType.forGenericType(getName(binding),tVars,
CharOperation.charToString(((SourceTypeBinding)binding).genericSignature()));
}
// LocalTypeBinding have a name $Local$, we can get the real name by using the signature....
if (binding instanceof LocalTypeBinding) {
LocalTypeBinding ltb = (LocalTypeBinding) binding;
if (ltb.constantPoolName() != null && ltb.constantPoolName().length > 0) {
return UnresolvedType.forSignature(new String(binding.signature()));
} else {
// we're reporting a problem and don't have a resolved name for an
// anonymous local type yet, report the issue on the enclosing type
return UnresolvedType.forSignature(new String(ltb.enclosingType.signature()));
}
}
return UnresolvedType.forName(getName(binding));
}
| public UnresolvedType fromBinding(TypeBinding binding) {
if (binding instanceof HelperInterfaceBinding) {
return ((HelperInterfaceBinding) binding).getTypeX();
}
if (binding == null || binding.qualifiedSourceName() == null) {
return ResolvedType.MISSING;
}
// first piece of generics support!
if (binding instanceof TypeVariableBinding) {
TypeVariableBinding tb = (TypeVariableBinding) binding;
UnresolvedTypeVariableReferenceType utvrt = (UnresolvedTypeVariableReferenceType) fromTypeVariableBinding(tb);
return utvrt;
}
// handle arrays since the component type may need special treatment too...
if (binding instanceof ArrayBinding) {
ArrayBinding aBinding = (ArrayBinding) binding;
UnresolvedType componentType = fromBinding(aBinding.leafComponentType);
return UnresolvedType.makeArray(componentType, aBinding.dimensions);
}
if (binding instanceof WildcardBinding) {
WildcardBinding eWB = (WildcardBinding) binding;
// Repair the bound
// e.g. If the bound for the wildcard is a typevariable, e.g. '? extends E' then
// the type variable in the unresolvedtype will be correct only in name. In that
// case let's set it correctly based on the one in the eclipse WildcardBinding
UnresolvedType theBound = null;
if (eWB.bound instanceof TypeVariableBinding) {
theBound = fromTypeVariableBinding((TypeVariableBinding)eWB.bound);
} else {
theBound = fromBinding(eWB.bound);
}
// if (eWB.boundKind == WildCard.SUPER) {
//
// }
WildcardedUnresolvedType theType = (WildcardedUnresolvedType) TypeFactory.createTypeFromSignature(CharOperation.charToString(eWB.genericTypeSignature()));
// if (theType.isGenericWildcard() && theType.isSuper()) theType.setLowerBound(theBound);
// if (theType.isGenericWildcard() && theType.isExtends()) theType.setUpperBound(theBound);
return theType;
}
if (binding instanceof ParameterizedTypeBinding) {
if (binding instanceof RawTypeBinding) {
// special case where no parameters are specified!
return UnresolvedType.forRawTypeName(getName(binding));
}
ParameterizedTypeBinding ptb = (ParameterizedTypeBinding) binding;
UnresolvedType[] arguments = null;
if (ptb.arguments!=null) { // null can mean this is an inner type of a Parameterized Type with no bounds of its own (pr100227)
arguments = new UnresolvedType[ptb.arguments.length];
for (int i = 0; i < arguments.length; i++) {
arguments[i] = fromBinding(ptb.arguments[i]);
}
}
String baseTypeSignature = null;
ResolvedType baseType = getWorld().resolve(UnresolvedType.forName(getName(binding)),true);
if (!baseType.isMissing()) {
// can legitimately be missing if a bound refers to a type we haven't added to the world yet...
// pr168044 - sometimes (whilst resolving types) we are working with 'half finished' types and so (for example) the underlying generic type for a raw type hasnt been set yet
//if (!baseType.isGenericType() && arguments!=null) baseType = baseType.getGenericType();
baseTypeSignature = baseType.getErasureSignature();
} else {
baseTypeSignature = UnresolvedType.forName(getName(binding)).getSignature();
}
// Create an unresolved parameterized type. We can't create a resolved one as the
// act of resolution here may cause recursion problems since the parameters may
// be type variables that we haven't fixed up yet.
if (arguments==null) arguments=new UnresolvedType[0];
// StringBuffer parameterizedSig = new StringBuffer();
// parameterizedSig.append(ResolvedType.PARAMETERIZED_TYPE_IDENTIFIER);
//
//// String parameterizedSig = new StringBuffer().append(ResolvedType.PARAMETERIZED_TYPE_IDENTIFIER).append(CharOperation.charToString(binding.genericTypeSignature()).substring(1)).toString();
// return TypeFactory.createUnresolvedParameterizedType(parameterizedSig,baseTypeSignature,arguments);
return TypeFactory.createUnresolvedParameterizedType(baseTypeSignature,arguments);
}
// Convert the source type binding for a generic type into a generic UnresolvedType
// notice we can easily determine the type variables from the eclipse object
// and we can recover the generic signature from it too - so we pass those
// to the forGenericType() method.
if (binding.isGenericType() &&
!binding.isParameterizedType() &&
!binding.isRawType()) {
TypeVariableBinding[] tvbs = binding.typeVariables();
TypeVariable[] tVars = new TypeVariable[tvbs.length];
for (int i = 0; i < tvbs.length; i++) {
TypeVariableBinding eclipseV = tvbs[i];
tVars[i] = ((TypeVariableReference)fromTypeVariableBinding(eclipseV)).getTypeVariable();
}
//TODO asc generics - temporary guard....
if (!(binding instanceof SourceTypeBinding))
throw new RuntimeException("Cant get the generic sig for "+binding.debugName());
return UnresolvedType.forGenericType(getName(binding),tVars,
CharOperation.charToString(((SourceTypeBinding)binding).genericSignature()));
}
// LocalTypeBinding have a name $Local$, we can get the real name by using the signature....
if (binding instanceof LocalTypeBinding) {
LocalTypeBinding ltb = (LocalTypeBinding) binding;
if (ltb.constantPoolName() != null && ltb.constantPoolName().length > 0) {
return UnresolvedType.forSignature(new String(binding.signature()));
} else {
// we're reporting a problem and don't have a resolved name for an
// anonymous local type yet, report the issue on the enclosing type
return UnresolvedType.forSignature(new String(ltb.enclosingType.signature()));
}
}
return UnresolvedType.forName(getName(binding));
}
|
diff --git a/src/org/red5/server/api/service/ServiceUtils.java b/src/org/red5/server/api/service/ServiceUtils.java
index cbce99d6..9428edbf 100644
--- a/src/org/red5/server/api/service/ServiceUtils.java
+++ b/src/org/red5/server/api/service/ServiceUtils.java
@@ -1,331 +1,334 @@
package org.red5.server.api.service;
/*
* RED5 Open Source Flash Server - http://www.osflash.org/red5
*
* Copyright (c) 2006-2007 by respective authors (see below). All rights reserved.
*
* This library 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 library 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 library; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.red5.server.api.IClient;
import org.red5.server.api.IConnection;
import org.red5.server.api.IScope;
import org.red5.server.api.Red5;
/**
* Utility functions to invoke methods on connections.
*
* @author The Red5 Project ([email protected])
* @author Joachim Bauch ([email protected])
*
*/
public class ServiceUtils {
/**
* Invoke a method on the current connection.
*
* @param method
* name of the method to invoke
* @param params
* parameters to pass to the method
* @return <code>true</code> if the connection supports method calls,
* otherwise <code>false</code>
*/
public static boolean invokeOnConnection(String method, Object[] params) {
return invokeOnConnection(method, params, null);
}
/**
* Invoke a method on the current connection and handle result.
*
* @param method
* name of the method to invoke
* @param params
* parameters to pass to the method
* @param callback
* object to notify when result is received
* @return <code>true</code> if the connection supports method calls,
* otherwise <code>false</code>
*/
public static boolean invokeOnConnection(String method, Object[] params,
IPendingServiceCallback callback) {
IConnection conn = Red5.getConnectionLocal();
return invokeOnConnection(conn, method, params, callback);
}
/**
* Invoke a method on a given connection.
*
* @param conn
* connection to invoke method on
* @param method
* name of the method to invoke
* @param params
* parameters to pass to the method
* @return <code>true</code> if the connection supports method calls,
* otherwise <code>false</code>
*/
public static boolean invokeOnConnection(IConnection conn, String method,
Object[] params) {
return invokeOnConnection(conn, method, params, null);
}
/**
* Invoke a method on a given connection and handle result.
*
* @param conn
* connection to invoke method on
* @param method
* name of the method to invoke
* @param params
* parameters to pass to the method
* @param callback
* object to notify when result is received
* @return <code>true</code> if the connection supports method calls,
* otherwise <code>false</code>
*/
public static boolean invokeOnConnection(IConnection conn, String method,
Object[] params, IPendingServiceCallback callback) {
if (conn instanceof IServiceCapableConnection) {
if (callback == null) {
((IServiceCapableConnection) conn).invoke(method, params);
} else {
((IServiceCapableConnection) conn).invoke(method, params,
callback);
}
return true;
} else {
return false;
}
}
/**
* Invoke a method on all connections to the current scope.
*
* @param method
* name of the method to invoke
* @param params
* parameters to pass to the method
*/
public static void invokeOnAllConnections(String method, Object[] params) {
invokeOnAllConnections(method, params, null);
}
/**
* Invoke a method on all connections to the current scope and handle
* result.
*
* @param method
* name of the method to invoke
* @param params
* parameters to pass to the method
* @param callback
* object to notify when result is received
*/
public static void invokeOnAllConnections(String method, Object[] params,
IPendingServiceCallback callback) {
IScope scope = Red5.getConnectionLocal().getScope();
invokeOnAllConnections(scope, method, params, callback);
}
/**
* Invoke a method on all connections to a given scope.
*
* @param scope
* scope to get connections for
* @param method
* name of the method to invoke
* @param params
* parameters to pass to the method
*/
public static void invokeOnAllConnections(IScope scope, String method,
Object[] params) {
invokeOnAllConnections(scope, method, params, null);
}
/**
* Invoke a method on all connections to a given scope and handle result.
*
* @param scope
* scope to get connections for
* @param method
* name of the method to invoke
* @param params
* parameters to pass to the method
* @param callback
* object to notify when result is received
*/
public static void invokeOnAllConnections(IScope scope, String method,
Object[] params, IPendingServiceCallback callback) {
invokeOnClient(null, scope, method, params, callback);
}
/**
* Invoke a method on all connections of a client to a given scope.
*
* @param client
* client to get connections for
* @param scope
* scope to get connections of the client from
* @param method
* name of the method to invoke
* @param params
* parameters to pass to the method
*/
public static void invokeOnClient(IClient client, IScope scope,
String method, Object[] params) {
invokeOnClient(client, scope, method, params, null);
}
/**
* Invoke a method on all connections of a client to a given scope and
* handle result.
*
* @param client
* client to get connections for
* @param scope
* scope to get connections of the client from
* @param method
* name of the method to invoke
* @param params
* parameters to pass to the method
* @param callback
* object to notify when result is received
*/
public static void invokeOnClient(IClient client, IScope scope,
String method, Object[] params, IPendingServiceCallback callback) {
Set<IConnection> connections;
if (client == null) {
connections = new HashSet<IConnection>();
Iterator<IConnection> iter = scope.getConnections();
while (iter.hasNext()) {
connections.add(iter.next());
}
} else {
connections = scope.lookupConnections(client);
+ if (connections == null)
+ // Client is not connected to the scope
+ return;
}
if (callback == null) {
for (IConnection conn : connections) {
invokeOnConnection(conn, method, params);
}
} else {
for (IConnection conn : connections) {
invokeOnConnection(conn, method, params, callback);
}
}
}
/**
* Notify a method on the current connection.
*
* @param method
* name of the method to notify
* @param params
* parameters to pass to the method
* @return <code>true</code> if the connection supports method calls,
* otherwise <code>false</code>
*/
public static boolean notifyOnConnection(String method, Object[] params) {
IConnection conn = Red5.getConnectionLocal();
return notifyOnConnection(conn, method, params);
}
/**
* Notify a method on a given connection.
*
* @param conn
* connection to notify method on
* @param method
* name of the method to notify
* @param params
* parameters to pass to the method
* @return <code>true</code> if the connection supports method calls,
* otherwise <code>false</code>
*/
public static boolean notifyOnConnection(IConnection conn, String method,
Object[] params) {
if (conn instanceof IServiceCapableConnection) {
((IServiceCapableConnection) conn).notify(method, params);
return true;
} else {
return false;
}
}
/**
* Notify a method on all connections to the current scope.
*
* @param method
* name of the method to notifynotify
* @param params
* parameters to pass to the method
*/
public static void notifyOnAllConnections(String method, Object[] params) {
IScope scope = Red5.getConnectionLocal().getScope();
notifyOnAllConnections(scope, method, params);
}
/**
* Notfy a method on all connections to a given scope.
*
* @param scope
* scope to get connections for
* @param method
* name of the method to notify
* @param params
* parameters to pass to the method
*/
public static void notifyOnAllConnections(IScope scope, String method,
Object[] params) {
notifyOnClient(null, scope, method, params);
}
/**
* Notify a method on all connections of a client to a given scope.
*
* @param client
* client to get connections for
* @param scope
* scope to get connections of the client from
* @param method
* name of the method to notify
* @param params
* parameters to pass to the method
*/
public static void notifyOnClient(IClient client, IScope scope,
String method, Object[] params) {
Set<IConnection> connections;
if (client == null) {
connections = new HashSet<IConnection>();
Iterator<IConnection> iter = scope.getConnections();
while (iter.hasNext()) {
connections.add(iter.next());
}
} else {
connections = scope.lookupConnections(client);
}
for (IConnection conn : connections) {
notifyOnConnection(conn, method, params);
}
}
}
| true | true | public static void invokeOnClient(IClient client, IScope scope,
String method, Object[] params, IPendingServiceCallback callback) {
Set<IConnection> connections;
if (client == null) {
connections = new HashSet<IConnection>();
Iterator<IConnection> iter = scope.getConnections();
while (iter.hasNext()) {
connections.add(iter.next());
}
} else {
connections = scope.lookupConnections(client);
}
if (callback == null) {
for (IConnection conn : connections) {
invokeOnConnection(conn, method, params);
}
} else {
for (IConnection conn : connections) {
invokeOnConnection(conn, method, params, callback);
}
}
}
| public static void invokeOnClient(IClient client, IScope scope,
String method, Object[] params, IPendingServiceCallback callback) {
Set<IConnection> connections;
if (client == null) {
connections = new HashSet<IConnection>();
Iterator<IConnection> iter = scope.getConnections();
while (iter.hasNext()) {
connections.add(iter.next());
}
} else {
connections = scope.lookupConnections(client);
if (connections == null)
// Client is not connected to the scope
return;
}
if (callback == null) {
for (IConnection conn : connections) {
invokeOnConnection(conn, method, params);
}
} else {
for (IConnection conn : connections) {
invokeOnConnection(conn, method, params, callback);
}
}
}
|
diff --git a/test/org/apache/pig/test/TestGrunt.java b/test/org/apache/pig/test/TestGrunt.java
index 263e82ba..9ac7b9f6 100644
--- a/test/org/apache/pig/test/TestGrunt.java
+++ b/test/org/apache/pig/test/TestGrunt.java
@@ -1,1424 +1,1424 @@
/*
* 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.pig.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import junit.framework.Assert;
import org.apache.log4j.Appender;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Level;
import org.apache.log4j.PatternLayout;
import org.apache.pig.ExecType;
import org.apache.pig.PigException;
import org.apache.pig.PigServer;
import org.apache.pig.backend.executionengine.ExecException;
import org.apache.pig.backend.executionengine.ExecJob;
import org.apache.pig.backend.executionengine.ExecJob.JOB_STATUS;
import org.apache.pig.impl.PigContext;
import org.apache.pig.impl.io.FileLocalizer;
import org.apache.pig.impl.logicalLayer.FrontendException;
import org.apache.pig.test.Util.ProcessReturnInfo;
import org.apache.pig.tools.grunt.Grunt;
import org.apache.pig.tools.parameters.ParameterSubstitutionPreprocessor;
import org.apache.pig.tools.pigscript.parser.ParseException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class TestGrunt {
static MiniCluster cluster = MiniCluster.buildCluster();
private String basedir = "test/org/apache/pig/test/data";
@BeforeClass
public static void oneTimeSetup() throws Exception {
cluster.setProperty("opt.multiquery","true");
}
@AfterClass
public static void oneTimeTearDown() throws Exception {
cluster.shutDown();
}
@Test
public void testCopyFromLocal() throws Throwable {
PigServer server = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
PigContext context = server.getPigContext();
String strCmd = "copyFromLocal /bin/sh sh_copy ;";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
}
@Test
public void testDefine() throws Throwable {
PigServer server = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
PigContext context = server.getPigContext();
String strCmd = "define myudf org.apache.pig.builtin.AVG();\n";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
try {
grunt.exec();
} catch (Exception e) {
assertTrue(e.getMessage().contains("Encountered \"define\""));
}
assertTrue(null != context.getFuncSpecFromAlias("myudf"));
}
@Test
public void testBagSchema() throws Throwable {
PigServer server = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
PigContext context = server.getPigContext();
String strCmd = "a = load 'input1' as (b: bag{t:(i: int, c:chararray, f: float)});\n";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
}
@Test
public void testBagSchemaFail() throws Throwable {
PigServer server = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
PigContext context = server.getPigContext();
String strCmd = "a = load 'input1'as (b: bag{t:(i: int, c:chararray, f: float)});\n";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
try {
grunt.exec();
} catch (Exception e) {
assertTrue(e.getMessage().contains("<line 1, column 62>")
&& e.getMessage().contains("mismatched input ';' expecting RIGHT_PAREN"));
}
}
@Test
public void testBagConstant() throws Throwable {
PigServer server = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
PigContext context = server.getPigContext();
String strCmd = "a = load 'input1'; b = foreach a generate {(1, '1', 0.4f),(2, '2', 0.45)};\n";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
}
@Test
public void testBagConstantWithSchema() throws Throwable {
PigServer server = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
PigContext context = server.getPigContext();
String strCmd = "a = load 'input1'; b = foreach a generate "
+ "{(1, '1', 0.4f),(2, '2', 0.45)} as "
+ "b: bag{t:(i: int, c:chararray, d: double)};\n";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
}
@Test
public void testBagConstantInForeachBlock() throws Throwable {
PigServer server = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
PigContext context = server.getPigContext();
String strCmd = "a = load 'input1'; "
+ "b = foreach a {generate {(1, '1', 0.4f),(2, '2', 0.45)};};\n";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
}
@Test
public void testBagConstantWithSchemaInForeachBlock() throws Throwable {
PigServer server = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
PigContext context = server.getPigContext();
String strCmd = "a = load 'input1'; "
+ "b = foreach a {generate {(1, '1', 0.4f),(2, '2', 0.45)} "
+ "as b: bag{t:(i: int, c:chararray, d: double)};};\n";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
}
@Test
public void testParsingAsInForeachBlock() throws Throwable {
PigServer server = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
PigContext context = server.getPigContext();
String strCmd = "a = load 'foo' as (foo, fast); "
+ "b = group a by foo; c = foreach b "
+ "{generate SUM(a.fast) as fast;};\n";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
}
@Test
public void testParsingAsInForeachWithOutBlock() throws Throwable {
PigServer server = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
PigContext context = server.getPigContext();
String strCmd = "a = load 'foo' as (foo, fast); "
+ "b = group a by foo; c = foreach b generate SUM(a.fast) as fast;\n";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
}
@Test
public void testParsingWordWithAsInForeachBlock() throws Throwable {
PigServer server = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
PigContext context = server.getPigContext();
String strCmd = "a = load 'foo' as (foo, fast); "
+ "b = group a by foo; c = foreach b {generate SUM(a.fast);};\n";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
}
@Test
public void testParsingWordWithAsInForeachWithOutBlock() throws Throwable {
PigServer server = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
PigContext context = server.getPigContext();
String strCmd = "a = load 'foo' as (foo, fast); "
+ "b = group a by foo; c = foreach b generate SUM(a.fast);\n";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
}
@Test
public void testParsingWordWithAsInForeachWithOutBlock2() throws Throwable {
PigServer server = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
PigContext context = server.getPigContext();
String strCmd = "cash = load 'foo' as (foo, fast); "
+ "b = foreach cash generate fast * 2.0;\n";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
}
@Test
public void testParsingGenerateInForeachBlock() throws Throwable {
PigServer server = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
PigContext context = server.getPigContext();
String strCmd = "a = load 'foo' as (foo, fast, regenerate); "
+ "b = group a by foo; c = foreach b {generate a.regenerate;};\n";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
}
@Test
public void testParsingGenerateInForeachWithOutBlock() throws Throwable {
PigServer server = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
PigContext context = server.getPigContext();
String strCmd = "a = load 'foo' as (foo, fast, regenerate); "
+ "b = group a by foo; c = foreach b generate a.regenerate;\n";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
}
@Test
public void testParsingAsGenerateInForeachBlock() throws Throwable {
PigServer server = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
PigContext context = server.getPigContext();
String strCmd = "a = load 'foo' as (foo, fast, regenerate); "
+ "b = group a by foo; c = foreach b {generate "
+ "{(1, '1', 0.4f),(2, '2', 0.45)} "
+ "as b: bag{t:(i: int, cease:chararray, degenerate: double)}, "
+ "SUM(a.fast) as fast, a.regenerate as degenerated;};\n";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
}
@Test
public void testParsingAsGenerateInForeachWithOutBlock() throws Throwable {
PigServer server = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
PigContext context = server.getPigContext();
String strCmd = "a = load 'foo' as (foo, fast, regenerate); "
+ "b = group a by foo; c = foreach b generate "
+ "{(1, '1', 0.4f),(2, '2', 0.45)} "
+ "as b: bag{t:(i: int, cease:chararray, degenerate: double)}, "
+ "SUM(a.fast) as fast, a.regenerate as degenerated;\n";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
}
@Test
public void testRunStatment() throws Throwable {
PigServer server = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
PigContext context = server.getPigContext();
String strCmd = "a = load 'foo' as (foo, fast, regenerate);"
+ " run -param LIMIT=5 -param_file " + basedir
+ "/test_broken.ppf " + basedir + "/testsub.pig; explain bar";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
}
@Test
public void testExecStatment() throws Throwable {
PigServer server = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
PigContext context = server.getPigContext();
boolean caught = false;
String strCmd = "a = load 'foo' as (foo, fast, regenerate);"
+ " exec -param LIMIT=5 -param FUNCTION=COUNT "
+ "-param FILE=foo " + basedir + "/testsub.pig; explain bar;";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
try {
grunt.exec();
} catch (Exception e) {
caught = true;
assertTrue(e.getMessage().contains("alias bar"));
}
assertTrue(caught);
}
@Test
public void testRunStatmentNested() throws Throwable {
PigServer server = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
PigContext context = server.getPigContext();
String strCmd = "a = load 'foo' as (foo, fast, regenerate); run "
+ basedir + "/testsubnested_run.pig; explain bar";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
}
@Test
public void testExecStatmentNested() throws Throwable {
PigServer server = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
PigContext context = server.getPigContext();
boolean caught = false;
String strCmd = "a = load 'foo' as (foo, fast, regenerate); exec "
+ basedir + "/testsubnested_exec.pig; explain bar";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
try {
grunt.exec();
} catch (Exception e) {
caught = true;
assertTrue(e.getMessage().contains("alias bar"));
}
assertTrue(caught);
}
@Test
public void testErrorLineNumber() throws Throwable {
PigServer server = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
PigContext context = server.getPigContext();
String strCmd = "A = load 'x' as ( u:int, v:chararray );\n" +
"sh ls\n" +
"B = foreach A generate u , v; C = distinct 'xxx';\n" +
"store C into 'y';";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
try {
grunt.exec();
} catch (Exception e) {
assertTrue(e.getMessage().contains("line 3, column 42"));
return;
}
Assert.fail( "Test case is supposed to fail." );
}
@Test
public void testExplainEmpty() throws Throwable {
PigServer server = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
PigContext context = server.getPigContext();
String strCmd = "a = load 'foo' as (foo, fast, regenerate); run "
+ basedir + "/testsubnested_run.pig; explain";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
}
@Test
public void testExplainScript() throws Throwable {
PigServer server = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
PigContext context = server.getPigContext();
String strCmd = "a = load 'foo' as (foo, fast, regenerate); explain -script "
+ basedir + "/testsubnested_run.pig;";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
}
/**
* PIG-2084
* Check if only statements used in query are validated, in non-interactive
* /non-check mode. There is an 'unused' statement in query that would otherise
* fail the validation.
* Primary purpose of test is to verify that check not happening for
* every statement.
* @throws Throwable
*/
@Test
public void testExplainScriptIsEachStatementValidated() throws Throwable {
PigServer server = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
PigContext context = server.getPigContext();
String strCmd = "a = load 'foo' as (foo, fast, regenerate);" +
"b = foreach a generate foo + 'x' + 1;" +
"c = foreach a generate foo, fast;" +
"explain c; ";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
}
@Test
public void testIllustrateScript() throws Throwable {
PigServer server = new PigServer(ExecType.LOCAL, new Properties());
PigContext context = server.getPigContext();
String strCmd = "illustrate -script "
+ basedir + "/illustrate.pig;";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
}
@Test
public void testIllustrateScript2() throws Throwable {
PigServer server = new PigServer(ExecType.LOCAL, new Properties());
PigContext context = server.getPigContext();
String strCmd = "illustrate -script "
+ basedir + "/illustrate2.pig;";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
}
@Test
public void testIllustrateScript3() throws Throwable {
PigServer server = new PigServer(ExecType.LOCAL, new Properties());
PigContext context = server.getPigContext();
String strCmd = "illustrate -script "
+ basedir + "/illustrate3.pig;";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
}
@Test
public void testIllustrateScript4() throws Throwable {
// empty line/field test
PigServer server = new PigServer(ExecType.LOCAL, new Properties());
PigContext context = server.getPigContext();
String strCmd = "illustrate -script "
+ basedir + "/illustrate4.pig;";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
}
@Test
public void testIllustrateScript5() throws Throwable {
// empty line/field test
PigServer server = new PigServer(ExecType.LOCAL, new Properties());
PigContext context = server.getPigContext();
String strCmd = "illustrate -script "
+ basedir + "/illustrate5.pig;";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
}
@Test
public void testIllustrateScript6() throws Throwable {
// empty line/field test
PigServer server = new PigServer(ExecType.LOCAL, new Properties());
PigContext context = server.getPigContext();
String strCmd = "illustrate -script "
+ basedir + "/illustrate6.pig;";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
}
@Test
public void testIllustrateScript7() throws Throwable {
// empty line/field test
PigServer server = new PigServer(ExecType.LOCAL, new Properties());
PigContext context = server.getPigContext();
String strCmd = "illustrate -script "
+ basedir + "/illustrate7.pig;";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
}
/**
* verify that grunt commands are ignored in explain -script mode
*/
@Test
public void testExplainScript2() throws Throwable {
PigServer server = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
PigContext context = server.getPigContext();
String strCmd = "explain -script "
+ basedir + "/explainScript.pig;";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
String logMessagesFile = "TestGrunt-testExplainScript2-stderr.txt";
// add a file based appender to the root logger so we can parse the
// messages logged by grunt and verify that grunt commands are ignored
// in explain -script mode
Appender fileAppender = new FileAppender(new PatternLayout(), logMessagesFile);
try {
org.apache.log4j.LogManager.getRootLogger().addAppender(fileAppender);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
BufferedReader in = new BufferedReader(new FileReader(logMessagesFile));
String gruntLoggingContents = "";
//read file into a string
String line;
while ( (line = in.readLine()) != null) {
gruntLoggingContents += line + "\n";
}
in.close();
String[] cmds = new String[] { "'rm/rmf'", "'cp'", "'cat'", "'cd'", "'pwd'",
"'copyFromLocal'", "'copyToLocal'", "'describe'", "'ls'",
"'mkdir'", "'illustrate'", "'run/exec'", "'fs'", "'aliases'",
"'mv'", "'dump'" };
for (String c : cmds) {
String expected = c + " statement is ignored while processing " +
"'explain -script' or '-check'";
assertTrue("Checking if " + gruntLoggingContents + " contains " +
expected, gruntLoggingContents.contains(expected));
}
} finally {
org.apache.log4j.LogManager.getRootLogger().removeAppender(fileAppender);
new File(logMessagesFile).delete();
}
}
@Test
public void testExplainBrief() throws Throwable {
PigServer server = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
PigContext context = server.getPigContext();
String strCmd = "a = load 'foo' as (foo, fast, regenerate); explain -brief -script "
+ basedir + "/testsubnested_run.pig;";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
}
@Test
public void testExplainDot() throws Throwable {
PigServer server = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
PigContext context = server.getPigContext();
String strCmd = "a = load 'foo' as (foo, fast, regenerate); explain -dot -script "
+ basedir + "/testsubnested_run.pig;";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
}
@Test
public void testExplainOut() throws Throwable {
PigServer server = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
PigContext context = server.getPigContext();
String strCmd = "a = load 'foo' as (foo, fast, regenerate); explain -out /tmp -script "
+ basedir + "/testsubnested_run.pig;";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
}
@Test
public void testPartialExecution() throws Throwable {
PigServer server = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
PigContext context = server.getPigContext();
FileLocalizer.setInitialized(false);
String strCmd = "rmf bar; rmf baz; "
+ "a = load '"
+ Util.generateURI("file:test/org/apache/pig/test/data/passwd",
context)
+ "';"
+ "store a into 'bar'; exec; a = load 'bar'; store a into 'baz';\n";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
}
@Test
public void testFileCmds() throws Throwable {
PigServer server = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
PigContext context = server.getPigContext();
String strCmd =
"rmf bar; rmf baz;"
+"a = load '"
+ Util.generateURI("file:test/org/apache/pig/test/data/passwd", context) + "';"
+"store a into 'bar';"
+"cp bar baz;"
+"rm bar; rm baz;"
+"store a into 'baz';"
+"store a into 'bar';"
+"rm baz; rm bar;"
+"store a into 'baz';"
+"mv baz bar;"
+"b = load 'bar';"
+"store b into 'baz';"
+"cat baz;"
+"rm baz;"
+"rm bar;\n";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
}
@Test
public void testCD() throws Throwable {
PigServer server = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
PigContext context = server.getPigContext();
String strCmd =
"mkdir /tmp;"
+"mkdir /tmp/foo;"
+"cd /tmp;"
+"rmf bar; rmf foo/baz;"
+"copyFromLocal test/org/apache/pig/test/data/passwd bar;"
+"a = load 'bar';"
+"cd foo;"
+"store a into 'baz';"
+"cd /;"
+"rm /tmp/bar; rm /tmp/foo/baz;";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
}
@Test
public void testDump() throws Throwable {
PigServer server = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
PigContext context = server.getPigContext();
String strCmd =
"rmf bla;"
+"a = load '"
+ Util.generateURI("file:test/org/apache/pig/test/data/passwd", context) + "';"
+"e = group a by $0;"
+"f = foreach e generate group, COUNT($1);"
+"store f into 'bla';"
+"f1 = load 'bla';"
+"g = order f1 by $1;"
+"dump g;";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
}
@Test
public void testIllustrate() throws Throwable {
PigServer server = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
PigContext context = server.getPigContext();
String strCmd =
"rmf bla;"
+"a = load '"
+ Util.generateURI("file:test/org/apache/pig/test/data/passwd", context) + "';"
+"e = group a by $0;"
+"f = foreach e generate group, COUNT($1);"
+"store f into 'bla';"
+"f1 = load 'bla' as (f:chararray);"
+"g = order f1 by $0;"
+"illustrate g;";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
}
@Test
public void testKeepGoing() throws Throwable {
PigServer server = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
PigContext context = server.getPigContext();
String filename =
Util.generateURI("file:test/org/apache/pig/test/data/passwd", context);
String strCmd =
"rmf bar;"
+"rmf foo;"
+"rmf baz;"
+"A = load '" + filename + "';"
+"B = foreach A generate 1;"
+"C = foreach A generate 0/0;"
+"store B into 'foo';"
+"store C into 'bar';"
+"A = load '" + filename + "';"
+"B = stream A through `false`;"
+"store B into 'baz';"
+"cat bar;";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
}
@Test
public void testKeepGoigFailed() throws Throwable {
PigServer server = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
PigContext context = server.getPigContext();
Util.copyFromLocalToCluster(cluster, "test/org/apache/pig/test/data/passwd", "passwd");
String strCmd =
"rmf bar;"
+"rmf foo;"
+"rmf baz;"
+"A = load 'passwd';"
+"B = foreach A generate 1;"
+"C = foreach A generate 0/0;"
+"store B into 'foo';"
+"store C into 'bar';"
+"A = load 'passwd';"
+"B = stream A through `false`;"
+"store B into 'baz';"
+"cat baz;";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
boolean caught = false;
try {
grunt.exec();
} catch (Exception e) {
caught = true;
assertTrue(e.getMessage().contains("baz does not exist"));
}
assertTrue(caught);
}
@Test
public void testInvalidParam() throws Throwable {
PigServer server = new PigServer(ExecType.LOCAL, cluster.getProperties());
PigContext context = server.getPigContext();
String strCmd =
"run -param -param;";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
boolean caught = false;
try {
grunt.exec();
} catch (ParseException e) {
caught = true;
assertTrue(e.getMessage().contains("Encountered"));
}
assertTrue(caught);
}
@Test
public void testStopOnFailure() throws Throwable {
PigServer server = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
PigContext context = server.getPigContext();
context.getProperties().setProperty("stop.on.failure", ""+true);
String strCmd =
"rmf bar;\n"
+"rmf foo;\n"
+"rmf baz;\n"
+"copyFromLocal test/org/apache/pig/test/data/passwd pre;\n"
+"A = load '"
+ Util.generateURI("file:test/org/apache/pig/test/data/passwd", context) + "';\n"
+"B = stream A through `false`;\n"
+"store B into 'bar' using BinStorage();\n"
+"A = load 'bar';\n"
+"store A into 'foo';\n"
+"cp pre done;\n";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
boolean caught = false;
try {
grunt.exec();
} catch (PigException e) {
caught = true;
assertTrue(e.getErrorCode() == 6017);
}
assertFalse(server.existsFile("done"));
assertTrue(caught);
}
@Test
public void testFsCommand() throws Throwable {
PigServer server = new PigServer(ExecType.MAPREDUCE,cluster.getProperties());
PigContext context = server.getPigContext();
String strCmd =
"fs -ls /;"
+"fs -mkdir /fstmp;"
+"fs -mkdir /fstmp/foo;"
+"cd /fstmp;"
+"fs -copyFromLocal test/org/apache/pig/test/data/passwd bar;"
+"a = load 'bar';"
+"cd foo;"
+"store a into 'baz';"
+"cd /;"
+"fs -ls .;"
+"fs -rmr /fstmp/foo/baz;";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
}
@Test
public void testShellCommand(){
try {
PigServer server = new PigServer(ExecType.MAPREDUCE,cluster.getProperties());
PigContext context = server.getPigContext();
String strQuote = "'";
String strRemoveFile = "rm";
String strRemoveDir = "rmdir";
if (Util.WINDOWS)
{
strQuote = "\"";
strRemoveFile = "del";
strRemoveDir = "rd";
}
String strCmd = "sh mkdir test_shell_tmp;";
// Create a temp directory via command and make sure it exists
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
assertTrue(new File("test_shell_tmp").exists());
// Remove the temp directory via shell and make sure it is gone
strCmd = "sh " + strRemoveDir + " test_shell_tmp;";
cmd = new ByteArrayInputStream(strCmd.getBytes());
reader = new InputStreamReader(cmd);
grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
assertFalse(new File("test_shell_tmp").exists());
// Verify pipes are usable in the command context by piping data to a file
strCmd = "sh echo hello world > tempShFileToTestShCommand";
cmd = new ByteArrayInputStream(strCmd.getBytes());
reader = new InputStreamReader(cmd);
grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
BufferedReader fileReader = null;
fileReader = new BufferedReader(new FileReader("tempShFileToTestShCommand"));
assertTrue(fileReader.readLine().trim().equals("hello world"));
fileReader.close();
// Remove the file via cmd and make sure it is gone
strCmd = "sh " + strRemoveFile + " tempShFileToTestShCommand";
cmd = new ByteArrayInputStream(strCmd.getBytes());
reader = new InputStreamReader(cmd);
grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
assertFalse(new File("tempShFileToTestShCommand").exists());
if (Util.WINDOWS) {
strCmd = "sh echo foo > TouchedFileInsideGrunt_61 | dir /B | findstr TouchedFileInsideGrunt_61 > fileContainingTouchedFileInsideGruntShell_71";
}
else {
strCmd = "sh touch TouchedFileInsideGrunt_61 | ls | grep TouchedFileInsideGrunt_61 > fileContainingTouchedFileInsideGruntShell_71";
}
cmd = new ByteArrayInputStream(strCmd.getBytes());
reader = new InputStreamReader(cmd);
grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
fileReader = new BufferedReader(new FileReader("fileContainingTouchedFileInsideGruntShell_71"));
assertTrue(fileReader.readLine().trim().equals("TouchedFileInsideGrunt_61"));
fileReader.close();
strCmd = "sh " + strRemoveFile+" fileContainingTouchedFileInsideGruntShell_71";
cmd = new ByteArrayInputStream(strCmd.getBytes());
reader = new InputStreamReader(cmd);
grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
assertFalse(new File("fileContainingTouchedFileInsideGruntShell_71").exists());
- strCmd = "sh bash -c 'rm TouchedFileInsideGrunt_61'";
+ strCmd = "sh " + strRemoveFile + " TouchedFileInsideGrunt_61";
cmd = new ByteArrayInputStream(strCmd.getBytes());
reader = new InputStreamReader(cmd);
grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
assertFalse(new File("TouchedFileInsideGrunt_61").exists());
} catch (ExecException e) {
e.printStackTrace();
fail();
} catch (Throwable e) {
e.printStackTrace();
fail();
}
}
// See PIG-2497
@Test
public void testShellCommandOrder() throws Throwable {
PigServer server = new PigServer(ExecType.LOCAL, new Properties());
File inputFile = File.createTempFile("test", "txt");
PrintWriter pwInput = new PrintWriter(new FileWriter(inputFile));
pwInput.println("1");
pwInput.close();
File inputScript = File.createTempFile("test", "");
File outputFile = File.createTempFile("test", "txt");
outputFile.delete();
PrintWriter pwScript = new PrintWriter(new FileWriter(inputScript));
pwScript.println("a = load '" + inputFile.getAbsolutePath() + "';");
pwScript.println("store a into '" + outputFile.getAbsolutePath() + "';");
pwScript.println("sh rm -rf " + inputFile.getAbsolutePath());
pwScript.close();
InputStream inputStream = new FileInputStream(inputScript.getAbsoluteFile());
server.setBatchOn();
server.registerScript(inputStream);
List<ExecJob> execJobs = server.executeBatch();
Assert.assertTrue(execJobs.get(0).getStatus() == JOB_STATUS.COMPLETED);
}
@Test
public void testSetPriority() throws Throwable {
PigServer server = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
PigContext context = server.getPigContext();
String strCmd = "set job.priority high\n";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
assertEquals("high", context.getProperties().getProperty(PigContext.JOB_PRIORITY));
}
@Test
public void testSetWithQuotes() throws Throwable {
PigServer server = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
PigContext context = server.getPigContext();
String strCmd = "set job.priority 'high'\n";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
assertEquals("high", context.getProperties().getProperty(PigContext.JOB_PRIORITY));
}
@Test
public void testRegisterWithQuotes() throws Throwable {
PigServer server = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
PigContext context = server.getPigContext();
String strCmd = "register 'pig-withouthadoop.jar'\n";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
assertEquals(context.extraJars+ " of size 1", 1, context.extraJars.size());
assertTrue(context.extraJars.get(0)+" ends with /pig-withouthadoop.jar", context.extraJars.get(0).toString().endsWith("/pig-withouthadoop.jar"));
}
@Test
public void testRegisterWithoutQuotes() throws Throwable {
PigServer server = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
PigContext context = server.getPigContext();
String strCmd = "register pig-withouthadoop.jar\n";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
assertEquals(context.extraJars+ " of size 1", 1, context.extraJars.size());
assertTrue(context.extraJars.get(0)+" ends with /pig-withouthadoop.jar", context.extraJars.get(0).toString().endsWith("/pig-withouthadoop.jar"));
}
@Test
public void testRegisterScripts() throws Throwable {
String[] script = {
"#!/usr/bin/python",
"@outputSchema(\"x:{t:(num:long)}\")",
"def square(number):" ,
"\treturn (number * number)"
};
Util.createLocalInputFile( "testRegisterScripts.py", script);
PigServer server = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
PigContext context = server.getPigContext();
String strCmd = "register testRegisterScripts.py using jython as pig\n";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
assertTrue(context.getFuncSpecFromAlias("pig.square") != null);
}
@Test
public void testScriptMissingLastNewLine() throws Throwable {
PigServer server = new PigServer(ExecType.LOCAL);
PigContext context = server.getPigContext();
String strCmd = "A = load 'bar';\nB = foreach A generate $0;";
ParameterSubstitutionPreprocessor psp = new ParameterSubstitutionPreprocessor(50);
BufferedReader pin = new BufferedReader(new StringReader(strCmd));
StringWriter writer = new StringWriter();
psp.genSubstitutedFile(pin, writer, null, null);
pin = new BufferedReader(new StringReader(writer.toString()));
Grunt grunt = new Grunt(pin, context);
int results[] = grunt.exec();
for (int i=0; i<results.length; i++) {
assertTrue(results[i] == 0);
}
}
// Test case for PIG-740 to report an error near the double quotes rather
// than an unrelated EOF error message
@Test
public void testBlockErrMessage() throws Throwable {
PigServer server = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
PigContext context = server.getPigContext();
String script = "A = load 'inputdata' using PigStorage() as ( curr_searchQuery );\n" +
"B = foreach A { domain = CONCAT(curr_searchQuery,\"^www\\.\");\n" +
" generate domain; };\n";
ByteArrayInputStream cmd = new ByteArrayInputStream(script.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
try {
grunt.exec();
} catch(FrontendException e) {
e.printStackTrace();
assertTrue(e.getMessage().contains("Error during parsing. <line 2, column 49> Unexpected character '\"'"));
}
}
@Test
public void testCheckScript() throws Throwable {
// a query which has grunt commands intermixed with pig statements - this
// should pass through successfully with the check and all the grunt commands
// should be ignored during the check.
String query = "rmf input-copy.txt; cat 'foo'; a = load '1.txt' ; " +
"aliases;illustrate a; copyFromLocal foo bar; copyToLocal foo bar; " +
"describe a; mkdir foo; run bar.pig; exec bar.pig; cp foo bar; " +
"explain a;cd 'bar'; pwd; ls ; fs -ls ; fs -rmr foo; mv foo bar; " +
"dump a;store a into 'input-copy.txt' ; a = load '2.txt' as (b);" +
"explain a; rm foo; store a into 'bar';";
String[] cmds = new String[] { "'rm/rmf'", "'cp'", "'cat'", "'cd'", "'pwd'",
"'copyFromLocal'", "'copyToLocal'", "'describe'", "'ls'",
"'mkdir'", "'illustrate'", "'run/exec'", "'fs'", "'aliases'",
"'mv'", "'dump'" };
ArrayList<String> msgs = new ArrayList<String>();
for (String c : cmds) {
msgs.add(c + " statement is ignored while processing " +
"'explain -script' or '-check'");
}
validate(query, true, msgs.toArray(new String[0]));
}
@Test
public void testCheckScriptSyntaxErr() throws Throwable {
// a query which has grunt commands intermixed with pig statements - this
// should fail with the -check option with a syntax error
// the query has a typo - chararay instead of chararray
String query = "a = load '1.txt' ; fs -rmr foo; mv foo bar; dump a;" +
"store a into 'input-copy.txt' ; dump a; a = load '2.txt' as " +
"(b:chararay);explain a; rm foo; store a into 'bar';";
String[] cmds = new String[] { "'fs'", "'mv'", "'dump'" };
ArrayList<String> msgs = new ArrayList<String>();
for (String c : cmds) {
msgs.add(c + " statement is ignored while processing " +
"'explain -script' or '-check'");
}
msgs.add("Syntax error");
validate(query, false, msgs.toArray(new String[0]));
}
@Test
public void testCheckScriptTypeCheckErr() throws Throwable {
// a query which has grunt commands intermixed with pig statements - this
// should fail with the -check option with a type checking error
// the query has incompatible types in bincond
String query = "a = load 'foo.pig' as (s:chararray); dump a; explain a; " +
"store a into 'foobar'; b = foreach a generate " +
"(s == 2 ? 1 : 2.0); store b into 'bar';";
String[] cmds = new String[] { "'dump'" };
ArrayList<String> msgs = new ArrayList<String>();
for (String c : cmds) {
msgs.add(c + " statement is ignored while processing " +
"'explain -script' or '-check'");
}
msgs.add("incompatible types in Equal Operator");
validate(query, false, msgs.toArray(new String[0]));
}
private void validate(String query, boolean syntaxOk,
String[] logMessagesToCheck) throws Throwable {
File scriptFile = Util.createFile(new String[] { query});
String scriptFileName = scriptFile.getAbsolutePath();
String cmd = "java -cp " + System.getProperty("java.class.path") +
" org.apache.pig.Main -x local -c " + scriptFileName;
ProcessReturnInfo pri = Util.executeJavaCommandAndReturnInfo(cmd);
for (String msg : logMessagesToCheck) {
assertTrue("Checking if " + pri.stderrContents + " contains " +
msg, pri.stderrContents.contains(msg));
}
if(syntaxOk) {
assertTrue("Checking that the syntax OK message was printed on " +
"stderr <" + pri.stderrContents + ">",
pri.stderrContents.contains("syntax OK"));
} else {
assertFalse("Checking that the syntax OK message was NOT printed on " +
"stderr <" + pri.stderrContents + ">",
pri.stderrContents.contains("syntax OK"));
}
}
@Test
public void testSet() throws Throwable {
String strCmd = "set my.arbitrary.key my.arbitrary.value\n";
PigContext pc = new PigServer(ExecType.LOCAL).getPigContext();
InputStreamReader reader = new InputStreamReader(new ByteArrayInputStream(strCmd.getBytes()));
new Grunt(new BufferedReader(reader), pc).exec();
assertEquals("my.arbitrary.value", pc.getProperties().getProperty("my.arbitrary.key"));
}
@Test
public void testCheckScriptTypeCheckErrNoStoreDump() throws Throwable {
//the query has not store or dump, but in when -check is used
// all statements should be validated
String query = "a = load 'foo.pig' as (s:chararray); " +
"b = foreach a generate $1;";
String msg = "Trying to access non-existent column";
validateGruntCheckFail(query, msg);
}
private void validateGruntCheckFail(String piglatin, String errMsg) throws Throwable{
String scriptFile = "myscript.pig";
try {
BufferedReader br = new BufferedReader(new StringReader(piglatin));
Grunt grunt = new Grunt(br, new PigContext(ExecType.LOCAL, new Properties()));
String [] inp = {piglatin};
Util.createLocalInputFile(scriptFile, inp);
grunt.checkScript(scriptFile);
Assert.fail("Expected exception isn't thrown");
} catch (FrontendException e) {
Util.checkMessageInException(e, errMsg);
}
}
@Test
public void testDebugOn() throws Throwable {
String strCmd = "set debug on\n";
PigContext pc = new PigServer(ExecType.LOCAL).getPigContext();
InputStreamReader reader = new InputStreamReader(new ByteArrayInputStream(strCmd.getBytes()));
new Grunt(new BufferedReader(reader), pc).exec();
assertEquals(Level.DEBUG.toString(), pc.getLog4jProperties().getProperty("log4j.logger.org.apache.pig"));
}
@Test
public void testDebugOff() throws Throwable {
String strCmd = "set debug off\n";
PigContext pc = new PigServer(ExecType.LOCAL).getPigContext();
InputStreamReader reader = new InputStreamReader(new ByteArrayInputStream(strCmd.getBytes()));
new Grunt(new BufferedReader(reader), pc).exec();
assertEquals(Level.INFO.toString(), pc.getLog4jProperties().getProperty("log4j.logger.org.apache.pig"));
}
}
| true | true | public void testShellCommand(){
try {
PigServer server = new PigServer(ExecType.MAPREDUCE,cluster.getProperties());
PigContext context = server.getPigContext();
String strQuote = "'";
String strRemoveFile = "rm";
String strRemoveDir = "rmdir";
if (Util.WINDOWS)
{
strQuote = "\"";
strRemoveFile = "del";
strRemoveDir = "rd";
}
String strCmd = "sh mkdir test_shell_tmp;";
// Create a temp directory via command and make sure it exists
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
assertTrue(new File("test_shell_tmp").exists());
// Remove the temp directory via shell and make sure it is gone
strCmd = "sh " + strRemoveDir + " test_shell_tmp;";
cmd = new ByteArrayInputStream(strCmd.getBytes());
reader = new InputStreamReader(cmd);
grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
assertFalse(new File("test_shell_tmp").exists());
// Verify pipes are usable in the command context by piping data to a file
strCmd = "sh echo hello world > tempShFileToTestShCommand";
cmd = new ByteArrayInputStream(strCmd.getBytes());
reader = new InputStreamReader(cmd);
grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
BufferedReader fileReader = null;
fileReader = new BufferedReader(new FileReader("tempShFileToTestShCommand"));
assertTrue(fileReader.readLine().trim().equals("hello world"));
fileReader.close();
// Remove the file via cmd and make sure it is gone
strCmd = "sh " + strRemoveFile + " tempShFileToTestShCommand";
cmd = new ByteArrayInputStream(strCmd.getBytes());
reader = new InputStreamReader(cmd);
grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
assertFalse(new File("tempShFileToTestShCommand").exists());
if (Util.WINDOWS) {
strCmd = "sh echo foo > TouchedFileInsideGrunt_61 | dir /B | findstr TouchedFileInsideGrunt_61 > fileContainingTouchedFileInsideGruntShell_71";
}
else {
strCmd = "sh touch TouchedFileInsideGrunt_61 | ls | grep TouchedFileInsideGrunt_61 > fileContainingTouchedFileInsideGruntShell_71";
}
cmd = new ByteArrayInputStream(strCmd.getBytes());
reader = new InputStreamReader(cmd);
grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
fileReader = new BufferedReader(new FileReader("fileContainingTouchedFileInsideGruntShell_71"));
assertTrue(fileReader.readLine().trim().equals("TouchedFileInsideGrunt_61"));
fileReader.close();
strCmd = "sh " + strRemoveFile+" fileContainingTouchedFileInsideGruntShell_71";
cmd = new ByteArrayInputStream(strCmd.getBytes());
reader = new InputStreamReader(cmd);
grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
assertFalse(new File("fileContainingTouchedFileInsideGruntShell_71").exists());
strCmd = "sh bash -c 'rm TouchedFileInsideGrunt_61'";
cmd = new ByteArrayInputStream(strCmd.getBytes());
reader = new InputStreamReader(cmd);
grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
assertFalse(new File("TouchedFileInsideGrunt_61").exists());
} catch (ExecException e) {
e.printStackTrace();
fail();
} catch (Throwable e) {
e.printStackTrace();
fail();
}
}
| public void testShellCommand(){
try {
PigServer server = new PigServer(ExecType.MAPREDUCE,cluster.getProperties());
PigContext context = server.getPigContext();
String strQuote = "'";
String strRemoveFile = "rm";
String strRemoveDir = "rmdir";
if (Util.WINDOWS)
{
strQuote = "\"";
strRemoveFile = "del";
strRemoveDir = "rd";
}
String strCmd = "sh mkdir test_shell_tmp;";
// Create a temp directory via command and make sure it exists
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
assertTrue(new File("test_shell_tmp").exists());
// Remove the temp directory via shell and make sure it is gone
strCmd = "sh " + strRemoveDir + " test_shell_tmp;";
cmd = new ByteArrayInputStream(strCmd.getBytes());
reader = new InputStreamReader(cmd);
grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
assertFalse(new File("test_shell_tmp").exists());
// Verify pipes are usable in the command context by piping data to a file
strCmd = "sh echo hello world > tempShFileToTestShCommand";
cmd = new ByteArrayInputStream(strCmd.getBytes());
reader = new InputStreamReader(cmd);
grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
BufferedReader fileReader = null;
fileReader = new BufferedReader(new FileReader("tempShFileToTestShCommand"));
assertTrue(fileReader.readLine().trim().equals("hello world"));
fileReader.close();
// Remove the file via cmd and make sure it is gone
strCmd = "sh " + strRemoveFile + " tempShFileToTestShCommand";
cmd = new ByteArrayInputStream(strCmd.getBytes());
reader = new InputStreamReader(cmd);
grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
assertFalse(new File("tempShFileToTestShCommand").exists());
if (Util.WINDOWS) {
strCmd = "sh echo foo > TouchedFileInsideGrunt_61 | dir /B | findstr TouchedFileInsideGrunt_61 > fileContainingTouchedFileInsideGruntShell_71";
}
else {
strCmd = "sh touch TouchedFileInsideGrunt_61 | ls | grep TouchedFileInsideGrunt_61 > fileContainingTouchedFileInsideGruntShell_71";
}
cmd = new ByteArrayInputStream(strCmd.getBytes());
reader = new InputStreamReader(cmd);
grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
fileReader = new BufferedReader(new FileReader("fileContainingTouchedFileInsideGruntShell_71"));
assertTrue(fileReader.readLine().trim().equals("TouchedFileInsideGrunt_61"));
fileReader.close();
strCmd = "sh " + strRemoveFile+" fileContainingTouchedFileInsideGruntShell_71";
cmd = new ByteArrayInputStream(strCmd.getBytes());
reader = new InputStreamReader(cmd);
grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
assertFalse(new File("fileContainingTouchedFileInsideGruntShell_71").exists());
strCmd = "sh " + strRemoveFile + " TouchedFileInsideGrunt_61";
cmd = new ByteArrayInputStream(strCmd.getBytes());
reader = new InputStreamReader(cmd);
grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
assertFalse(new File("TouchedFileInsideGrunt_61").exists());
} catch (ExecException e) {
e.printStackTrace();
fail();
} catch (Throwable e) {
e.printStackTrace();
fail();
}
}
|
diff --git a/src/storage/cz/vity/freerapid/plugins/services/storage/StorageFileRunner.java b/src/storage/cz/vity/freerapid/plugins/services/storage/StorageFileRunner.java
index a5aa5c0d..7aa47dab 100644
--- a/src/storage/cz/vity/freerapid/plugins/services/storage/StorageFileRunner.java
+++ b/src/storage/cz/vity/freerapid/plugins/services/storage/StorageFileRunner.java
@@ -1,96 +1,96 @@
package cz.vity.freerapid.plugins.services.storage;
import cz.vity.freerapid.plugins.exceptions.ErrorDuringDownloadingException;
import cz.vity.freerapid.plugins.exceptions.PluginImplementationException;
import cz.vity.freerapid.plugins.exceptions.ServiceConnectionProblemException;
import cz.vity.freerapid.plugins.exceptions.URLNotAvailableAnymoreException;
import cz.vity.freerapid.plugins.webclient.AbstractRunner;
import cz.vity.freerapid.plugins.webclient.FileState;
import cz.vity.freerapid.plugins.webclient.MethodBuilder;
import cz.vity.freerapid.plugins.webclient.utils.PlugUtils;
import org.apache.commons.httpclient.methods.GetMethod;
import java.io.IOException;
import java.util.logging.Logger;
/**
* Class which contains main code
*
* @author Vity
*/
class StorageFileRunner extends AbstractRunner {
private final static Logger logger = Logger.getLogger(StorageFileRunner.class.getName());
@Override
public void runCheck() throws Exception { //this method validates file
super.runCheck();
final GetMethod getMethod = getGetMethod(fileURL);//make first request
if (makeRedirectedRequest(getMethod)) {
checkProblems();
checkNameAndSize(getContentAsString());//ok let's extract file name and size from the page
} else
throw new PluginImplementationException();
}
private void checkNameAndSize(String content) throws ErrorDuringDownloadingException {
PlugUtils.checkName(httpFile, content, "Downloading:</span>", "<span class=\"light\"");
PlugUtils.checkFileSize(httpFile, content, "class=\"light\">(", ")</span>");
httpFile.setFileState(FileState.CHECKED_AND_EXISTING);
}
@Override
public void run() throws Exception {
super.run();
logger.info("Starting download in TASK " + fileURL);
final GetMethod method = getGetMethod(fileURL); //create GET request
if (makeRedirectedRequest(method)) { //we make the main request
final String contentAsString = getContentAsString();//check for response
checkProblems();//check problems
checkNameAndSize(contentAsString);//extract file name and size from the page
final String directLink = PlugUtils.getStringBetween(getContentAsString(), "you can visit ", " directly");
String state;
ResponseParser json;
do {
json = getParser(directLink);
state = json.getString("state");
if ("wait".equals(state)) {
final int countDown = json.getInt("countdown");
downloadTask.sleep(countDown + 1);
} else break;
} while (true);
if ("failed".equals(state)) {
throw new ServiceConnectionProblemException("The download failed. Please try again later");
} else if ("ok".equals(state)) {
final String link = json.getString("link");
logger.info("link:" + link);
final int countDown = json.getInt("countdown");
downloadTask.sleep(countDown + 1);//musi byt
//here is the download link extraction
- this.client.getHTTPClient().getParams().setParameter("dontUseHeaderFilename", true);
+ // this.client.getHTTPClient().getParams().setParameter("dontUseHeaderFilename", true);
if (!tryDownloadAndSaveFile(getMethodBuilder().setReferer(fileURL).setAction(link).toHttpMethod())) {
checkProblems();//if downloading failed
logger.warning(getContentAsString());//log the info
throw new PluginImplementationException();//some unknown problem
}
} else throw new PluginImplementationException("Unknown state");//some unknown problem
} else {
checkProblems();
throw new ServiceConnectionProblemException();
}
}
private ResponseParser getParser(String directLink) throws PluginImplementationException, IOException {
final MethodBuilder mb = getMethodBuilder().setReferer(fileURL).setAction(directLink);
if (makeRedirectedRequest(mb.toHttpMethod())) {
return new ResponseParser(getContentAsString());
} else throw new PluginImplementationException("No JSon object response");
}
private void checkProblems() throws ErrorDuringDownloadingException {
final String contentAsString = getContentAsString();
if (contentAsString.contains("File not found")) {
throw new URLNotAvailableAnymoreException("File not found"); //let to know user in FRD
}
}
}
| true | true | public void run() throws Exception {
super.run();
logger.info("Starting download in TASK " + fileURL);
final GetMethod method = getGetMethod(fileURL); //create GET request
if (makeRedirectedRequest(method)) { //we make the main request
final String contentAsString = getContentAsString();//check for response
checkProblems();//check problems
checkNameAndSize(contentAsString);//extract file name and size from the page
final String directLink = PlugUtils.getStringBetween(getContentAsString(), "you can visit ", " directly");
String state;
ResponseParser json;
do {
json = getParser(directLink);
state = json.getString("state");
if ("wait".equals(state)) {
final int countDown = json.getInt("countdown");
downloadTask.sleep(countDown + 1);
} else break;
} while (true);
if ("failed".equals(state)) {
throw new ServiceConnectionProblemException("The download failed. Please try again later");
} else if ("ok".equals(state)) {
final String link = json.getString("link");
logger.info("link:" + link);
final int countDown = json.getInt("countdown");
downloadTask.sleep(countDown + 1);//musi byt
//here is the download link extraction
this.client.getHTTPClient().getParams().setParameter("dontUseHeaderFilename", true);
if (!tryDownloadAndSaveFile(getMethodBuilder().setReferer(fileURL).setAction(link).toHttpMethod())) {
checkProblems();//if downloading failed
logger.warning(getContentAsString());//log the info
throw new PluginImplementationException();//some unknown problem
}
} else throw new PluginImplementationException("Unknown state");//some unknown problem
} else {
checkProblems();
throw new ServiceConnectionProblemException();
}
}
| public void run() throws Exception {
super.run();
logger.info("Starting download in TASK " + fileURL);
final GetMethod method = getGetMethod(fileURL); //create GET request
if (makeRedirectedRequest(method)) { //we make the main request
final String contentAsString = getContentAsString();//check for response
checkProblems();//check problems
checkNameAndSize(contentAsString);//extract file name and size from the page
final String directLink = PlugUtils.getStringBetween(getContentAsString(), "you can visit ", " directly");
String state;
ResponseParser json;
do {
json = getParser(directLink);
state = json.getString("state");
if ("wait".equals(state)) {
final int countDown = json.getInt("countdown");
downloadTask.sleep(countDown + 1);
} else break;
} while (true);
if ("failed".equals(state)) {
throw new ServiceConnectionProblemException("The download failed. Please try again later");
} else if ("ok".equals(state)) {
final String link = json.getString("link");
logger.info("link:" + link);
final int countDown = json.getInt("countdown");
downloadTask.sleep(countDown + 1);//musi byt
//here is the download link extraction
// this.client.getHTTPClient().getParams().setParameter("dontUseHeaderFilename", true);
if (!tryDownloadAndSaveFile(getMethodBuilder().setReferer(fileURL).setAction(link).toHttpMethod())) {
checkProblems();//if downloading failed
logger.warning(getContentAsString());//log the info
throw new PluginImplementationException();//some unknown problem
}
} else throw new PluginImplementationException("Unknown state");//some unknown problem
} else {
checkProblems();
throw new ServiceConnectionProblemException();
}
}
|
diff --git a/src/org/jruby/compiler/impl/StandardASMCompiler.java b/src/org/jruby/compiler/impl/StandardASMCompiler.java
index e15f69c38..3185e6582 100644
--- a/src/org/jruby/compiler/impl/StandardASMCompiler.java
+++ b/src/org/jruby/compiler/impl/StandardASMCompiler.java
@@ -1,1860 +1,1860 @@
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.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.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2006 Charles O Nutter <[email protected]>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby.compiler.impl;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
import jregex.Pattern;
import org.jruby.MetaClass;
import org.jruby.Ruby;
import org.jruby.RubyArray;
import org.jruby.RubyBignum;
import org.jruby.RubyBoolean;
import org.jruby.RubyClass;
import org.jruby.RubyFixnum;
import org.jruby.RubyFloat;
import org.jruby.RubyHash;
import org.jruby.RubyModule;
import org.jruby.RubyObject;
import org.jruby.RubyRange;
import org.jruby.RubyRegexp;
import org.jruby.RubyString;
import org.jruby.RubySymbol;
import org.jruby.ast.Node;
import org.jruby.ast.executable.Script;
import org.jruby.compiler.ArrayCallback;
import org.jruby.compiler.BranchCallback;
import org.jruby.compiler.ClosureCallback;
import org.jruby.compiler.Compiler;
import org.jruby.compiler.NotCompilableException;
import org.jruby.evaluator.EvaluationState;
import org.jruby.exceptions.JumpException;
import org.jruby.exceptions.RaiseException;
import org.jruby.internal.runtime.GlobalVariables;
import org.jruby.internal.runtime.methods.DynamicMethod;
import org.jruby.internal.runtime.methods.WrapperMethod;
import org.jruby.lexer.yacc.ISourcePosition;
import org.jruby.parser.BlockStaticScope;
import org.jruby.parser.LocalStaticScope;
import org.jruby.parser.StaticScope;
import org.jruby.runtime.Arity;
import org.jruby.runtime.Block;
import org.jruby.runtime.CallType;
import org.jruby.runtime.CallbackFactory;
import org.jruby.runtime.CompiledBlock;
import org.jruby.runtime.CompiledBlockCallback;
import org.jruby.runtime.DynamicScope;
import org.jruby.runtime.MethodFactory;
import org.jruby.runtime.MethodIndex;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.Visibility;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.ByteList;
import org.jruby.util.CodegenUtils;
import org.jruby.util.JRubyClassLoader;
import org.jruby.util.collections.SinglyLinkedList;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Label;
import org.objectweb.asm.Opcodes;
/**
*
* @author headius
*/
public class StandardASMCompiler implements Compiler, Opcodes {
private static final CodegenUtils cg = CodegenUtils.instance;
private static final String THREADCONTEXT = cg.p(ThreadContext.class);
private static final String RUBY = cg.p(Ruby.class);
private static final String IRUBYOBJECT = cg.p(IRubyObject.class);
private static final String METHOD_SIGNATURE =
cg.sig(IRubyObject.class, new Class[] { ThreadContext.class, IRubyObject.class, IRubyObject[].class, Block.class });
private static final String CLOSURE_SIGNATURE =
cg.sig(IRubyObject.class, new Class[] { ThreadContext.class, IRubyObject.class, IRubyObject[].class });
private static final int THREADCONTEXT_INDEX = 0;
private static final int SELF_INDEX = 1;
private static final int ARGS_INDEX = 2;
private static final int CLOSURE_INDEX = 3;
private static final int SCOPE_INDEX = 4;
private static final int RUNTIME_INDEX = 5;
private static final int VISIBILITY_INDEX = 6;
private static final int LOCAL_VARS_INDEX = 7;
private Stack SkinnyMethodAdapters = new Stack();
private Stack arities = new Stack();
private Stack scopeStarts = new Stack();
private String classname;
private String sourcename;
//Map classWriters = new HashMacg.p();
private ClassWriter classWriter;
ClassWriter currentMultiStub = null;
int methodIndex = -1;
int multiStubCount = -1;
int innerIndex = -1;
int lastLine = -1;
/**
* Used to make determinations about non-local returns and similar flow control
*/
boolean isCompilingClosure;
/** Creates a new instance of StandardCompilerContext */
public StandardASMCompiler(String classname, String sourcename) {
this.classname = classname;
this.sourcename = sourcename;
}
public StandardASMCompiler(Node node) {
// determine new class name based on filename of incoming node
// must generate unique classnames for evals, since they could be generated many times in a given run
classname = "EVAL" + hashCode();
sourcename = "EVAL" + hashCode();
}
public Class loadClass(Ruby runtime) throws ClassNotFoundException {
JRubyClassLoader jcl = runtime.getJRubyClassLoader();
jcl.defineClass(cg.c(classname), classWriter.toByteArray());
return jcl.loadClass(cg.c(classname));
}
public void writeClass(File destination) throws IOException {
writeClass(classname, destination, classWriter);
}
private void writeClass(String classname, File destination, ClassWriter writer) throws IOException {
String fullname = classname + ".class";
String filename = null;
String path = null;
if (fullname.lastIndexOf("/") == -1) {
filename = fullname;
path = "";
} else {
filename = fullname.substring(fullname.lastIndexOf("/") + 1);
path = fullname.substring(0, fullname.lastIndexOf("/"));
}
// create dir if necessary
File pathfile = new File(destination, path);
pathfile.mkdirs();
FileOutputStream out = new FileOutputStream(new File(pathfile, filename));
out.write(writer.toByteArray());
}
public String getClassname() {
return classname;
}
public String getSourcename() {
return sourcename;
}
public ClassVisitor getClassVisitor() {
return classWriter;
}
public SkinnyMethodAdapter getMethodAdapter() {
return (SkinnyMethodAdapter)SkinnyMethodAdapters.peek();
}
public SkinnyMethodAdapter popMethodAdapter() {
return (SkinnyMethodAdapter)SkinnyMethodAdapters.pop();
}
public void pushMethodAdapter(SkinnyMethodAdapter mv) {
SkinnyMethodAdapters.push(mv);
}
public int getArity() {
return ((Integer)arities.peek()).intValue();
}
public void pushArity(int arity) {
arities.push(new Integer(arity));
}
public int popArity() {
return ((Integer)arities.pop()).intValue();
}
public void pushScopeStart(Label start) {
scopeStarts.push(start);
}
public Label popScopeStart() {
return (Label)scopeStarts.pop();
}
public void startScript() {
classWriter = new ClassWriter(true);
// Create the class with the appropriate class name and source file
classWriter.visit(V1_4, ACC_PUBLIC + ACC_SUPER, classname, null, cg.p(Object.class), new String[] {cg.p(Script.class)});
classWriter.visitSource(sourcename, null);
createConstructor();
}
public void endScript() {
// add Script#run impl, used for running this script with a specified threadcontext and self
// root method of a script is always in __load__ method
String methodName = "__file__";
SkinnyMethodAdapter mv = new SkinnyMethodAdapter(getClassVisitor().visitMethod(ACC_PUBLIC, "run", METHOD_SIGNATURE, null, null));
mv.start();
// invoke __file__ with threadcontext, self, args (null), and block (null)
// These are all +1 because run is an instance method where others are static
mv.aload(THREADCONTEXT_INDEX + 1);
mv.aload(SELF_INDEX + 1);
mv.aload(ARGS_INDEX + 1);
mv.aload(CLOSURE_INDEX + 1);
mv.invokestatic(classname, methodName, METHOD_SIGNATURE);
mv.areturn();
mv.end();
// add main impl, used for detached or command-line execution of this script with a new runtime
// root method of a script is always in stub0, method0
mv = new SkinnyMethodAdapter(getClassVisitor().visitMethod(ACC_PUBLIC | ACC_STATIC, "main", cg.sig(Void.TYPE, cg.params(String[].class)), null, null));
mv.start();
// new instance to invoke run against
mv.newobj(classname);
mv.dup();
mv.invokespecial(classname, "<init>", cg.sig(Void.TYPE));
// invoke run with threadcontext and topself
mv.invokestatic(cg.p(Ruby.class), "getDefaultInstance", cg.sig(Ruby.class));
mv.dup();
mv.invokevirtual(RUBY, "getCurrentContext", cg.sig(ThreadContext.class));
mv.swap();
mv.invokevirtual(RUBY, "getTopSelf", cg.sig(IRubyObject.class));
mv.getstatic(cg.p(IRubyObject.class), "NULL_ARRAY", cg.ci(IRubyObject[].class));
mv.getstatic(cg.p(Block.class), "NULL_BLOCK", cg.ci(Block.class));
mv.invokevirtual(classname, "run", METHOD_SIGNATURE);
mv.voidreturn();
mv.end();
}
private void createConstructor() {
ClassVisitor cv = getClassVisitor();
SkinnyMethodAdapter mv = new SkinnyMethodAdapter(cv.visitMethod(ACC_PUBLIC, "<init>", cg.sig(Void.TYPE), null, null));
mv.start();
mv.aload(0);
mv.invokespecial(cg.p(Object.class), "<init>",
cg.sig(Void.TYPE));
mv.voidreturn();
mv.end();
}
public Object beginMethod(String friendlyName, int arity) {
SkinnyMethodAdapter newMethod = new SkinnyMethodAdapter(getClassVisitor().visitMethod(ACC_PUBLIC | ACC_STATIC, friendlyName, METHOD_SIGNATURE, null, null));
pushMethodAdapter(newMethod);
newMethod.start();
// set up a local IRuby variable
newMethod.aload(THREADCONTEXT_INDEX);
invokeThreadContext("getRuntime", cg.sig(Ruby.class));
newMethod.astore(RUNTIME_INDEX);
// check arity
newMethod.ldc(new Integer(arity));
newMethod.invokestatic(cg.p(Arity.class), "createArity", cg.sig(Arity.class, cg.params(Integer.TYPE)));
loadRuntime();
newMethod.aload(ARGS_INDEX);
newMethod.invokevirtual(cg.p(Arity.class), "checkArity", cg.sig(Void.TYPE, cg.params(Ruby.class, IRubyObject[].class)));
// set visibility
newMethod.getstatic(cg.p(Visibility.class), "PRIVATE", cg.ci(Visibility.class));
newMethod.astore(VISIBILITY_INDEX);
// store the local vars in a local variable
loadThreadContext();
invokeThreadContext("getCurrentScope", cg.sig(DynamicScope.class));
newMethod.dup();
newMethod.astore(LOCAL_VARS_INDEX);
newMethod.invokevirtual(cg.p(DynamicScope.class), "getValues", cg.sig(IRubyObject[].class));
newMethod.astore(SCOPE_INDEX);
// arraycopy arguments into local vars array
newMethod.aload(LOCAL_VARS_INDEX);
newMethod.aload(ARGS_INDEX);
newMethod.ldc(new Integer(arity));
newMethod.invokevirtual(cg.p(DynamicScope.class), "setArgValues", cg.sig(Void.TYPE, cg.params(IRubyObject[].class, Integer.TYPE)));
// visit a label to start scoping for local vars in this method
Label start = new Label();
newMethod.label(start);
pushScopeStart(start);
// push down the argument count of this method
pushArity(arity);
return newMethod;
}
public void endMethod(Object token) {
assert token instanceof SkinnyMethodAdapter;
SkinnyMethodAdapter mv = (SkinnyMethodAdapter)token;
// return last value from execution
mv.areturn();
// end of variable scope
Label end = new Label();
mv.label(end);
// local variable for lvars array
mv.visitLocalVariable("lvars", cg.ci(IRubyObject[].class), null, popScopeStart(), end, LOCAL_VARS_INDEX);
mv.end();
popMethodAdapter();
popArity();
}
public void lineNumber(ISourcePosition position) {
if (lastLine == (lastLine = position.getEndLine())) return; // did not change lines for this node, don't bother relabeling
Label l = new Label();
SkinnyMethodAdapter mv = getMethodAdapter();
mv.label(l);
// line numbers are zero-based; add one for them to make sense in an editor
mv.visitLineNumber(position.getStartLine() + 1, l);
}
public void invokeAttrAssign(String name) {
SkinnyMethodAdapter mv = getMethodAdapter();
// get args[length - 1] and stuff it under the receiver
mv.dup();
mv.dup();
mv.arraylength();
mv.iconst_1();
mv.isub();
mv.arrayload();
mv.dup_x2();
mv.pop();
invokeDynamic(name, true, true, CallType.NORMAL, null, true);
// pop result, use args[length - 1] captured above
mv.pop();
}
public static IRubyObject doAttrAssign(IRubyObject receiver, IRubyObject[] args, ThreadContext context, String name, IRubyObject caller, CallType callType, Block block) {
if (receiver == caller) {
callType = CallType.VARIABLE;
}
try {
return receiver.compilerCallMethod(context, name, args, caller, callType, block);
} catch (StackOverflowError sfe) {
throw context.getRuntime().newSystemStackError("stack level too deep");
}
}
public static IRubyObject doAttrAssignIndexed(IRubyObject receiver, IRubyObject[] args, ThreadContext context, byte methodIndex, String name, IRubyObject caller, CallType callType, Block block) {
if (receiver == caller) {
callType = CallType.VARIABLE;
}
try {
return receiver.compilerCallMethodWithIndex(context, methodIndex, name, args, caller, callType, block);
} catch (StackOverflowError sfe) {
throw context.getRuntime().newSystemStackError("stack level too deep");
}
}
public static IRubyObject doInvokeDynamic(IRubyObject receiver, IRubyObject[] args, ThreadContext context, String name, IRubyObject caller, CallType callType, Block block) {
try {
return receiver.compilerCallMethod(context, name, args, caller, callType, block);
} catch (StackOverflowError sfe) {
throw context.getRuntime().newSystemStackError("stack level too deep");
}
}
public static IRubyObject doInvokeDynamicIndexed(IRubyObject receiver, IRubyObject[] args, ThreadContext context, byte methodIndex, String name, IRubyObject caller, CallType callType, Block block) {
try {
return receiver.compilerCallMethodWithIndex(context, methodIndex, name, args, caller, callType, block);
} catch (StackOverflowError sfe) {
throw context.getRuntime().newSystemStackError("stack level too deep");
}
}
public void invokeDynamic(String name, boolean hasReceiver, boolean hasArgs, CallType callType, ClosureCallback closureArg, boolean attrAssign) {
SkinnyMethodAdapter mv = getMethodAdapter();
String callSig = cg.sig(IRubyObject.class, cg.params(IRubyObject.class, IRubyObject[].class, ThreadContext.class, String.class, IRubyObject.class, CallType.class, Block.class));
String callSigIndexed = cg.sig(IRubyObject.class, cg.params(IRubyObject.class, IRubyObject[].class, ThreadContext.class, Byte.TYPE, String.class, IRubyObject.class, CallType.class, Block.class));
int index = MethodIndex.getIndex(name);
if (hasArgs) {
if (hasReceiver) {
// Call with args
// receiver already present
} else {
// FCall
// no receiver present, use self
loadSelf();
// put self under args
mv.swap();
}
} else {
if (hasReceiver) {
// receiver already present
// empty args list
mv.getstatic(cg.p(IRubyObject.class), "NULL_ARRAY", cg.ci(IRubyObject[].class));
} else {
// VCall
// no receiver present, use self
loadSelf();
// empty args list
mv.getstatic(cg.p(IRubyObject.class), "NULL_ARRAY", cg.ci(IRubyObject[].class));
}
}
loadThreadContext();
if (index != 0) {
// load method index
mv.ldc(new Integer(index));
}
mv.ldc(name);
// load self for visibility checks
loadSelf();
mv.getstatic(cg.p(CallType.class), callType.toString(), cg.ci(CallType.class));
if (closureArg == null) {
mv.getstatic(cg.p(Block.class), "NULL_BLOCK", cg.ci(Block.class));
} else {
closureArg.compile(this);
}
Label tryBegin = new Label();
Label tryEnd = new Label();
Label tryCatch = new Label();
if (closureArg != null) {
// wrap with try/catch for block flow-control exceptions
// FIXME: for flow-control from containing blocks, but it's not working right;
// stack is not as expected for invoke calls below...
//mv.trycatch(tryBegin, tryEnd, tryCatch, cg.p(JumpException.class));
mv.label(tryBegin);
}
if (attrAssign) {
if (index != 0) {
invokeUtilityMethod("doAttrAssignIndexed", callSigIndexed);
} else {
- invokeUtilityMethod("doAttrAssignDynamic", callSig);
+ invokeUtilityMethod("doAttrAssign", callSig);
}
} else {
if (index != 0) {
invokeUtilityMethod("doInvokeDynamicIndexed", callSigIndexed);
} else {
invokeUtilityMethod("doInvokeDynamic", callSig);
}
}
if (closureArg != null) {
mv.label(tryEnd);
// no physical break, terminate loop and skip catch block
Label normalEnd = new Label();
mv.go_to(normalEnd);
mv.label(tryCatch);
{
loadClosure();
invokeUtilityMethod("handleJumpException", cg.sig(IRubyObject.class, cg.params(JumpException.class, Block.class)));
}
mv.label(normalEnd);
}
}
public static IRubyObject handleJumpException(JumpException je, Block block) {
// JRUBY-530, Kernel#loop case:
if (je.isBreakInKernelLoop()) {
// consume and rethrow or just keep rethrowing?
if (block == je.getTarget()) je.setBreakInKernelLoop(false);
throw je;
}
return (IRubyObject) je.getValue();
}
public void yield(boolean hasArgs) {
loadClosure();
SkinnyMethodAdapter method = getMethodAdapter();
if (hasArgs) {
method.swap();
loadThreadContext();
method.swap();
// args now here
} else {
loadThreadContext();
// empty args
method.aconst_null();
}
method.aconst_null();
method.aconst_null();
method.ldc(Boolean.FALSE);
method.invokevirtual(cg.p(Block.class), "yield", cg.sig(IRubyObject.class, cg.params(ThreadContext.class, IRubyObject.class, IRubyObject.class, RubyModule.class, Boolean.TYPE)));
}
private void invokeIRubyObject(String methodName, String signature) {
getMethodAdapter().invokeinterface(IRUBYOBJECT, methodName, signature);
}
public void loadThreadContext() {
getMethodAdapter().aload(THREADCONTEXT_INDEX);
}
public void loadClosure() {
loadThreadContext();
invokeThreadContext("getFrameBlock", cg.sig(Block.class));
}
public void loadSelf() {
getMethodAdapter().aload(SELF_INDEX);
}
public void loadRuntime() {
getMethodAdapter().aload(RUNTIME_INDEX);
}
public void loadVisibility() {
getMethodAdapter().aload(VISIBILITY_INDEX);
}
public void loadNil() {
loadRuntime();
invokeIRuby("getNil", cg.sig(IRubyObject.class));
}
public void loadSymbol(String symbol) {
loadRuntime();
SkinnyMethodAdapter mv = getMethodAdapter();
mv.ldc(symbol);
invokeIRuby("newSymbol", cg.sig(RubySymbol.class, cg.params(String.class)));
}
public void loadObject() {
loadRuntime();
invokeIRuby("getObject", cg.sig(RubyClass.class, cg.params()));
}
public void consumeCurrentValue() {
getMethodAdapter().pop();
}
public void duplicateCurrentValue() {
getMethodAdapter().dup();
}
public void swapValues() {
getMethodAdapter().swap();
}
public void retrieveSelf() {
loadSelf();
}
public void retrieveSelfClass() {
loadSelf();
invokeIRubyObject("getMetaClass", cg.sig(RubyClass.class));
}
public void assignLocalVariable(int index) {
SkinnyMethodAdapter mv = getMethodAdapter();
mv.dup();
mv.aload(SCOPE_INDEX);
mv.swap();
mv.ldc(new Integer(index));
mv.swap();
mv.arraystore();
}
public void assignLastLine() {
SkinnyMethodAdapter mv = getMethodAdapter();
mv.dup();
loadThreadContext();
invokeThreadContext("getCurrentScope", cg.sig(DynamicScope.class));
mv.swap();
mv.invokevirtual(cg.p(DynamicScope.class), "setLastLine", cg.sig(Void.TYPE, cg.params(IRubyObject.class)));
}
public void assignLocalVariableBlockArg(int argIndex, int varIndex) {
SkinnyMethodAdapter mv = getMethodAdapter();
// this is copying values, but it would be more efficient to just use the args in-place
mv.aload(LOCAL_VARS_INDEX);
mv.ldc(new Integer(varIndex));
mv.aload(ARGS_INDEX);
mv.ldc(new Integer(argIndex));
mv.arrayload();
mv.iconst_0();
mv.invokevirtual(cg.p(DynamicScope.class), "setValue", cg.sig(Void.TYPE, cg.params(Integer.TYPE, IRubyObject.class, Integer.TYPE)));
}
public void retrieveLocalVariable(int index) {
SkinnyMethodAdapter mv = getMethodAdapter();
mv.aload(SCOPE_INDEX);
mv.ldc(new Integer(index));
mv.arrayload();
}
public void retrieveLastLine() {
SkinnyMethodAdapter mv = getMethodAdapter();
loadThreadContext();
invokeThreadContext("getCurrentScope", cg.sig(DynamicScope.class));
mv.invokevirtual(cg.p(DynamicScope.class), "getLastLine", cg.sig(IRubyObject.class));
loadRuntime();
invokeUtilityMethod("nullToNil", cg.sig(IRubyObject.class, cg.params(IRubyObject.class, Ruby.class)));
}
public void retrieveBackRef() {
SkinnyMethodAdapter mv = getMethodAdapter();
loadThreadContext();
invokeThreadContext("getCurrentScope", cg.sig(DynamicScope.class));
mv.invokevirtual(cg.p(DynamicScope.class), "getBackRef", cg.sig(IRubyObject.class));
loadRuntime();
invokeUtilityMethod("nullToNil", cg.sig(IRubyObject.class, cg.params(IRubyObject.class, Ruby.class)));
}
public static IRubyObject nullToNil(IRubyObject value, Ruby runtime) {
return value != null ? value : runtime.getNil();
}
public void assignLocalVariable(int index, int depth) {
if (depth == 0) {
assignLocalVariable(index);
return;
}
SkinnyMethodAdapter mv = getMethodAdapter();
mv.dup();
mv.aload(LOCAL_VARS_INDEX);
mv.swap();
mv.ldc(new Integer(index));
mv.swap();
mv.ldc(new Integer(depth));
mv.invokevirtual(cg.p(DynamicScope.class), "setValue", cg.sig(Void.TYPE, cg.params(Integer.TYPE, IRubyObject.class, Integer.TYPE)));
}
public void assignLocalVariableBlockArg(int argIndex, int varIndex, int depth) {
if (depth == 0) {
assignLocalVariableBlockArg(argIndex, varIndex);
return;
}
SkinnyMethodAdapter mv = getMethodAdapter();
mv.aload(LOCAL_VARS_INDEX);
mv.ldc(new Integer(varIndex));
mv.aload(ARGS_INDEX);
mv.ldc(new Integer(argIndex));
mv.arrayload();
mv.ldc(new Integer(depth));
mv.invokevirtual(cg.p(DynamicScope.class), "setValue", cg.sig(Void.TYPE, cg.params(Integer.TYPE, IRubyObject.class, Integer.TYPE)));
}
public void retrieveLocalVariable(int index, int depth) {
if (depth == 0) {
retrieveLocalVariable(index);
return;
}
SkinnyMethodAdapter mv = getMethodAdapter();
mv.aload(LOCAL_VARS_INDEX);
mv.ldc(new Integer(index));
mv.ldc(new Integer(depth));
mv.invokevirtual(cg.p(DynamicScope.class), "getValue", cg.sig(IRubyObject.class, cg.params(Integer.TYPE, Integer.TYPE)));
}
public void assignConstantInCurrent(String name) {
SkinnyMethodAdapter mv = getMethodAdapter();
loadThreadContext();
mv.ldc(name);
mv.dup2_x1();
mv.pop2();
invokeThreadContext("setConstantInCurrent", cg.sig(IRubyObject.class, cg.params(String.class, IRubyObject.class)));
}
public void assignConstantInModule(String name) {
SkinnyMethodAdapter mv = getMethodAdapter();
loadThreadContext();
mv.ldc(name);
mv.swap2();
invokeThreadContext("setConstantInCurrent", cg.sig(IRubyObject.class, cg.params(String.class, RubyModule.class, IRubyObject.class)));
}
public void assignConstantInObject(String name) {
SkinnyMethodAdapter mv = getMethodAdapter();
// load Object under value
loadRuntime();
invokeIRuby("getObject", cg.sig(RubyClass.class, cg.params()));
mv.swap();
assignConstantInModule(name);
}
public void retrieveConstant(String name) {
SkinnyMethodAdapter mv = getMethodAdapter();
loadThreadContext();
mv.ldc(name);
invokeThreadContext("getConstant", cg.sig(IRubyObject.class, cg.params(String.class)));
}
public void retrieveClassVariable(String name) {
loadThreadContext();
loadRuntime();
loadSelf();
getMethodAdapter().ldc(name);
invokeUtilityMethod("fetchClassVariable", cg.sig(IRubyObject.class, cg.params(ThreadContext.class, Ruby.class, IRubyObject.class, String.class)));
}
public void assignClassVariable(String name) {
SkinnyMethodAdapter method = getMethodAdapter();
loadThreadContext();
method.swap();
loadRuntime();
method.swap();
loadSelf();
method.swap();
getMethodAdapter().ldc(name);
method.swap();
invokeUtilityMethod("setClassVariable", cg.sig(IRubyObject.class, cg.params(ThreadContext.class, Ruby.class, IRubyObject.class, String.class, IRubyObject.class)));
}
public static IRubyObject fetchClassVariable(ThreadContext context, Ruby runtime, IRubyObject self, String name) {
RubyModule rubyClass = EvaluationState.getClassVariableBase(context, runtime);
if (rubyClass == null) {
rubyClass = self.getMetaClass();
}
return rubyClass.getClassVar(name);
}
public static IRubyObject setClassVariable(ThreadContext context, Ruby runtime, IRubyObject self, String name, IRubyObject value) {
RubyModule rubyClass = EvaluationState.getClassVariableBase(context, runtime);
if (rubyClass == null) {
rubyClass = self.getMetaClass();
}
rubyClass.setClassVar(name, value);
return value;
}
private void loadScope(int depth) {
SkinnyMethodAdapter mv = getMethodAdapter();
// get the appropriate array out of the scopes
mv.aload(SCOPE_INDEX);
mv.ldc(new Integer(depth - 1));
mv.arrayload();
}
public void createNewFloat(double value) {
SkinnyMethodAdapter mv = getMethodAdapter();
loadRuntime();
mv.ldc(new Double(value));
invokeIRuby("newFloat", cg.sig(RubyFloat.class, cg.params(Double.TYPE)));
}
public void createNewFixnum(long value) {
SkinnyMethodAdapter mv = getMethodAdapter();
loadRuntime();
mv.ldc(new Long(value));
invokeIRuby("newFixnum", cg.sig(RubyFixnum.class, cg.params(Long.TYPE)));
}
public void createNewBignum(BigInteger value) {
SkinnyMethodAdapter mv = getMethodAdapter();
loadRuntime();
mv.ldc(value.toString());
mv.invokestatic(cg.p(RubyBignum.class) , "newBignum", cg.sig(RubyBignum.class,cg.params(Ruby.class,String.class)));
}
public void createNewString(ArrayCallback callback, int count) {
SkinnyMethodAdapter mv = getMethodAdapter();
loadRuntime();
invokeIRuby("newString", cg.sig(RubyString.class, cg.params()));
for(int i = 0; i < count; i++) {
callback.nextValue(this, null, i);
mv.invokevirtual(cg.p(RubyString.class), "append", cg.sig(RubyString.class, cg.params(IRubyObject.class)));
}
}
public void createNewString(ByteList value) {
SkinnyMethodAdapter mv = getMethodAdapter();
// FIXME: this is sub-optimal, storing string value in a java.lang.String again
loadRuntime();
mv.ldc(value.toString());
invokeIRuby("newString", cg.sig(RubyString.class, cg.params(String.class)));
}
public void createNewSymbol(String name) {
loadRuntime();
getMethodAdapter().ldc(name);
invokeIRuby("newSymbol", cg.sig(RubySymbol.class, cg.params(String.class)));
}
public void createNewArray() {
SkinnyMethodAdapter mv = getMethodAdapter();
loadRuntime();
// put under object array already present
mv.swap();
invokeIRuby("newArrayNoCopy", cg.sig(RubyArray.class, cg.params(IRubyObject[].class)));
}
public void createEmptyArray() {
SkinnyMethodAdapter mv = getMethodAdapter();
loadRuntime();
invokeIRuby("newArray", cg.sig(RubyArray.class, cg.params()));
}
public void createObjectArray(Object[] sourceArray, ArrayCallback callback) {
buildObjectArray(IRUBYOBJECT, sourceArray, callback);
}
private void buildObjectArray(String type, Object[] sourceArray, ArrayCallback callback) {
SkinnyMethodAdapter mv = getMethodAdapter();
mv.ldc(new Integer(sourceArray.length));
mv.anewarray(type);
for (int i = 0; i < sourceArray.length; i++) {
mv.dup();
mv.ldc(new Integer(i));
callback.nextValue(this, sourceArray, i);
mv.arraystore();
}
}
public void createEmptyHash() {
SkinnyMethodAdapter mv = getMethodAdapter();
loadRuntime();
mv.invokestatic(cg.p(RubyHash.class), "newHash", cg.sig(RubyHash.class, cg.params(Ruby.class)));
}
public void createNewHash(Object elements, ArrayCallback callback, int keyCount) {
SkinnyMethodAdapter mv = getMethodAdapter();
loadRuntime();
// create a new hashmap
mv.newobj(cg.p(HashMap.class));
mv.dup();
mv.invokespecial(cg.p(HashMap.class), "<init>", cg.sig(Void.TYPE));
for (int i = 0; i < keyCount; i++) {
mv.dup();
callback.nextValue(this, elements, i);
mv.invokevirtual(cg.p(HashMap.class), "put", cg.sig(Object.class, cg.params(Object.class, Object.class)));
mv.pop();
}
loadNil();
mv.invokestatic(cg.p(RubyHash.class), "newHash", cg.sig(RubyHash.class, cg.params(Ruby.class, Map.class, IRubyObject.class)));
}
public void createNewRange(boolean isExclusive) {
SkinnyMethodAdapter mv = getMethodAdapter();
loadRuntime();
mv.dup_x2();
mv.pop();
mv.ldc(new Boolean(isExclusive));
mv.invokestatic(cg.p(RubyRange.class), "newRange", cg.sig(RubyRange.class, cg.params(Ruby.class, IRubyObject.class, IRubyObject.class, Boolean.TYPE)));
}
/**
* Invoke IRubyObject.isTrue
*/
private void isTrue() {
invokeIRubyObject("isTrue", cg.sig(Boolean.TYPE));
}
public void performBooleanBranch(BranchCallback trueBranch, BranchCallback falseBranch) {
Label afterJmp = new Label();
Label falseJmp = new Label();
SkinnyMethodAdapter mv = getMethodAdapter();
// call isTrue on the result
isTrue();
mv.ifeq(falseJmp); // EQ == 0 (i.e. false)
trueBranch.branch(this);
mv.go_to(afterJmp);
// FIXME: optimize for cases where we have no false branch
mv.label(falseJmp);
falseBranch.branch(this);
mv.label(afterJmp);
}
public void performLogicalAnd(BranchCallback longBranch) {
Label afterJmp = new Label();
Label falseJmp = new Label();
SkinnyMethodAdapter mv = getMethodAdapter();
// dup it since we need to return appropriately if it's false
mv.dup();
// call isTrue on the result
isTrue();
mv.ifeq(falseJmp); // EQ == 0 (i.e. false)
// pop the extra result and replace with the send part of the AND
mv.pop();
longBranch.branch(this);
mv.label(falseJmp);
}
public void performLogicalOr(BranchCallback longBranch) {
Label afterJmp = new Label();
Label falseJmp = new Label();
SkinnyMethodAdapter mv = getMethodAdapter();
// dup it since we need to return appropriately if it's false
mv.dup();
// call isTrue on the result
isTrue();
mv.ifne(falseJmp); // EQ == 0 (i.e. false)
// pop the extra result and replace with the send part of the AND
mv.pop();
longBranch.branch(this);
mv.label(falseJmp);
}
public void performBooleanLoop(BranchCallback condition, BranchCallback body, boolean checkFirst) {
// FIXME: handle next/continue, break, etc
SkinnyMethodAdapter mv = getMethodAdapter();
Label tryBegin = new Label();
Label tryEnd = new Label();
Label tryCatch = new Label();
mv.trycatch(tryBegin, tryEnd, tryCatch, cg.p(JumpException.class));
mv.label(tryBegin);
{
Label endJmp = new Label();
if (checkFirst) {
// calculate condition
condition.branch(this);
// call isTrue on the result
isTrue();
mv.ifeq(endJmp); // EQ == 0 (i.e. false)
}
Label topJmp = new Label();
mv.label(topJmp);
body.branch(this);
// clear result after each loop
mv.pop();
// calculate condition
condition.branch(this);
// call isTrue on the result
isTrue();
mv.ifne(topJmp); // NE == nonzero (i.e. true)
if (checkFirst) {
mv.label(endJmp);
}
}
mv.label(tryEnd);
// no physical break, terminate loop and skip catch block
Label normalBreak = new Label();
mv.go_to(normalBreak);
mv.label(tryCatch);
{
mv.dup();
mv.invokevirtual(cg.p(JumpException.class), "getJumpType", cg.sig(JumpException.JumpType.class));
mv.invokevirtual(cg.p(JumpException.JumpType.class), "getTypeId", cg.sig(Integer.TYPE));
Label tryDefault = new Label();
Label breakLabel = new Label();
mv.lookupswitch(tryDefault, new int[] {JumpException.JumpType.BREAK}, new Label[] {breakLabel});
// default is to just re-throw unhandled exception
mv.label(tryDefault);
mv.athrow();
// break just terminates the loop normally, unless it's a block break...
mv.label(breakLabel);
// JRUBY-530 behavior
mv.dup();
mv.invokevirtual(cg.p(JumpException.class), "getTarget", cg.sig(Object.class));
loadClosure();
Label notBlockBreak = new Label();
mv.if_acmpne(notBlockBreak);
mv.dup();
mv.aconst_null();
mv.invokevirtual(cg.p(JumpException.class), "setTarget", cg.sig(Void.TYPE, cg.params(Object.class)));
mv.athrow();
mv.label(notBlockBreak);
// target is not == closure, normal loop exit, pop remaining exception object
mv.pop();
}
mv.label(normalBreak);
loadNil();
}
public void performReturn() {
if (isCompilingClosure) {
throw new NotCompilableException("Can't compile non-local return");
}
// otherwise, just do a local return
SkinnyMethodAdapter mv = getMethodAdapter();
mv.areturn();
}
public static CompiledBlock createBlock(ThreadContext context, IRubyObject self, int arity, String[] staticScopeNames, CompiledBlockCallback callback) {
StaticScope staticScope = new BlockStaticScope(context.getCurrentScope().getStaticScope(), staticScopeNames);
return new CompiledBlock(context, self, Arity.createArity(arity), new DynamicScope(staticScope, context.getCurrentScope()), callback);
}
public void createNewClosure(StaticScope scope, int arity, ClosureCallback body, ClosureCallback args) {
// FIXME: This isn't quite done yet; waiting to have full support for passing closures so we can test it
ClassVisitor cv = getClassVisitor();
SkinnyMethodAdapter method;
String closureMethodName = "closure" + ++innerIndex;
String closureFieldName = "_" + closureMethodName;
// declare the field
cv.visitField(ACC_PRIVATE | ACC_STATIC, closureFieldName, cg.ci(CompiledBlockCallback.class), null, null);
////////////////////////////
// closure implementation
method = new SkinnyMethodAdapter(cv.visitMethod(ACC_PUBLIC | ACC_STATIC, closureMethodName, CLOSURE_SIGNATURE, null, null));
// FIXME: I don't like this pre/post state management.
boolean previousIsCompilingClosure = isCompilingClosure;
isCompilingClosure = true;
pushMethodAdapter(method);
method.start();
// store the local vars in a local variable
loadThreadContext();
invokeThreadContext("getCurrentScope", cg.sig(DynamicScope.class));
method.dup();
method.astore(LOCAL_VARS_INDEX);
method.invokevirtual(cg.p(DynamicScope.class), "getValues", cg.sig(IRubyObject[].class));
method.astore(SCOPE_INDEX);
// set up a local IRuby variable
method.aload(THREADCONTEXT_INDEX);
invokeThreadContext("getRuntime", cg.sig(Ruby.class));
method.astore(RUNTIME_INDEX);
// set up block arguments
args.compile(this);
// start of scoping for closure's vars
Label start = new Label();
method.label(start);
// visit the body of the closure
body.compile(this);
method.areturn();
// end of scoping for closure's vars
Label end = new Label();
method.label(end);
method.end();
popMethodAdapter();
// FIXME: I don't like this pre/post state management.
isCompilingClosure = previousIsCompilingClosure;
method = getMethodAdapter();
// Done with closure compilation
/////////////////////////////////////////////////////////////////////////////
// Now, store a compiled block object somewhere we can access it in the future
// in current method, load the field to see if we've created a BlockCallback yet
method.getstatic(classname, closureFieldName, cg.ci(CompiledBlockCallback.class));
Label alreadyCreated = new Label();
method.ifnonnull(alreadyCreated);
// no callback, construct it
getCallbackFactory();
method.ldc(closureMethodName);
method.invokevirtual(cg.p(CallbackFactory.class), "getBlockCallback", cg.sig(CompiledBlockCallback.class, cg.params(String.class)));
method.putstatic(classname, closureFieldName, cg.ci(CompiledBlockCallback.class));
method.label(alreadyCreated);
// Construct the block for passing to the target method
loadThreadContext();
loadSelf();
method.ldc(new Integer(arity));
buildStaticScopeNames(method, scope);
method.getstatic(classname, closureFieldName, cg.ci(CompiledBlockCallback.class));
invokeUtilityMethod("createBlock", cg.sig(CompiledBlock.class, cg.params(ThreadContext.class, IRubyObject.class, Integer.TYPE, String[].class, CompiledBlockCallback.class)));
}
private void buildStaticScopeNames(SkinnyMethodAdapter method, StaticScope scope) {
// construct static scope list of names
method.ldc(new Integer(scope.getNumberOfVariables()));
method.anewarray(cg.p(String.class));
for (int i = 0; i < scope.getNumberOfVariables(); i++) {
method.dup();
method.ldc(new Integer(i));
method.ldc(scope.getVariables()[i]);
method.arraystore();
}
}
/**
* This is for utility methods used by the compiler, to reduce the amount of code generation necessary.
* Most of these currently live on StandardASMCompiler, but should be moved to a more appropriate location.
*/
private void invokeUtilityMethod(String methodName, String signature) {
getMethodAdapter().invokestatic(cg.p(StandardASMCompiler.class), methodName, signature);
}
private void invokeThreadContext(String methodName, String signature) {
SkinnyMethodAdapter mv = getMethodAdapter();
mv.invokevirtual(THREADCONTEXT, methodName, signature);
}
private void invokeIRuby(String methodName, String signature) {
SkinnyMethodAdapter mv = getMethodAdapter();
mv.invokevirtual(RUBY, methodName, signature);
}
private void getCallbackFactory() {
loadRuntime();
SkinnyMethodAdapter mv = getMethodAdapter();
mv.ldc(classname);
mv.invokestatic(cg.p(Class.class), "forName", cg.sig(Class.class, cg.params(String.class)));
invokeIRuby("callbackFactory", cg.sig(CallbackFactory.class, cg.params(Class.class)));
}
private void getRubyClass() {
loadSelf();
// FIXME: This doesn't seem *quite* right. If actually within a class...end, is self.getMetaClass the correct class? should be self, no?
invokeIRubyObject("getMetaClass", cg.sig(RubyClass.class));
}
private void getCRef() {
loadThreadContext();
// FIXME: This doesn't seem *quite* right. If actually within a class...end, is self.getMetaClass the correct class? should be self, no?
invokeThreadContext("peekCRef", cg.sig(SinglyLinkedList.class));
}
private void newTypeError(String error) {
loadRuntime();
getMethodAdapter().ldc(error);
invokeIRuby("newTypeError", cg.sig(RaiseException.class, cg.params(String.class)));
}
private void getCurrentVisibility() {
loadThreadContext();
invokeThreadContext("getCurrentVisibility", cg.sig(Visibility.class));
}
private void println() {
SkinnyMethodAdapter mv = getMethodAdapter();
mv.dup();
mv.getstatic(cg.p(System.class), "out", cg.ci(PrintStream.class));
mv.swap();
mv.invokevirtual(cg.p(PrintStream.class), "println", cg.sig(Void.TYPE, cg.params(Object.class)));
}
public void defineAlias(String newName, String oldName) {
getRubyClass();
getMethodAdapter().ldc(newName);
getMethodAdapter().ldc(oldName);
getMethodAdapter().invokevirtual(cg.p(RubyModule.class), "defineAlias", cg.sig(Void.TYPE,cg.params(String.class,String.class)));
loadNil();
// TODO: should call method_added, and possibly push nil.
}
public static IRubyObject def(ThreadContext context, Visibility visibility, IRubyObject self, Class compiledClass, String name, String javaName, String[] scopeNames, int arity) {
Ruby runtime = context.getRuntime();
// FIXME: This is what the old def did, but doesn't work in the compiler for top-level methods. Hmm.
RubyModule containingClass = context.getRubyClass();
//RubyModule containingClass = self.getMetaClass();
if (containingClass == null) {
throw runtime.newTypeError("No class to add method.");
}
if (containingClass == runtime.getObject() && name == "initialize") {
runtime.getWarnings().warn("redefining Object#initialize may cause infinite loop");
}
SinglyLinkedList cref = context.peekCRef();
StaticScope scope = new LocalStaticScope(null, scopeNames);
MethodFactory factory = MethodFactory.createFactory();
DynamicMethod method = null;
if (name == "initialize" || visibility.isModuleFunction() || context.isTopLevel()) {
method = factory.getCompiledMethod(containingClass, compiledClass, javaName, Arity.createArity(arity), Visibility.PRIVATE, cref, scope);
} else {
method = factory.getCompiledMethod(containingClass, compiledClass, javaName, Arity.createArity(arity), visibility, cref, scope);
}
containingClass.addMethod(name, method);
if (visibility.isModuleFunction()) {
containingClass.getSingletonClass().addMethod(
name,
new WrapperMethod(containingClass.getSingletonClass(), method,
Visibility.PUBLIC));
containingClass.callMethod(context, "singleton_method_added", runtime.newSymbol(name));
}
// 'class << state.self' and 'class << obj' uses defn as opposed to defs
if (containingClass.isSingleton()) {
((MetaClass) containingClass).getAttachedObject().callMethod(
context, "singleton_method_added", runtime.newSymbol(name));
} else {
containingClass.callMethod(context, "method_added", runtime.newSymbol(name));
}
return runtime.getNil();
}
public void defineNewMethod(String name, int arity, StaticScope scope, ClosureCallback body) {
if (isCompilingClosure) {
throw new NotCompilableException("Can't compile def within closure yet");
}
// TODO: build arg list based on number of args, optionals, etc
++methodIndex;
String methodName = cg.cleanJavaIdentifier(name) + "__" + methodIndex;
beginMethod(methodName, arity);
SkinnyMethodAdapter mv = getMethodAdapter();
// callback to fill in method body
body.compile(this);
endMethod(mv);
// return to previous method
mv = getMethodAdapter();
// prepare to call "def" utility method to handle def logic
loadThreadContext();
loadVisibility();
loadSelf();
// load the class we're creating, for binding purposes
mv.ldc(classname.replace('/', '.'));
mv.invokestatic(cg.p(Class.class), "forName", cg.sig(Class.class, cg.params(String.class)));
mv.ldc(name);
mv.ldc(methodName);
buildStaticScopeNames(mv, scope);
mv.ldc(new Integer(arity));
mv.invokestatic(cg.p(StandardASMCompiler.class),
"def",
cg.sig(IRubyObject.class, cg.params(ThreadContext.class, Visibility.class, IRubyObject.class, Class.class, String.class, String.class, String[].class, Integer.TYPE)));
}
public void loadFalse() {
loadRuntime();
invokeIRuby("getFalse", cg.sig(RubyBoolean.class));
}
public void loadTrue() {
loadRuntime();
invokeIRuby("getTrue", cg.sig(RubyBoolean.class));
}
public void retrieveInstanceVariable(String name) {
loadSelf();
SkinnyMethodAdapter mv = getMethodAdapter();
mv.ldc(name);
invokeIRubyObject("getInstanceVariable", cg.sig(IRubyObject.class, cg.params(String.class)));
// check if it's null; if so, load nil
mv.dup();
Label notNull = new Label();
mv.ifnonnull(notNull);
// pop the dup'ed null
mv.pop();
// replace it with nil
loadNil();
mv.label(notNull);
}
public void assignInstanceVariable(String name) {
SkinnyMethodAdapter mv = getMethodAdapter();
loadSelf();
mv.swap();
mv.ldc(name);
mv.swap();
invokeIRubyObject("setInstanceVariable", cg.sig(IRubyObject.class, cg.params(String.class, IRubyObject.class)));
}
public void assignInstanceVariableBlockArg(int argIndex, String name) {
SkinnyMethodAdapter mv = getMethodAdapter();
loadSelf();
mv.ldc(name);
mv.aload(ARGS_INDEX);
mv.ldc(new Integer(argIndex));
mv.arrayload();
invokeIRubyObject("setInstanceVariable", cg.sig(IRubyObject.class, cg.params(String.class, IRubyObject.class)));
}
public void retrieveGlobalVariable(String name) {
loadRuntime();
SkinnyMethodAdapter mv = getMethodAdapter();
invokeIRuby("getGlobalVariables", cg.sig(GlobalVariables.class));
mv.ldc(name);
mv.invokevirtual(cg.p(GlobalVariables.class), "get", cg.sig(IRubyObject.class, cg.params(String.class)));
}
public void assignGlobalVariable(String name) {
loadRuntime();
SkinnyMethodAdapter mv = getMethodAdapter();
invokeIRuby("getGlobalVariables", cg.sig(GlobalVariables.class));
mv.swap();
mv.ldc(name);
mv.swap();
mv.invokevirtual(cg.p(GlobalVariables.class), "set", cg.sig(IRubyObject.class, cg.params(String.class, IRubyObject.class)));
}
public void assignGlobalVariableBlockArg(int argIndex, String name) {
loadRuntime();
SkinnyMethodAdapter mv = getMethodAdapter();
invokeIRuby("getGlobalVariables", cg.sig(GlobalVariables.class));
mv.ldc(name);
mv.aload(ARGS_INDEX);
mv.ldc(new Integer(argIndex));
mv.arrayload();
mv.invokevirtual(cg.p(GlobalVariables.class), "set", cg.sig(IRubyObject.class, cg.params(String.class, IRubyObject.class)));
}
public void negateCurrentValue() {
SkinnyMethodAdapter mv = getMethodAdapter();
isTrue();
Label isTrue = new Label();
Label end = new Label();
mv.ifne(isTrue);
loadTrue();
mv.go_to(end);
mv.label(isTrue);
loadFalse();
mv.label(end);
}
public void splatCurrentValue() {
SkinnyMethodAdapter method = getMethodAdapter();
method.invokestatic(cg.p(EvaluationState.class), "splatValue", cg.sig(IRubyObject.class, cg.params(IRubyObject.class)));
}
public void singlifySplattedValue() {
SkinnyMethodAdapter method = getMethodAdapter();
method.invokestatic(cg.p(EvaluationState.class), "aValueSplat", cg.sig(IRubyObject.class, cg.params(IRubyObject.class)));
}
public void ensureRubyArray() {
SkinnyMethodAdapter method = getMethodAdapter();
method.invokestatic(cg.p(StandardASMCompiler.class), "ensureRubyArray", cg.sig(RubyArray.class, cg.params(IRubyObject.class)));
}
public static RubyArray ensureRubyArray(IRubyObject value) {
if (!(value instanceof RubyArray)) {
value = RubyArray.newArray(value.getRuntime(), value);
}
return (RubyArray)value;
}
public void forEachInValueArray(int start, int count, Object source, ArrayCallback callback) {
SkinnyMethodAdapter method = getMethodAdapter();
Label noMoreArrayElements = new Label();
for (; start < count; start++) {
// confirm we're not past the end of the array
method.dup(); // dup the original array object
method.invokevirtual(cg.p(RubyArray.class), "getLength", cg.sig(Integer.TYPE, cg.params()));
method.ldc(new Integer(start));
method.ifle(noMoreArrayElements); // if length <= start, end loop
// extract item from array
method.dup(); // dup the original array object
method.ldc(new Integer(start)); // index for the item
method.invokevirtual(cg.p(RubyArray.class), "entry",
cg.sig(IRubyObject.class, cg.params(Long.TYPE))); // extract item
callback.nextValue(this, source, start);
}
method.label(noMoreArrayElements);
}
public void loadInteger(int value) {
throw new UnsupportedOperationException("Not supported yet.");
}
public void performGEBranch(BranchCallback trueBranch,
BranchCallback falseBranch) {
throw new UnsupportedOperationException("Not supported yet.");
}
public void performGTBranch(BranchCallback trueBranch,
BranchCallback falseBranch) {
throw new UnsupportedOperationException("Not supported yet.");
}
public void performLEBranch(BranchCallback trueBranch,
BranchCallback falseBranch) {
throw new UnsupportedOperationException("Not supported yet.");
}
public void performLTBranch(BranchCallback trueBranch,
BranchCallback falseBranch) {
throw new UnsupportedOperationException("Not supported yet.");
}
public void loadRubyArraySize() {
throw new UnsupportedOperationException("Not supported yet.");
}
public void issueBreakEvent() {
SkinnyMethodAdapter mv = getMethodAdapter();
mv.newobj(cg.p(JumpException.class));
mv.dup();
mv.getstatic(cg.p(JumpException.JumpType.class), "BreakJump", cg.ci(JumpException.JumpType.class));
mv.invokespecial(cg.p(JumpException.class), "<init>", cg.sig(Void.TYPE, cg.params(JumpException.JumpType.class)));
// set result into jump exception
mv.dup_x1();
mv.swap();
mv.invokevirtual(cg.p(JumpException.class), "setValue", cg.sig(Void.TYPE, cg.params(Object.class)));
mv.athrow();
}
public void asString() {
SkinnyMethodAdapter mv = getMethodAdapter();
mv.invokeinterface(cg.p(IRubyObject.class), "asString", cg.sig(RubyString.class, cg.params()));
}
public void nthRef(int match) {
SkinnyMethodAdapter mv = getMethodAdapter();
mv.ldc(new Integer(match));
loadThreadContext();
invokeThreadContext("getBackref", cg.sig(IRubyObject.class, cg.params()));
mv.invokestatic(cg.p(RubyRegexp.class), "nth_match", cg.sig(IRubyObject.class, cg.params(Integer.TYPE,IRubyObject.class)));
}
public void match() {
SkinnyMethodAdapter mv = getMethodAdapter();
mv.invokevirtual(cg.p(RubyRegexp.class), "match2", cg.sig(IRubyObject.class, cg.params()));
}
public void match2() {
SkinnyMethodAdapter mv = getMethodAdapter();
mv.invokevirtual(cg.p(RubyRegexp.class), "match", cg.sig(IRubyObject.class, cg.params(IRubyObject.class)));
}
public void match3() {
SkinnyMethodAdapter mv = getMethodAdapter();
mv.dup();
mv.visitTypeInsn(INSTANCEOF, cg.p(RubyString.class));
Label l0 = new Label();
mv.visitJumpInsn(IFEQ, l0);
mv.invokevirtual(cg.p(RubyRegexp.class), "match", cg.sig(IRubyObject.class, cg.params(IRubyObject.class)));
Label l1 = new Label();
mv.visitJumpInsn(GOTO, l1);
mv.visitLabel(l0);
mv.swap();
loadThreadContext();
mv.swap();
mv.ldc("=~");
mv.swap();
mv.invokeinterface(cg.p(IRubyObject.class), "callMethod", cg.sig(IRubyObject.class, cg.params(ThreadContext.class, String.class, IRubyObject.class)));
mv.visitLabel(l1);
}
private int constants = 0;
private String getNewConstant(String type, String name_prefix) {
ClassVisitor cv = getClassVisitor();
String realName;
synchronized(this) {
realName = name_prefix + constants++;
}
// declare the field
cv.visitField(ACC_PRIVATE|ACC_STATIC, realName, type, null, null).visitEnd();
return realName;
}
private final static org.jruby.RegexpTranslator TRANS = new org.jruby.RegexpTranslator();
public static int regexpLiteralFlags(int options) {
return TRANS.flagsFor(options,0);
}
public static Pattern regexpLiteral(Ruby runtime, String ptr, int options) {
try {
return TRANS.translate(ptr, options, 0);
} catch(jregex.PatternSyntaxException e) {
throw runtime.newRegexpError(e.getMessage());
}
}
public void createNewRegexp(final ByteList value, final int options, final String lang) {
SkinnyMethodAdapter mv = getMethodAdapter();
String name = getNewConstant(cg.ci(Pattern.class),"literal_re_");
String name_flags = getNewConstant(cg.ci(Integer.TYPE),"literal_re_flags_");
loadRuntime();
// load string, for Regexp#source and Regexp#inspect
mv.ldc(value.toString());
// in current method, load the field to see if we've created a Pattern yet
mv.visitFieldInsn(GETSTATIC, classname, name, cg.ci(Pattern.class));
mv.dup();
Label alreadyCreated = new Label();
mv.ifnonnull(alreadyCreated);
mv.pop();
mv.ldc(new Integer(options));
invokeUtilityMethod("regexpLiteralFlags",cg.sig(Integer.TYPE,cg.params(Integer.TYPE)));
mv.visitFieldInsn(PUTSTATIC, classname, name_flags, cg.ci(Integer.TYPE));
loadRuntime();
mv.ldc(value.toString());
mv.ldc(new Integer(options));
invokeUtilityMethod("regexpLiteral",cg.sig(Pattern.class,cg.params(Ruby.class,String.class,Integer.TYPE)));
mv.dup();
mv.visitFieldInsn(PUTSTATIC, classname, name, cg.ci(Pattern.class));
mv.label(alreadyCreated);
mv.visitFieldInsn(GETSTATIC, classname, name_flags, cg.ci(Integer.TYPE));
if(null == lang) {
mv.aconst_null();
} else {
mv.ldc(lang);
}
mv.invokestatic(cg.p(RubyRegexp.class), "newRegexp", cg.sig(RubyRegexp.class, cg.params(Ruby.class, String.class, Pattern.class, Integer.TYPE, String.class)));
}
public void defineClass(String name, StaticScope staticScope, ClosureCallback superCallback, ClosureCallback pathCallback, ClosureCallback bodyCallback) {
// TODO: build arg list based on number of args, optionals, etc
++methodIndex;
String methodName = "rubyclass__" + cg.cleanJavaIdentifier(name) + "__" + methodIndex;
beginMethod(methodName, 0);
SkinnyMethodAdapter mv = getMethodAdapter();
// class def bodies default to public visibility
mv.getstatic(cg.p(Visibility.class), "PUBLIC", cg.ci(Visibility.class));
mv.astore(VISIBILITY_INDEX);
// Here starts the logic for the class definition
loadRuntime();
superCallback.compile(this);
invokeUtilityMethod("prepareSuperClass", cg.sig(RubyClass.class, cg.params(Ruby.class, IRubyObject.class)));
loadThreadContext();
pathCallback.compile(this);
invokeUtilityMethod("prepareClassNamespace", cg.sig(RubyModule.class, cg.params(ThreadContext.class, IRubyObject.class)));
mv.swap();
mv.ldc(name);
mv.swap();
mv.invokevirtual(cg.p(RubyModule.class), "defineOrGetClassUnder", cg.sig(RubyClass.class, cg.params(String.class, RubyClass.class)));
// set self to the class
mv.dup();
mv.astore(SELF_INDEX);
// CLASS BODY
loadThreadContext();
mv.swap();
// FIXME: this should be in a try/finally
invokeThreadContext("preCompiledClass", cg.sig(Void.TYPE, cg.params(RubyModule.class)));
bodyCallback.compile(this);
loadThreadContext();
invokeThreadContext("postCompiledClass", cg.sig(Void.TYPE, cg.params()));
endMethod(mv);
// return to previous method
mv = getMethodAdapter();
// prepare to call class definition method
loadThreadContext();
loadSelf();
mv.getstatic(cg.p(IRubyObject.class), "NULL_ARRAY", cg.ci(IRubyObject[].class));
mv.getstatic(cg.p(Block.class), "NULL_BLOCK", cg.ci(Block.class));
mv.invokestatic(classname, methodName, METHOD_SIGNATURE);
}
public void defineModule(String name, StaticScope staticScope, ClosureCallback pathCallback, ClosureCallback bodyCallback) {
// TODO: build arg list based on number of args, optionals, etc
++methodIndex;
String methodName = "rubymodule__" + cg.cleanJavaIdentifier(name) + "__" + methodIndex;
beginMethod(methodName, 0);
SkinnyMethodAdapter mv = getMethodAdapter();
// module def bodies default to public visibility
mv.getstatic(cg.p(Visibility.class), "PUBLIC", cg.ci(Visibility.class));
mv.astore(VISIBILITY_INDEX);
// Here starts the logic for the module definition
loadThreadContext();
pathCallback.compile(this);
invokeUtilityMethod("prepareClassNamespace", cg.sig(RubyModule.class, cg.params(ThreadContext.class, IRubyObject.class)));
mv.ldc(name);
mv.invokevirtual(cg.p(RubyModule.class), "defineModuleUnder", cg.sig(RubyModule.class, cg.params(String.class)));
// set self to the module
mv.dup();
mv.astore(SELF_INDEX);
// MODULE BODY
loadThreadContext();
mv.swap();
// FIXME: this should be in a try/finally
invokeThreadContext("preCompiledClass", cg.sig(Void.TYPE, cg.params(RubyModule.class)));
bodyCallback.compile(this);
loadThreadContext();
invokeThreadContext("postCompiledClass", cg.sig(Void.TYPE, cg.params()));
endMethod(mv);
// return to previous method
mv = getMethodAdapter();
// prepare to call class definition method
loadThreadContext();
loadSelf();
mv.getstatic(cg.p(IRubyObject.class), "NULL_ARRAY", cg.ci(IRubyObject[].class));
mv.getstatic(cg.p(Block.class), "NULL_BLOCK", cg.ci(Block.class));
mv.invokestatic(classname, methodName, METHOD_SIGNATURE);
}
public static RubyClass prepareSuperClass(Ruby runtime, IRubyObject rubyClass) {
if (rubyClass != null) {
if(!(rubyClass instanceof RubyClass)) {
throw runtime.newTypeError("superclass must be a Class (" + RubyObject.trueFalseNil(rubyClass) + ") given");
}
return (RubyClass)rubyClass;
}
return (RubyClass)null;
}
public static RubyModule prepareClassNamespace(ThreadContext context, IRubyObject rubyModule) {
if (rubyModule == null || rubyModule.isNil()) {
rubyModule = (RubyModule) context.peekCRef().getValue();
if (rubyModule == null) {
throw context.getRuntime().newTypeError("no outer class/module");
}
}
return (RubyModule)rubyModule;
}
public void pollThreadEvents() {
loadThreadContext();
invokeThreadContext("pollThreadEvents", cg.sig(Void.TYPE));
}
}
| true | true | public void invokeDynamic(String name, boolean hasReceiver, boolean hasArgs, CallType callType, ClosureCallback closureArg, boolean attrAssign) {
SkinnyMethodAdapter mv = getMethodAdapter();
String callSig = cg.sig(IRubyObject.class, cg.params(IRubyObject.class, IRubyObject[].class, ThreadContext.class, String.class, IRubyObject.class, CallType.class, Block.class));
String callSigIndexed = cg.sig(IRubyObject.class, cg.params(IRubyObject.class, IRubyObject[].class, ThreadContext.class, Byte.TYPE, String.class, IRubyObject.class, CallType.class, Block.class));
int index = MethodIndex.getIndex(name);
if (hasArgs) {
if (hasReceiver) {
// Call with args
// receiver already present
} else {
// FCall
// no receiver present, use self
loadSelf();
// put self under args
mv.swap();
}
} else {
if (hasReceiver) {
// receiver already present
// empty args list
mv.getstatic(cg.p(IRubyObject.class), "NULL_ARRAY", cg.ci(IRubyObject[].class));
} else {
// VCall
// no receiver present, use self
loadSelf();
// empty args list
mv.getstatic(cg.p(IRubyObject.class), "NULL_ARRAY", cg.ci(IRubyObject[].class));
}
}
loadThreadContext();
if (index != 0) {
// load method index
mv.ldc(new Integer(index));
}
mv.ldc(name);
// load self for visibility checks
loadSelf();
mv.getstatic(cg.p(CallType.class), callType.toString(), cg.ci(CallType.class));
if (closureArg == null) {
mv.getstatic(cg.p(Block.class), "NULL_BLOCK", cg.ci(Block.class));
} else {
closureArg.compile(this);
}
Label tryBegin = new Label();
Label tryEnd = new Label();
Label tryCatch = new Label();
if (closureArg != null) {
// wrap with try/catch for block flow-control exceptions
// FIXME: for flow-control from containing blocks, but it's not working right;
// stack is not as expected for invoke calls below...
//mv.trycatch(tryBegin, tryEnd, tryCatch, cg.p(JumpException.class));
mv.label(tryBegin);
}
if (attrAssign) {
if (index != 0) {
invokeUtilityMethod("doAttrAssignIndexed", callSigIndexed);
} else {
invokeUtilityMethod("doAttrAssignDynamic", callSig);
}
} else {
if (index != 0) {
invokeUtilityMethod("doInvokeDynamicIndexed", callSigIndexed);
} else {
invokeUtilityMethod("doInvokeDynamic", callSig);
}
}
if (closureArg != null) {
mv.label(tryEnd);
// no physical break, terminate loop and skip catch block
Label normalEnd = new Label();
mv.go_to(normalEnd);
mv.label(tryCatch);
{
loadClosure();
invokeUtilityMethod("handleJumpException", cg.sig(IRubyObject.class, cg.params(JumpException.class, Block.class)));
}
mv.label(normalEnd);
}
}
| public void invokeDynamic(String name, boolean hasReceiver, boolean hasArgs, CallType callType, ClosureCallback closureArg, boolean attrAssign) {
SkinnyMethodAdapter mv = getMethodAdapter();
String callSig = cg.sig(IRubyObject.class, cg.params(IRubyObject.class, IRubyObject[].class, ThreadContext.class, String.class, IRubyObject.class, CallType.class, Block.class));
String callSigIndexed = cg.sig(IRubyObject.class, cg.params(IRubyObject.class, IRubyObject[].class, ThreadContext.class, Byte.TYPE, String.class, IRubyObject.class, CallType.class, Block.class));
int index = MethodIndex.getIndex(name);
if (hasArgs) {
if (hasReceiver) {
// Call with args
// receiver already present
} else {
// FCall
// no receiver present, use self
loadSelf();
// put self under args
mv.swap();
}
} else {
if (hasReceiver) {
// receiver already present
// empty args list
mv.getstatic(cg.p(IRubyObject.class), "NULL_ARRAY", cg.ci(IRubyObject[].class));
} else {
// VCall
// no receiver present, use self
loadSelf();
// empty args list
mv.getstatic(cg.p(IRubyObject.class), "NULL_ARRAY", cg.ci(IRubyObject[].class));
}
}
loadThreadContext();
if (index != 0) {
// load method index
mv.ldc(new Integer(index));
}
mv.ldc(name);
// load self for visibility checks
loadSelf();
mv.getstatic(cg.p(CallType.class), callType.toString(), cg.ci(CallType.class));
if (closureArg == null) {
mv.getstatic(cg.p(Block.class), "NULL_BLOCK", cg.ci(Block.class));
} else {
closureArg.compile(this);
}
Label tryBegin = new Label();
Label tryEnd = new Label();
Label tryCatch = new Label();
if (closureArg != null) {
// wrap with try/catch for block flow-control exceptions
// FIXME: for flow-control from containing blocks, but it's not working right;
// stack is not as expected for invoke calls below...
//mv.trycatch(tryBegin, tryEnd, tryCatch, cg.p(JumpException.class));
mv.label(tryBegin);
}
if (attrAssign) {
if (index != 0) {
invokeUtilityMethod("doAttrAssignIndexed", callSigIndexed);
} else {
invokeUtilityMethod("doAttrAssign", callSig);
}
} else {
if (index != 0) {
invokeUtilityMethod("doInvokeDynamicIndexed", callSigIndexed);
} else {
invokeUtilityMethod("doInvokeDynamic", callSig);
}
}
if (closureArg != null) {
mv.label(tryEnd);
// no physical break, terminate loop and skip catch block
Label normalEnd = new Label();
mv.go_to(normalEnd);
mv.label(tryCatch);
{
loadClosure();
invokeUtilityMethod("handleJumpException", cg.sig(IRubyObject.class, cg.params(JumpException.class, Block.class)));
}
mv.label(normalEnd);
}
}
|
diff --git a/sch-kp-web/src/main/java/hu/sch/kp/web/pages/pontigenyles/PontIgenylesLeadas.java b/sch-kp-web/src/main/java/hu/sch/kp/web/pages/pontigenyles/PontIgenylesLeadas.java
index a65b355a..88a8cab1 100644
--- a/sch-kp-web/src/main/java/hu/sch/kp/web/pages/pontigenyles/PontIgenylesLeadas.java
+++ b/sch-kp-web/src/main/java/hu/sch/kp/web/pages/pontigenyles/PontIgenylesLeadas.java
@@ -1,128 +1,127 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package hu.sch.kp.web.pages.pontigenyles;
import hu.sch.kp.web.util.ListDataProviderCompoundPropertyModelImpl;
import hu.sch.domain.Ertekeles;
import hu.sch.domain.Felhasznalo;
import hu.sch.domain.PontIgeny;
import hu.sch.kp.services.ErtekelesManagerLocal;
import hu.sch.kp.web.pages.ertekeles.Ertekelesek;
import hu.sch.kp.web.templates.SecuredPageTemplate;
import java.util.List;
import javax.ejb.EJB;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.markup.repeater.data.DataView;
import org.apache.wicket.markup.repeater.data.IDataProvider;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.validation.IValidatable;
import org.apache.wicket.validation.IValidator;
import org.apache.wicket.validation.ValidationError;
import org.apache.wicket.validation.validator.NumberValidator.RangeValidator;
/**
*
* @author hege
*/
public class PontIgenylesLeadas extends SecuredPageTemplate {
@EJB(name = "ErtekelesManagerBean")
ErtekelesManagerLocal ertekelesManager;
- public PontIgenylesLeadas(Ertekeles ert) {
+ public PontIgenylesLeadas(final Ertekeles ert) {
setHeaderLabelText("Pontigénylés leadása");
//TODO jogosultság?!
final Long ertekelesId = ert.getId();
final List<PontIgeny> igenylista = igenyeketElokeszit(ert);
setModel(new CompoundPropertyModel(ert));
add(new Label("csoport.nev"));
add(new Label("szemeszter"));
add(new FeedbackPanel("pagemessages"));
// Űrlap létrehozása
Form igform = new Form("igenyekform") {
@Override
protected void onSubmit() {
// pontok tárolása
ertekelesManager.pontIgenyekLeadasa(ertekelesId, igenylista);
getSession().info(getLocalizer().getString("info.PontIgenylesMentve", this));
setResponsePage(Ertekelesek.class);
}
};
// Bevitelhez táblázat létrehozása
IDataProvider provider =
new ListDataProviderCompoundPropertyModelImpl(igenylista);
DataView dview = new DataView("igenyek", provider) {
// QPA csoport pontozásvalidátora
final IValidator QpaPontValidator = RangeValidator.range(0, 100);
// A többi csoport pontozásvalidátora
final IValidator pontValidator = RangeValidator.range(0, 50);
// QPA csoport ID-ja
private final long SCH_QPA_ID = 27L;
@Override
protected void populateItem(Item item) {
- final PontIgeny igeny = (PontIgeny) item.getModelObject();
final ValidationError validationError = new ValidationError();
validationError.addMessageKey("err.MinimumPontHiba");
item.add(new Label("felhasznalo.nev"));
item.add(new Label("felhasznalo.becenev"));
TextField pont = new TextField("pont");
//csoportfüggő validátor hozzácsatolása
- if (igeny.getErtekeles().getCsoport().getId().equals(SCH_QPA_ID)) {
+ if (ert.getCsoport().getId().equals(SCH_QPA_ID)) {
pont.add(QpaPontValidator);
} else {
pont.add(pontValidator);
}
//olyan validátor, ami akkor dob hibát ha 0 és 5 pont között adott meg
pont.add(new IValidator() {
public void validate(IValidatable arg0) {
final Integer pont = (Integer) arg0.getValue();
if (pont.compareTo(5) < 0 && pont.compareTo(0) > 0) {
arg0.error(validationError);
}
}
});
item.add(pont);
}
};
igform.add(dview);
add(igform);
}
private List<PontIgeny> igenyeketElokeszit(Ertekeles ert) {
List<Felhasznalo> csoporttagok =
userManager.getCsoporttagokWithoutOregtagok(ert.getCsoport().getId());
List<PontIgeny> igenyek =
ertekelesManager.findPontIgenyekForErtekeles(ert.getId());
//tagok és igények összefésülése
if (igenyek.size() == 0) {
for (Felhasznalo f : csoporttagok) {
igenyek.add(new PontIgeny(f, 0));
}
} else {
// TODO tényleges összefésülés
if (igenyek.size() != csoporttagok.size()) {
// TODO összefésülés
throw new UnsupportedOperationException("PontIgény - Csoporttag összefésülés még nincs implementálva");
}
}
return igenyek;
}
}
| false | true | public PontIgenylesLeadas(Ertekeles ert) {
setHeaderLabelText("Pontigénylés leadása");
//TODO jogosultság?!
final Long ertekelesId = ert.getId();
final List<PontIgeny> igenylista = igenyeketElokeszit(ert);
setModel(new CompoundPropertyModel(ert));
add(new Label("csoport.nev"));
add(new Label("szemeszter"));
add(new FeedbackPanel("pagemessages"));
// Űrlap létrehozása
Form igform = new Form("igenyekform") {
@Override
protected void onSubmit() {
// pontok tárolása
ertekelesManager.pontIgenyekLeadasa(ertekelesId, igenylista);
getSession().info(getLocalizer().getString("info.PontIgenylesMentve", this));
setResponsePage(Ertekelesek.class);
}
};
// Bevitelhez táblázat létrehozása
IDataProvider provider =
new ListDataProviderCompoundPropertyModelImpl(igenylista);
DataView dview = new DataView("igenyek", provider) {
// QPA csoport pontozásvalidátora
final IValidator QpaPontValidator = RangeValidator.range(0, 100);
// A többi csoport pontozásvalidátora
final IValidator pontValidator = RangeValidator.range(0, 50);
// QPA csoport ID-ja
private final long SCH_QPA_ID = 27L;
@Override
protected void populateItem(Item item) {
final PontIgeny igeny = (PontIgeny) item.getModelObject();
final ValidationError validationError = new ValidationError();
validationError.addMessageKey("err.MinimumPontHiba");
item.add(new Label("felhasznalo.nev"));
item.add(new Label("felhasznalo.becenev"));
TextField pont = new TextField("pont");
//csoportfüggő validátor hozzácsatolása
if (igeny.getErtekeles().getCsoport().getId().equals(SCH_QPA_ID)) {
pont.add(QpaPontValidator);
} else {
pont.add(pontValidator);
}
//olyan validátor, ami akkor dob hibát ha 0 és 5 pont között adott meg
pont.add(new IValidator() {
public void validate(IValidatable arg0) {
final Integer pont = (Integer) arg0.getValue();
if (pont.compareTo(5) < 0 && pont.compareTo(0) > 0) {
arg0.error(validationError);
}
}
});
item.add(pont);
}
};
igform.add(dview);
add(igform);
}
| public PontIgenylesLeadas(final Ertekeles ert) {
setHeaderLabelText("Pontigénylés leadása");
//TODO jogosultság?!
final Long ertekelesId = ert.getId();
final List<PontIgeny> igenylista = igenyeketElokeszit(ert);
setModel(new CompoundPropertyModel(ert));
add(new Label("csoport.nev"));
add(new Label("szemeszter"));
add(new FeedbackPanel("pagemessages"));
// Űrlap létrehozása
Form igform = new Form("igenyekform") {
@Override
protected void onSubmit() {
// pontok tárolása
ertekelesManager.pontIgenyekLeadasa(ertekelesId, igenylista);
getSession().info(getLocalizer().getString("info.PontIgenylesMentve", this));
setResponsePage(Ertekelesek.class);
}
};
// Bevitelhez táblázat létrehozása
IDataProvider provider =
new ListDataProviderCompoundPropertyModelImpl(igenylista);
DataView dview = new DataView("igenyek", provider) {
// QPA csoport pontozásvalidátora
final IValidator QpaPontValidator = RangeValidator.range(0, 100);
// A többi csoport pontozásvalidátora
final IValidator pontValidator = RangeValidator.range(0, 50);
// QPA csoport ID-ja
private final long SCH_QPA_ID = 27L;
@Override
protected void populateItem(Item item) {
final ValidationError validationError = new ValidationError();
validationError.addMessageKey("err.MinimumPontHiba");
item.add(new Label("felhasznalo.nev"));
item.add(new Label("felhasznalo.becenev"));
TextField pont = new TextField("pont");
//csoportfüggő validátor hozzácsatolása
if (ert.getCsoport().getId().equals(SCH_QPA_ID)) {
pont.add(QpaPontValidator);
} else {
pont.add(pontValidator);
}
//olyan validátor, ami akkor dob hibát ha 0 és 5 pont között adott meg
pont.add(new IValidator() {
public void validate(IValidatable arg0) {
final Integer pont = (Integer) arg0.getValue();
if (pont.compareTo(5) < 0 && pont.compareTo(0) > 0) {
arg0.error(validationError);
}
}
});
item.add(pont);
}
};
igform.add(dview);
add(igform);
}
|
diff --git a/tests/org.jboss.tools.switchyard.ui.bot.test/src/org/jboss/tools/switchyard/ui/bot/test/UseCaseFileGatewayTest.java b/tests/org.jboss.tools.switchyard.ui.bot.test/src/org/jboss/tools/switchyard/ui/bot/test/UseCaseFileGatewayTest.java
index 7f29739f..fa254750 100644
--- a/tests/org.jboss.tools.switchyard.ui.bot.test/src/org/jboss/tools/switchyard/ui/bot/test/UseCaseFileGatewayTest.java
+++ b/tests/org.jboss.tools.switchyard.ui.bot.test/src/org/jboss/tools/switchyard/ui/bot/test/UseCaseFileGatewayTest.java
@@ -1,105 +1,105 @@
package org.jboss.tools.switchyard.ui.bot.test;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.FileWriter;
import org.jboss.reddeer.eclipse.condition.ConsoleHasText;
import org.jboss.reddeer.eclipse.ui.perspectives.JavaEEPerspective;
import org.jboss.reddeer.junit.requirement.inject.InjectRequirement;
import org.jboss.reddeer.junit.runner.RedDeerSuite;
import org.jboss.reddeer.requirements.openperspective.OpenPerspectiveRequirement.OpenPerspective;
import org.jboss.reddeer.requirements.server.ServerReqState;
import org.jboss.reddeer.swt.wait.WaitUntil;
import org.jboss.tools.runtime.reddeer.requirement.ServerReqType;
import org.jboss.tools.runtime.reddeer.requirement.ServerRequirement.Server;
import org.jboss.tools.switchyard.reddeer.binding.FileBindingPage;
import org.jboss.tools.switchyard.reddeer.component.Service;
import org.jboss.tools.switchyard.reddeer.component.SwitchYardComponent;
import org.jboss.tools.switchyard.reddeer.editor.SwitchYardEditor;
import org.jboss.tools.switchyard.reddeer.editor.TextEditor;
import org.jboss.tools.switchyard.reddeer.requirement.SwitchYardRequirement;
import org.jboss.tools.switchyard.reddeer.requirement.SwitchYardRequirement.SwitchYard;
import org.jboss.tools.switchyard.reddeer.server.ServerDeployment;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* File gateway test
*
* @author apodhrad
*
*/
@SwitchYard(server = @Server(type = ServerReqType.ANY, state = ServerReqState.RUNNING))
@OpenPerspective(JavaEEPerspective.class)
@RunWith(RedDeerSuite.class)
public class UseCaseFileGatewayTest {
public static final String PROJECT = "file_project";
public static final String PACKAGE = "com.example.switchyard.file_project";
@InjectRequirement
private SwitchYardRequirement switchyardRequirement;
@Before @After
public void closeSwitchyardFile() {
try {
new SwitchYardEditor().saveAndClose();
} catch (Exception ex) {
// it is ok, we just try to close switchyard.xml if it is open
}
}
@Test
public void fileGatewayTest() throws Exception {
switchyardRequirement.project(PROJECT).impl("Bean").binding("File").create();
// Create new service and interface
new SwitchYardEditor().addBeanImplementation().createNewInterface("Info").finish();
// Edit the interface
new SwitchYardComponent("Info").doubleClick();
new TextEditor("Info.java").typeAfter("interface", "void printInfo(String body);")
.saveAndClose();
// Edit the bean
new SwitchYardComponent("InfoBean").doubleClick();
new TextEditor("InfoBean.java").typeAfter("public class", "@Override").newLine()
.type("public void printInfo(String body) {").newLine()
.type("System.out.println(\"Body: \" + body);}").saveAndClose();
new SwitchYardEditor().save();
// Promote info service
new Service("Info").promoteService().activate().setServiceName("InfoService").finish();
// Add File binding
new Service("InfoService").addBinding("File");
FileBindingPage wizard = new FileBindingPage();
File input = new File("target/input");
input.mkdirs();
File output = new File("target/processed");
output.mkdirs();
wizard.setName("file-binding");
- wizard.getDirectory().setText(input.getAbsolutePath());
+ wizard.getDirectory().setText(input.getAbsolutePath().replaceAll("\\", "/"));
wizard.getAutoCreateMissingDirectoriesinFilePath().toggle(true);
- wizard.getMove().setText(output.getAbsolutePath());
+ wizard.getMove().setText(output.getAbsolutePath().replaceAll("\\", "/"));
wizard.finish();
new SwitchYardEditor().save();
// Deploy and test the project
new ServerDeployment(switchyardRequirement.getConfig().getName()).deployProject(PROJECT);
FileWriter out = new FileWriter(new File(input, "test.txt"));
out.write("Hello File Gateway");
out.flush();
out.close();
new WaitUntil(new ConsoleHasText("Body: Hello File Gateway"));
File file = new File(output, "test.txt");
assertTrue("File 'test.txt' wasn't processed", file.exists());
}
}
| false | true | public void fileGatewayTest() throws Exception {
switchyardRequirement.project(PROJECT).impl("Bean").binding("File").create();
// Create new service and interface
new SwitchYardEditor().addBeanImplementation().createNewInterface("Info").finish();
// Edit the interface
new SwitchYardComponent("Info").doubleClick();
new TextEditor("Info.java").typeAfter("interface", "void printInfo(String body);")
.saveAndClose();
// Edit the bean
new SwitchYardComponent("InfoBean").doubleClick();
new TextEditor("InfoBean.java").typeAfter("public class", "@Override").newLine()
.type("public void printInfo(String body) {").newLine()
.type("System.out.println(\"Body: \" + body);}").saveAndClose();
new SwitchYardEditor().save();
// Promote info service
new Service("Info").promoteService().activate().setServiceName("InfoService").finish();
// Add File binding
new Service("InfoService").addBinding("File");
FileBindingPage wizard = new FileBindingPage();
File input = new File("target/input");
input.mkdirs();
File output = new File("target/processed");
output.mkdirs();
wizard.setName("file-binding");
wizard.getDirectory().setText(input.getAbsolutePath());
wizard.getAutoCreateMissingDirectoriesinFilePath().toggle(true);
wizard.getMove().setText(output.getAbsolutePath());
wizard.finish();
new SwitchYardEditor().save();
// Deploy and test the project
new ServerDeployment(switchyardRequirement.getConfig().getName()).deployProject(PROJECT);
FileWriter out = new FileWriter(new File(input, "test.txt"));
out.write("Hello File Gateway");
out.flush();
out.close();
new WaitUntil(new ConsoleHasText("Body: Hello File Gateway"));
File file = new File(output, "test.txt");
assertTrue("File 'test.txt' wasn't processed", file.exists());
}
| public void fileGatewayTest() throws Exception {
switchyardRequirement.project(PROJECT).impl("Bean").binding("File").create();
// Create new service and interface
new SwitchYardEditor().addBeanImplementation().createNewInterface("Info").finish();
// Edit the interface
new SwitchYardComponent("Info").doubleClick();
new TextEditor("Info.java").typeAfter("interface", "void printInfo(String body);")
.saveAndClose();
// Edit the bean
new SwitchYardComponent("InfoBean").doubleClick();
new TextEditor("InfoBean.java").typeAfter("public class", "@Override").newLine()
.type("public void printInfo(String body) {").newLine()
.type("System.out.println(\"Body: \" + body);}").saveAndClose();
new SwitchYardEditor().save();
// Promote info service
new Service("Info").promoteService().activate().setServiceName("InfoService").finish();
// Add File binding
new Service("InfoService").addBinding("File");
FileBindingPage wizard = new FileBindingPage();
File input = new File("target/input");
input.mkdirs();
File output = new File("target/processed");
output.mkdirs();
wizard.setName("file-binding");
wizard.getDirectory().setText(input.getAbsolutePath().replaceAll("\\", "/"));
wizard.getAutoCreateMissingDirectoriesinFilePath().toggle(true);
wizard.getMove().setText(output.getAbsolutePath().replaceAll("\\", "/"));
wizard.finish();
new SwitchYardEditor().save();
// Deploy and test the project
new ServerDeployment(switchyardRequirement.getConfig().getName()).deployProject(PROJECT);
FileWriter out = new FileWriter(new File(input, "test.txt"));
out.write("Hello File Gateway");
out.flush();
out.close();
new WaitUntil(new ConsoleHasText("Body: Hello File Gateway"));
File file = new File(output, "test.txt");
assertTrue("File 'test.txt' wasn't processed", file.exists());
}
|
diff --git a/src/erki/xpeter/parsers/Sed.java b/src/erki/xpeter/parsers/Sed.java
index 3267261..48d9891 100644
--- a/src/erki/xpeter/parsers/Sed.java
+++ b/src/erki/xpeter/parsers/Sed.java
@@ -1,46 +1,46 @@
package erki.xpeter.parsers;
import java.util.TreeMap;
import erki.api.util.Log;
import erki.api.util.Observer;
import erki.xpeter.Bot;
import erki.xpeter.msg.Message;
import erki.xpeter.msg.TextMessage;
public class Sed implements Parser, Observer<TextMessage> {
private TreeMap<String, String> lastSaid = new TreeMap<String, String>();
@Override
public void init(Bot bot) {
bot.register(TextMessage.class, this);
}
@Override
public void destroy(Bot bot) {
bot.deregister(TextMessage.class, this);
}
@Override
public void inform(TextMessage msg) {
String text = msg.getText();
String nick = msg.getNick();
- if (lastSaid.containsKey(nick) && text.startsWith("s") && text.length() > 1) {
+ if (lastSaid.containsKey(nick) && text.startsWith("s") && text.length() > 2) {
String delimiter = text.substring(1, 2);
String rest = text.substring(2, text.length() - 1);
if (text.endsWith(delimiter) && rest.contains(delimiter)) {
String regex = rest.substring(0, rest.indexOf(delimiter));
String replacement = rest.substring(rest.indexOf(delimiter) + 1);
Log.debug("Replacing " + regex + " with " + replacement + ".");
String result = lastSaid.get(nick).replaceAll(regex, replacement);
msg.respond(new Message(nick + " meinte: " + result));
return;
}
}
lastSaid.put(nick, text);
}
}
| true | true | public void inform(TextMessage msg) {
String text = msg.getText();
String nick = msg.getNick();
if (lastSaid.containsKey(nick) && text.startsWith("s") && text.length() > 1) {
String delimiter = text.substring(1, 2);
String rest = text.substring(2, text.length() - 1);
if (text.endsWith(delimiter) && rest.contains(delimiter)) {
String regex = rest.substring(0, rest.indexOf(delimiter));
String replacement = rest.substring(rest.indexOf(delimiter) + 1);
Log.debug("Replacing " + regex + " with " + replacement + ".");
String result = lastSaid.get(nick).replaceAll(regex, replacement);
msg.respond(new Message(nick + " meinte: " + result));
return;
}
}
lastSaid.put(nick, text);
}
| public void inform(TextMessage msg) {
String text = msg.getText();
String nick = msg.getNick();
if (lastSaid.containsKey(nick) && text.startsWith("s") && text.length() > 2) {
String delimiter = text.substring(1, 2);
String rest = text.substring(2, text.length() - 1);
if (text.endsWith(delimiter) && rest.contains(delimiter)) {
String regex = rest.substring(0, rest.indexOf(delimiter));
String replacement = rest.substring(rest.indexOf(delimiter) + 1);
Log.debug("Replacing " + regex + " with " + replacement + ".");
String result = lastSaid.get(nick).replaceAll(regex, replacement);
msg.respond(new Message(nick + " meinte: " + result));
return;
}
}
lastSaid.put(nick, text);
}
|
diff --git a/src/Entity.java b/src/Entity.java
index 331c383..cca39e7 100644
--- a/src/Entity.java
+++ b/src/Entity.java
@@ -1,117 +1,117 @@
import java.awt.Image;
public class Entity extends GameComponents{
private Image img;
private int life;
private double grad;
private Bullet bullet;
public void update(boolean a[],double b) {
if(a[0]){setY_Point(getY_Point()-1);}
if(a[1]){setY_Point(getY_Point()+1);}
if(a[2]){setX_Point(getX_Point()-1);}
if(a[3]){setX_Point(getX_Point()+1);}
- grad=grad+b;
+ grad=b;
double i = ( getX_Point()+25-Math.cos( grad ) * 25);
double j=(getY_Point()+25-Math.sin( grad ) * 25 );
double m = ( getX_Point()+25+Math.cos( grad ) * 25);
double n=(getY_Point()+25+Math.sin( grad ) * 25 );
int dirX=(int)(i-m);
int dirY=(int)(j-n);
if(a[4]){
long time = System.currentTimeMillis();
- if(FightClub.getLasttime()+2000<time){
+ if(FightClub.getLasttime()+500<time){
FightClub.setLasttime(time);
- bullet= new Bullet(20,20,dirX,dirY,(int)i+2,(int)j+2);
- System.out.println("Works over here!" + bullet.getY_Point());
+ bullet= new Bullet(10,10,dirX,dirY,(int)i-5,(int)j-5,grad);
+ //System.out.println("Works over here!" + bullet.getY_Point());
FightClub.getBullets().add(bullet);
}
}
// System.out.println(i + " "+ j);
// System.out.println(m + " "+ n);
// System.out.println(dirX+" "+ dirY);
}
/**
* @return the color
*/
public Image getImg() {
return img;
}
/**
* @param color the color to set
*/
public void setImg(Image img) {
this.img = img;
}
/**
* @return the life
*/
public int getLife() {
return life;
}
/**
* @param life the life to set
*/
public void setLife(int life) {
this.life = life;
}
/**
* @return the grad
*/
public double getGrad() {
return grad;
}
/**
* @param grad the grad to set
*/
public void setGrad(double grad) {
this.grad = grad;
}
}
| false | true | public void update(boolean a[],double b) {
if(a[0]){setY_Point(getY_Point()-1);}
if(a[1]){setY_Point(getY_Point()+1);}
if(a[2]){setX_Point(getX_Point()-1);}
if(a[3]){setX_Point(getX_Point()+1);}
grad=grad+b;
double i = ( getX_Point()+25-Math.cos( grad ) * 25);
double j=(getY_Point()+25-Math.sin( grad ) * 25 );
double m = ( getX_Point()+25+Math.cos( grad ) * 25);
double n=(getY_Point()+25+Math.sin( grad ) * 25 );
int dirX=(int)(i-m);
int dirY=(int)(j-n);
if(a[4]){
long time = System.currentTimeMillis();
if(FightClub.getLasttime()+2000<time){
FightClub.setLasttime(time);
bullet= new Bullet(20,20,dirX,dirY,(int)i+2,(int)j+2);
System.out.println("Works over here!" + bullet.getY_Point());
FightClub.getBullets().add(bullet);
}
}
// System.out.println(i + " "+ j);
// System.out.println(m + " "+ n);
// System.out.println(dirX+" "+ dirY);
}
| public void update(boolean a[],double b) {
if(a[0]){setY_Point(getY_Point()-1);}
if(a[1]){setY_Point(getY_Point()+1);}
if(a[2]){setX_Point(getX_Point()-1);}
if(a[3]){setX_Point(getX_Point()+1);}
grad=b;
double i = ( getX_Point()+25-Math.cos( grad ) * 25);
double j=(getY_Point()+25-Math.sin( grad ) * 25 );
double m = ( getX_Point()+25+Math.cos( grad ) * 25);
double n=(getY_Point()+25+Math.sin( grad ) * 25 );
int dirX=(int)(i-m);
int dirY=(int)(j-n);
if(a[4]){
long time = System.currentTimeMillis();
if(FightClub.getLasttime()+500<time){
FightClub.setLasttime(time);
bullet= new Bullet(10,10,dirX,dirY,(int)i-5,(int)j-5,grad);
//System.out.println("Works over here!" + bullet.getY_Point());
FightClub.getBullets().add(bullet);
}
}
// System.out.println(i + " "+ j);
// System.out.println(m + " "+ n);
// System.out.println(dirX+" "+ dirY);
}
|
diff --git a/src/share/classes/javafx/reflect/FXContext.java b/src/share/classes/javafx/reflect/FXContext.java
index 059a9dc1e..d53a0c649 100644
--- a/src/share/classes/javafx/reflect/FXContext.java
+++ b/src/share/classes/javafx/reflect/FXContext.java
@@ -1,129 +1,129 @@
/*
* Copyright 1999-2008 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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 General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javafx.reflect;
/** Context for reflective operations.
* All the various operations are based on a {@code FXContext}.
* This is similar to JDI's {@code VirtualMachine} interface.
* In "normal" useage there is a single {@code FXContext} that is
* basically a wrapper around {@code java.lang.reflect}, but (for
* example) for remote reflection you could have an implementation
* based on JDI.
* Corresponds to {@code com.sun.jdi.VirtualMachine}.
*/
public abstract class FXContext {
/** Find context-dependent default {@code FXContext}.
* (For now, this always returns the same {@code LocalReflectionContext}.)
*/
public static FXContext getInstance() {
// For now - later might do some more fancy searching.
return FXLocal.getContext();
}
protected FXContext() {
}
public static final String INTERFACE_SUFFIX = "$Intf";
public static final String FXOBJECT_NAME =
"com.sun.javafx.runtime.FXObject";
/** Get the {@code FXClassType} for the class with the given name. */
public abstract FXClassType findClass(String name);
FXType anyType = findClass("java.lang.Object");
/** Get the {@code FXType} for the "any" type. */
public FXType getAnyType() { return anyType; }
/** Get the run-time representation of the JavaFX {@code Boolean} type. */
public FXPrimitiveType getBooleanType() {
return FXPrimitiveType.booleanType;
}
/** Get the run-time representation of the JavaFX {@code Integer} type. */
public FXPrimitiveType getIntegerType() {
return FXPrimitiveType.integerType;
}
/** Get the run-time representation of the JavaFX {@code Number} type. */
public FXPrimitiveType getNumberType() {
return FXPrimitiveType.numberType;
}
/** Get the run-time representation of the JavaFX {@code Void} type. */
public FXPrimitiveType getVoidType() {
return FXPrimitiveType.voidType;
}
/** Create a helper object for building a sequence value. */
public FXSequenceBuilder makeSequenceBuilder(FXType elementType) {
return new FXSequenceBuilder(this, elementType);
}
/** Create a sequence value from one or more FXValues.
* Concatenates all of the input values (which might be themselves
* sequences or null).
* @param elementType
* @param values the values to be concatenated
* @return the new sequence value
*/
public FXValue makeSequence(FXType elementType, FXValue... values) {
FXSequenceBuilder builder = makeSequenceBuilder(elementType);
- for (int i = 0; i <= values.length; i++)
+ for (int i = 0; i < values.length; i++)
builder.append(values[i]);
return builder.getSequence();
}
/** Create a sequence value from an array of singleton FXValues.
* This is a low-level routine than {@link #makeSequence},
* which takes arguments than can be nul or themselves sequences.
* @param values Input values. (This array is re-used, not copied.
* It must not be modified after the method is called.)
* All of the values must be singleton values.
* @param nvalues Number of items in the sequence.
* (We require that {@code nvalues >= values.length}.)
* @param elementType
* @return the new sequence value
*/
public FXValue makeSequenceValue(FXValue[] values, int nvalues, FXType elementType) {
return new FXSequenceValue(values, nvalues, elementType);
}
/* Create an {@code Boolean} value from a {@code boolean}. */
public FXValue mirrorOf (boolean value) {
return new FXBooleanValue(value, getBooleanType());
}
/* Create an {@code Integer} value from an {@code int}. */
public FXValue mirrorOf (int value) {
return new FXIntegerValue(value, getIntegerType());
}
/* Create an {@code Number} value from aq {@code double}. */
public FXValue mirrorOf (double value) {
return new FXNumberValue(value, getNumberType());
}
public abstract FXValue mirrorOf (String value);
}
| true | true | public FXValue makeSequence(FXType elementType, FXValue... values) {
FXSequenceBuilder builder = makeSequenceBuilder(elementType);
for (int i = 0; i <= values.length; i++)
builder.append(values[i]);
return builder.getSequence();
}
| public FXValue makeSequence(FXType elementType, FXValue... values) {
FXSequenceBuilder builder = makeSequenceBuilder(elementType);
for (int i = 0; i < values.length; i++)
builder.append(values[i]);
return builder.getSequence();
}
|
diff --git a/src/logic/level/Level.java b/src/logic/level/Level.java
index f1a6a7b..1b73c92 100644
--- a/src/logic/level/Level.java
+++ b/src/logic/level/Level.java
@@ -1,198 +1,198 @@
package logic.level;
import logic.Engine;
import logic.Player;
import logic.Consts.DataDir;
import logic.level.LevelData.Background.FieldData;
import logic.level.LevelData.Background.LayerData;
import logic.level.LevelData.Background.StaticData;
import logic.level.LevelData.Spawn;
import logic.level.LevelData.SpawnSet;
import EntitySystems.*;
import EntitySystems.Components.Angle;
import EntitySystems.Components.Position;
import EntitySystems.Components.Renderable;
import EntitySystems.Components.Rotation;
import EntitySystems.Components.Scrollable;
import EntitySystems.Components.Velocity;
import aurelienribon.tweenengine.TweenManager;
import com.artemis.Entity;
import com.artemis.World;
import com.artemis.managers.GroupManager;
import com.artemis.managers.TagManager;
import com.artemis.utils.ImmutableBag;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Texture.TextureWrap;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.Array;
import com.shipvgdc.sugdk.graphics.SpriteSheet;
public class Level{
//we set a constant maximum amount of sprites we draw to keep performance at its peak
//sprites includes both bullets and creatures, pretty much anything in the world
private static final int MAX_SPRITES = 128;
private int currentEnemyGroup;
//game load data files
public LevelData data;
ImmutableBag<Entity> activeEnemies;
public static final float[] FOV = {0, 0, 190, 220};
/**
* Container of all the entities for this level
*/
public World world;
/**
* Loads and constructs a level
* @param id - name of the level
*/
public Level(String id)
{
data = new LevelData(id);
this.world = Engine.world;
}
public void advance(float delta)
{
world.setDelta(delta);
world.process();
Engine.score += 10f*delta;
}
/**
* Draws the render system
*/
public void draw(SpriteBatch batch)
{
world.getSystem(RenderSystem.class).draw(batch);
}
/**
* sets all the level's data into its starting positions
*/
public void start()
{
GroupManager gm = this.world.getManager(GroupManager.class);
TagManager tm = this.world.getManager(TagManager.class);
// place the enemies in the world
for (int i = 0; i < data.enemyData.size; i++)
{
SpawnSet s = data.enemyData.get(i);
for (int j = 0; j < s.spawns.size; j++)
{
Spawn enemy = s.spawns.get(j);
Entity e = this.world.createEntity();
e = s.atlas.createEnemy(enemy.name, e);
Position p = (Position)e.getComponent(Position.CType);
p.location.x = enemy.pos.x;
p.location.y = enemy.pos.y;
this.world.addEntity(e);
}
}
//create layered background
for (int i = 0; i < data.background.stack.size; i++)
{
Entity layer = this.world.createEntity();
FieldData f = data.background.stack.get(i);
Texture t = Engine.assets.get(f.image, Texture.class);
Sprite s = new Sprite(t);
if (f instanceof LayerData)
{
LayerData d = (LayerData)data.background.stack.get(i);
t.setWrap(TextureWrap.Repeat, TextureWrap.Repeat);
- s.setSize(FOV[2], FOV[3]);
+ s.setSize(Math.max(t.getWidth(), FOV[2]), Math.max(t.getHeight(),FOV[3]));
layer.addComponent(new Position(), Position.CType);
layer.addComponent(new Scrollable(0, d.rate, Math.max(FOV[2]/(float)t.getWidth(), 1.0f), Math.max(FOV[3]/(float)t.getHeight(), 1.0f)), Scrollable.CType);
}
else if (f instanceof StaticData)
{
StaticData d = (StaticData)data.background.stack.get(i);
layer.addComponent(new Position(d.x, d.y), Position.CType);
layer.addComponent(new Angle(0), Angle.CType);
layer.addComponent(new Rotation(d.dps), Rotation.CType);
}
layer.addComponent(new Renderable(s), Renderable.CType);
gm.add(layer, "Field");
this.world.addEntity(layer);
}
//load banners
Texture t = Engine.assets.get(DataDir.Ui+"banners.png", Texture.class);
t.setWrap(TextureWrap.Repeat, TextureWrap.ClampToEdge);
SpriteSheet bannerTex = new SpriteSheet(t, 1, 3);
for (int i = 0; i < 3; i++)
{
Entity e = this.world.createEntity();
TextureRegion r = bannerTex.getFrame(i);
Sprite s = new Sprite(r);
s.setSize(FOV[3], 12);
s.setRotation(90);
s.setOrigin(0, 0);
e.addComponent(new Position(0, 0, 12, 0));
e.addComponent(new Scrollable(.35f, 0f, FOV[3]/bannerTex.getFrameWidth(), 1f, r));
e.addComponent(new Renderable(s));
gm.add(e, "Banner");
gm.add(e, "Banner"+(char)(i+65));
e.addToWorld();
e = this.world.createEntity();
s = new Sprite(r);
s.setSize(FOV[3], 12);
s.setRotation(-90);
s.setOrigin(0, 0);
s.flip(false, true);
e.addComponent(new Position(FOV[2], 0, -12, FOV[3]));
e.addComponent(new Scrollable(-.35f, 0f, 220f/bannerTex.getFrameWidth(), 1f, r));
e.addComponent(new Renderable(s));
gm.add(e, "Banner");
gm.add(e, "Banner"+(char)(i+65));
e.addToWorld();
}
this.world.initialize();
Engine.score = 0f;
Position p = (Position)Engine.player.getComponent(Position.CType);
p.location.x = FOV[2]/2.0f;
}
/**
* Loads the assets necessary for the level to be displayed
*/
public void loadAssets() {
for (int i = 0; i < data.background.stack.size; i++)
{
FieldData f = data.background.stack.get(i);
Engine.assets.load(f.image, Texture.class);
}
Engine.assets.load(data.bgm, Music.class);
Engine.assets.load(DataDir.Ui + "banners.png", Texture.class);
}
}
| true | true | public void start()
{
GroupManager gm = this.world.getManager(GroupManager.class);
TagManager tm = this.world.getManager(TagManager.class);
// place the enemies in the world
for (int i = 0; i < data.enemyData.size; i++)
{
SpawnSet s = data.enemyData.get(i);
for (int j = 0; j < s.spawns.size; j++)
{
Spawn enemy = s.spawns.get(j);
Entity e = this.world.createEntity();
e = s.atlas.createEnemy(enemy.name, e);
Position p = (Position)e.getComponent(Position.CType);
p.location.x = enemy.pos.x;
p.location.y = enemy.pos.y;
this.world.addEntity(e);
}
}
//create layered background
for (int i = 0; i < data.background.stack.size; i++)
{
Entity layer = this.world.createEntity();
FieldData f = data.background.stack.get(i);
Texture t = Engine.assets.get(f.image, Texture.class);
Sprite s = new Sprite(t);
if (f instanceof LayerData)
{
LayerData d = (LayerData)data.background.stack.get(i);
t.setWrap(TextureWrap.Repeat, TextureWrap.Repeat);
s.setSize(FOV[2], FOV[3]);
layer.addComponent(new Position(), Position.CType);
layer.addComponent(new Scrollable(0, d.rate, Math.max(FOV[2]/(float)t.getWidth(), 1.0f), Math.max(FOV[3]/(float)t.getHeight(), 1.0f)), Scrollable.CType);
}
else if (f instanceof StaticData)
{
StaticData d = (StaticData)data.background.stack.get(i);
layer.addComponent(new Position(d.x, d.y), Position.CType);
layer.addComponent(new Angle(0), Angle.CType);
layer.addComponent(new Rotation(d.dps), Rotation.CType);
}
layer.addComponent(new Renderable(s), Renderable.CType);
gm.add(layer, "Field");
this.world.addEntity(layer);
}
//load banners
Texture t = Engine.assets.get(DataDir.Ui+"banners.png", Texture.class);
t.setWrap(TextureWrap.Repeat, TextureWrap.ClampToEdge);
SpriteSheet bannerTex = new SpriteSheet(t, 1, 3);
for (int i = 0; i < 3; i++)
{
Entity e = this.world.createEntity();
TextureRegion r = bannerTex.getFrame(i);
Sprite s = new Sprite(r);
s.setSize(FOV[3], 12);
s.setRotation(90);
s.setOrigin(0, 0);
e.addComponent(new Position(0, 0, 12, 0));
e.addComponent(new Scrollable(.35f, 0f, FOV[3]/bannerTex.getFrameWidth(), 1f, r));
e.addComponent(new Renderable(s));
gm.add(e, "Banner");
gm.add(e, "Banner"+(char)(i+65));
e.addToWorld();
e = this.world.createEntity();
s = new Sprite(r);
s.setSize(FOV[3], 12);
s.setRotation(-90);
s.setOrigin(0, 0);
s.flip(false, true);
e.addComponent(new Position(FOV[2], 0, -12, FOV[3]));
e.addComponent(new Scrollable(-.35f, 0f, 220f/bannerTex.getFrameWidth(), 1f, r));
e.addComponent(new Renderable(s));
gm.add(e, "Banner");
gm.add(e, "Banner"+(char)(i+65));
e.addToWorld();
}
this.world.initialize();
Engine.score = 0f;
Position p = (Position)Engine.player.getComponent(Position.CType);
p.location.x = FOV[2]/2.0f;
}
| public void start()
{
GroupManager gm = this.world.getManager(GroupManager.class);
TagManager tm = this.world.getManager(TagManager.class);
// place the enemies in the world
for (int i = 0; i < data.enemyData.size; i++)
{
SpawnSet s = data.enemyData.get(i);
for (int j = 0; j < s.spawns.size; j++)
{
Spawn enemy = s.spawns.get(j);
Entity e = this.world.createEntity();
e = s.atlas.createEnemy(enemy.name, e);
Position p = (Position)e.getComponent(Position.CType);
p.location.x = enemy.pos.x;
p.location.y = enemy.pos.y;
this.world.addEntity(e);
}
}
//create layered background
for (int i = 0; i < data.background.stack.size; i++)
{
Entity layer = this.world.createEntity();
FieldData f = data.background.stack.get(i);
Texture t = Engine.assets.get(f.image, Texture.class);
Sprite s = new Sprite(t);
if (f instanceof LayerData)
{
LayerData d = (LayerData)data.background.stack.get(i);
t.setWrap(TextureWrap.Repeat, TextureWrap.Repeat);
s.setSize(Math.max(t.getWidth(), FOV[2]), Math.max(t.getHeight(),FOV[3]));
layer.addComponent(new Position(), Position.CType);
layer.addComponent(new Scrollable(0, d.rate, Math.max(FOV[2]/(float)t.getWidth(), 1.0f), Math.max(FOV[3]/(float)t.getHeight(), 1.0f)), Scrollable.CType);
}
else if (f instanceof StaticData)
{
StaticData d = (StaticData)data.background.stack.get(i);
layer.addComponent(new Position(d.x, d.y), Position.CType);
layer.addComponent(new Angle(0), Angle.CType);
layer.addComponent(new Rotation(d.dps), Rotation.CType);
}
layer.addComponent(new Renderable(s), Renderable.CType);
gm.add(layer, "Field");
this.world.addEntity(layer);
}
//load banners
Texture t = Engine.assets.get(DataDir.Ui+"banners.png", Texture.class);
t.setWrap(TextureWrap.Repeat, TextureWrap.ClampToEdge);
SpriteSheet bannerTex = new SpriteSheet(t, 1, 3);
for (int i = 0; i < 3; i++)
{
Entity e = this.world.createEntity();
TextureRegion r = bannerTex.getFrame(i);
Sprite s = new Sprite(r);
s.setSize(FOV[3], 12);
s.setRotation(90);
s.setOrigin(0, 0);
e.addComponent(new Position(0, 0, 12, 0));
e.addComponent(new Scrollable(.35f, 0f, FOV[3]/bannerTex.getFrameWidth(), 1f, r));
e.addComponent(new Renderable(s));
gm.add(e, "Banner");
gm.add(e, "Banner"+(char)(i+65));
e.addToWorld();
e = this.world.createEntity();
s = new Sprite(r);
s.setSize(FOV[3], 12);
s.setRotation(-90);
s.setOrigin(0, 0);
s.flip(false, true);
e.addComponent(new Position(FOV[2], 0, -12, FOV[3]));
e.addComponent(new Scrollable(-.35f, 0f, 220f/bannerTex.getFrameWidth(), 1f, r));
e.addComponent(new Renderable(s));
gm.add(e, "Banner");
gm.add(e, "Banner"+(char)(i+65));
e.addToWorld();
}
this.world.initialize();
Engine.score = 0f;
Position p = (Position)Engine.player.getComponent(Position.CType);
p.location.x = FOV[2]/2.0f;
}
|
diff --git a/src/haven/GLFrameBuffer.java b/src/haven/GLFrameBuffer.java
index c0dcbefa..6ba006ae 100644
--- a/src/haven/GLFrameBuffer.java
+++ b/src/haven/GLFrameBuffer.java
@@ -1,176 +1,177 @@
/*
* This file is part of the Haven & Hearth game client.
* Copyright (C) 2009 Fredrik Tolf <[email protected]>, and
* Björn Johannessen <[email protected]>
*
* Redistribution and/or modification of this file is subject to the
* terms of the GNU Lesser General Public License, version 3, as
* published by the Free Software Foundation.
*
* 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 General Public License for more details.
*
* Other parts of this source tree adhere to other copying
* rights. Please see the file `COPYING' in the root directory of the
* source tree for details.
*
* A copy the GNU Lesser General Public License is distributed along
* with the source tree of which this file is a part in the file
* `doc/LPGL-3'. If it is missing for any reason, please see the Free
* Software Foundation's website at <http://www.fsf.org/>, or write
* to the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307 USA
*/
package haven;
import javax.media.opengl.*;
public class GLFrameBuffer extends GLState {
public static final Slot<GLFrameBuffer> slot = new Slot<GLFrameBuffer>(Slot.Type.SYS, GLFrameBuffer.class, HavenPanel.global);
private final TexGL[] color;
private final TexGL depth;
private final RenderBuffer altdepth;
private FBO fbo;
public static class FBO extends GLObject {
public final int id;
public FBO(GL gl) {
super(gl);
int[] buf = new int[1];
gl.glGenFramebuffersEXT(1, buf, 0);
this.id = buf[0];
GOut.checkerr(gl);
}
protected void delete() {
int[] buf = {id};
gl.glDeleteFramebuffersEXT(1, buf, 0);
GOut.checkerr(gl);
}
}
public static class RenderBuffer {
public final Coord sz;
public final int fmt;
private RBO rbo;
public RenderBuffer(Coord sz, int fmt) {
this.sz = sz;
this.fmt = fmt;
}
public int glid(GL gl) {
if((rbo != null) && (rbo.gl != gl))
dispose();
if(rbo == null) {
rbo = new RBO(gl);
gl.glBindRenderbufferEXT(GL.GL_RENDERBUFFER_EXT, rbo.id);
gl.glRenderbufferStorageEXT(GL.GL_RENDERBUFFER_EXT, fmt, sz.x, sz.y);
}
return(rbo.id);
}
public void dispose() {
synchronized(this) {
if(rbo != null) {
rbo.dispose();
rbo = null;
}
}
}
public static class RBO extends GLObject {
public final int id;
public RBO(GL gl) {
super(gl);
int[] buf = new int[1];
gl.glGenRenderbuffersEXT(1, buf, 0);
this.id = buf[0];
GOut.checkerr(gl);
}
protected void delete() {
int[] buf = {id};
gl.glDeleteRenderbuffersEXT(1, buf, 0);
GOut.checkerr(gl);
}
}
}
public GLFrameBuffer(TexGL color, TexGL depth) {
if(color == null)
this.color = new TexGL[0];
else
this.color = new TexGL[] {color};
if((this.depth = depth) == null) {
if(this.color.length == 0)
throw(new RuntimeException("Cannot create a framebuffer with neither color nor depth"));
this.altdepth = new RenderBuffer(this.color[0].tdim, GL.GL_DEPTH_COMPONENT);
} else {
this.altdepth = null;
}
}
public Coord sz() {
/* This is not perfect, but there's no current (or probably
* sane) situation where it would fail. */
if(depth != null)
return(depth.sz());
else
return(altdepth.sz);
}
public void apply(GOut g) {
GL gl = g.gl;
synchronized(this) {
if((fbo != null) && (fbo.gl != gl))
dispose();
if(fbo == null) {
fbo = new FBO(gl);
gl.glBindFramebufferEXT(GL.GL_FRAMEBUFFER_EXT, fbo.id);
for(int i = 0; i < color.length; i++)
gl.glFramebufferTexture2DEXT(GL.GL_FRAMEBUFFER_EXT, GL.GL_COLOR_ATTACHMENT0_EXT + i, GL.GL_TEXTURE_2D, color[i].glid(g), 0);
if(depth != null)
gl.glFramebufferTexture2DEXT(GL.GL_FRAMEBUFFER_EXT, GL.GL_DEPTH_ATTACHMENT_EXT, GL.GL_TEXTURE_2D, depth.glid(g), 0);
else
gl.glFramebufferRenderbufferEXT(GL.GL_FRAMEBUFFER_EXT, GL.GL_DEPTH_ATTACHMENT_EXT, GL.GL_RENDERBUFFER_EXT, altdepth.glid(gl));
+ GOut.checkerr(gl);
int st = gl.glCheckFramebufferStatusEXT(GL.GL_FRAMEBUFFER_EXT);
if(st != GL.GL_FRAMEBUFFER_COMPLETE_EXT)
throw(new RuntimeException("FBO failed completeness test: " + st));
} else {
gl.glBindFramebufferEXT(GL.GL_FRAMEBUFFER_EXT, fbo.id);
}
if(color.length == 0) {
gl.glDrawBuffer(GL.GL_NONE);
gl.glReadBuffer(GL.GL_NONE);
}
}
}
public void unapply(GOut g) {
GL gl = g.gl;
gl.glBindFramebufferEXT(GL.GL_FRAMEBUFFER_EXT, 0);
if(color.length == 0) {
gl.glDrawBuffer(GL.GL_BACK);
gl.glReadBuffer(GL.GL_BACK);
}
}
public void prep(Buffer buf) {
buf.put(slot, this);
}
public void dispose() {
synchronized(this) {
if(fbo != null) {
fbo.dispose();
fbo = null;
}
}
}
}
| true | true | public void apply(GOut g) {
GL gl = g.gl;
synchronized(this) {
if((fbo != null) && (fbo.gl != gl))
dispose();
if(fbo == null) {
fbo = new FBO(gl);
gl.glBindFramebufferEXT(GL.GL_FRAMEBUFFER_EXT, fbo.id);
for(int i = 0; i < color.length; i++)
gl.glFramebufferTexture2DEXT(GL.GL_FRAMEBUFFER_EXT, GL.GL_COLOR_ATTACHMENT0_EXT + i, GL.GL_TEXTURE_2D, color[i].glid(g), 0);
if(depth != null)
gl.glFramebufferTexture2DEXT(GL.GL_FRAMEBUFFER_EXT, GL.GL_DEPTH_ATTACHMENT_EXT, GL.GL_TEXTURE_2D, depth.glid(g), 0);
else
gl.glFramebufferRenderbufferEXT(GL.GL_FRAMEBUFFER_EXT, GL.GL_DEPTH_ATTACHMENT_EXT, GL.GL_RENDERBUFFER_EXT, altdepth.glid(gl));
int st = gl.glCheckFramebufferStatusEXT(GL.GL_FRAMEBUFFER_EXT);
if(st != GL.GL_FRAMEBUFFER_COMPLETE_EXT)
throw(new RuntimeException("FBO failed completeness test: " + st));
} else {
gl.glBindFramebufferEXT(GL.GL_FRAMEBUFFER_EXT, fbo.id);
}
if(color.length == 0) {
gl.glDrawBuffer(GL.GL_NONE);
gl.glReadBuffer(GL.GL_NONE);
}
}
}
| public void apply(GOut g) {
GL gl = g.gl;
synchronized(this) {
if((fbo != null) && (fbo.gl != gl))
dispose();
if(fbo == null) {
fbo = new FBO(gl);
gl.glBindFramebufferEXT(GL.GL_FRAMEBUFFER_EXT, fbo.id);
for(int i = 0; i < color.length; i++)
gl.glFramebufferTexture2DEXT(GL.GL_FRAMEBUFFER_EXT, GL.GL_COLOR_ATTACHMENT0_EXT + i, GL.GL_TEXTURE_2D, color[i].glid(g), 0);
if(depth != null)
gl.glFramebufferTexture2DEXT(GL.GL_FRAMEBUFFER_EXT, GL.GL_DEPTH_ATTACHMENT_EXT, GL.GL_TEXTURE_2D, depth.glid(g), 0);
else
gl.glFramebufferRenderbufferEXT(GL.GL_FRAMEBUFFER_EXT, GL.GL_DEPTH_ATTACHMENT_EXT, GL.GL_RENDERBUFFER_EXT, altdepth.glid(gl));
GOut.checkerr(gl);
int st = gl.glCheckFramebufferStatusEXT(GL.GL_FRAMEBUFFER_EXT);
if(st != GL.GL_FRAMEBUFFER_COMPLETE_EXT)
throw(new RuntimeException("FBO failed completeness test: " + st));
} else {
gl.glBindFramebufferEXT(GL.GL_FRAMEBUFFER_EXT, fbo.id);
}
if(color.length == 0) {
gl.glDrawBuffer(GL.GL_NONE);
gl.glReadBuffer(GL.GL_NONE);
}
}
}
|
diff --git a/common/src/com/intellij/plugins/haxe/util/HaxeCommonCompilerUtil.java b/common/src/com/intellij/plugins/haxe/util/HaxeCommonCompilerUtil.java
index e2f968b..f22f205 100644
--- a/common/src/com/intellij/plugins/haxe/util/HaxeCommonCompilerUtil.java
+++ b/common/src/com/intellij/plugins/haxe/util/HaxeCommonCompilerUtil.java
@@ -1,198 +1,201 @@
package com.intellij.plugins.haxe.util;
import com.intellij.execution.process.BaseOSProcessHandler;
import com.intellij.execution.process.ProcessAdapter;
import com.intellij.execution.process.ProcessEvent;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.plugins.haxe.HaxeCommonBundle;
import com.intellij.plugins.haxe.config.HaxeTarget;
import com.intellij.plugins.haxe.config.NMETarget;
import com.intellij.plugins.haxe.module.HaxeModuleSettingsBase;
import com.intellij.util.BooleanValueHolder;
import com.intellij.util.text.StringTokenizer;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
/**
* @author: Fedor.Korotkov
*/
public class HaxeCommonCompilerUtil {
public interface CompilationContext {
@NotNull
HaxeModuleSettingsBase getModuleSettings();
String getModuleName();
void errorHandler(String message);
void log(String message);
String getSdkHomePath();
boolean isDebug();
String getSdkName();
List<String> getSourceRoots();
String getCompileOutputPath();
boolean handleOutput(String[] lines);
}
public static boolean compile(final CompilationContext context) {
HaxeModuleSettingsBase settings = context.getModuleSettings();
if (settings.isExcludeFromCompilation()) {
context.log("Module " + context.getModuleName() + " is excluded from compilation.");
return true;
}
final String mainClass = settings.getMainClass();
final String fileName = settings.getOutputFileName();
if (settings.isUseUserPropertiesToBuild()) {
if (mainClass == null || mainClass.length() == 0) {
context.errorHandler(HaxeCommonBundle.message("no.main.class.for.module", context.getModuleName()));
return false;
}
if (fileName == null || fileName.length() == 0) {
context.errorHandler(HaxeCommonBundle.message("no.output.file.name.for.module", context.getModuleName()));
return false;
}
}
final HaxeTarget target = settings.getHaxeTarget();
final NMETarget nmeTarget = settings.getNmeTarget();
if (target == null && !settings.isUseNmmlToBuild()) {
context.errorHandler(HaxeCommonBundle.message("no.target.for.module", context.getModuleName()));
return false;
}
if (nmeTarget == null && settings.isUseNmmlToBuild()) {
context.errorHandler(HaxeCommonBundle.message("no.target.for.module", context.getModuleName()));
return false;
}
if (context.getSdkHomePath() == null) {
context.errorHandler(HaxeCommonBundle.message("no.sdk.for.module", context.getModuleName()));
return false;
}
final String sdkExePath = HaxeSdkUtilBase.getCompilerPathByFolderPath(context.getSdkHomePath());
if (sdkExePath == null || sdkExePath.isEmpty()) {
context.errorHandler(HaxeCommonBundle.message("invalid.haxe.sdk.for.module", context.getModuleName()));
return false;
}
final String haxelibPath = HaxeSdkUtilBase.getHaxelibPathByFolderPath(context.getSdkHomePath());
if (settings.isUseNmmlToBuild() && (haxelibPath == null || haxelibPath.isEmpty())) {
context.errorHandler(HaxeCommonBundle.message("no.haxelib.for.sdk", context.getSdkName()));
return false;
}
final List<String> commandLine = new ArrayList<String>();
if (settings.isUseNmmlToBuild()) {
commandLine.add(haxelibPath);
}
else {
commandLine.add(sdkExePath);
}
String workingPath = context.getCompileOutputPath() + "/" + (context.isDebug() ? "debug" : "release");
if (settings.isUseNmmlToBuild()) {
setupNME(commandLine, context);
}
else if (settings.isUseHxmlToBuild()) {
- String hxmlPath = FileUtil.toSystemDependentName(settings.getHxmlPath());
- commandLine.add(hxmlPath);
- workingPath = hxmlPath.substring(0, hxmlPath.lastIndexOf('/'));
+ String hxmlPath = settings.getHxmlPath();
+ commandLine.add(FileUtil.toSystemDependentName(hxmlPath));
+ final int endIndex = hxmlPath.lastIndexOf('/');
+ if (endIndex > 0) {
+ workingPath = hxmlPath.substring(0, endIndex);
+ }
if (context.isDebug() && settings.getHaxeTarget() == HaxeTarget.FLASH) {
commandLine.add("-D");
commandLine.add("fdb");
commandLine.add("-debug");
}
}
else {
setupUserProperties(commandLine, context);
}
final BooleanValueHolder hasErrors = new BooleanValueHolder(false);
try {
final File workingDirectory = new File(FileUtil.toSystemDependentName(workingPath));
if (!workingDirectory.exists()) {
workingDirectory.mkdir();
}
BaseOSProcessHandler handler = new BaseOSProcessHandler(
new ProcessBuilder(commandLine).directory(workingDirectory).start(),
null,
Charset.defaultCharset()
);
handler.addProcessListener(new ProcessAdapter() {
@Override
public void onTextAvailable(ProcessEvent event, Key outputType) {
final boolean messageHasErrors = context.handleOutput(event.getText().split("\\n"));
hasErrors.setValue(hasErrors.getValue() || messageHasErrors);
}
});
handler.startNotify();
handler.waitFor();
}
catch (IOException e) {
context.errorHandler("process throw exception: " + e.getMessage());
return false;
}
return !hasErrors.getValue();
}
private static void setupUserProperties(List<String> commandLine, CompilationContext context) {
final HaxeModuleSettingsBase settings = context.getModuleSettings();
commandLine.add("-main");
commandLine.add(settings.getMainClass());
final StringTokenizer argumentsTokenizer = new StringTokenizer(settings.getArguments());
while (argumentsTokenizer.hasMoreTokens()) {
commandLine.add(argumentsTokenizer.nextToken());
}
if (context.isDebug()) {
commandLine.add("-debug");
}
if (settings.getHaxeTarget() == HaxeTarget.FLASH && context.isDebug()) {
commandLine.add("-D");
commandLine.add("fdb");
}
for (String sourceRoot : context.getSourceRoots()) {
commandLine.add("-cp");
commandLine.add(sourceRoot);
}
commandLine.add(settings.getHaxeTarget().getCompilerFlag());
commandLine.add(settings.getOutputFileName());
}
private static void setupNME(List<String> commandLine, CompilationContext context) {
final HaxeModuleSettingsBase settings = context.getModuleSettings();
commandLine.add("run");
commandLine.add("nme");
commandLine.add("build");
commandLine.add(settings.getNmmlPath());
commandLine.add(settings.getNmeTarget().getTargetFlag());
if (context.isDebug()) {
commandLine.add("-Ddebug");
}
if (settings.getNmeTarget() == NMETarget.FLASH && context.isDebug()) {
commandLine.add("-Dfdb");
}
}
}
| true | true | public static boolean compile(final CompilationContext context) {
HaxeModuleSettingsBase settings = context.getModuleSettings();
if (settings.isExcludeFromCompilation()) {
context.log("Module " + context.getModuleName() + " is excluded from compilation.");
return true;
}
final String mainClass = settings.getMainClass();
final String fileName = settings.getOutputFileName();
if (settings.isUseUserPropertiesToBuild()) {
if (mainClass == null || mainClass.length() == 0) {
context.errorHandler(HaxeCommonBundle.message("no.main.class.for.module", context.getModuleName()));
return false;
}
if (fileName == null || fileName.length() == 0) {
context.errorHandler(HaxeCommonBundle.message("no.output.file.name.for.module", context.getModuleName()));
return false;
}
}
final HaxeTarget target = settings.getHaxeTarget();
final NMETarget nmeTarget = settings.getNmeTarget();
if (target == null && !settings.isUseNmmlToBuild()) {
context.errorHandler(HaxeCommonBundle.message("no.target.for.module", context.getModuleName()));
return false;
}
if (nmeTarget == null && settings.isUseNmmlToBuild()) {
context.errorHandler(HaxeCommonBundle.message("no.target.for.module", context.getModuleName()));
return false;
}
if (context.getSdkHomePath() == null) {
context.errorHandler(HaxeCommonBundle.message("no.sdk.for.module", context.getModuleName()));
return false;
}
final String sdkExePath = HaxeSdkUtilBase.getCompilerPathByFolderPath(context.getSdkHomePath());
if (sdkExePath == null || sdkExePath.isEmpty()) {
context.errorHandler(HaxeCommonBundle.message("invalid.haxe.sdk.for.module", context.getModuleName()));
return false;
}
final String haxelibPath = HaxeSdkUtilBase.getHaxelibPathByFolderPath(context.getSdkHomePath());
if (settings.isUseNmmlToBuild() && (haxelibPath == null || haxelibPath.isEmpty())) {
context.errorHandler(HaxeCommonBundle.message("no.haxelib.for.sdk", context.getSdkName()));
return false;
}
final List<String> commandLine = new ArrayList<String>();
if (settings.isUseNmmlToBuild()) {
commandLine.add(haxelibPath);
}
else {
commandLine.add(sdkExePath);
}
String workingPath = context.getCompileOutputPath() + "/" + (context.isDebug() ? "debug" : "release");
if (settings.isUseNmmlToBuild()) {
setupNME(commandLine, context);
}
else if (settings.isUseHxmlToBuild()) {
String hxmlPath = FileUtil.toSystemDependentName(settings.getHxmlPath());
commandLine.add(hxmlPath);
workingPath = hxmlPath.substring(0, hxmlPath.lastIndexOf('/'));
if (context.isDebug() && settings.getHaxeTarget() == HaxeTarget.FLASH) {
commandLine.add("-D");
commandLine.add("fdb");
commandLine.add("-debug");
}
}
else {
setupUserProperties(commandLine, context);
}
final BooleanValueHolder hasErrors = new BooleanValueHolder(false);
try {
final File workingDirectory = new File(FileUtil.toSystemDependentName(workingPath));
if (!workingDirectory.exists()) {
workingDirectory.mkdir();
}
BaseOSProcessHandler handler = new BaseOSProcessHandler(
new ProcessBuilder(commandLine).directory(workingDirectory).start(),
null,
Charset.defaultCharset()
);
handler.addProcessListener(new ProcessAdapter() {
@Override
public void onTextAvailable(ProcessEvent event, Key outputType) {
final boolean messageHasErrors = context.handleOutput(event.getText().split("\\n"));
hasErrors.setValue(hasErrors.getValue() || messageHasErrors);
}
});
handler.startNotify();
handler.waitFor();
}
catch (IOException e) {
context.errorHandler("process throw exception: " + e.getMessage());
return false;
}
return !hasErrors.getValue();
}
| public static boolean compile(final CompilationContext context) {
HaxeModuleSettingsBase settings = context.getModuleSettings();
if (settings.isExcludeFromCompilation()) {
context.log("Module " + context.getModuleName() + " is excluded from compilation.");
return true;
}
final String mainClass = settings.getMainClass();
final String fileName = settings.getOutputFileName();
if (settings.isUseUserPropertiesToBuild()) {
if (mainClass == null || mainClass.length() == 0) {
context.errorHandler(HaxeCommonBundle.message("no.main.class.for.module", context.getModuleName()));
return false;
}
if (fileName == null || fileName.length() == 0) {
context.errorHandler(HaxeCommonBundle.message("no.output.file.name.for.module", context.getModuleName()));
return false;
}
}
final HaxeTarget target = settings.getHaxeTarget();
final NMETarget nmeTarget = settings.getNmeTarget();
if (target == null && !settings.isUseNmmlToBuild()) {
context.errorHandler(HaxeCommonBundle.message("no.target.for.module", context.getModuleName()));
return false;
}
if (nmeTarget == null && settings.isUseNmmlToBuild()) {
context.errorHandler(HaxeCommonBundle.message("no.target.for.module", context.getModuleName()));
return false;
}
if (context.getSdkHomePath() == null) {
context.errorHandler(HaxeCommonBundle.message("no.sdk.for.module", context.getModuleName()));
return false;
}
final String sdkExePath = HaxeSdkUtilBase.getCompilerPathByFolderPath(context.getSdkHomePath());
if (sdkExePath == null || sdkExePath.isEmpty()) {
context.errorHandler(HaxeCommonBundle.message("invalid.haxe.sdk.for.module", context.getModuleName()));
return false;
}
final String haxelibPath = HaxeSdkUtilBase.getHaxelibPathByFolderPath(context.getSdkHomePath());
if (settings.isUseNmmlToBuild() && (haxelibPath == null || haxelibPath.isEmpty())) {
context.errorHandler(HaxeCommonBundle.message("no.haxelib.for.sdk", context.getSdkName()));
return false;
}
final List<String> commandLine = new ArrayList<String>();
if (settings.isUseNmmlToBuild()) {
commandLine.add(haxelibPath);
}
else {
commandLine.add(sdkExePath);
}
String workingPath = context.getCompileOutputPath() + "/" + (context.isDebug() ? "debug" : "release");
if (settings.isUseNmmlToBuild()) {
setupNME(commandLine, context);
}
else if (settings.isUseHxmlToBuild()) {
String hxmlPath = settings.getHxmlPath();
commandLine.add(FileUtil.toSystemDependentName(hxmlPath));
final int endIndex = hxmlPath.lastIndexOf('/');
if (endIndex > 0) {
workingPath = hxmlPath.substring(0, endIndex);
}
if (context.isDebug() && settings.getHaxeTarget() == HaxeTarget.FLASH) {
commandLine.add("-D");
commandLine.add("fdb");
commandLine.add("-debug");
}
}
else {
setupUserProperties(commandLine, context);
}
final BooleanValueHolder hasErrors = new BooleanValueHolder(false);
try {
final File workingDirectory = new File(FileUtil.toSystemDependentName(workingPath));
if (!workingDirectory.exists()) {
workingDirectory.mkdir();
}
BaseOSProcessHandler handler = new BaseOSProcessHandler(
new ProcessBuilder(commandLine).directory(workingDirectory).start(),
null,
Charset.defaultCharset()
);
handler.addProcessListener(new ProcessAdapter() {
@Override
public void onTextAvailable(ProcessEvent event, Key outputType) {
final boolean messageHasErrors = context.handleOutput(event.getText().split("\\n"));
hasErrors.setValue(hasErrors.getValue() || messageHasErrors);
}
});
handler.startNotify();
handler.waitFor();
}
catch (IOException e) {
context.errorHandler("process throw exception: " + e.getMessage());
return false;
}
return !hasErrors.getValue();
}
|
diff --git a/net/sf/mpxj/sample/MpxjCreate.java b/net/sf/mpxj/sample/MpxjCreate.java
index 5a75ee0..0dc137c 100644
--- a/net/sf/mpxj/sample/MpxjCreate.java
+++ b/net/sf/mpxj/sample/MpxjCreate.java
@@ -1,310 +1,310 @@
/*
* file: MpxCreate.java
* author: Jon Iles
* copyright: (c) Packwood Software Limited 2002-2003
* date: 08/02/2003
*/
/*
* This library 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 library 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 library; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
package net.sf.mpxj.sample;
import java.text.SimpleDateFormat;
import net.sf.mpxj.Duration;
import net.sf.mpxj.ProjectCalendar;
import net.sf.mpxj.ProjectCalendarException;
import net.sf.mpxj.ProjectFile;
import net.sf.mpxj.ProjectHeader;
import net.sf.mpxj.Relation;
import net.sf.mpxj.RelationType;
import net.sf.mpxj.Resource;
import net.sf.mpxj.ResourceAssignment;
import net.sf.mpxj.Task;
import net.sf.mpxj.TimeUnit;
import net.sf.mpxj.mpx.MPXWriter;
import net.sf.mpxj.mspdi.MSPDIWriter;
import net.sf.mpxj.utility.NumberUtility;
import net.sf.mpxj.writer.ProjectWriter;
/**
* This example illustrates creation of an MPX or an MSPDI file from scratch.
* The output type of the file generated by this class depends on the file
* name extension supplied by the user. A .xml extension will generate an
* MSPDI file, anything else will generate an MPX file.
*/
public class MpxjCreate
{
/**
* Main method.
*
* @param args array of command line arguments
*/
public static void main (String[] args)
{
try
{
if (args.length != 1)
{
System.out.println ("Usage: MpxCreate <output file name>");
}
else
{
create (args[0]);
}
}
catch (Exception ex)
{
ex.printStackTrace(System.out);
}
}
/**
* Creates a writer which will generate the required type of output file.
*
* @param filename file name
* @return ProjectWriter instance
*/
private static ProjectWriter getWriter (String filename)
{
ProjectWriter result;
String suffix;
if (filename.length() < 4)
{
suffix = ".MPX";
}
else
{
suffix = filename.substring(filename.length()-4).toUpperCase();
}
if (suffix.equals(".XML") == true)
{
result = new MSPDIWriter ();
}
else
{
result = new MPXWriter ();
}
return (result);
}
/**
* This method creates a summary task, two sub-tasks and a milestone,
* all with the appropriate constraints between them. The tasks are
* assigned to two resources. Note that Microsoft Project is fussy
* about the order in which things appear in the file. If you are going
* to assign resources to tasks, the resources must appear in the
* file before the tasks.
*
* @param filename output file name
*/
private static void create (String filename)
throws Exception
{
//
// Create a simple date format to allow us to
// easily set date values.
//
SimpleDateFormat df = new SimpleDateFormat ("dd/MM/yyyy");
//
// Create an empty MPX or MSPDI file. The filename is passed to
// this method purely to allow it to determine the type of
// file to create.
//
ProjectFile file = new ProjectFile();
//
// Uncomment these lines to test the use of alternative
// delimiters and separators for MPX file output.
//
//file.setDelimiter(';');
//file.setDecimalSeparator(',');
//file.setThousandsSeparator('.');
//
// Configure the file to automatically generate identifiers for tasks.
//
file.setAutoTaskID(true);
file.setAutoTaskUniqueID(true);
//
// Configure the file to automatically generate identifiers for resources.
//
file.setAutoResourceID(true);
file.setAutoResourceUniqueID(true);
//
// Configure the file to automatically generate outline levels
// and outline numbers.
//
file.setAutoOutlineLevel(true);
file.setAutoOutlineNumber(true);
//
// Configure the file to automatically generate WBS labels
//
file.setAutoWBS(true);
//
// Configure the file to automatically generate identifiers for calendars
// (not strictly necessary here, but required if generating MSPDI files)
//
file.setAutoCalendarUniqueID(true);
//
// Add a default calendar called "Standard"
//
ProjectCalendar calendar = file.addDefaultBaseCalendar();
//
// Add a holiday to the calendar to demonstrate calendar exceptions
//
ProjectCalendarException exception = calendar.addCalendarException();
exception.setFromDate(df.parse("13/03/2006"));
exception.setToDate(df.parse("13/03/2006"));
exception.setWorking(false);
//
// Retrieve the project header and set the start date. Note Microsoft
// Project appears to reset all task dates relative to this date, so this
// date must match the start date of the earliest task for you to see
// the expected results. If this value is not set, it will default to
// today's date.
//
ProjectHeader header = file.getProjectHeader();
header.setStartDate(df.parse("01/01/2003"));
//
// Add resources
//
Resource resource1 = file.addResource();
resource1.setName("Resource1");
Resource resource2 = file.addResource();
resource2.setName("Resource2");
//
// This next line is not required, it is here simply to test the
// output file format when alternative separators and delimiters
// are used.
//
resource2.setMaxUnits(new Double(50.0));
//
// Create a summary task
//
Task task1 = file.addTask();
task1.setName ("Summary Task");
//
// Create the first sub task
//
Task task2 = task1.addTask();
task2.setName ("First Sub Task");
task2.setDuration (Duration.getInstance (10.5, TimeUnit.DAYS));
task2.setStart (df.parse("01/01/2003"));
//
// We'll set this task up as being 50% complete. If we have no resource
// assignments for this task, this is enough information for MS Project.
// If we do have resource assignments, the assignment record needs to
// contain the corresponding work and actual work fields set to the
// correct values in order for MS project to mark the task as complete
// or partially complete.
//
task2.setPercentageComplete(NumberUtility.getDouble(50.0));
task2.setActualStart(df.parse("01/01/2003"));
//
// Create the second sub task
//
Task task3 = task1.addTask();
task3.setName ("Second Sub Task");
task3.setStart (df.parse("11/01/2003"));
task3.setDuration (Duration.getInstance (10, TimeUnit.DAYS));
//
// Link these two tasks
//
Relation rel1 = task3.addPredecessor (task2);
rel1.setType(RelationType.FINISH_START);
//
// Add a milestone
//
Task milestone1 = task1.addTask();
milestone1.setName ("Milestone");
milestone1.setStart (df.parse("21/01/2003"));
milestone1.setDuration (Duration.getInstance (0, TimeUnit.DAYS));
Relation rel2 = milestone1.addPredecessor (task3);
rel2.setType (RelationType.FINISH_START);
//
// This final task has a percent complete value, but no
- // resource assignments. This is an intersting case it it requires
+ // resource assignments. This is an interesting case it it requires
// special processing to generate the MSPDI file correctly.
//
Task task4 = file.addTask();
task4.setName ("Last Task");
task4.setDuration (Duration.getInstance (8, TimeUnit.DAYS));
task4.setStart (df.parse("01/01/2003"));
task4.setPercentageComplete(NumberUtility.getDouble(70.0));
task4.setActualStart(df.parse("01/01/2003"));
//
// Assign resources to tasks
//
ResourceAssignment assignment1 = task2.addResourceAssignment (resource1);
ResourceAssignment assignment2 = task3.addResourceAssignment (resource2);
//
// As the first task is partially complete, and we are adding
// a resource assignment, we must set the work and actual work
// fields in the assignment to appropriate values, or MS Project
// won't recognise the task as being complete or partially complete
//
assignment1.setWork(Duration.getInstance (80, TimeUnit.HOURS));
assignment1.setActualWork(Duration.getInstance (40, TimeUnit.HOURS));
//
// If we were just generating an MPX file, we would already have enough
// attributes set to create the file correctly. If we want to generate
// an MSPDI file, we must also set the assignment start dates and
// the remaining work attribute. The assignment start dates will normally
// be the same as the task start dates.
//
assignment1.setRemainingWork(Duration.getInstance (40, TimeUnit.HOURS));
assignment2.setRemainingWork(Duration.getInstance (80, TimeUnit.HOURS));
assignment1.setStart(df.parse("01/01/2003"));
assignment2.setStart(df.parse("11/01/2003"));
//
// Write the file
//
ProjectWriter writer = getWriter(filename);
writer.write (file, filename);
}
}
| true | true | private static void create (String filename)
throws Exception
{
//
// Create a simple date format to allow us to
// easily set date values.
//
SimpleDateFormat df = new SimpleDateFormat ("dd/MM/yyyy");
//
// Create an empty MPX or MSPDI file. The filename is passed to
// this method purely to allow it to determine the type of
// file to create.
//
ProjectFile file = new ProjectFile();
//
// Uncomment these lines to test the use of alternative
// delimiters and separators for MPX file output.
//
//file.setDelimiter(';');
//file.setDecimalSeparator(',');
//file.setThousandsSeparator('.');
//
// Configure the file to automatically generate identifiers for tasks.
//
file.setAutoTaskID(true);
file.setAutoTaskUniqueID(true);
//
// Configure the file to automatically generate identifiers for resources.
//
file.setAutoResourceID(true);
file.setAutoResourceUniqueID(true);
//
// Configure the file to automatically generate outline levels
// and outline numbers.
//
file.setAutoOutlineLevel(true);
file.setAutoOutlineNumber(true);
//
// Configure the file to automatically generate WBS labels
//
file.setAutoWBS(true);
//
// Configure the file to automatically generate identifiers for calendars
// (not strictly necessary here, but required if generating MSPDI files)
//
file.setAutoCalendarUniqueID(true);
//
// Add a default calendar called "Standard"
//
ProjectCalendar calendar = file.addDefaultBaseCalendar();
//
// Add a holiday to the calendar to demonstrate calendar exceptions
//
ProjectCalendarException exception = calendar.addCalendarException();
exception.setFromDate(df.parse("13/03/2006"));
exception.setToDate(df.parse("13/03/2006"));
exception.setWorking(false);
//
// Retrieve the project header and set the start date. Note Microsoft
// Project appears to reset all task dates relative to this date, so this
// date must match the start date of the earliest task for you to see
// the expected results. If this value is not set, it will default to
// today's date.
//
ProjectHeader header = file.getProjectHeader();
header.setStartDate(df.parse("01/01/2003"));
//
// Add resources
//
Resource resource1 = file.addResource();
resource1.setName("Resource1");
Resource resource2 = file.addResource();
resource2.setName("Resource2");
//
// This next line is not required, it is here simply to test the
// output file format when alternative separators and delimiters
// are used.
//
resource2.setMaxUnits(new Double(50.0));
//
// Create a summary task
//
Task task1 = file.addTask();
task1.setName ("Summary Task");
//
// Create the first sub task
//
Task task2 = task1.addTask();
task2.setName ("First Sub Task");
task2.setDuration (Duration.getInstance (10.5, TimeUnit.DAYS));
task2.setStart (df.parse("01/01/2003"));
//
// We'll set this task up as being 50% complete. If we have no resource
// assignments for this task, this is enough information for MS Project.
// If we do have resource assignments, the assignment record needs to
// contain the corresponding work and actual work fields set to the
// correct values in order for MS project to mark the task as complete
// or partially complete.
//
task2.setPercentageComplete(NumberUtility.getDouble(50.0));
task2.setActualStart(df.parse("01/01/2003"));
//
// Create the second sub task
//
Task task3 = task1.addTask();
task3.setName ("Second Sub Task");
task3.setStart (df.parse("11/01/2003"));
task3.setDuration (Duration.getInstance (10, TimeUnit.DAYS));
//
// Link these two tasks
//
Relation rel1 = task3.addPredecessor (task2);
rel1.setType(RelationType.FINISH_START);
//
// Add a milestone
//
Task milestone1 = task1.addTask();
milestone1.setName ("Milestone");
milestone1.setStart (df.parse("21/01/2003"));
milestone1.setDuration (Duration.getInstance (0, TimeUnit.DAYS));
Relation rel2 = milestone1.addPredecessor (task3);
rel2.setType (RelationType.FINISH_START);
//
// This final task has a percent complete value, but no
// resource assignments. This is an intersting case it it requires
// special processing to generate the MSPDI file correctly.
//
Task task4 = file.addTask();
task4.setName ("Last Task");
task4.setDuration (Duration.getInstance (8, TimeUnit.DAYS));
task4.setStart (df.parse("01/01/2003"));
task4.setPercentageComplete(NumberUtility.getDouble(70.0));
task4.setActualStart(df.parse("01/01/2003"));
//
// Assign resources to tasks
//
ResourceAssignment assignment1 = task2.addResourceAssignment (resource1);
ResourceAssignment assignment2 = task3.addResourceAssignment (resource2);
//
// As the first task is partially complete, and we are adding
// a resource assignment, we must set the work and actual work
// fields in the assignment to appropriate values, or MS Project
// won't recognise the task as being complete or partially complete
//
assignment1.setWork(Duration.getInstance (80, TimeUnit.HOURS));
assignment1.setActualWork(Duration.getInstance (40, TimeUnit.HOURS));
//
// If we were just generating an MPX file, we would already have enough
// attributes set to create the file correctly. If we want to generate
// an MSPDI file, we must also set the assignment start dates and
// the remaining work attribute. The assignment start dates will normally
// be the same as the task start dates.
//
assignment1.setRemainingWork(Duration.getInstance (40, TimeUnit.HOURS));
assignment2.setRemainingWork(Duration.getInstance (80, TimeUnit.HOURS));
assignment1.setStart(df.parse("01/01/2003"));
assignment2.setStart(df.parse("11/01/2003"));
//
// Write the file
//
ProjectWriter writer = getWriter(filename);
writer.write (file, filename);
}
| private static void create (String filename)
throws Exception
{
//
// Create a simple date format to allow us to
// easily set date values.
//
SimpleDateFormat df = new SimpleDateFormat ("dd/MM/yyyy");
//
// Create an empty MPX or MSPDI file. The filename is passed to
// this method purely to allow it to determine the type of
// file to create.
//
ProjectFile file = new ProjectFile();
//
// Uncomment these lines to test the use of alternative
// delimiters and separators for MPX file output.
//
//file.setDelimiter(';');
//file.setDecimalSeparator(',');
//file.setThousandsSeparator('.');
//
// Configure the file to automatically generate identifiers for tasks.
//
file.setAutoTaskID(true);
file.setAutoTaskUniqueID(true);
//
// Configure the file to automatically generate identifiers for resources.
//
file.setAutoResourceID(true);
file.setAutoResourceUniqueID(true);
//
// Configure the file to automatically generate outline levels
// and outline numbers.
//
file.setAutoOutlineLevel(true);
file.setAutoOutlineNumber(true);
//
// Configure the file to automatically generate WBS labels
//
file.setAutoWBS(true);
//
// Configure the file to automatically generate identifiers for calendars
// (not strictly necessary here, but required if generating MSPDI files)
//
file.setAutoCalendarUniqueID(true);
//
// Add a default calendar called "Standard"
//
ProjectCalendar calendar = file.addDefaultBaseCalendar();
//
// Add a holiday to the calendar to demonstrate calendar exceptions
//
ProjectCalendarException exception = calendar.addCalendarException();
exception.setFromDate(df.parse("13/03/2006"));
exception.setToDate(df.parse("13/03/2006"));
exception.setWorking(false);
//
// Retrieve the project header and set the start date. Note Microsoft
// Project appears to reset all task dates relative to this date, so this
// date must match the start date of the earliest task for you to see
// the expected results. If this value is not set, it will default to
// today's date.
//
ProjectHeader header = file.getProjectHeader();
header.setStartDate(df.parse("01/01/2003"));
//
// Add resources
//
Resource resource1 = file.addResource();
resource1.setName("Resource1");
Resource resource2 = file.addResource();
resource2.setName("Resource2");
//
// This next line is not required, it is here simply to test the
// output file format when alternative separators and delimiters
// are used.
//
resource2.setMaxUnits(new Double(50.0));
//
// Create a summary task
//
Task task1 = file.addTask();
task1.setName ("Summary Task");
//
// Create the first sub task
//
Task task2 = task1.addTask();
task2.setName ("First Sub Task");
task2.setDuration (Duration.getInstance (10.5, TimeUnit.DAYS));
task2.setStart (df.parse("01/01/2003"));
//
// We'll set this task up as being 50% complete. If we have no resource
// assignments for this task, this is enough information for MS Project.
// If we do have resource assignments, the assignment record needs to
// contain the corresponding work and actual work fields set to the
// correct values in order for MS project to mark the task as complete
// or partially complete.
//
task2.setPercentageComplete(NumberUtility.getDouble(50.0));
task2.setActualStart(df.parse("01/01/2003"));
//
// Create the second sub task
//
Task task3 = task1.addTask();
task3.setName ("Second Sub Task");
task3.setStart (df.parse("11/01/2003"));
task3.setDuration (Duration.getInstance (10, TimeUnit.DAYS));
//
// Link these two tasks
//
Relation rel1 = task3.addPredecessor (task2);
rel1.setType(RelationType.FINISH_START);
//
// Add a milestone
//
Task milestone1 = task1.addTask();
milestone1.setName ("Milestone");
milestone1.setStart (df.parse("21/01/2003"));
milestone1.setDuration (Duration.getInstance (0, TimeUnit.DAYS));
Relation rel2 = milestone1.addPredecessor (task3);
rel2.setType (RelationType.FINISH_START);
//
// This final task has a percent complete value, but no
// resource assignments. This is an interesting case it it requires
// special processing to generate the MSPDI file correctly.
//
Task task4 = file.addTask();
task4.setName ("Last Task");
task4.setDuration (Duration.getInstance (8, TimeUnit.DAYS));
task4.setStart (df.parse("01/01/2003"));
task4.setPercentageComplete(NumberUtility.getDouble(70.0));
task4.setActualStart(df.parse("01/01/2003"));
//
// Assign resources to tasks
//
ResourceAssignment assignment1 = task2.addResourceAssignment (resource1);
ResourceAssignment assignment2 = task3.addResourceAssignment (resource2);
//
// As the first task is partially complete, and we are adding
// a resource assignment, we must set the work and actual work
// fields in the assignment to appropriate values, or MS Project
// won't recognise the task as being complete or partially complete
//
assignment1.setWork(Duration.getInstance (80, TimeUnit.HOURS));
assignment1.setActualWork(Duration.getInstance (40, TimeUnit.HOURS));
//
// If we were just generating an MPX file, we would already have enough
// attributes set to create the file correctly. If we want to generate
// an MSPDI file, we must also set the assignment start dates and
// the remaining work attribute. The assignment start dates will normally
// be the same as the task start dates.
//
assignment1.setRemainingWork(Duration.getInstance (40, TimeUnit.HOURS));
assignment2.setRemainingWork(Duration.getInstance (80, TimeUnit.HOURS));
assignment1.setStart(df.parse("01/01/2003"));
assignment2.setStart(df.parse("11/01/2003"));
//
// Write the file
//
ProjectWriter writer = getWriter(filename);
writer.write (file, filename);
}
|
diff --git a/org.eclipse.jdt.debug.tests/tests/org/eclipse/jdt/debug/tests/viewers/ChildrenUpdateTests.java b/org.eclipse.jdt.debug.tests/tests/org/eclipse/jdt/debug/tests/viewers/ChildrenUpdateTests.java
index 84a6c8d2e..11189ae0a 100644
--- a/org.eclipse.jdt.debug.tests/tests/org/eclipse/jdt/debug/tests/viewers/ChildrenUpdateTests.java
+++ b/org.eclipse.jdt.debug.tests/tests/org/eclipse/jdt/debug/tests/viewers/ChildrenUpdateTests.java
@@ -1,220 +1,220 @@
/*******************************************************************************
* Copyright (c) 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.debug.tests.viewers;
import org.eclipse.debug.internal.ui.DebugUIPlugin;
import org.eclipse.debug.internal.ui.viewers.model.ChildrenUpdate;
import org.eclipse.debug.internal.ui.viewers.model.ILabelUpdateListener;
import org.eclipse.debug.internal.ui.viewers.model.ITreeModelContentProviderTarget;
import org.eclipse.debug.internal.ui.viewers.model.TreeModelContentProvider;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IModelChangedListener;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IModelDelta;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IPresentationContext;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IViewerUpdateListener;
import org.eclipse.debug.internal.ui.viewers.model.provisional.ModelDelta;
import org.eclipse.jdt.debug.tests.AbstractDebugTest;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.jface.viewers.ViewerLabel;
import org.eclipse.swt.widgets.Display;
/**
* Tests coalescing of children update requests.
*
* @since 3.3
*/
public class ChildrenUpdateTests extends AbstractDebugTest {
class BogusModelContentProvider extends TreeModelContentProvider {
/* (non-Javadoc)
* @see org.eclipse.debug.internal.ui.viewers.model.ModelContentProvider#getViewer()
*/
protected ITreeModelContentProviderTarget getViewer() {
return new ITreeModelContentProviderTarget(){
public void setSelection(ISelection selection) {
}
public void removeSelectionChangedListener(ISelectionChangedListener listener) {
}
public void addSelectionChangedListener(ISelectionChangedListener listener) {
}
public void updateViewer(IModelDelta delta) {
}
- public void setSelection(ISelection selection, boolean reveal) {
+ public void setSelection(ISelection selection, boolean reveal, boolean force) {
}
public void setInput(Object object) {
}
public void setAutoExpandLevel(int level) {
}
public void saveElementState(TreePath path, ModelDelta delta) {
}
public void removeViewerUpdateListener(IViewerUpdateListener listener) {
}
public void removeModelChangedListener(IModelChangedListener listener) {
}
public void removeLabelUpdateListener(ILabelUpdateListener listener) {
}
public ISelection getSelection() {
return null;
}
public IPresentationContext getPresentationContext() {
return null;
}
public Object getInput() {
return null;
}
public ViewerLabel getElementLabel(TreePath path, String columnId) {
return null;
}
public Display getDisplay() {
return DebugUIPlugin.getStandardDisplay();
}
public int getAutoExpandLevel() {
return 0;
}
public void addViewerUpdateListener(IViewerUpdateListener listener) {
}
public void addModelChangedListener(IModelChangedListener listener) {
}
public void addLabelUpdateListener(ILabelUpdateListener listener) {
}
public void update(Object element) {
}
public void setHasChildren(Object elementOrTreePath, boolean hasChildren) {
}
public void setExpandedState(Object elementOrTreePath, boolean expanded) {
}
public void setChildCount(Object elementOrTreePath, int count) {
}
public void reveal(TreePath path, int index) {
}
public void replace(Object parentOrTreePath, int index, Object element) {
}
public void remove(Object parentOrTreePath, int index) {
}
public void remove(Object elementOrTreePath) {
}
public void refresh() {
}
public void refresh(Object element) {
}
public boolean overrideSelection(ISelection current, ISelection candidate) {
return false;
}
public void insert(Object parentOrTreePath, Object element, int position) {
}
public TreePath getTopElementPath() {
return null;
}
public ViewerFilter[] getFilters() {
return null;
}
public boolean getExpandedState(Object elementOrTreePath) {
return false;
}
public Object getChildElement(TreePath path, int index) {
return null;
}
public int getChildCount(TreePath path) {
return 0;
}
public int findElementIndex(TreePath parentPath, Object element) {
return 0;
}
public void expandToLevel(Object elementOrTreePath, int level) {
}
public void autoExpand(TreePath elementPath) {
}
};
}
}
/**
* @param name
*/
public ChildrenUpdateTests(String name) {
super(name);
}
protected TreeModelContentProvider getContentProvider() {
return new BogusModelContentProvider();
}
/**
* Tests coalescing of requests
*/
public void testCoalesce () {
Object element = new Object();
TreeModelContentProvider cp = getContentProvider();
ChildrenUpdate update1 = new ChildrenUpdate(cp, element, TreePath.EMPTY, element, 1, null, null);
ChildrenUpdate update2 = new ChildrenUpdate(cp, element, TreePath.EMPTY, element, 2, null, null);
assertTrue("Should coalesce", update1.coalesce(update2));
assertEquals("Wrong offset", 1, update1.getOffset());
assertEquals("Wrong length", 2, update1.getLength());
update2 = new ChildrenUpdate(cp, element, TreePath.EMPTY, element, 3, null, null);
assertTrue("Should coalesce", update1.coalesce(update2));
assertEquals("Wrong offset", 1, update1.getOffset());
assertEquals("Wrong length", 3, update1.getLength());
update2 = new ChildrenUpdate(cp, element, TreePath.EMPTY, element, 2, null, null);
assertTrue("Should coalesce", update1.coalesce(update2));
assertEquals("Wrong offset", 1, update1.getOffset());
assertEquals("Wrong length", 3, update1.getLength());
update2 = new ChildrenUpdate(cp, element, TreePath.EMPTY, element, 5, null, null);
assertFalse("Should not coalesce", update1.coalesce(update2));
assertEquals("Wrong offset", 1, update1.getOffset());
assertEquals("Wrong length", 3, update1.getLength());
}
}
| true | true | protected ITreeModelContentProviderTarget getViewer() {
return new ITreeModelContentProviderTarget(){
public void setSelection(ISelection selection) {
}
public void removeSelectionChangedListener(ISelectionChangedListener listener) {
}
public void addSelectionChangedListener(ISelectionChangedListener listener) {
}
public void updateViewer(IModelDelta delta) {
}
public void setSelection(ISelection selection, boolean reveal) {
}
public void setInput(Object object) {
}
public void setAutoExpandLevel(int level) {
}
public void saveElementState(TreePath path, ModelDelta delta) {
}
public void removeViewerUpdateListener(IViewerUpdateListener listener) {
}
public void removeModelChangedListener(IModelChangedListener listener) {
}
public void removeLabelUpdateListener(ILabelUpdateListener listener) {
}
public ISelection getSelection() {
return null;
}
public IPresentationContext getPresentationContext() {
return null;
}
public Object getInput() {
return null;
}
public ViewerLabel getElementLabel(TreePath path, String columnId) {
return null;
}
public Display getDisplay() {
return DebugUIPlugin.getStandardDisplay();
}
public int getAutoExpandLevel() {
return 0;
}
public void addViewerUpdateListener(IViewerUpdateListener listener) {
}
public void addModelChangedListener(IModelChangedListener listener) {
}
public void addLabelUpdateListener(ILabelUpdateListener listener) {
}
public void update(Object element) {
}
public void setHasChildren(Object elementOrTreePath, boolean hasChildren) {
}
public void setExpandedState(Object elementOrTreePath, boolean expanded) {
}
public void setChildCount(Object elementOrTreePath, int count) {
}
public void reveal(TreePath path, int index) {
}
public void replace(Object parentOrTreePath, int index, Object element) {
}
public void remove(Object parentOrTreePath, int index) {
}
public void remove(Object elementOrTreePath) {
}
public void refresh() {
}
public void refresh(Object element) {
}
public boolean overrideSelection(ISelection current, ISelection candidate) {
return false;
}
public void insert(Object parentOrTreePath, Object element, int position) {
}
public TreePath getTopElementPath() {
return null;
}
public ViewerFilter[] getFilters() {
return null;
}
public boolean getExpandedState(Object elementOrTreePath) {
return false;
}
public Object getChildElement(TreePath path, int index) {
return null;
}
public int getChildCount(TreePath path) {
return 0;
}
public int findElementIndex(TreePath parentPath, Object element) {
return 0;
}
public void expandToLevel(Object elementOrTreePath, int level) {
}
public void autoExpand(TreePath elementPath) {
}
};
}
| protected ITreeModelContentProviderTarget getViewer() {
return new ITreeModelContentProviderTarget(){
public void setSelection(ISelection selection) {
}
public void removeSelectionChangedListener(ISelectionChangedListener listener) {
}
public void addSelectionChangedListener(ISelectionChangedListener listener) {
}
public void updateViewer(IModelDelta delta) {
}
public void setSelection(ISelection selection, boolean reveal, boolean force) {
}
public void setInput(Object object) {
}
public void setAutoExpandLevel(int level) {
}
public void saveElementState(TreePath path, ModelDelta delta) {
}
public void removeViewerUpdateListener(IViewerUpdateListener listener) {
}
public void removeModelChangedListener(IModelChangedListener listener) {
}
public void removeLabelUpdateListener(ILabelUpdateListener listener) {
}
public ISelection getSelection() {
return null;
}
public IPresentationContext getPresentationContext() {
return null;
}
public Object getInput() {
return null;
}
public ViewerLabel getElementLabel(TreePath path, String columnId) {
return null;
}
public Display getDisplay() {
return DebugUIPlugin.getStandardDisplay();
}
public int getAutoExpandLevel() {
return 0;
}
public void addViewerUpdateListener(IViewerUpdateListener listener) {
}
public void addModelChangedListener(IModelChangedListener listener) {
}
public void addLabelUpdateListener(ILabelUpdateListener listener) {
}
public void update(Object element) {
}
public void setHasChildren(Object elementOrTreePath, boolean hasChildren) {
}
public void setExpandedState(Object elementOrTreePath, boolean expanded) {
}
public void setChildCount(Object elementOrTreePath, int count) {
}
public void reveal(TreePath path, int index) {
}
public void replace(Object parentOrTreePath, int index, Object element) {
}
public void remove(Object parentOrTreePath, int index) {
}
public void remove(Object elementOrTreePath) {
}
public void refresh() {
}
public void refresh(Object element) {
}
public boolean overrideSelection(ISelection current, ISelection candidate) {
return false;
}
public void insert(Object parentOrTreePath, Object element, int position) {
}
public TreePath getTopElementPath() {
return null;
}
public ViewerFilter[] getFilters() {
return null;
}
public boolean getExpandedState(Object elementOrTreePath) {
return false;
}
public Object getChildElement(TreePath path, int index) {
return null;
}
public int getChildCount(TreePath path) {
return 0;
}
public int findElementIndex(TreePath parentPath, Object element) {
return 0;
}
public void expandToLevel(Object elementOrTreePath, int level) {
}
public void autoExpand(TreePath elementPath) {
}
};
}
|
diff --git a/src/rajawali/ATransformable3D.java b/src/rajawali/ATransformable3D.java
index 49acbcf4..07a57cd3 100644
--- a/src/rajawali/ATransformable3D.java
+++ b/src/rajawali/ATransformable3D.java
@@ -1,236 +1,238 @@
package rajawali;
import rajawali.math.AngleAxis;
import rajawali.math.Matrix4;
import rajawali.math.Number3D;
import rajawali.math.Number3D.Axis;
import rajawali.math.Quaternion;
import android.opengl.Matrix;
public abstract class ATransformable3D {
protected Number3D mPosition, mRotation, mScale;
protected Quaternion mOrientation;
protected Quaternion mTmpOrientation;
protected Number3D mRotationAxis;
protected Number3D mAxisX, mAxisY, mAxisZ;
protected boolean mRotationDirty;
protected Number3D mLookAt;
protected Number3D mTmpAxis, mTmpVec;
protected boolean mIsCamera, mQuatWasSet;
protected AngleAxis mAngleAxis;
public ATransformable3D() {
mPosition = new Number3D();
mRotation = new Number3D();
mScale = new Number3D(1, 1, 1);
mOrientation = new Quaternion();
mTmpOrientation = new Quaternion();
mAxisX = Number3D.getAxisVector(Axis.X);
mAxisY = Number3D.getAxisVector(Axis.Y);
mAxisZ = Number3D.getAxisVector(Axis.Z);
mTmpAxis = new Number3D();
mTmpVec = new Number3D();
mAngleAxis = new AngleAxis();
mRotationDirty = true;
}
public void setPosition(Number3D position) {
mPosition.setAllFrom(position);
}
public void setPosition(float x, float y, float z) {
mPosition.setAll(x, y, z);
}
public Number3D getPosition() {
return mPosition;
}
public void setX(float x) {
mPosition.x = x;
}
public float getX() {
return mPosition.x;
}
public void setY(float y) {
mPosition.y = y;
}
public float getY() {
return mPosition.y;
}
public void setZ(float z) {
mPosition.z = z;
}
public float getZ() {
return mPosition.z;
}
Number3D mTmpRotX = new Number3D();
Number3D mTmpRotY = new Number3D();
Number3D mTmpRotZ = new Number3D();
float[] mLookAtMatrix = new float[16];
Matrix4 mmm;
public void setOrientation() {
if(!mRotationDirty && mLookAt == null) return;
mOrientation.setIdentity();
if(mLookAt != null) {
mLookAt.x = -mLookAt.x;
mTmpRotZ.setAllFrom(mLookAt);
mTmpRotZ.normalize();
mTmpRotX = Number3D.cross(mAxisY, mTmpRotZ);
mTmpRotX.normalize();
mTmpRotY = Number3D.cross(mTmpRotZ, mTmpRotX);
mTmpRotY.normalize();
Matrix.setIdentityM(mLookAtMatrix, 0);
mLookAtMatrix[0] = mTmpRotX.x;
mLookAtMatrix[1] = mTmpRotX.y;
mLookAtMatrix[2] = mTmpRotX.z;
mLookAtMatrix[4] = mTmpRotY.x;
mLookAtMatrix[5] = mTmpRotY.y;
mLookAtMatrix[6] = mTmpRotY.z;
mLookAtMatrix[8] = mTmpRotZ.x;
mLookAtMatrix[9] = mTmpRotZ.y;
mLookAtMatrix[10] = mTmpRotZ.z;
} else {
- mOrientation.multiply(mTmpOrientation.fromAngleAxis(mIsCamera ? -mRotation.x : -mRotation.x, mAxisX));
- mOrientation.multiply(mTmpOrientation.fromAngleAxis(mIsCamera ? -mRotation.y + 180 : mRotation.y, mAxisY));
- mOrientation.multiply(mTmpOrientation.fromAngleAxis(mIsCamera ? -mRotation.z : mRotation.z, mAxisZ));
+ mOrientation.multiply(mTmpOrientation.fromAngleAxis(mIsCamera ? -mRotation.x : mRotation.x, mAxisX));
+ mOrientation.multiply(mTmpOrientation.fromAngleAxis(mIsCamera ? mRotation.y + 180 : mRotation.y, mAxisY));
+ mOrientation.multiply(mTmpOrientation.fromAngleAxis(mIsCamera ? mRotation.z : mRotation.z, mAxisZ));
+ if(mIsCamera)
+ mOrientation.inverseSelf();
}
}
public void rotateAround(Number3D axis, float angle) {
rotateAround(axis, angle);
}
public void rotateAround(Number3D axis, float angle, boolean append) {
if(append) {
mTmpOrientation.fromAngleAxis(angle, axis);
mOrientation.multiply(mTmpOrientation);
} else {
mOrientation.fromAngleAxis(angle, axis);
}
mRotationDirty = false;
}
public Quaternion getOrientation() {
return new Quaternion(mOrientation);
}
public void setOrientation(Quaternion quat) {
mOrientation.setAllFrom(quat);
mRotationDirty = false;
}
public void setRotation(float rotX, float rotY, float rotZ) {
mRotation.x = rotX;
mRotation.y = rotY;
mRotation.z = rotZ;
mRotationDirty = true;
}
public void setRotX(float rotX) {
mRotation.x = rotX;
mRotationDirty = true;
}
public float getRotX() {
return mRotation.x;
}
public void setRotY(float rotY) {
mRotation.y = rotY;
mRotationDirty = true;
}
public float getRotY() {
return mRotation.y;
}
public void setRotZ(float rotZ) {
mRotation.z = rotZ;
mRotationDirty = true;
}
public float getRotZ() {
return mRotation.z;
}
public Number3D getRotation() {
return mRotation;
}
public void setRotation(Number3D rotation) {
mRotation.setAllFrom(rotation);
mRotationDirty = true;
}
public void setScale(float scale) {
mScale.x = scale;
mScale.y = scale;
mScale.z = scale;
}
public void setScale(float scaleX, float scaleY, float scaleZ) {
mScale.x = scaleX;
mScale.y = scaleY;
mScale.z = scaleZ;
}
public void setScaleX(float scaleX) {
mScale.x = scaleX;
}
public float getScaleX() {
return mScale.x;
}
public void setScaleY(float scaleY) {
mScale.y = scaleY;
}
public float getScaleY() {
return mScale.y;
}
public void setScaleZ(float scaleZ) {
mScale.z = scaleZ;
}
public float getScaleZ() {
return mScale.z;
}
public Number3D getScale() {
return mScale;
}
public void setScale(Number3D scale) {
mScale = scale;
}
public void setLookAt(float x, float y, float z) {
if(mLookAt == null) mLookAt = new Number3D();
mLookAt.x = x;
mLookAt.y = y;
mLookAt.z = z;
mRotationDirty = true;
}
public void setLookAt(Number3D lookAt) {
if(lookAt == null) {
mLookAt = null;
return;
}
setLookAt(lookAt.x, lookAt.y, lookAt.z);
}
}
| true | true | public void setOrientation() {
if(!mRotationDirty && mLookAt == null) return;
mOrientation.setIdentity();
if(mLookAt != null) {
mLookAt.x = -mLookAt.x;
mTmpRotZ.setAllFrom(mLookAt);
mTmpRotZ.normalize();
mTmpRotX = Number3D.cross(mAxisY, mTmpRotZ);
mTmpRotX.normalize();
mTmpRotY = Number3D.cross(mTmpRotZ, mTmpRotX);
mTmpRotY.normalize();
Matrix.setIdentityM(mLookAtMatrix, 0);
mLookAtMatrix[0] = mTmpRotX.x;
mLookAtMatrix[1] = mTmpRotX.y;
mLookAtMatrix[2] = mTmpRotX.z;
mLookAtMatrix[4] = mTmpRotY.x;
mLookAtMatrix[5] = mTmpRotY.y;
mLookAtMatrix[6] = mTmpRotY.z;
mLookAtMatrix[8] = mTmpRotZ.x;
mLookAtMatrix[9] = mTmpRotZ.y;
mLookAtMatrix[10] = mTmpRotZ.z;
} else {
mOrientation.multiply(mTmpOrientation.fromAngleAxis(mIsCamera ? -mRotation.x : -mRotation.x, mAxisX));
mOrientation.multiply(mTmpOrientation.fromAngleAxis(mIsCamera ? -mRotation.y + 180 : mRotation.y, mAxisY));
mOrientation.multiply(mTmpOrientation.fromAngleAxis(mIsCamera ? -mRotation.z : mRotation.z, mAxisZ));
}
}
| public void setOrientation() {
if(!mRotationDirty && mLookAt == null) return;
mOrientation.setIdentity();
if(mLookAt != null) {
mLookAt.x = -mLookAt.x;
mTmpRotZ.setAllFrom(mLookAt);
mTmpRotZ.normalize();
mTmpRotX = Number3D.cross(mAxisY, mTmpRotZ);
mTmpRotX.normalize();
mTmpRotY = Number3D.cross(mTmpRotZ, mTmpRotX);
mTmpRotY.normalize();
Matrix.setIdentityM(mLookAtMatrix, 0);
mLookAtMatrix[0] = mTmpRotX.x;
mLookAtMatrix[1] = mTmpRotX.y;
mLookAtMatrix[2] = mTmpRotX.z;
mLookAtMatrix[4] = mTmpRotY.x;
mLookAtMatrix[5] = mTmpRotY.y;
mLookAtMatrix[6] = mTmpRotY.z;
mLookAtMatrix[8] = mTmpRotZ.x;
mLookAtMatrix[9] = mTmpRotZ.y;
mLookAtMatrix[10] = mTmpRotZ.z;
} else {
mOrientation.multiply(mTmpOrientation.fromAngleAxis(mIsCamera ? -mRotation.x : mRotation.x, mAxisX));
mOrientation.multiply(mTmpOrientation.fromAngleAxis(mIsCamera ? mRotation.y + 180 : mRotation.y, mAxisY));
mOrientation.multiply(mTmpOrientation.fromAngleAxis(mIsCamera ? mRotation.z : mRotation.z, mAxisZ));
if(mIsCamera)
mOrientation.inverseSelf();
}
}
|
diff --git a/workbench/org.carrot2.workbench.core/src/org/carrot2/workbench/core/ui/AttributeList.java b/workbench/org.carrot2.workbench.core/src/org/carrot2/workbench/core/ui/AttributeList.java
index 4d8929431..ffe4ea709 100644
--- a/workbench/org.carrot2.workbench.core/src/org/carrot2/workbench/core/ui/AttributeList.java
+++ b/workbench/org.carrot2.workbench.core/src/org/carrot2/workbench/core/ui/AttributeList.java
@@ -1,296 +1,296 @@
package org.carrot2.workbench.core.ui;
import java.text.Collator;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import org.carrot2.core.ProcessingComponent;
import org.carrot2.util.attribute.AttributeDescriptor;
import org.carrot2.workbench.core.helpers.GUIFactory;
import org.carrot2.workbench.editors.*;
import org.carrot2.workbench.editors.factory.EditorFactory;
import org.carrot2.workbench.editors.factory.EditorNotFoundException;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
/**
* An SWT composite displaying an alphabetically ordered list of
* {@link IAttributeEditor}s.
*/
public final class AttributeList extends Composite
implements IAttributeChangeProvider
{
/**
* A list of {@link AttributeDescriptor}s, indexed by their keys.
*/
private final Map<String, AttributeDescriptor> attributeDescriptors;
/**
* A map between attribute keys and {@link IAttributeEditor}s
* visible in this component.
*/
private Map<String, IAttributeEditor> editors = Maps.newHashMap();
/**
* Optional component class attribute descriptors come from.
*/
private Class<? extends ProcessingComponent> componentClazz;
/**
* Attribute change listeners.
*/
private final List<IAttributeListener> listeners =
new CopyOnWriteArrayList<IAttributeListener>();
/**
* Forward events from editors to external listeners.
*/
private final IAttributeListener forwardListener = new IAttributeListener()
{
public void attributeChange(AttributeChangedEvent event)
{
for (IAttributeListener listener : listeners)
{
listener.attributeChange(event);
}
}
public void contentChanging(IAttributeEditor editor, Object value)
{
for (IAttributeListener listener : listeners)
{
listener.contentChanging(editor, value);
}
}
};
/**
* Create a new editor list for a given set of attribute descriptors and
* an (optional) component class.
*/
@SuppressWarnings("unchecked")
public AttributeList(Composite parent,
Map<String, AttributeDescriptor> attributeDescriptors)
{
this(parent, attributeDescriptors, null);
}
/**
* Create a new editor list for a given set of attribute descriptors and
* an (optional) component class.
*/
@SuppressWarnings("unchecked")
public AttributeList(Composite parent,
Map<String, AttributeDescriptor> attributeDescriptors, Class<?> componentClazz)
{
super(parent, SWT.NONE);
this.attributeDescriptors = attributeDescriptors;
/*
* Only store component clazz if it is assignable to
* {@link ProcessingComponent}.
*/
if (componentClazz != null && ProcessingComponent.class.isAssignableFrom(componentClazz))
{
this.componentClazz = (Class<? extends ProcessingComponent>) componentClazz;
}
createComponents();
}
/**
* Sets the <code>key</code> editor's current value to <code>value</code>.
*/
public void setAttribute(String key, Object value)
{
final IAttributeEditor editor = editors.get(key);
if (editor != null)
{
editor.setValue(value);
}
}
/*
*
*/
public void addAttributeChangeListener(IAttributeListener listener)
{
this.listeners.add(listener);
}
/*
*
*/
public void removeAttributeChangeListener(IAttributeListener listener)
{
this.listeners.remove(listener);
}
/**
*
*/
public void dispose()
{
/*
* Unregister listeners.
*/
for (IAttributeEditor editor : this.editors.values())
{
editor.removeAttributeChangeListener(forwardListener);
}
super.dispose();
}
/**
* Create internal GUI.
*/
private void createComponents()
{
/*
* Sort alphabetically by label.
*/
final Locale locale = Locale.getDefault();
final Map<String,String> labels = Maps.newHashMap();
for (Map.Entry<String, AttributeDescriptor> entry : attributeDescriptors.entrySet())
{
labels.put(entry.getKey(), getLabel(entry.getValue()).toLowerCase(locale));
}
final Collator collator = Collator.getInstance(locale);
final List<String> sortedKeys = Lists.newArrayList(labels.keySet());
Collections.sort(sortedKeys, new Comparator<String>() {
public int compare(String a, String b)
{
return collator.compare(labels.get(a), labels.get(b));
}
});
/*
* Create editors and inquire about their layout needs.
*/
- final Map<String, IAttributeEditor> editors = Maps.newHashMap();
+ editors = Maps.newHashMap();
final Map<String, AttributeEditorInfo> editorInfos = Maps.newHashMap();
int maxColumns = 1;
for (String key : sortedKeys)
{
final AttributeDescriptor descriptor = attributeDescriptors.get(key);
IAttributeEditor editor = null;
try
{
editor = EditorFactory.getEditorFor(this.componentClazz, descriptor);
final AttributeEditorInfo info = editor.init(descriptor);
editorInfos.put(key, info);
maxColumns = Math.max(maxColumns, info.columns);
}
catch (EditorNotFoundException ex)
{
/*
* Skip editor.
*/
editor = null;
}
editors.put(key, editor);
}
/*
* Prepare the layout for this editor.
*/
final GridLayout layout = GUIFactory.zeroMarginGridLayout();
layout.makeColumnsEqualWidth = false;
layout.numColumns = maxColumns;
this.setLayout(layout);
/*
* Create visual components for editors.
*/
final GridDataFactory labelFactory = GridDataFactory.fillDefaults()
.span(maxColumns, 1);
for (String key : sortedKeys)
{
final AttributeDescriptor descriptor = attributeDescriptors.get(key);
final IAttributeEditor editor = editors.get(key);
final AttributeEditorInfo editorInfo = editorInfos.get(key);
// Add label to editors that do not have it.
if (editor == null || editorInfo.displaysOwnLabel == false)
{
final Label label = new Label(this, SWT.LEAD);
label.setText(getLabel(descriptor));
label.setToolTipText(getToolTip(descriptor));
label.setLayoutData(labelFactory.create());
}
// Add the editor, if available.
if (editor != null)
{
editor.createEditor(this, maxColumns);
editor.setValue(attributeDescriptors.get(descriptor.key).defaultValue);
editors.put(editor.getAttributeKey(), editor);
/*
* Forward events from this editor to all our listeners.
*/
editor.addAttributeChangeListener(forwardListener);
}
else
{
final Label label = new Label(this, SWT.BORDER);
label.setText("No suitable editor");
label.setEnabled(false);
label.setLayoutData(labelFactory.create());
}
}
}
/*
*
*/
private String getLabel(AttributeDescriptor descriptor)
{
String text = null;
if (descriptor.metadata != null)
{
text = descriptor.metadata.getLabelOrTitle();
}
if (text == null)
{
text = "(no label available)";
}
return text;
}
/*
*
*/
private String getToolTip(AttributeDescriptor descriptor)
{
String text = null;
if (descriptor.metadata != null)
{
text = descriptor.metadata.getDescription();
}
return text;
}
}
| true | true | private void createComponents()
{
/*
* Sort alphabetically by label.
*/
final Locale locale = Locale.getDefault();
final Map<String,String> labels = Maps.newHashMap();
for (Map.Entry<String, AttributeDescriptor> entry : attributeDescriptors.entrySet())
{
labels.put(entry.getKey(), getLabel(entry.getValue()).toLowerCase(locale));
}
final Collator collator = Collator.getInstance(locale);
final List<String> sortedKeys = Lists.newArrayList(labels.keySet());
Collections.sort(sortedKeys, new Comparator<String>() {
public int compare(String a, String b)
{
return collator.compare(labels.get(a), labels.get(b));
}
});
/*
* Create editors and inquire about their layout needs.
*/
final Map<String, IAttributeEditor> editors = Maps.newHashMap();
final Map<String, AttributeEditorInfo> editorInfos = Maps.newHashMap();
int maxColumns = 1;
for (String key : sortedKeys)
{
final AttributeDescriptor descriptor = attributeDescriptors.get(key);
IAttributeEditor editor = null;
try
{
editor = EditorFactory.getEditorFor(this.componentClazz, descriptor);
final AttributeEditorInfo info = editor.init(descriptor);
editorInfos.put(key, info);
maxColumns = Math.max(maxColumns, info.columns);
}
catch (EditorNotFoundException ex)
{
/*
* Skip editor.
*/
editor = null;
}
editors.put(key, editor);
}
/*
* Prepare the layout for this editor.
*/
final GridLayout layout = GUIFactory.zeroMarginGridLayout();
layout.makeColumnsEqualWidth = false;
layout.numColumns = maxColumns;
this.setLayout(layout);
/*
* Create visual components for editors.
*/
final GridDataFactory labelFactory = GridDataFactory.fillDefaults()
.span(maxColumns, 1);
for (String key : sortedKeys)
{
final AttributeDescriptor descriptor = attributeDescriptors.get(key);
final IAttributeEditor editor = editors.get(key);
final AttributeEditorInfo editorInfo = editorInfos.get(key);
// Add label to editors that do not have it.
if (editor == null || editorInfo.displaysOwnLabel == false)
{
final Label label = new Label(this, SWT.LEAD);
label.setText(getLabel(descriptor));
label.setToolTipText(getToolTip(descriptor));
label.setLayoutData(labelFactory.create());
}
// Add the editor, if available.
if (editor != null)
{
editor.createEditor(this, maxColumns);
editor.setValue(attributeDescriptors.get(descriptor.key).defaultValue);
editors.put(editor.getAttributeKey(), editor);
/*
* Forward events from this editor to all our listeners.
*/
editor.addAttributeChangeListener(forwardListener);
}
else
{
final Label label = new Label(this, SWT.BORDER);
label.setText("No suitable editor");
label.setEnabled(false);
label.setLayoutData(labelFactory.create());
}
}
}
| private void createComponents()
{
/*
* Sort alphabetically by label.
*/
final Locale locale = Locale.getDefault();
final Map<String,String> labels = Maps.newHashMap();
for (Map.Entry<String, AttributeDescriptor> entry : attributeDescriptors.entrySet())
{
labels.put(entry.getKey(), getLabel(entry.getValue()).toLowerCase(locale));
}
final Collator collator = Collator.getInstance(locale);
final List<String> sortedKeys = Lists.newArrayList(labels.keySet());
Collections.sort(sortedKeys, new Comparator<String>() {
public int compare(String a, String b)
{
return collator.compare(labels.get(a), labels.get(b));
}
});
/*
* Create editors and inquire about their layout needs.
*/
editors = Maps.newHashMap();
final Map<String, AttributeEditorInfo> editorInfos = Maps.newHashMap();
int maxColumns = 1;
for (String key : sortedKeys)
{
final AttributeDescriptor descriptor = attributeDescriptors.get(key);
IAttributeEditor editor = null;
try
{
editor = EditorFactory.getEditorFor(this.componentClazz, descriptor);
final AttributeEditorInfo info = editor.init(descriptor);
editorInfos.put(key, info);
maxColumns = Math.max(maxColumns, info.columns);
}
catch (EditorNotFoundException ex)
{
/*
* Skip editor.
*/
editor = null;
}
editors.put(key, editor);
}
/*
* Prepare the layout for this editor.
*/
final GridLayout layout = GUIFactory.zeroMarginGridLayout();
layout.makeColumnsEqualWidth = false;
layout.numColumns = maxColumns;
this.setLayout(layout);
/*
* Create visual components for editors.
*/
final GridDataFactory labelFactory = GridDataFactory.fillDefaults()
.span(maxColumns, 1);
for (String key : sortedKeys)
{
final AttributeDescriptor descriptor = attributeDescriptors.get(key);
final IAttributeEditor editor = editors.get(key);
final AttributeEditorInfo editorInfo = editorInfos.get(key);
// Add label to editors that do not have it.
if (editor == null || editorInfo.displaysOwnLabel == false)
{
final Label label = new Label(this, SWT.LEAD);
label.setText(getLabel(descriptor));
label.setToolTipText(getToolTip(descriptor));
label.setLayoutData(labelFactory.create());
}
// Add the editor, if available.
if (editor != null)
{
editor.createEditor(this, maxColumns);
editor.setValue(attributeDescriptors.get(descriptor.key).defaultValue);
editors.put(editor.getAttributeKey(), editor);
/*
* Forward events from this editor to all our listeners.
*/
editor.addAttributeChangeListener(forwardListener);
}
else
{
final Label label = new Label(this, SWT.BORDER);
label.setText("No suitable editor");
label.setEnabled(false);
label.setLayoutData(labelFactory.create());
}
}
}
|
diff --git a/javanet/gnu/cajo/utils/MonitorItem.java b/javanet/gnu/cajo/utils/MonitorItem.java
index 9cf22aa4..81e26f3b 100644
--- a/javanet/gnu/cajo/utils/MonitorItem.java
+++ b/javanet/gnu/cajo/utils/MonitorItem.java
@@ -1,200 +1,204 @@
package gnu.cajo.utils;
import gnu.cajo.invoke.*;
import java.rmi.server.RemoteServer;
import java.rmi.RemoteException;
import java.rmi.server.ServerNotActiveException;
import java.io.PrintStream;
import java.io.OutputStream;
import java.io.ObjectOutputStream;
/*
* Item Invocation Monitor
* Copyright (c) 1999 John Catherino
*
* For issues or suggestions mailto:[email protected]
*
* 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, at version 2.1 of the license, or any
* later version. The license differs from the GNU General Public License
* (GPL) to allow this library to be used in proprietary applications. The
* standard GPL would forbid this.
*
* 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 General Public License for more details.
*
* To receive a copy of the GNU Lesser General Public License visit their
* website at http://www.fsf.org/licenses/lgpl.html or via snail mail at Free
* Software Foundation Inc., 59 Temple Place Suite 330, Boston MA 02111-1307
* USA
*/
/**
* This class is used to instrument an object for invocation logging
* purposes. It is intended as a replacement for standard RMI logging, in that
* this logger is aware of the Invoke package methodology, and can decode it
* properly. Specifically, it will gather information about the calling
* client, the method called, the inbound and outbound data. It will also
* record the approximate time between client invocations, the time used to
* service the invocation, and the approximate percentage of free memory
* available at the completion of the operation. Subclassing of MonitorItem
* is allowed; primarily to create self-monitoring classes.
* <p><i>Note:</i> monitoring an item can be expensive in runtime efficiency.
* It is best used for debug and performance analysis, during development, or
* in production, for items that would not be called very frequently.
*
* @version 1.0, 01-Nov-99 Initial release
* @author John Catherino
*/
public class MonitorItem implements Invoke {
private final Object item;
private final OutputStream os;
private long oldtime = System.currentTimeMillis();
/**
* This creates the monitor object, to instrument the target object's use.
* The the logging information is passed to the OutputStream, where it can
* be logged to a file, a socket, or simply sent to the console (System.out).
* The logged data is in text format.
* @param item The object to receive the client invocation.
* @param os The OutputStream to send the formatted log information.
*/
public MonitorItem(Object item, OutputStream os) {
this.item = item;
this.os = os instanceof PrintStream ? os : new PrintStream(os);
}
/**
* This creates the monitor object, to instrument the target object's use.
* The the logging information is passed to an ObjectOutputStream.
* <i>Note:</i> this type of monitoring provides both the greatest detail,
* and can be most easily manipulated programmatically. However, it is even
* </i>more</i> expensive than text logging. The log file can become
* <i>extremely</i> large, if the objects passed in or out are complex, or
* if the object is called frequently. Therefore, it is <u>highly</u>
* recommended to implement the ObjectOutputStream on top of a
* GZipOutputStream.
* @param item The object to receive the client invocation.
* @param os The ObjectOutputStream to send input and result objects.
*/
public MonitorItem(Object item, ObjectOutputStream os) {
this.item = item;
this.os = os;
}
/**
* This method is overridden here to ensure that two different monitor
* items holding the target item return the same value.
* @return The hash code returned by the target item
*/
public int hashCode() { return item.hashCode(); }
/**
* This method is overridden here to ensure that two different monitor
* items holding the same target item return true.
* @param obj An object, presumably another item, to compare
* @return True if the inner items are equivalent, otherwise false
*/
public boolean equals(Object obj) { return item.equals(obj); }
/**
* This method is overridden here to provide the name of the internal
* object, rather than the name of the Monitor object.
* @return The string returned by the internal item's toString method.
*/
public String toString() { return item.toString(); }
/**
* This method logs the incoming calls, passing the caller's data to the
* internal item. It records the following information:<ul>
* <li> The name of the item being called
* <li> The host address of the caller (or localhost)
* <li> The method the caller is invoking
* <li> The data the caller is sending
* <li> The data resulting from the invocation, or the Exception
* <li> The idle time between invocations, in milliseconds.
* <li> The run time of the invocation time, in milliseconds
* <li> The free memory percentage, following the invocation</ul>
* If the write operation to the log file results in an exception, the
* stack trace of will be printed to System.err.
* @param method The internal object's public method being called.
* @param args The arguments to pass to the internal object's method.
* @return The sychronous data, if any, resulting from the invocation.
* @throws RemoteException For a network related failure.
* @throws NoSuchMethodException If the method/agruments signature cannot
* be matched to the internal object's public method interface.
* @throws Exception If the internal object's method rejects the invocation.
*/
public Object invoke(String method, Object args) throws Exception {
long time = System.currentTimeMillis();
Object result = null;
try { return result = Remote.invoke(item, method, args); }
catch(Exception x) {
result = x;
throw x;
} finally {
int run = (int)(System.currentTimeMillis() - time);
String clientHost = null;
try { clientHost = RemoteServer.getClientHost(); }
catch(ServerNotActiveException x) { clientHost = "localhost"; }
Runtime rt = Runtime.getRuntime();
int freeMemory =
(int)((rt.freeMemory() * 100) / rt.totalMemory());
ObjectOutputStream oos =
os instanceof ObjectOutputStream ? (ObjectOutputStream) os : null;
PrintStream ps = os instanceof PrintStream ? (PrintStream) os : null;
synchronized(os) {
try {
if (oos != null) {
oos.writeObject( new Object[] {
clientHost, item.toString(), // may not be serializable!
method, args, result, new Long(time - oldtime),
new Integer(run), new Integer(freeMemory)
});
oos.flush(); // just for good measure...
} else if (ps != null) {
ps.print("\nCaller host = ");
ps.print(clientHost);
ps.print("\nItem called = ");
ps.print(item.toString());
ps.print("\nMethod call = ");
ps.print(method);
ps.print("\nMethod args = ");
if (args instanceof java.rmi.MarshalledObject)
args = ((java.rmi.MarshalledObject)args).get();
if (args instanceof Object[]) {
ps.print("<array>");
for (int i = 0; i < ((Object[])args).length; i++) {
ps.print("\n\t[");
ps.print(i);
ps.print("] =\t");
- ps.print(((Object[])args)[i].toString());
+ if (((Object[])args)[i] != null)
+ ps.print(((Object[])args)[i].toString());
+ else ps.print("null");
}
} else ps.print(args != null ? args.toString() : "null");
ps.print("\nResult data = ");
if (result instanceof java.rmi.MarshalledObject)
result = ((java.rmi.MarshalledObject)result).get();
if (result instanceof Exception) {
((Exception)result).printStackTrace(ps);
} else if (result instanceof Object[]) {
ps.print("array");
for (int i = 0; i < ((Object[])result).length; i++) {
ps.print("\n\t[");
ps.print(i);
ps.print("] =\t");
- ps.print(((Object[])result)[i].toString());
+ if (((Object[])result)[i] != null)
+ ps.print(((Object[])result)[i].toString());
+ else ps.print("null");
}
} else ps.print(result != null ? result.toString() : "null");
ps.print("\nIdle time = ");
ps.print(time - oldtime);
ps.print(" ms");
ps.print("\nBusy time = ");
ps.print(run);
ps.print(" ms");
ps.print("\nFree memory = ");
ps.print(freeMemory);
ps.println('%');
}
} catch(Exception x) { x.printStackTrace(System.err); }
}
oldtime = time;
}
}
}
| false | true | public Object invoke(String method, Object args) throws Exception {
long time = System.currentTimeMillis();
Object result = null;
try { return result = Remote.invoke(item, method, args); }
catch(Exception x) {
result = x;
throw x;
} finally {
int run = (int)(System.currentTimeMillis() - time);
String clientHost = null;
try { clientHost = RemoteServer.getClientHost(); }
catch(ServerNotActiveException x) { clientHost = "localhost"; }
Runtime rt = Runtime.getRuntime();
int freeMemory =
(int)((rt.freeMemory() * 100) / rt.totalMemory());
ObjectOutputStream oos =
os instanceof ObjectOutputStream ? (ObjectOutputStream) os : null;
PrintStream ps = os instanceof PrintStream ? (PrintStream) os : null;
synchronized(os) {
try {
if (oos != null) {
oos.writeObject( new Object[] {
clientHost, item.toString(), // may not be serializable!
method, args, result, new Long(time - oldtime),
new Integer(run), new Integer(freeMemory)
});
oos.flush(); // just for good measure...
} else if (ps != null) {
ps.print("\nCaller host = ");
ps.print(clientHost);
ps.print("\nItem called = ");
ps.print(item.toString());
ps.print("\nMethod call = ");
ps.print(method);
ps.print("\nMethod args = ");
if (args instanceof java.rmi.MarshalledObject)
args = ((java.rmi.MarshalledObject)args).get();
if (args instanceof Object[]) {
ps.print("<array>");
for (int i = 0; i < ((Object[])args).length; i++) {
ps.print("\n\t[");
ps.print(i);
ps.print("] =\t");
ps.print(((Object[])args)[i].toString());
}
} else ps.print(args != null ? args.toString() : "null");
ps.print("\nResult data = ");
if (result instanceof java.rmi.MarshalledObject)
result = ((java.rmi.MarshalledObject)result).get();
if (result instanceof Exception) {
((Exception)result).printStackTrace(ps);
} else if (result instanceof Object[]) {
ps.print("array");
for (int i = 0; i < ((Object[])result).length; i++) {
ps.print("\n\t[");
ps.print(i);
ps.print("] =\t");
ps.print(((Object[])result)[i].toString());
}
} else ps.print(result != null ? result.toString() : "null");
ps.print("\nIdle time = ");
ps.print(time - oldtime);
ps.print(" ms");
ps.print("\nBusy time = ");
ps.print(run);
ps.print(" ms");
ps.print("\nFree memory = ");
ps.print(freeMemory);
ps.println('%');
}
} catch(Exception x) { x.printStackTrace(System.err); }
}
oldtime = time;
}
}
| public Object invoke(String method, Object args) throws Exception {
long time = System.currentTimeMillis();
Object result = null;
try { return result = Remote.invoke(item, method, args); }
catch(Exception x) {
result = x;
throw x;
} finally {
int run = (int)(System.currentTimeMillis() - time);
String clientHost = null;
try { clientHost = RemoteServer.getClientHost(); }
catch(ServerNotActiveException x) { clientHost = "localhost"; }
Runtime rt = Runtime.getRuntime();
int freeMemory =
(int)((rt.freeMemory() * 100) / rt.totalMemory());
ObjectOutputStream oos =
os instanceof ObjectOutputStream ? (ObjectOutputStream) os : null;
PrintStream ps = os instanceof PrintStream ? (PrintStream) os : null;
synchronized(os) {
try {
if (oos != null) {
oos.writeObject( new Object[] {
clientHost, item.toString(), // may not be serializable!
method, args, result, new Long(time - oldtime),
new Integer(run), new Integer(freeMemory)
});
oos.flush(); // just for good measure...
} else if (ps != null) {
ps.print("\nCaller host = ");
ps.print(clientHost);
ps.print("\nItem called = ");
ps.print(item.toString());
ps.print("\nMethod call = ");
ps.print(method);
ps.print("\nMethod args = ");
if (args instanceof java.rmi.MarshalledObject)
args = ((java.rmi.MarshalledObject)args).get();
if (args instanceof Object[]) {
ps.print("<array>");
for (int i = 0; i < ((Object[])args).length; i++) {
ps.print("\n\t[");
ps.print(i);
ps.print("] =\t");
if (((Object[])args)[i] != null)
ps.print(((Object[])args)[i].toString());
else ps.print("null");
}
} else ps.print(args != null ? args.toString() : "null");
ps.print("\nResult data = ");
if (result instanceof java.rmi.MarshalledObject)
result = ((java.rmi.MarshalledObject)result).get();
if (result instanceof Exception) {
((Exception)result).printStackTrace(ps);
} else if (result instanceof Object[]) {
ps.print("array");
for (int i = 0; i < ((Object[])result).length; i++) {
ps.print("\n\t[");
ps.print(i);
ps.print("] =\t");
if (((Object[])result)[i] != null)
ps.print(((Object[])result)[i].toString());
else ps.print("null");
}
} else ps.print(result != null ? result.toString() : "null");
ps.print("\nIdle time = ");
ps.print(time - oldtime);
ps.print(" ms");
ps.print("\nBusy time = ");
ps.print(run);
ps.print(" ms");
ps.print("\nFree memory = ");
ps.print(freeMemory);
ps.println('%');
}
} catch(Exception x) { x.printStackTrace(System.err); }
}
oldtime = time;
}
}
|
diff --git a/src/com/ichi2/anki/DeckOptions.java b/src/com/ichi2/anki/DeckOptions.java
index 6e0d7699..29683a4e 100644
--- a/src/com/ichi2/anki/DeckOptions.java
+++ b/src/com/ichi2/anki/DeckOptions.java
@@ -1,573 +1,573 @@
package com.ichi2.anki;
/****************************************************************************************
* Copyright (c) 2009 Casey Link <[email protected]> *
* Copyright (c) 2012 Norbert Nagold <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.util.Log;
import android.view.KeyEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.ichi2.anim.ActivityTransitionAnimation;
import com.ichi2.anki.R;
import com.ichi2.anki.receiver.SdCardReceiver;
import com.ichi2.libanki.Collection;
import com.ichi2.themes.Themes;
/**
* Preferences for the current deck.
*/
public class DeckOptions extends PreferenceActivity implements OnSharedPreferenceChangeListener {
private JSONObject mOptions;
private JSONObject mDeck;
private Collection mCol;
private BroadcastReceiver mUnmountReceiver = null;
public class DeckPreferenceHack implements SharedPreferences {
private Map<String, String> mValues = new HashMap<String, String>();
private Map<String, String> mSummaries = new HashMap<String, String>();
public DeckPreferenceHack() {
this.cacheValues();
}
protected void cacheValues() {
Log.i(AnkiDroidApp.TAG, "DeckOptions - CacheValues");
try {
mOptions = mCol.getDecks().confForDid(mDeck.getLong("id"));
mValues.put("name", mDeck.getString("name"));
mValues.put("desc", mDeck.getString("desc"));
mValues.put("deckConf", mDeck.getString("conf"));
mValues.put("maxAnswerTime", mOptions.getString("maxTaken"));
mValues.put("showAnswerTimer", Boolean.toString(mOptions.getInt("timer") == 1));
mValues.put("autoPlayAudio", Boolean.toString(mOptions.getBoolean("autoplay")));
mValues.put("replayQuestion", Boolean.toString(mOptions.getBoolean("replayq")));
// new
JSONObject newOptions = mOptions.getJSONObject("new");
mValues.put("newSteps", getDelays(newOptions.getJSONArray("delays")));
mValues.put("newGradIvl", newOptions.getJSONArray("ints").getString(0));
mValues.put("newEasy", newOptions.getJSONArray("ints").getString(1));
mValues.put("newFactor", Integer.toString(newOptions.getInt("initialFactor") / 10));
mValues.put("newOrder", newOptions.getString("order"));
mValues.put("newPerDay", newOptions.getString("perDay"));
mValues.put("newSeparate", Boolean.toString(newOptions.getBoolean("separate")));
// rev
JSONObject revOptions = mOptions.getJSONObject("rev");
mValues.put("revPerDay", revOptions.getString("perDay"));
mValues.put("revSpaceMax", Integer.toString((int) (revOptions.getDouble("fuzz") * 100)));
mValues.put("revSpaceMin", revOptions.getString("minSpace"));
mValues.put("easyBonus", Integer.toString((int) (revOptions.getDouble("ease4") * 100)));
mValues.put("revIvlFct", revOptions.getString("ivlFct"));
mValues.put("revMaxIvl", revOptions.getString("maxIvl"));
// lapse
JSONObject lapOptions = mOptions.getJSONObject("lapse");
mValues.put("lapSteps", getDelays(lapOptions.getJSONArray("delays")));
mValues.put("lapNewIvl", Integer.toString((int) (lapOptions.getDouble("mult") * 100)));
mValues.put("lapMinIvl", lapOptions.getString("minInt"));
mValues.put("lapLeechThres", lapOptions.getString("leechFails"));
mValues.put("lapLeechAct", lapOptions.getString("leechAction"));
} catch (JSONException e) {
addMissingValues();
finish();
}
}
public class Editor implements SharedPreferences.Editor {
private ContentValues mUpdate = new ContentValues();
@Override
public SharedPreferences.Editor clear() {
Log.d(AnkiDroidApp.TAG, "clear()");
mUpdate = new ContentValues();
return this;
}
@Override
public boolean commit() {
Log.d(AnkiDroidApp.TAG, "DeckOptions - commit() changes back to database");
try {
for (Entry<String, Object> entry : mUpdate.valueSet()) {
Log.i(AnkiDroidApp.TAG, "Change value for key '" + entry.getKey() + "': " + entry.getValue());
if (entry.getKey().equals("name")) {
if (!mCol.getDecks().rename(mDeck, (String) entry.getValue())) {
Themes.showThemedToast(DeckOptions.this,
getResources().getString(R.string.rename_error, mDeck.get("name")), false);
}
} else if (entry.getKey().equals("desc")) {
mDeck.put("desc", (String) entry.getValue());
mCol.getDecks().save(mDeck);
} else if (entry.getKey().equals("deckConf")) {
mCol.getDecks().setConf(mDeck, Long.parseLong((String) entry.getValue()));
mOptions = mCol.getDecks().confForDid(mDeck.getLong("id"));
} else if (entry.getKey().equals("maxAnswerTime")) {
mOptions.put("maxTaken", Integer.parseInt((String) entry.getValue()));
} else if (entry.getKey().equals("showAnswerTimer")) {
mOptions.put("timer", (Boolean) entry.getValue() ? 1 : 0);
} else if (entry.getKey().equals("autoPlayAudio")) {
mOptions.put("autoplay", (Boolean) entry.getValue());
} else if (entry.getKey().equals("replayQuestion")) {
mOptions.put("replayq", (Boolean) entry.getValue());
} else if (entry.getKey().equals("newSteps")) {
String steps = (String) entry.getValue();
if (steps.matches("[0-9\\s]*")) {
mOptions.getJSONObject("new").put("delays", getDelays(steps));
}
} else if (entry.getKey().equals("newGradIvl")) {
JSONArray ja = new JSONArray();
ja.put(Integer.parseInt((String) entry.getValue()));
ja.put(mOptions.getJSONObject("new").getJSONArray("ints").get(1));
mOptions.getJSONObject("new").put("ints", ja);
} else if (entry.getKey().equals("newEasy")) {
JSONArray ja = new JSONArray();
ja.put(mOptions.getJSONObject("new").getJSONArray("ints").get(0));
ja.put(Integer.parseInt((String) entry.getValue()));
mOptions.getJSONObject("new").put("ints", ja);
} else if (entry.getKey().equals("initialFactor")) {
mOptions.getJSONObject("new").put("initialFactor",
(int) (Integer.parseInt((String) entry.getValue()) * 10));
} else if (entry.getKey().equals("newOrder")) {
mOptions.getJSONObject("new").put("order", Integer.parseInt((String) entry.getValue()));
} else if (entry.getKey().equals("newPerDay")) {
mOptions.getJSONObject("new").put("perDay", Integer.parseInt((String) entry.getValue()));
} else if (entry.getKey().equals("newSeparate")) {
mOptions.getJSONObject("new").put("separate", (Boolean) entry.getValue());
} else if (entry.getKey().equals("revPerDay")) {
mOptions.getJSONObject("rev").put("perDay", Integer.parseInt((String) entry.getValue()));
} else if (entry.getKey().equals("revSpaceMax")) {
mOptions.getJSONObject("rev").put("fuzz",
Integer.parseInt((String) entry.getValue()) / 100.0f);
} else if (entry.getKey().equals("revSpaceMin")) {
mOptions.getJSONObject("rev").put("minSpace", Integer.parseInt((String) entry.getValue()));
} else if (entry.getKey().equals("easyBonus")) {
mOptions.getJSONObject("rev").put("ease4",
Integer.parseInt((String) entry.getValue()) / 100.0f);
} else if (entry.getKey().equals("revIvlFct")) {
mOptions.getJSONObject("rev").put("ivlFct", Double.parseDouble((String) entry.getValue()));
} else if (entry.getKey().equals("revMaxIvl")) {
mOptions.getJSONObject("rev").put("maxIvl", Integer.parseInt((String) entry.getValue()));
} else if (entry.getKey().equals("lapSteps")) {
String steps = (String) entry.getValue();
if (steps.matches("[0-9\\s]*")) {
mOptions.getJSONObject("lapse").put("delays", getDelays(steps));
}
} else if (entry.getKey().equals("lapNewIvl")) {
- mOptions.getJSONObject("lapse").put("mult", Float.parseFloat((String) entry.getValue()));
+ mOptions.getJSONObject("lapse").put("mult", Float.parseFloat((String) entry.getValue()) / 100);
} else if (entry.getKey().equals("lapMinIvl")) {
mOptions.getJSONObject("lapse").put("minInt", Integer.parseInt((String) entry.getValue()));
} else if (entry.getKey().equals("lapLeechThres")) {
mOptions.getJSONObject("lapse").put("leechFails",
Integer.parseInt((String) entry.getValue()));
} else if (entry.getKey().equals("lapLeechAct")) {
mOptions.getJSONObject("lapse").put("leechAction",
Integer.parseInt((String) entry.getValue()));
}
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
// save conf
try {
mCol.getDecks().save(mOptions);
} catch (RuntimeException e) {
Log.e(AnkiDroidApp.TAG, "DeckOptions - RuntimeException on saving conf: " + e);
AnkiDroidApp.saveExceptionReportFile(e, "DeckOptionsSaveConf");
setResult(DeckPicker.RESULT_DB_ERROR);
finish();
}
// make sure we refresh the parent cached values
cacheValues();
updateSummaries();
// and update any listeners
for (OnSharedPreferenceChangeListener listener : listeners) {
listener.onSharedPreferenceChanged(DeckPreferenceHack.this, null);
}
return true;
}
@Override
public SharedPreferences.Editor putBoolean(String key, boolean value) {
mUpdate.put(key, value);
return this;
}
@Override
public SharedPreferences.Editor putFloat(String key, float value) {
mUpdate.put(key, value);
return this;
}
@Override
public SharedPreferences.Editor putInt(String key, int value) {
mUpdate.put(key, value);
return this;
}
@Override
public SharedPreferences.Editor putLong(String key, long value) {
mUpdate.put(key, value);
return this;
}
@Override
public SharedPreferences.Editor putString(String key, String value) {
mUpdate.put(key, value);
return this;
}
@Override
public SharedPreferences.Editor remove(String key) {
Log.d(this.getClass().toString(), String.format("Editor.remove(key=%s)", key));
mUpdate.remove(key);
return this;
}
public void apply() {
commit();
}
// @Override On Android 1.5 this is not Override
public android.content.SharedPreferences.Editor putStringSet(String arg0, Set<String> arg1) {
// TODO Auto-generated method stub
return null;
}
}
@Override
public boolean contains(String key) {
return mValues.containsKey(key);
}
@Override
public Editor edit() {
return new Editor();
}
@Override
public Map<String, ?> getAll() {
return mValues;
}
@Override
public boolean getBoolean(String key, boolean defValue) {
return Boolean.valueOf(this.getString(key, Boolean.toString(defValue)));
}
@Override
public float getFloat(String key, float defValue) {
return Float.valueOf(this.getString(key, Float.toString(defValue)));
}
@Override
public int getInt(String key, int defValue) {
return Integer.valueOf(this.getString(key, Integer.toString(defValue)));
}
@Override
public long getLong(String key, long defValue) {
return Long.valueOf(this.getString(key, Long.toString(defValue)));
}
@Override
public String getString(String key, String defValue) {
Log.d(this.getClass().toString(), String.format("getString(key=%s, defValue=%s)", key, defValue));
if (!mValues.containsKey(key)) {
return defValue;
}
return mValues.get(key);
}
public List<OnSharedPreferenceChangeListener> listeners = new LinkedList<OnSharedPreferenceChangeListener>();
@Override
public void registerOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) {
listeners.add(listener);
}
@Override
public void unregisterOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) {
listeners.remove(listener);
}
// @Override On Android 1.5 this is not Override
public Set<String> getStringSet(String arg0, Set<String> arg1) {
// TODO Auto-generated method stub
return null;
}
}
private DeckPreferenceHack mPref;
@Override
public SharedPreferences getSharedPreferences(String name, int mode) {
Log.d(this.getClass().toString(), String.format("getSharedPreferences(name=%s)", name));
return mPref;
}
@Override
protected void onCreate(Bundle icicle) {
// Workaround for bug 4611: http://code.google.com/p/android/issues/detail?id=4611
if (AnkiDroidApp.SDK_VERSION >= 7 && AnkiDroidApp.SDK_VERSION <= 10) {
Themes.applyTheme(this, Themes.THEME_ANDROID_DARK);
}
super.onCreate(icicle);
mCol = AnkiDroidApp.getCol();
if (mCol == null) {
finish();
return;
}
mDeck = mCol.getDecks().current();
registerExternalStorageListener();
if (mCol == null) {
Log.i(AnkiDroidApp.TAG, "DeckOptions - No Collection loaded");
finish();
return;
} else {
mPref = new DeckPreferenceHack();
mPref.registerOnSharedPreferenceChangeListener(this);
this.addPreferencesFromResource(R.xml.deck_options);
this.buildLists();
this.updateSummaries();
}
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
// update values on changed preference
this.updateSummaries();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
Log.i(AnkiDroidApp.TAG, "DeckOptions - onBackPressed()");
finish();
if (AnkiDroidApp.SDK_VERSION > 4) {
ActivityTransitionAnimation.slide(this, ActivityTransitionAnimation.FADE);
}
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mUnmountReceiver != null) {
unregisterReceiver(mUnmountReceiver);
}
}
protected void updateSummaries() {
// for all text preferences, set summary as current database value
for (String key : mPref.mValues.keySet()) {
Preference pref = this.findPreference(key);
String value = null;
if (pref == null) {
continue;
} else if (pref instanceof CheckBoxPreference) {
continue;
} else if (pref instanceof ListPreference) {
ListPreference lp = (ListPreference) pref;
value = lp.getEntry() != null ? lp.getEntry().toString() : "";
} else {
value = this.mPref.getString(key, "");
}
// update summary
if (!mPref.mSummaries.containsKey(key)) {
CharSequence s = pref.getSummary();
mPref.mSummaries.put(key, s != null ? pref.getSummary().toString() : null);
}
String summ = mPref.mSummaries.get(key);
if (summ != null && summ.contains("XXX")) {
pref.setSummary(summ.replace("XXX", value));
} else {
pref.setSummary(value);
}
}
}
protected void buildLists() {
ListPreference deckConfPref = (ListPreference) findPreference("deckConf");
ArrayList<JSONObject> confs = mCol.getDecks().allConf();
Collections.sort(confs, new JSONNameComparator());
String[] confValues = new String[confs.size()];
String[] confLabels = new String[confs.size()];
try {
for (int i = 0; i < confs.size(); i++) {
JSONObject o = confs.get(i);
confValues[i] = o.getString("id");
confLabels[i] = o.getString("name");
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
deckConfPref.setEntries(confLabels);
deckConfPref.setEntryValues(confValues);
deckConfPref.setValue(mPref.getString("deckConf", "0"));
ListPreference newOrderPref = (ListPreference) findPreference("newOrder");
newOrderPref.setEntries(R.array.new_order_labels);
newOrderPref.setEntryValues(R.array.new_order_values);
newOrderPref.setValue(mPref.getString("newOrder", "0"));
ListPreference leechActPref = (ListPreference) findPreference("lapLeechAct");
leechActPref.setEntries(R.array.leech_action_labels);
leechActPref.setEntryValues(R.array.leech_action_values);
leechActPref.setValue(mPref.getString("lapLeechAct", "0"));
}
public static String getDelays(JSONArray a) {
StringBuilder sb = new StringBuilder();
try {
for (int i = 0; i < a.length(); i++) {
sb.append(a.getString(i)).append(" ");
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
return sb.toString().trim();
}
public static JSONArray getDelays(String delays) {
JSONArray ja = new JSONArray();
for (String s : delays.split(" ")) {
ja.put(Integer.parseInt(s));
}
return ja;
}
public class JSONNameComparator implements Comparator<JSONObject> {
@Override
public int compare(JSONObject lhs, JSONObject rhs) {
String o1;
String o2;
try {
o1 = lhs.getString("name");
o2 = rhs.getString("name");
} catch (JSONException e) {
throw new RuntimeException(e);
}
return o1.compareToIgnoreCase(o2);
}
}
/**
* finish when sd card is ejected
*/
private void registerExternalStorageListener() {
if (mUnmountReceiver == null) {
mUnmountReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(SdCardReceiver.MEDIA_EJECT)) {
finish();
}
}
};
IntentFilter iFilter = new IntentFilter();
iFilter.addAction(SdCardReceiver.MEDIA_EJECT);
registerReceiver(mUnmountReceiver, iFilter);
}
}
private void addMissingValues() {
try {
for (JSONObject o : mCol.getDecks().all()) {
JSONObject conf = mCol.getDecks().confForDid(o.getLong("id"));
if (!conf.has("replayq")) {
conf.put("replayq", true);
mCol.getDecks().save(conf);
}
}
} catch (JSONException e1) {
// nothing
}
}
}
| true | true | public boolean commit() {
Log.d(AnkiDroidApp.TAG, "DeckOptions - commit() changes back to database");
try {
for (Entry<String, Object> entry : mUpdate.valueSet()) {
Log.i(AnkiDroidApp.TAG, "Change value for key '" + entry.getKey() + "': " + entry.getValue());
if (entry.getKey().equals("name")) {
if (!mCol.getDecks().rename(mDeck, (String) entry.getValue())) {
Themes.showThemedToast(DeckOptions.this,
getResources().getString(R.string.rename_error, mDeck.get("name")), false);
}
} else if (entry.getKey().equals("desc")) {
mDeck.put("desc", (String) entry.getValue());
mCol.getDecks().save(mDeck);
} else if (entry.getKey().equals("deckConf")) {
mCol.getDecks().setConf(mDeck, Long.parseLong((String) entry.getValue()));
mOptions = mCol.getDecks().confForDid(mDeck.getLong("id"));
} else if (entry.getKey().equals("maxAnswerTime")) {
mOptions.put("maxTaken", Integer.parseInt((String) entry.getValue()));
} else if (entry.getKey().equals("showAnswerTimer")) {
mOptions.put("timer", (Boolean) entry.getValue() ? 1 : 0);
} else if (entry.getKey().equals("autoPlayAudio")) {
mOptions.put("autoplay", (Boolean) entry.getValue());
} else if (entry.getKey().equals("replayQuestion")) {
mOptions.put("replayq", (Boolean) entry.getValue());
} else if (entry.getKey().equals("newSteps")) {
String steps = (String) entry.getValue();
if (steps.matches("[0-9\\s]*")) {
mOptions.getJSONObject("new").put("delays", getDelays(steps));
}
} else if (entry.getKey().equals("newGradIvl")) {
JSONArray ja = new JSONArray();
ja.put(Integer.parseInt((String) entry.getValue()));
ja.put(mOptions.getJSONObject("new").getJSONArray("ints").get(1));
mOptions.getJSONObject("new").put("ints", ja);
} else if (entry.getKey().equals("newEasy")) {
JSONArray ja = new JSONArray();
ja.put(mOptions.getJSONObject("new").getJSONArray("ints").get(0));
ja.put(Integer.parseInt((String) entry.getValue()));
mOptions.getJSONObject("new").put("ints", ja);
} else if (entry.getKey().equals("initialFactor")) {
mOptions.getJSONObject("new").put("initialFactor",
(int) (Integer.parseInt((String) entry.getValue()) * 10));
} else if (entry.getKey().equals("newOrder")) {
mOptions.getJSONObject("new").put("order", Integer.parseInt((String) entry.getValue()));
} else if (entry.getKey().equals("newPerDay")) {
mOptions.getJSONObject("new").put("perDay", Integer.parseInt((String) entry.getValue()));
} else if (entry.getKey().equals("newSeparate")) {
mOptions.getJSONObject("new").put("separate", (Boolean) entry.getValue());
} else if (entry.getKey().equals("revPerDay")) {
mOptions.getJSONObject("rev").put("perDay", Integer.parseInt((String) entry.getValue()));
} else if (entry.getKey().equals("revSpaceMax")) {
mOptions.getJSONObject("rev").put("fuzz",
Integer.parseInt((String) entry.getValue()) / 100.0f);
} else if (entry.getKey().equals("revSpaceMin")) {
mOptions.getJSONObject("rev").put("minSpace", Integer.parseInt((String) entry.getValue()));
} else if (entry.getKey().equals("easyBonus")) {
mOptions.getJSONObject("rev").put("ease4",
Integer.parseInt((String) entry.getValue()) / 100.0f);
} else if (entry.getKey().equals("revIvlFct")) {
mOptions.getJSONObject("rev").put("ivlFct", Double.parseDouble((String) entry.getValue()));
} else if (entry.getKey().equals("revMaxIvl")) {
mOptions.getJSONObject("rev").put("maxIvl", Integer.parseInt((String) entry.getValue()));
} else if (entry.getKey().equals("lapSteps")) {
String steps = (String) entry.getValue();
if (steps.matches("[0-9\\s]*")) {
mOptions.getJSONObject("lapse").put("delays", getDelays(steps));
}
} else if (entry.getKey().equals("lapNewIvl")) {
mOptions.getJSONObject("lapse").put("mult", Float.parseFloat((String) entry.getValue()));
} else if (entry.getKey().equals("lapMinIvl")) {
mOptions.getJSONObject("lapse").put("minInt", Integer.parseInt((String) entry.getValue()));
} else if (entry.getKey().equals("lapLeechThres")) {
mOptions.getJSONObject("lapse").put("leechFails",
Integer.parseInt((String) entry.getValue()));
} else if (entry.getKey().equals("lapLeechAct")) {
mOptions.getJSONObject("lapse").put("leechAction",
Integer.parseInt((String) entry.getValue()));
}
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
// save conf
try {
mCol.getDecks().save(mOptions);
} catch (RuntimeException e) {
Log.e(AnkiDroidApp.TAG, "DeckOptions - RuntimeException on saving conf: " + e);
AnkiDroidApp.saveExceptionReportFile(e, "DeckOptionsSaveConf");
setResult(DeckPicker.RESULT_DB_ERROR);
finish();
}
// make sure we refresh the parent cached values
cacheValues();
updateSummaries();
// and update any listeners
for (OnSharedPreferenceChangeListener listener : listeners) {
listener.onSharedPreferenceChanged(DeckPreferenceHack.this, null);
}
return true;
}
| public boolean commit() {
Log.d(AnkiDroidApp.TAG, "DeckOptions - commit() changes back to database");
try {
for (Entry<String, Object> entry : mUpdate.valueSet()) {
Log.i(AnkiDroidApp.TAG, "Change value for key '" + entry.getKey() + "': " + entry.getValue());
if (entry.getKey().equals("name")) {
if (!mCol.getDecks().rename(mDeck, (String) entry.getValue())) {
Themes.showThemedToast(DeckOptions.this,
getResources().getString(R.string.rename_error, mDeck.get("name")), false);
}
} else if (entry.getKey().equals("desc")) {
mDeck.put("desc", (String) entry.getValue());
mCol.getDecks().save(mDeck);
} else if (entry.getKey().equals("deckConf")) {
mCol.getDecks().setConf(mDeck, Long.parseLong((String) entry.getValue()));
mOptions = mCol.getDecks().confForDid(mDeck.getLong("id"));
} else if (entry.getKey().equals("maxAnswerTime")) {
mOptions.put("maxTaken", Integer.parseInt((String) entry.getValue()));
} else if (entry.getKey().equals("showAnswerTimer")) {
mOptions.put("timer", (Boolean) entry.getValue() ? 1 : 0);
} else if (entry.getKey().equals("autoPlayAudio")) {
mOptions.put("autoplay", (Boolean) entry.getValue());
} else if (entry.getKey().equals("replayQuestion")) {
mOptions.put("replayq", (Boolean) entry.getValue());
} else if (entry.getKey().equals("newSteps")) {
String steps = (String) entry.getValue();
if (steps.matches("[0-9\\s]*")) {
mOptions.getJSONObject("new").put("delays", getDelays(steps));
}
} else if (entry.getKey().equals("newGradIvl")) {
JSONArray ja = new JSONArray();
ja.put(Integer.parseInt((String) entry.getValue()));
ja.put(mOptions.getJSONObject("new").getJSONArray("ints").get(1));
mOptions.getJSONObject("new").put("ints", ja);
} else if (entry.getKey().equals("newEasy")) {
JSONArray ja = new JSONArray();
ja.put(mOptions.getJSONObject("new").getJSONArray("ints").get(0));
ja.put(Integer.parseInt((String) entry.getValue()));
mOptions.getJSONObject("new").put("ints", ja);
} else if (entry.getKey().equals("initialFactor")) {
mOptions.getJSONObject("new").put("initialFactor",
(int) (Integer.parseInt((String) entry.getValue()) * 10));
} else if (entry.getKey().equals("newOrder")) {
mOptions.getJSONObject("new").put("order", Integer.parseInt((String) entry.getValue()));
} else if (entry.getKey().equals("newPerDay")) {
mOptions.getJSONObject("new").put("perDay", Integer.parseInt((String) entry.getValue()));
} else if (entry.getKey().equals("newSeparate")) {
mOptions.getJSONObject("new").put("separate", (Boolean) entry.getValue());
} else if (entry.getKey().equals("revPerDay")) {
mOptions.getJSONObject("rev").put("perDay", Integer.parseInt((String) entry.getValue()));
} else if (entry.getKey().equals("revSpaceMax")) {
mOptions.getJSONObject("rev").put("fuzz",
Integer.parseInt((String) entry.getValue()) / 100.0f);
} else if (entry.getKey().equals("revSpaceMin")) {
mOptions.getJSONObject("rev").put("minSpace", Integer.parseInt((String) entry.getValue()));
} else if (entry.getKey().equals("easyBonus")) {
mOptions.getJSONObject("rev").put("ease4",
Integer.parseInt((String) entry.getValue()) / 100.0f);
} else if (entry.getKey().equals("revIvlFct")) {
mOptions.getJSONObject("rev").put("ivlFct", Double.parseDouble((String) entry.getValue()));
} else if (entry.getKey().equals("revMaxIvl")) {
mOptions.getJSONObject("rev").put("maxIvl", Integer.parseInt((String) entry.getValue()));
} else if (entry.getKey().equals("lapSteps")) {
String steps = (String) entry.getValue();
if (steps.matches("[0-9\\s]*")) {
mOptions.getJSONObject("lapse").put("delays", getDelays(steps));
}
} else if (entry.getKey().equals("lapNewIvl")) {
mOptions.getJSONObject("lapse").put("mult", Float.parseFloat((String) entry.getValue()) / 100);
} else if (entry.getKey().equals("lapMinIvl")) {
mOptions.getJSONObject("lapse").put("minInt", Integer.parseInt((String) entry.getValue()));
} else if (entry.getKey().equals("lapLeechThres")) {
mOptions.getJSONObject("lapse").put("leechFails",
Integer.parseInt((String) entry.getValue()));
} else if (entry.getKey().equals("lapLeechAct")) {
mOptions.getJSONObject("lapse").put("leechAction",
Integer.parseInt((String) entry.getValue()));
}
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
// save conf
try {
mCol.getDecks().save(mOptions);
} catch (RuntimeException e) {
Log.e(AnkiDroidApp.TAG, "DeckOptions - RuntimeException on saving conf: " + e);
AnkiDroidApp.saveExceptionReportFile(e, "DeckOptionsSaveConf");
setResult(DeckPicker.RESULT_DB_ERROR);
finish();
}
// make sure we refresh the parent cached values
cacheValues();
updateSummaries();
// and update any listeners
for (OnSharedPreferenceChangeListener listener : listeners) {
listener.onSharedPreferenceChanged(DeckPreferenceHack.this, null);
}
return true;
}
|
diff --git a/src/testopia/API/TestopiaTestCase.java b/src/testopia/API/TestopiaTestCase.java
index 628ab15..e4b2b44 100644
--- a/src/testopia/API/TestopiaTestCase.java
+++ b/src/testopia/API/TestopiaTestCase.java
@@ -1,431 +1,431 @@
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Bugzilla Testopia Java API.
*
* The Initial Developer of the Original Code is Andrew Nelson.
* Portions created by Andrew Nelson are Copyright (C) 2006
* Novell. All Rights Reserved.
*
* Contributor(s): Andrew Nelson <[email protected]>
*
*/
package testopia.API;
import java.util.HashMap;
import java.util.Map;
import org.apache.xmlrpc.XmlRpcException;
public class TestopiaTestCase extends TestopiaObject{
//inputed values to get a testCase
private Integer caseID;
//values for updates
//private Integer defaultTesterID = null;
private IntegerAttribute isAutomated = new IntegerAttribute(null);
private IntegerAttribute priorityID= new IntegerAttribute(null);
private IntegerAttribute categoryID= new IntegerAttribute(null);
private IntegerAttribute canview= new IntegerAttribute(null);
private StringAttribute arguments= new StringAttribute(null);
private StringAttribute alias= new StringAttribute(null);
private StringAttribute requirement= new StringAttribute(null);
private StringAttribute script= new StringAttribute(null);
private StringAttribute caseStatusID= new StringAttribute(null);
private StringAttribute summary= new StringAttribute(null);
/**
* @param userName your bugzilla/testopia userName
* @param password your password
* @param url the url of the testopia server
* @param caseID - Integer the caseID, you may enter null here if you are creating a test case
*/
public TestopiaTestCase(Session session, Integer caseID)
{
this.caseID = caseID;
this.session = session;
this.listMethod = "TestCase.list";
}
/**
*
* @param alias String - the new Alias
*/
public void setAlias(String alias) {
this.alias.set(alias);
}
/**
*
* @param arguments String - the new arguments
*/
public void setArguments(String arguments) {
this.arguments.set(arguments);
}
/**
*
* @param canview
*/
public void setCanview(boolean canview) {
this.canview.set(canview? 1: 0);
}
/**
*
* @param caseStatusID String - the new case Status ID
*/
public void setCaseStatusID(String caseStatusID) {
this.caseStatusID.set(caseStatusID);
}
/**
*
* @param categoryID int - the new categorID
*/
public void setCategoryID(int categoryID) {
this.categoryID.set(categoryID);
}
/**
*
* @param defaultTesterID int - the new defaultTesterID
*/
/*public void setDefaultTesterID(int defaultTesterID) {
this.defaultTesterID.set(defaultTesterID);
}*/
/**
*
* @param isAutomated boolean - true if it's to be set automated,
* false otherwise
*/
public void setIsAutomated(boolean isAutomated) {
this.isAutomated.set(isAutomated? 1:0);
}
/**
*
* @param priorityID - int the new priorityID
*/
public void setPriorityID(int priorityID) {
this.priorityID.set(priorityID);
}
/**
*
* @param requirement String - the new requirement
*/
public void setRequirement(String requirement) {
this.requirement.set(requirement);
}
/**
*
* @param script String - the new script
*/
public void setScript(String script) {
this.script.set(script);
}
/**
*
* @param summary String - the new summary
*/
public void setSummary(String summary) {
this.summary.set(summary);
}
/**
* Adds a component to the testCase
* @param componentID the ID of the component that will be added to the
* testCase
* @throws Exception
* @throws XmlRpcException
*/
public void addComponent(int componentID)
throws TestopiaException, XmlRpcException
{
if(caseID == null)
throw new TestopiaException("CaseID cannot be null");
//add the component to the test case
this.callXmlrpcMethod("TestCase.add_component",
caseID,
componentID);
}
/**
* Removes a component to the testCase
* @param componentID the ID of the component that will be removed from the
* testCase
* @throws Exception
* @throws XmlRpcException
*/
public void removeComponent(int componentID)
throws TestopiaException, XmlRpcException
{
if(caseID == null)
throw new TestopiaException("CaseID cannot be null");
//add the component to the test case
this.callXmlrpcMethod("TestCase.remove_component",
caseID,
componentID);
}
/**
* Gets the components as an array of hashMaps or null if
* an error occurs
* @return an array of component hashMaps or null
* @throws Exception
*/
public Object[] getComponents()
throws TestopiaException, XmlRpcException
{
if(caseID == null)
throw new TestopiaException("CaseID cannot be null");
return (Object[]) this.callXmlrpcMethod("TestCase.get_components",
caseID);
}
/**
* Updates are not called when the .set is used. You must call update after all your sets
* to push the changes over to testopia.
* @throws Exception if planID is null
* @throws XmlRpcException
* (you made the TestCase with a null caseID and have not created a new test plan)
*/
public void update()
throws TestopiaException, XmlRpcException
{
if (caseID == null)
throw new TestopiaException("caseID is null.");
//hashmap to store attributes to be updated
HashMap<String, Object> map = new HashMap<String, Object>();
//add attributes that need to be updated to the hashmap
- if(isAutomated != null)
+ if(isAutomated.isDirty())
map.put("isautomated", isAutomated.get().intValue());
- if(priorityID != null)
+ if(priorityID.isDirty())
map.put("priority_id", priorityID.get().intValue());
- if(canview != null)
+ if(canview.isDirty())
map.put("canview", canview.get().intValue());
- if(categoryID != null)
+ if(categoryID.isDirty())
map.put("category_id", categoryID.get());
- if(arguments != null)
+ if(arguments.isDirty())
map.put("arguments", arguments.get());
- if(alias != null)
+ if(alias.isDirty())
map.put("alias", alias.get());
- if(requirement != null)
+ if(requirement.isDirty())
map.put("requirement", requirement.get());
- if(script != null)
+ if(script.isDirty())
map.put("script", script.get());
- if(caseStatusID != null)
+ if(caseStatusID.isDirty())
map.put("case_status_id", caseStatusID.get());
- if(summary != null)
+ if(summary.isDirty())
map.put("summary", summary.get());
//update the testRunCase
this.callXmlrpcMethod("TestCase.update",
caseID,
map);
//make sure multiple updates aren't called
isAutomated.clean();
priorityID.clean();
categoryID.clean();
canview.clean();
arguments.clean();
alias.clean();
requirement.clean();
script.clean();
caseStatusID.clean();
summary.clean();
}
/**
*
* @param authorID the bugzilla/testopia ID of the author
* @param caseStatusID
* @param categoryID
* @param isAutomated
* @param planID the ID of the plan the testCase will be added to
* @param summary string - the summary of the testCase. Null allowed
* @param priorityID Integer - the priority of the testCase (0-5). Null allowed
* @return
* @throws XmlRpcException
*/
public int makeTestCase(int authorID, int caseStatusID, int categoryID,
boolean isAutomated, int planID, String summary,Integer priorityID)
throws XmlRpcException
{
int isAutomatedInt;
//convert to integer of 1 if isAutomated is true (1 == true)
if(isAutomated)
isAutomatedInt = 1;
//else convert to 0 for false (0 == false)
else
isAutomatedInt = 0;
//set the values for the test case
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("author_id", authorID);
map.put("case_status_id", caseStatusID);
map.put("category_id", categoryID);
map.put("isautomated", isAutomatedInt);
map.put("plan_id", planID);
//add the optional values if they are not null
if(summary != null)
map.put("summary", summary);
if(priorityID != null)
map.put("priority_id", priorityID.intValue());
//update the test case
Map result = (Map)this.callXmlrpcMethod("TestCase.create",
map);
caseID = (Integer)result.get("case_id");
//System.out.println(result);
return caseID;
}
public int makeTestCase(String author, String caseStatus, String category,
String product, String plan, String summary,String priority) throws XmlRpcException{
User user = new User(session, author);
int user_id = user.getAttributes();
TestPlan tp = new TestPlan(session, null);
Object[] results = tp.getList("name", plan);
//for (Object result: results) System.out.println("Found test plan:" + result.toString());
int tp_id = (Integer)((Map)results[0]).get("plan_id");
System.out.println("Found acceptance testplan id: " + tp_id);
Product prod = new Product(session);
int cat_id = prod.getCategoryIDByName(category, product);
System.out.println("Found category id: " + cat_id);
TestopiaTestCase tc2 = new TestopiaTestCase(session,null);
int pri_id = tc2.getPriorityIdByName(priority);
int stat_id = tc2.getStatusIdByName(caseStatus);
return makeTestCase(user_id, stat_id, cat_id, true, tp_id, summary, pri_id);
}
/**
* Gets the attributes of the test case, caseID must not be null
* @return a hashMap of all the values found. Returns null if there is an error
* and the TestCase cannot be returned
* @throws Exception
* @throws XmlRpcException
*/
@SuppressWarnings("unchecked")
public HashMap<String, Object> getAttributes()
throws TestopiaException, XmlRpcException
{
if (caseID == null)
throw new TestopiaException("caseID is null.");
//get the hashmap
return (HashMap<String, Object>) this.callXmlrpcMethod("TestCase.get",
caseID.intValue());
}
@Deprecated
public int getCategoryIdByName(String categoryName)
throws XmlRpcException
{
//get the result
return (Integer) this.callXmlrpcMethod("TestCase.lookup_category_id_by_name",
categoryName);
}
public int getPriorityIdByName(String categoryName) throws XmlRpcException
{
//get the result
return (Integer) this.callXmlrpcMethod("TestCase.lookup_priority_id_by_name",
categoryName);
}
public int getStatusIdByName(String categoryName) throws XmlRpcException
{
//get the result
return (Integer) this.callXmlrpcMethod("TestCase.lookup_status_id_by_name",
categoryName);
}
/**
* Uses Deprecated API -Use Product class for this
* @param categoryName the name of the category that the ID will be returned for. This will search within the
* test plans that this test case belongs to and return the first category with a matching name. 0 Will be
* returned if the category can't be found
* @return the ID of the specified product
* @throws XmlRpcException
*/
@Deprecated
public int getBuildIDByName(String categoryName)
throws XmlRpcException
{
//get the result
return (Integer)this.callXmlrpcMethod("TestCase.lookup_category_id_by_name",
categoryName);
}
public Integer getIsAutomated() {
return isAutomated.get();
}
public Integer getPriorityID() {
return priorityID.get();
}
public Integer getCategoryID() {
return categoryID.get();
}
public Integer getCanview() {
return canview.get();
}
public String getArguments() {
return arguments.get();
}
public String getAlias() {
return alias.get();
}
public String getRequirement() {
return requirement.get();
}
public String getScript() {
return script.get();
}
public String getCaseStatusID() {
return caseStatusID.get();
}
public String getSummary() {
return summary.get();
}
}
| false | true | public void update()
throws TestopiaException, XmlRpcException
{
if (caseID == null)
throw new TestopiaException("caseID is null.");
//hashmap to store attributes to be updated
HashMap<String, Object> map = new HashMap<String, Object>();
//add attributes that need to be updated to the hashmap
if(isAutomated != null)
map.put("isautomated", isAutomated.get().intValue());
if(priorityID != null)
map.put("priority_id", priorityID.get().intValue());
if(canview != null)
map.put("canview", canview.get().intValue());
if(categoryID != null)
map.put("category_id", categoryID.get());
if(arguments != null)
map.put("arguments", arguments.get());
if(alias != null)
map.put("alias", alias.get());
if(requirement != null)
map.put("requirement", requirement.get());
if(script != null)
map.put("script", script.get());
if(caseStatusID != null)
map.put("case_status_id", caseStatusID.get());
if(summary != null)
map.put("summary", summary.get());
//update the testRunCase
this.callXmlrpcMethod("TestCase.update",
caseID,
map);
//make sure multiple updates aren't called
isAutomated.clean();
priorityID.clean();
categoryID.clean();
canview.clean();
arguments.clean();
alias.clean();
requirement.clean();
script.clean();
caseStatusID.clean();
summary.clean();
}
| public void update()
throws TestopiaException, XmlRpcException
{
if (caseID == null)
throw new TestopiaException("caseID is null.");
//hashmap to store attributes to be updated
HashMap<String, Object> map = new HashMap<String, Object>();
//add attributes that need to be updated to the hashmap
if(isAutomated.isDirty())
map.put("isautomated", isAutomated.get().intValue());
if(priorityID.isDirty())
map.put("priority_id", priorityID.get().intValue());
if(canview.isDirty())
map.put("canview", canview.get().intValue());
if(categoryID.isDirty())
map.put("category_id", categoryID.get());
if(arguments.isDirty())
map.put("arguments", arguments.get());
if(alias.isDirty())
map.put("alias", alias.get());
if(requirement.isDirty())
map.put("requirement", requirement.get());
if(script.isDirty())
map.put("script", script.get());
if(caseStatusID.isDirty())
map.put("case_status_id", caseStatusID.get());
if(summary.isDirty())
map.put("summary", summary.get());
//update the testRunCase
this.callXmlrpcMethod("TestCase.update",
caseID,
map);
//make sure multiple updates aren't called
isAutomated.clean();
priorityID.clean();
categoryID.clean();
canview.clean();
arguments.clean();
alias.clean();
requirement.clean();
script.clean();
caseStatusID.clean();
summary.clean();
}
|
diff --git a/src/main/java/com/googlecode/jcimd/PacketSerializer.java b/src/main/java/com/googlecode/jcimd/PacketSerializer.java
index 1c92b98..7a59af6 100644
--- a/src/main/java/com/googlecode/jcimd/PacketSerializer.java
+++ b/src/main/java/com/googlecode/jcimd/PacketSerializer.java
@@ -1,361 +1,362 @@
/*
* Copyright 2010-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.googlecode.jcimd;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* <p>
* Serializes/deserializes CIMD packets in the following format:
* </p>
* <pre>
* HEADER Parameter List TRAILER
* <STX>ZZ:NNN<TAB>PPP:Parameter value<TAB>...CC<ETX>
* ^ ^ ^ ^ ^ ^ ^
* | | | | | | |
* | | | | | | +-- (end of text)
* | | | | | +-- check sum (two bytes)
* | | | | + parameter code (three bytes)
* | | | |
* | | | +-- delimiter
* | | |
* | | +-- packet number (three bytes)
* | +-- operation code (two bytes)
* +-- (start of text)
* </pre>
* <p>
* The packet sequence number is generated using an optional
* {@link PacketSequenceNumberGenerator}. If none is specified, then all packets
* are expected to have sequence numbers. Otherwise, an exception is thrown.
* <p>
* The <STX>, <TAB>, ":" (COLON), and <ETX> bytes are
* <em>not</em> part of the {@link Packet packet bean}. Instead, it is added upon
* serialization by this class.
* <p>
* To protect against buffer overflow, this class uses a {@link #setMaxMessageSize(int)
* maximum message size} which defaults to 4096 (1024 * 4) bytes.
*
* @author Lorenzo Dee
*
* @see #setSequenceNumberGenerator(PacketSequenceNumberGenerator)
*/
public class PacketSerializer {
public static final byte STX = 0x02;
public static final byte TAB = '\t'; // ASCII value is 9
public static final byte COLON = ':'; // ASCII value is 58
public static final byte ETX = 0x03;
public static final byte NUL = 0x00;
public static final int END_OF_STREAM = -1;
private static final int DEFAULT_MAX_SIZE = 1024 * 4;
private final Log logger;
private final boolean useChecksum;
private int maxMessageSize = DEFAULT_MAX_SIZE;
private PacketSequenceNumberGenerator sequenceNumberGenerator;
/**
* Constructs a serializer that uses and expects a two-byte checksum.
*/
public PacketSerializer() {
this(null, true);
}
/**
* Constructs a serializer with the given name that uses
* and expects a two-byte checksum.
* @param name name of this serializer (used in logging)
*/
public PacketSerializer(String name) {
this(name, true);
}
/**
* Constructs a serializer with the given name that will use
* two-byte checksum based on flag.
* @param name name of this serializer (used in logging)
* @param useChecksum flag to indicate to use checksum
*/
public PacketSerializer(String name, boolean useChecksum) {
if (name != null) {
this.logger = LogFactory.getLog(
this.getClass().getName() + "." + name);
} else {
this.logger = LogFactory.getLog(this.getClass());
}
this.useChecksum = useChecksum;
}
public int getMaxMessageSize() {
return maxMessageSize;
}
public void setMaxMessageSize(int maxMessageSize) {
if (maxMessageSize <= 0) {
throw new IllegalArgumentException(
"maxMessageSize must be greater than zero");
}
this.maxMessageSize = maxMessageSize;
}
public PacketSequenceNumberGenerator getSequenceNumberGenerator() {
return sequenceNumberGenerator;
}
public void setSequenceNumberGenerator(
PacketSequenceNumberGenerator sequenceNumberGenerator) {
this.sequenceNumberGenerator = sequenceNumberGenerator;
}
public void serialize(Packet packet, OutputStream outputStream)
throws IOException {
if (logger.isDebugEnabled()) {
logger.debug("Sending " + packet);
}
byte[] bytes = serializeToByteArray(packet);
outputStream.write(bytes);
if (this.useChecksum) {
int checkSum = calculateCheckSum(bytes);
AsciiUtils.writeIntAsHexAsciiBytes(checkSum, outputStream, 2);
}
outputStream.write(ETX);
}
private byte[] serializeToByteArray(Packet packet) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
outputStream.write(STX);
AsciiUtils.writeIntAsAsciiBytes(
packet.getOperationCode(), outputStream, 2);
outputStream.write(COLON);
Integer sequenceNumber = packet.getSequenceNumber();
if (sequenceNumber == null) {
if (logger.isTraceEnabled()) {
logger.trace("No sequence number in packet, generating one...");
}
if (this.sequenceNumberGenerator != null) {
sequenceNumber = this.sequenceNumberGenerator.nextSequence();
if (logger.isTraceEnabled()) {
logger.trace("Generated " + sequenceNumber + " as sequence number");
}
} else {
String message = "No sequence number generator. " +
"Please see PacketSerializer#setSequenceNumberGenerator(" +
"PacketSequenceNumberGenerator)";
logger.error(message);
throw new IOException(message);
}
}
AsciiUtils.writeIntAsAsciiBytes(
sequenceNumber, outputStream, 3);
outputStream.write(TAB);
for (Parameter parameter : packet.getParameters()) {
AsciiUtils.writeIntAsAsciiBytes(
parameter.getNumber(), outputStream, 3);
outputStream.write(COLON);
AsciiUtils.writeStringAsAsciiBytes(
parameter.getValue(), outputStream);
outputStream.write(TAB);
}
return outputStream.toByteArray();
}
/**
* Calculates the check sum of the given bytes.
*
* @param bytes the array from which a check sum is calculated
* @return the check sum
*/
private int calculateCheckSum(byte[] bytes) {
return calculateCheckSum(bytes, 0, bytes.length);
}
/**
* Calculates the check sum of the given range of bytes.
*
* @param bytes the array from which a check sum is calculated
* @param from the initial index of the range to be copied, inclusive
* @param to the final index of the range to be copied, exclusive.
* (This index may lie outside the array.)
* @return the check sum
*/
private int calculateCheckSum(byte[] bytes, int from, int to) {
int sum = 0;
for (int i = from; i < to; i++) {
sum += bytes[i];
sum &= 0xFF;
}
return sum;
}
public Packet deserialize(InputStream inputStream) throws IOException {
ByteArrayOutputStream temp = new ByteArrayOutputStream();
int b;
while ((b = inputStream.read()) != END_OF_STREAM) {
// Any data transmitted between packets SHALL be ignored.
if (b == STX) {
temp.write(b);
break;
}
}
if (b != STX) {
//throw new SoftEndOfStreamException();
throw new IOException(
"End of stream reached and still no <STX> byte");
}
// Read the input stream until ETX
while ((b = inputStream.read()) != END_OF_STREAM) {
temp.write(b);
if (b == ETX) {
break;
}
if (temp.size() >= getMaxMessageSize()) {
// Protect from buffer overflow
throw new IOException(
"Buffer overflow reached at " + temp.size()
+ " byte(s) and still no <ETX> byte");
}
}
if (b != ETX) {
throw new IOException(
"End of stream reached and still no <ETX> byte");
}
// Parse contents of "temp" (it contains the entire CIMD message
// including STX and ETX bytes).
byte bytes[] = temp.toByteArray();
if (logger.isTraceEnabled()) {
logger.trace("Received " + bytes.length + " byte(s)");
}
if (useChecksum) {
// Read two (2) bytes, just before the ETX byte.
StringBuilder buffer = new StringBuilder(2);
buffer.append((char) bytes[bytes.length - 3]);
buffer.append((char) bytes[bytes.length - 2]);
try {
int checksum = Integer.valueOf(buffer.toString(), 16);
int expectedChecksum = calculateCheckSum(bytes, 0, bytes.length - 3);
if (checksum != expectedChecksum) {
throw new IOException(
"Checksum error: expecting " + expectedChecksum
+ " but got " + checksum);
}
} catch (NumberFormatException e) {
throw new IOException(
"Checksum error: expecting HEX digits, but got " + buffer);
}
}
// Deserialize bytes, minus STX, CC (check sum), and ETX.
- Packet packet = deserializeFromByteArray(bytes, 1, bytes.length - 3);
+ int end = useChecksum ? bytes.length - 3 : bytes.length -1;
+ Packet packet = deserializeFromByteArray(bytes, 1, end);
if (logger.isDebugEnabled()) {
logger.debug("Received " + packet);
}
return packet;
}
private Packet deserializeFromByteArray(
byte[] bytes, int from, int to) throws IOException {
StringBuilder buffer = new StringBuilder();
int i = from;
// Read the operation code and packet number
i = readToBufferUntil(bytes, i, to, 2, buffer, COLON);
int operationCode = Integer.valueOf(buffer.toString());
buffer.setLength(0);
i = readToBufferUntil(bytes, i, to, -1, buffer, TAB);
int sequenceNumber = Integer.valueOf(buffer.toString());
buffer.setLength(0);
// Read the parameters
List<Parameter> parameters = new LinkedList<Parameter>();
while (i < to) {
i = readToBufferUntil(bytes, i, to, 3, buffer, COLON);
int parameterType = Integer.valueOf(buffer.toString());
buffer.setLength(0);
i = readToBufferUntil(bytes, i, to, -1, buffer, TAB);
String parameterValue = buffer.toString();
buffer.setLength(0);
parameters.add(new Parameter(parameterType, parameterValue));
}
return new Packet(operationCode, sequenceNumber,
parameters.toArray(new Parameter[0]));
}
/**
* Reads bytes and appends to buffer until the delimiter is reached,
* or the <em>to</em> is reached, or a reserved characters is reached.
* The reserved characters 0x00 (NUL), 0x02 (STX), 0x03 (ETX), 0x09
* (TAB) are not allowed in any parameter.
*
* @param bytes the array of bytes to read
* @param from the initial index of the range to be read, inclusive
* @param to the final index of the range to be read, exclusive.
* (This index may lie outside the array.)
* @param maxOffset the maximum offset that can be read before reaching
* delimiter. If this offset is exceeded, and no delimiter was
* reached, an exception will be thrown.
* @param buffer the buffer to append to
* @param delimiter the delimiter to reach
* @return the index (between <em>from</em> and <em>to</em>)
* when the delimiter was reached
* @throws IOException if a reserved character was reached, and it is
* not the expected <em>delimiter</em>.
*/
private int readToBufferUntil(
byte[] bytes, int from, int to, int maxOffset,
StringBuilder buffer, byte delimiter)
throws IOException {
int i = from;
while ((i < to) && (bytes[i] != delimiter)
// The reserved characters 0x00 (NUL), 0x02 (STX),
// 0x03 (ETX), 0x09 (TAB) are not allowed in any parameter
&& (bytes[i] != NUL) && (bytes[i] != STX)
&& (bytes[i] != ETX) && (bytes[i] != TAB)) {
buffer.append((char) bytes[i]);
i++;
if ((maxOffset > 0) && ((i - from) > maxOffset)) {
throw new IOException(
"Expecting 0x" + Integer.toHexString(delimiter)
+ " within " + maxOffset + " byte(s), " +
"but got 0x" + Integer.toHexString(bytes[i - 1]));
}
}
if (bytes[i] != delimiter) {
throw new IOException(
"Expecting 0x" + Integer.toHexString(delimiter)
+ " but got 0x" + Integer.toHexString(bytes[i]));
} else {
i++;
}
return i;
}
}
| true | true | public Packet deserialize(InputStream inputStream) throws IOException {
ByteArrayOutputStream temp = new ByteArrayOutputStream();
int b;
while ((b = inputStream.read()) != END_OF_STREAM) {
// Any data transmitted between packets SHALL be ignored.
if (b == STX) {
temp.write(b);
break;
}
}
if (b != STX) {
//throw new SoftEndOfStreamException();
throw new IOException(
"End of stream reached and still no <STX> byte");
}
// Read the input stream until ETX
while ((b = inputStream.read()) != END_OF_STREAM) {
temp.write(b);
if (b == ETX) {
break;
}
if (temp.size() >= getMaxMessageSize()) {
// Protect from buffer overflow
throw new IOException(
"Buffer overflow reached at " + temp.size()
+ " byte(s) and still no <ETX> byte");
}
}
if (b != ETX) {
throw new IOException(
"End of stream reached and still no <ETX> byte");
}
// Parse contents of "temp" (it contains the entire CIMD message
// including STX and ETX bytes).
byte bytes[] = temp.toByteArray();
if (logger.isTraceEnabled()) {
logger.trace("Received " + bytes.length + " byte(s)");
}
if (useChecksum) {
// Read two (2) bytes, just before the ETX byte.
StringBuilder buffer = new StringBuilder(2);
buffer.append((char) bytes[bytes.length - 3]);
buffer.append((char) bytes[bytes.length - 2]);
try {
int checksum = Integer.valueOf(buffer.toString(), 16);
int expectedChecksum = calculateCheckSum(bytes, 0, bytes.length - 3);
if (checksum != expectedChecksum) {
throw new IOException(
"Checksum error: expecting " + expectedChecksum
+ " but got " + checksum);
}
} catch (NumberFormatException e) {
throw new IOException(
"Checksum error: expecting HEX digits, but got " + buffer);
}
}
// Deserialize bytes, minus STX, CC (check sum), and ETX.
Packet packet = deserializeFromByteArray(bytes, 1, bytes.length - 3);
if (logger.isDebugEnabled()) {
logger.debug("Received " + packet);
}
return packet;
}
| public Packet deserialize(InputStream inputStream) throws IOException {
ByteArrayOutputStream temp = new ByteArrayOutputStream();
int b;
while ((b = inputStream.read()) != END_OF_STREAM) {
// Any data transmitted between packets SHALL be ignored.
if (b == STX) {
temp.write(b);
break;
}
}
if (b != STX) {
//throw new SoftEndOfStreamException();
throw new IOException(
"End of stream reached and still no <STX> byte");
}
// Read the input stream until ETX
while ((b = inputStream.read()) != END_OF_STREAM) {
temp.write(b);
if (b == ETX) {
break;
}
if (temp.size() >= getMaxMessageSize()) {
// Protect from buffer overflow
throw new IOException(
"Buffer overflow reached at " + temp.size()
+ " byte(s) and still no <ETX> byte");
}
}
if (b != ETX) {
throw new IOException(
"End of stream reached and still no <ETX> byte");
}
// Parse contents of "temp" (it contains the entire CIMD message
// including STX and ETX bytes).
byte bytes[] = temp.toByteArray();
if (logger.isTraceEnabled()) {
logger.trace("Received " + bytes.length + " byte(s)");
}
if (useChecksum) {
// Read two (2) bytes, just before the ETX byte.
StringBuilder buffer = new StringBuilder(2);
buffer.append((char) bytes[bytes.length - 3]);
buffer.append((char) bytes[bytes.length - 2]);
try {
int checksum = Integer.valueOf(buffer.toString(), 16);
int expectedChecksum = calculateCheckSum(bytes, 0, bytes.length - 3);
if (checksum != expectedChecksum) {
throw new IOException(
"Checksum error: expecting " + expectedChecksum
+ " but got " + checksum);
}
} catch (NumberFormatException e) {
throw new IOException(
"Checksum error: expecting HEX digits, but got " + buffer);
}
}
// Deserialize bytes, minus STX, CC (check sum), and ETX.
int end = useChecksum ? bytes.length - 3 : bytes.length -1;
Packet packet = deserializeFromByteArray(bytes, 1, end);
if (logger.isDebugEnabled()) {
logger.debug("Received " + packet);
}
return packet;
}
|
diff --git a/src/main/java/com/deepmine/by/services/RadioService.java b/src/main/java/com/deepmine/by/services/RadioService.java
index fb14bf0..7646d28 100644
--- a/src/main/java/com/deepmine/by/services/RadioService.java
+++ b/src/main/java/com/deepmine/by/services/RadioService.java
@@ -1,169 +1,167 @@
package com.deepmine.by.services;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.IBinder;
import android.util.Log;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import com.deepmine.by.MainActivity;
import com.deepmine.by.R;
import com.deepmine.by.components.TimerTaskPlus;
import com.deepmine.by.helpers.Constants;
import java.util.Timer;
/**
* Created by zyr3x on 01.10.13.
*/
public class RadioService extends Service implements Constants{
private static String TAG = MAIN_TAG+":RadioService";
private static final int NOTIFICATION_ID = 1;
private static boolean _isStartService = false;
private static boolean _isError = false;
private static Timer _timer = new Timer();
private static NotificationManager mNotificationManager = null;
private static MediaTask _mediaTask = null;
private static MediaPlayer _mediaPlayer = null;
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startid) {
_mediaTask = new MediaTask();
_mediaTask.execute();
return START_STICKY;
}
private void stopService() {
stop();
}
public void start()
{
try {
_mediaPlayer = new MediaPlayer();
_mediaPlayer.setDataSource(RADIO_SERVER_URL);
_mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
_mediaPlayer.prepare();
_mediaPlayer.start();
_isStartService = true;
} catch (Exception e) {
_isError = true;
_isStartService = false;
stop();
Log.d(TAG, "Exception in streaming mediaplayer e = " + e);
}
}
protected void updateTitle()
{
_timer = new Timer();
_timer.scheduleAtFixedRate(new TimerTaskPlus() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
if (_isStartService) {
- if (!DataService.getLastTitle().equals(DataService.getDataTitle().title)) {
updateNotification(
DataService.getDataTitle().artist,
DataService.getDataTitle().track
);
- }
}
}
});
}
},1000,1000);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
stop();
super.onDestroy();
}
public static void stop()
{
_isStartService = false;
if(_mediaTask !=null)
_mediaTask.cancel(false);
if(mNotificationManager!=null)
mNotificationManager.cancel(NOTIFICATION_ID);
if(_timer!=null)
_timer.cancel();
if(_mediaPlayer!=null)
_mediaPlayer.stop();
}
public static boolean isPlaying()
{
if(_mediaPlayer!= null)
return _isStartService;
else
return false;
}
public static boolean isErrors()
{
return _isError;
}
public static void cleanErrors()
{
_isError = false;
}
private void updateNotification(String title1, String title2) {
if(mNotificationManager==null)
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_play, RADIO_TITLE, System.currentTimeMillis());
notification.flags = Notification.FLAG_ONGOING_EVENT;
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0,notificationIntent, 0);
notification.setLatestEventInfo(getApplicationContext(), title1, title2, contentIntent);
mNotificationManager.notify(NOTIFICATION_ID,notification);
}
class MediaTask extends AsyncTask<Object, Void, Boolean> {
protected Boolean doInBackground(Object... arg) {
start();
return true;
}
protected void onPostExecute(Boolean flag) {
if(flag)
updateTitle();
}
}
}
| false | true | protected void updateTitle()
{
_timer = new Timer();
_timer.scheduleAtFixedRate(new TimerTaskPlus() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
if (_isStartService) {
if (!DataService.getLastTitle().equals(DataService.getDataTitle().title)) {
updateNotification(
DataService.getDataTitle().artist,
DataService.getDataTitle().track
);
}
}
}
});
}
},1000,1000);
}
| protected void updateTitle()
{
_timer = new Timer();
_timer.scheduleAtFixedRate(new TimerTaskPlus() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
if (_isStartService) {
updateNotification(
DataService.getDataTitle().artist,
DataService.getDataTitle().track
);
}
}
});
}
},1000,1000);
}
|
diff --git a/src/org/sortdc/sortdc/database/DatabaseMongo.java b/src/org/sortdc/sortdc/database/DatabaseMongo.java
index f01481e..0fd23d1 100644
--- a/src/org/sortdc/sortdc/database/DatabaseMongo.java
+++ b/src/org/sortdc/sortdc/database/DatabaseMongo.java
@@ -1,413 +1,414 @@
package org.sortdc.sortdc.database;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.sortdc.sortdc.dao.Category;
import org.sortdc.sortdc.dao.Document;
import org.sortdc.sortdc.dao.Word;
public class DatabaseMongo extends Database {
private DB db;
public DatabaseMongo() {
this.setHost("localhost");
this.setPort(27017);
}
/**
* Establishes connection with database
*
* @throws Exception
*/
public void connect() throws Exception {
if (this.db_name == null) {
throw new Exception("Dbname unset");
}
Mongo init = new Mongo(this.host, this.port);
if (this.username != null && this.password != null && !db.authenticate(this.username, this.password.toCharArray())) {
throw new Exception("Connection denied : incorrect database authentication");
}
DB database = init.getDB(this.db_name);
this.db = database;
this.init();
}
/**
* Initializes the database : creates tables if they don't exist
*
* @throws Exception
*/
private void init() throws Exception {
this.addUniqueIndex("categories", "name");
this.addUniqueIndex("documents", "name");
this.addUniqueIndex("words", "name");
}
/**
* Creates a unique index on a field
*
* @param collection
* @param field
* @throws Exception
*/
private void addUniqueIndex(String collection, String field) throws Exception{
DBObject obj = new BasicDBObject();
obj.put(field, 1);
DBObject options = new BasicDBObject();
options.put("unique", true);
db.getCollection("words").ensureIndex(obj, options);
}
/**
* Finds all registered categories
*
* @return Categories list
* @throws Exception
*/
public List<Category> findAllCategories() throws Exception {
List<Category> categories = new ArrayList();
DBCollection collection = this.db.getCollection("categories");
DBCursor cursor = collection.find();
while (cursor.hasNext()) {
DBObject obj = cursor.next();
Category category = new Category();
category.setId(obj.get("_id").toString());
category.setName(obj.get("name").toString());
categories.add(category);
}
cursor.close();
return categories;
}
/**
* Saves or updates a category
*
* @param category
* @throws Exception
*/
public synchronized void saveCategory(Category category) throws Exception {
DBCollection collection = this.db.getCollection("categories");
DBObject query = new BasicDBObject();
query.put("name", category.getName());
if (category.getId() == null) {
collection.insert(query);
} else {
query.put("_id", category.getId());
collection.save(query);
}
}
/**
* Deletes a category given its id
*
* @param category_id
* @throws Exception
*/
public void deleteCategoryById(String category_id) throws Exception {
this.deleteCategoryByParam("_id", category_id);
}
/**
* Deletes a category given its name
*
* @param category_id
* @throws Exception
*/
public void deleteCategoryByName(String category_name) throws Exception {
this.deleteCategoryByParam("name", category_name);
}
/**
* Deletes a category by a parameter (id or name)
*
* @param param search parameter
* @param value id or name
* @throws Exception
*/
private void deleteCategoryByParam(String param, String value) throws Exception {
DBCollection collection = this.db.getCollection("categories");
DBObject query = new BasicDBObject();
query.put(param, value);
collection.remove(query);
}
/**
* Finds a document given its id
*
* @param id document id
* @return document matching id
* @throws Exception
*/
public Document findDocumentById(String id) throws Exception {
return this.findDocumentByParam("_id", id);
}
/**
* Finds a document given its name
*
* @param name document name
* @return document matching name
* @throws Exception
*/
public Document findDocumentByName(String name) throws Exception {
return this.findDocumentByParam("name", name);
}
/**
* Finds a document by a parameter (id or name)
*
* @param param search parameter
* @param name document name
* @return document matching name
* @throws Exception
*/
private Document findDocumentByParam(String param, String value) throws Exception {
Document document = new Document();
DBCollection collection = this.db.getCollection("documents");
DBObject query = new BasicDBObject();
query.put(param, value);
DBCursor cursor = collection.find(query).limit(1);
if (cursor.hasNext()) {
DBObject current_doc = cursor.next();
document.setId((String) current_doc.get("_id"));
document.setName((String) current_doc.get("name"));
document.setCategoryId((String) current_doc.get("category_id"));
document.setWordsOccurrences((Map<String, Integer>) current_doc.get("words"));
} else {
throw new Exception("Document not found");
}
cursor.close();
return document;
}
/**
* Saves a new document or updates an existing one
*
* @param document document to save / update
* @throws Exception
*/
public synchronized void saveDocument(Document document) throws Exception {
if (document.getId() != null) {
Document old_document = this.findDocumentById(document.getId());
this.deleteDocumentWordsOcurrences(old_document);
}
DBCollection collection = this.db.getCollection("documents");
DBObject query = new BasicDBObject();
query.put("name", document.getName());
query.put("category_id", document.getCategoryId());
query.put("words", document.getWordsOccurrences());
if (document.getId() == null) {
collection.insert(query);
} else {
query.put("_id", document.getId());
collection.save(query);
}
Set<String> names = new HashSet<String>(document.getWordsOccurrences().keySet());
List<Word> words = this.findWordsByNames(names);
Map<String, Integer> occurences = new HashMap<String, Integer>();
for (Word word : words) {
names.remove(word.getName());
occurences = word.getOccurrencesByCategory();
if (occurences.containsKey(document.getCategoryId())) {
occurences.put(document.getCategoryId(), occurences.get(document.getCategoryId()) + document.getWordsOccurrences().get(word.getName()));
} else {
occurences.put(document.getCategoryId(), document.getWordsOccurrences().get(word.getName()));
}
word.setOccurrencesByCategory(occurences);
this.saveWord(word);
}
+ Map<String, Integer> occurences2 = new HashMap<String, Integer>();
for (String name : names) {
Word word = new Word();
word.setName(name);
- occurences.put(document.getCategoryId(), document.getWordsOccurrences().get(name));
- word.setOccurrencesByCategory(occurences);
+ occurences2.put(document.getCategoryId(), document.getWordsOccurrences().get(name));
+ word.setOccurrencesByCategory(occurences2);
this.saveWord(word);
}
}
/**
* Deletes words' occurrences of a document in a category
*
* @throws Exception
*/
private void deleteDocumentWordsOcurrences(Document document) throws Exception {
if (document.getId() != null) {
Map<String, Integer> occurences = document.getWordsOccurrences();
for (Map.Entry<String, Integer> doc_occurences : occurences.entrySet()) {
Word word = this.findWordByName(doc_occurences.getKey());
for (Map.Entry<String, Integer> word_occurences : word.getOccurrencesByCategory().entrySet()) {
if (word_occurences.getKey().equals(document.getCategoryId())) {
word_occurences.setValue(word_occurences.getValue() - doc_occurences.getValue());
this.saveWord(word);
}
}
}
}
}
/**
* Deletes a document given its id
*
* @param document_id
* @throws Exception
*/
public void deleteDocumentById(String document_id) throws Exception {
this.deleteDocumentByParam("_id", document_id);
}
/**
* Deletes a document given its name
*
* @param document_name
* @throws Exception
*/
public void deleteDocumentByName(String document_name) throws Exception {
this.deleteDocumentByParam("name", document_name);
}
/**
* Deletes a document by a parameter (id or name)
*
* @param param search parameter
* @param value id or name
* @throws Exception
*/
private void deleteDocumentByParam(String param, String value) throws Exception {
Document document = this.findDocumentByParam(param, value);
this.deleteDocumentWordsOcurrences(document);
DBCollection collection = this.db.getCollection("documents");
DBObject query = new BasicDBObject();
query.put(param, value);
collection.remove(query);
}
/**
* Finds a word given its id
*
* @param id word id
* @return word matching id
* @throws Exception
*/
public Word findWordById(String id) throws Exception {
return this.findWordByParam("_id", id);
}
/**
* Finds a word given its name
*
* @param name word name
* @return word matching name
* @throws Exception
*/
public Word findWordByName(String name) throws Exception {
return this.findWordByParam("name", name);
}
/**
* Finds a word by a parameter (id or name)
*
* @param param search parameter
* @param name word name
* @return word matching name
* @throws Exception
*/
private Word findWordByParam(String param, String value) throws Exception {
Word word = new Word();
DBCollection collection = this.db.getCollection("words");
DBObject query = new BasicDBObject();
query.put(param, value);
DBCursor cursor = collection.find(query).limit(1);
if (cursor.hasNext()) {
DBObject current_doc = cursor.next();
word.setId((String) current_doc.get("_id"));
word.setName((String) current_doc.get("name"));
word.setOccurrencesByCategory((Map<String, Integer>) current_doc.get("occurences"));
} else {
throw new Exception("Word not found");
}
cursor.close();
return word;
}
/**
* Finds a list of words given a set of names
*
* @param names set of names
* @return list of words matching names
* @throws Exception
*/
public List<Word> findWordsByNames(Set<String> names) throws Exception {
List<Word> words = new ArrayList<Word>();
DBCollection collection = this.db.getCollection("words");
DBObject query = new BasicDBObject();
query.put("name", new BasicDBObject("$in", names.toArray()));
DBCursor cursor = collection.find(query);
while (cursor.hasNext()) {
Word word = new Word();
DBObject current_word = cursor.next();
word.setId((String) current_word.get("_id"));
word.setName((String) current_word.get("name"));
word.setOccurrencesByCategory((Map<String, Integer>) current_word.get("occurences"));
words.add(word);
}
cursor.close();
return words;
}
/**
* Saves a new word or update an existing one
*
* @param word word to save / update
* @throws Exception
*/
public synchronized void saveWord(Word word) throws Exception {
DBCollection collection = this.db.getCollection("words");
DBObject query = new BasicDBObject();
query.put("name", word.getName());
Map<String, Integer> occurences = word.getOccurrencesByCategory();
DBObject word_occurences = new BasicDBObject();
for (Map.Entry<String, Integer> cat_occurences : occurences.entrySet()) {
System.out.println(cat_occurences.getKey()+","+cat_occurences.getValue());
}
query.put("occurences", word_occurences);
if (word.getId() == null) {
collection.insert(query);
} else {
query.put("_id", word.getId());
collection.save(query);
}
}
}
| false | true | public synchronized void saveDocument(Document document) throws Exception {
if (document.getId() != null) {
Document old_document = this.findDocumentById(document.getId());
this.deleteDocumentWordsOcurrences(old_document);
}
DBCollection collection = this.db.getCollection("documents");
DBObject query = new BasicDBObject();
query.put("name", document.getName());
query.put("category_id", document.getCategoryId());
query.put("words", document.getWordsOccurrences());
if (document.getId() == null) {
collection.insert(query);
} else {
query.put("_id", document.getId());
collection.save(query);
}
Set<String> names = new HashSet<String>(document.getWordsOccurrences().keySet());
List<Word> words = this.findWordsByNames(names);
Map<String, Integer> occurences = new HashMap<String, Integer>();
for (Word word : words) {
names.remove(word.getName());
occurences = word.getOccurrencesByCategory();
if (occurences.containsKey(document.getCategoryId())) {
occurences.put(document.getCategoryId(), occurences.get(document.getCategoryId()) + document.getWordsOccurrences().get(word.getName()));
} else {
occurences.put(document.getCategoryId(), document.getWordsOccurrences().get(word.getName()));
}
word.setOccurrencesByCategory(occurences);
this.saveWord(word);
}
for (String name : names) {
Word word = new Word();
word.setName(name);
occurences.put(document.getCategoryId(), document.getWordsOccurrences().get(name));
word.setOccurrencesByCategory(occurences);
this.saveWord(word);
}
}
| public synchronized void saveDocument(Document document) throws Exception {
if (document.getId() != null) {
Document old_document = this.findDocumentById(document.getId());
this.deleteDocumentWordsOcurrences(old_document);
}
DBCollection collection = this.db.getCollection("documents");
DBObject query = new BasicDBObject();
query.put("name", document.getName());
query.put("category_id", document.getCategoryId());
query.put("words", document.getWordsOccurrences());
if (document.getId() == null) {
collection.insert(query);
} else {
query.put("_id", document.getId());
collection.save(query);
}
Set<String> names = new HashSet<String>(document.getWordsOccurrences().keySet());
List<Word> words = this.findWordsByNames(names);
Map<String, Integer> occurences = new HashMap<String, Integer>();
for (Word word : words) {
names.remove(word.getName());
occurences = word.getOccurrencesByCategory();
if (occurences.containsKey(document.getCategoryId())) {
occurences.put(document.getCategoryId(), occurences.get(document.getCategoryId()) + document.getWordsOccurrences().get(word.getName()));
} else {
occurences.put(document.getCategoryId(), document.getWordsOccurrences().get(word.getName()));
}
word.setOccurrencesByCategory(occurences);
this.saveWord(word);
}
Map<String, Integer> occurences2 = new HashMap<String, Integer>();
for (String name : names) {
Word word = new Word();
word.setName(name);
occurences2.put(document.getCategoryId(), document.getWordsOccurrences().get(name));
word.setOccurrencesByCategory(occurences2);
this.saveWord(word);
}
}
|
diff --git a/bundles/org.eclipse.orion.server.git/src/org/eclipse/orion/server/git/servlets/GitCommitHandlerV1.java b/bundles/org.eclipse.orion.server.git/src/org/eclipse/orion/server/git/servlets/GitCommitHandlerV1.java
index 7f762406..e4416343 100644
--- a/bundles/org.eclipse.orion.server.git/src/org/eclipse/orion/server/git/servlets/GitCommitHandlerV1.java
+++ b/bundles/org.eclipse.orion.server.git/src/org/eclipse/orion/server/git/servlets/GitCommitHandlerV1.java
@@ -1,475 +1,475 @@
/*******************************************************************************
* Copyright (c) 2011 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.orion.server.git.servlets;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
import java.util.Map.Entry;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.core.runtime.*;
import org.eclipse.jgit.api.*;
import org.eclipse.jgit.api.errors.*;
import org.eclipse.jgit.diff.DiffEntry;
import org.eclipse.jgit.diff.DiffEntry.ChangeType;
import org.eclipse.jgit.errors.AmbiguousObjectException;
import org.eclipse.jgit.errors.MissingObjectException;
import org.eclipse.jgit.lib.*;
import org.eclipse.jgit.revwalk.*;
import org.eclipse.jgit.storage.file.FileRepository;
import org.eclipse.jgit.treewalk.TreeWalk;
import org.eclipse.jgit.treewalk.filter.*;
import org.eclipse.orion.internal.server.core.IOUtilities;
import org.eclipse.orion.internal.server.servlets.ProtocolConstants;
import org.eclipse.orion.internal.server.servlets.ServletResourceHandler;
import org.eclipse.orion.server.core.ServerStatus;
import org.eclipse.orion.server.git.*;
import org.eclipse.orion.server.git.servlets.GitUtils.Traverse;
import org.eclipse.orion.server.servlets.OrionServlet;
import org.eclipse.osgi.util.NLS;
import org.json.*;
/**
*
*/
public class GitCommitHandlerV1 extends ServletResourceHandler<String> {
private final static int PAGE_SIZE = 50;
private ServletResourceHandler<IStatus> statusHandler;
GitCommitHandlerV1(ServletResourceHandler<IStatus> statusHandler) {
this.statusHandler = statusHandler;
}
@Override
public boolean handleRequest(HttpServletRequest request, HttpServletResponse response, String path) throws ServletException {
Repository db = null;
try {
Path p = new Path(path);
switch (getMethod(request)) {
case GET :
return handleGet(request, response, db, p);
case PUT :
return handlePut(request, response, db, p);
case POST :
return handlePost(request, response, db, p);
}
} catch (Exception e) {
String msg = NLS.bind("Failed to process an operation on commits for {0}", path); //$NON-NLS-1$
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e));
} finally {
if (db != null)
db.close();
}
return false;
}
private boolean createCommitLocation(HttpServletRequest request, HttpServletResponse response, Repository db, String newCommitToCreatelocation) throws IOException, JSONException, URISyntaxException {
URI u = getURI(request);
IPath p = new Path(u.getPath());
IPath np = new Path("/"); //$NON-NLS-1$
for (int i = 0; i < p.segmentCount(); i++) {
String s = p.segment(i);
if (i == 2) {
s += ".." + newCommitToCreatelocation; //$NON-NLS-1$
}
np = np.append(s);
}
if (p.hasTrailingSeparator())
np = np.addTrailingSeparator();
URI nu = new URI(u.getScheme(), u.getUserInfo(), u.getHost(), u.getPort(), np.toString(), u.getQuery(), u.getFragment());
response.setHeader(ProtocolConstants.HEADER_LOCATION, nu.toString());
response.setStatus(HttpServletResponse.SC_OK);
return true;
}
private boolean handleGet(HttpServletRequest request, HttpServletResponse response, Repository db, Path path) throws CoreException, IOException, ServletException, JSONException, URISyntaxException {
IPath filePath = path.hasTrailingSeparator() ? path.removeFirstSegments(1) : path.removeFirstSegments(1).removeLastSegments(1);
Set<Entry<IPath, File>> set = GitUtils.getGitDirs(filePath, Traverse.GO_UP).entrySet();
File gitDir = set.iterator().next().getValue();
if (gitDir == null)
return false; // TODO: or an error response code, 405?
db = new FileRepository(gitDir);
// /{ref}/file/{projectId}...}
String parts = request.getParameter("parts"); //$NON-NLS-1$
String pattern = GitUtils.getRelativePath(path, set.iterator().next().getKey());
if (path.segmentCount() > 3 && "body".equals(parts)) { //$NON-NLS-1$
return handleGetCommitBody(request, response, db, path.segment(0), pattern);
}
if (path.segmentCount() > 2 && (parts == null || "log".equals(parts))) { //$NON-NLS-1$
return handleGetCommitLog(request, response, db, path.segment(0), pattern);
}
return false;
}
private boolean handleGetCommitBody(HttpServletRequest request, HttpServletResponse response, Repository db, String ref, String pattern) throws AmbiguousObjectException, IOException, ServletException {
ObjectId refId = db.resolve(ref);
if (refId == null) {
String msg = NLS.bind("Failed to generate commit log for ref {0}", ref);
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
}
RevWalk walk = new RevWalk(db);
walk.setTreeFilter(AndTreeFilter.create(PathFilterGroup.createFromStrings(Collections.singleton(pattern)), TreeFilter.ANY_DIFF));
RevCommit commit = walk.parseCommit(refId);
final TreeWalk w = TreeWalk.forPath(db, pattern, commit.getTree());
if (w == null) {
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, null, null));
}
ObjectId blobId = w.getObjectId(0);
ObjectStream stream = db.open(blobId, Constants.OBJ_BLOB).openStream();
IOUtilities.pipe(stream, response.getOutputStream(), true, false);
return true;
}
private boolean handleGetCommitLog(HttpServletRequest request, HttpServletResponse response, Repository db, String refIdsRange, String path) throws AmbiguousObjectException, IOException, ServletException, JSONException, URISyntaxException, CoreException {
int page = request.getParameter("page") != null ? new Integer(request.getParameter("page")).intValue() : 0; //$NON-NLS-1$ //$NON-NLS-2$
int pageSize = request.getParameter("pageSize") != null ? new Integer(request.getParameter("pageSize")).intValue() : PAGE_SIZE; //$NON-NLS-1$ //$NON-NLS-2$
ObjectId toObjectId = null;
ObjectId fromObjectId = null;
Ref toRefId = null;
Ref fromRefId = null;
if (refIdsRange.contains("..")) { //$NON-NLS-1$
String[] commits = refIdsRange.split("\\.\\."); //$NON-NLS-1$
if (commits.length != 2) {
String msg = NLS.bind("Failed to generate commit log for ref {0}", refIdsRange); //$NON-NLS-1$
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
}
fromObjectId = db.resolve(commits[0]);
fromRefId = db.getRef(commits[0]);
if (fromObjectId == null) {
String msg = NLS.bind("Failed to generate commit log for ref {0}", commits[0]); //$NON-NLS-1$
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
}
toObjectId = db.resolve(commits[1]);
toRefId = db.getRef(commits[1]);
if (toObjectId == null) {
String msg = NLS.bind("Failed to generate commit log for ref {0}", commits[1]); //$NON-NLS-1$
- return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
+ return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, "No ref or commit found: " + commits[1], null));
}
} else {
toObjectId = db.resolve(refIdsRange);
toRefId = db.getRef(refIdsRange);
if (toObjectId == null) {
String msg = NLS.bind("Failed to generate commit log for ref {0}", refIdsRange); //$NON-NLS-1$
- return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
+ return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, "No ref or commit found: " + refIdsRange, null));
}
}
Git git = new Git(db);
LogCommand log = git.log();
// set the commit range
log.add(toObjectId);
if (fromObjectId != null)
log.not(fromObjectId);
// set the path filter
TreeFilter filter = null;
boolean isRoot = true;
if (path != null && !"".equals(path)) { //$NON-NLS-1$
filter = AndTreeFilter.create(PathFilterGroup.createFromStrings(Collections.singleton(path)), TreeFilter.ANY_DIFF);
log.addPath(path);
isRoot = false;
}
try {
Iterable<RevCommit> commits = log.call();
JSONObject result = toJSON(db, OrionServlet.getURI(request), commits, page, pageSize, filter, isRoot);
result.put(GitConstants.KEY_REPOSITORY_PATH, isRoot ? "" : path);
if (toRefId != null) {
result.put(GitConstants.KEY_REMOTE, BaseToRemoteConverter.getRemoteBranchLocation(getURI(request), Repository.shortenRefName(toRefId.getName()), db, BaseToRemoteConverter.REMOVE_FIRST_3));
String refTargetName = toRefId.getTarget().getName();
if (refTargetName.startsWith(Constants.R_HEADS)) {
// this is a branch
result.put(GitConstants.KEY_LOG_TO_REF, BranchToJSONConverter.toJSON(toRefId.getTarget(), db, getURI(request), 3));
}
}
if (fromRefId != null) {
String refTargetName = fromRefId.getTarget().getName();
if (refTargetName.startsWith(Constants.R_HEADS)) {
// this is a branch
result.put(GitConstants.KEY_LOG_FROM_REF, BranchToJSONConverter.toJSON(fromRefId.getTarget(), db, getURI(request), 3));
}
}
OrionServlet.writeJSONResponse(request, response, result);
return true;
} catch (NoHeadException e) {
String msg = NLS.bind("No HEAD reference found when generating log for ref {0}", refIdsRange); //$NON-NLS-1$
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e));
} catch (JGitInternalException e) {
String msg = NLS.bind("An internal error occured when generating log for ref {0}", refIdsRange); //$NON-NLS-1$
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e));
}
}
private JSONObject toJSON(Repository db, URI baseLocation, Iterable<RevCommit> commits, int page, int pageSize, TreeFilter filter, boolean isRoot) throws JSONException, URISyntaxException, MissingObjectException, IOException {
boolean pageable = (page > 0);
int startIndex = (page - 1) * pageSize;
int index = 0;
JSONObject result = new JSONObject();
JSONArray children = new JSONArray();
for (RevCommit revCommit : commits) {
if (pageable && index < startIndex) {
index++;
continue;
}
if (pageable && index >= startIndex + pageSize)
break;
index++;
children.put(toJSON(db, revCommit, baseLocation, filter, isRoot));
}
result.put(ProtocolConstants.KEY_CHILDREN, children);
return result;
}
private JSONObject toJSON(Repository db, RevCommit revCommit, URI baseLocation, TreeFilter filter, boolean isRoot) throws JSONException, URISyntaxException, IOException {
JSONObject commit = new JSONObject();
commit.put(ProtocolConstants.KEY_LOCATION, createCommitLocation(baseLocation, revCommit.getName(), null));
commit.put(ProtocolConstants.KEY_CONTENT_LOCATION, createCommitLocation(baseLocation, revCommit.getName(), "parts=body")); //$NON-NLS-1$
commit.put(GitConstants.KEY_DIFF, createDiffLocation(baseLocation, revCommit.getName(), null, null, isRoot));
commit.put(ProtocolConstants.KEY_NAME, revCommit.getName());
commit.put(GitConstants.KEY_AUTHOR_NAME, revCommit.getAuthorIdent().getName());
commit.put(GitConstants.KEY_AUTHOR_EMAIL, revCommit.getAuthorIdent().getEmailAddress());
commit.put(GitConstants.KEY_COMMITTER_NAME, revCommit.getCommitterIdent().getName());
commit.put(GitConstants.KEY_COMMITTER_EMAIL, revCommit.getCommitterIdent().getEmailAddress());
commit.put(GitConstants.KEY_COMMIT_TIME, ((long) revCommit.getCommitTime()) * 1000 /* time in milliseconds */);
commit.put(GitConstants.KEY_COMMIT_MESSAGE, revCommit.getFullMessage());
commit.put(ProtocolConstants.KEY_CHILDREN, toJSON(getTagsForCommit(db, revCommit)));
commit.put(ProtocolConstants.KEY_TYPE, GitConstants.COMMIT_TYPE);
if (revCommit.getParentCount() > 0) {
JSONArray diffs = new JSONArray();
final TreeWalk tw = new TreeWalk(db);
final RevWalk rw = new RevWalk(db);
RevCommit parent = rw.parseCommit(revCommit.getParent(0));
tw.reset(parent.getTree(), revCommit.getTree());
tw.setRecursive(true);
if (filter != null)
tw.setFilter(filter);
else
tw.setFilter(TreeFilter.ANY_DIFF);
List<DiffEntry> l = DiffEntry.scan(tw);
for (DiffEntry entr : l) {
JSONObject diff = new JSONObject();
diff.put(ProtocolConstants.KEY_TYPE, GitConstants.DIFF_TYPE);
diff.put(GitConstants.KEY_COMMIT_DIFF_NEWPATH, entr.getNewPath());
diff.put(GitConstants.KEY_COMMIT_DIFF_OLDPATH, entr.getOldPath());
diff.put(GitConstants.KEY_COMMIT_DIFF_CHANGETYPE, entr.getChangeType().toString());
// add diff location for the commit
String path = entr.getChangeType() != ChangeType.DELETE ? entr.getNewPath() : entr.getOldPath();
diff.put(GitConstants.KEY_DIFF, createDiffLocation(baseLocation, revCommit.getName(), revCommit.getParent(0).getName(), path, isRoot));
diffs.put(diff);
}
tw.release();
commit.put(GitConstants.KEY_COMMIT_DIFFS, diffs);
}
return commit;
}
private JSONArray toJSON(Map<String, Ref> revTags) throws JSONException {
JSONArray children = new JSONArray();
for (Entry<String, Ref> revTag : revTags.entrySet()) {
JSONObject tag = new JSONObject();
tag.put(ProtocolConstants.KEY_NAME, revTag.getKey());
tag.put(ProtocolConstants.KEY_FULL_NAME, revTag.getValue().getName());
children.put(tag);
}
return children;
}
private URI createCommitLocation(URI baseLocation, String commitName, String parameters) throws URISyntaxException {
return new URI(baseLocation.getScheme(), baseLocation.getAuthority(), GitServlet.GIT_URI + "/" + GitConstants.COMMIT_RESOURCE + "/" + commitName + "/" + new Path(baseLocation.getPath()).removeFirstSegments(3), parameters, null); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
private URI createDiffLocation(URI baseLocation, String toRefId, String fromRefId, String path, boolean isRoot) throws URISyntaxException {
String diffPath = GitServlet.GIT_URI + "/" + GitConstants.DIFF_RESOURCE + "/"; //$NON-NLS-1$ //$NON-NLS-2$
if (fromRefId != null)
diffPath += fromRefId + ".."; //$NON-NLS-1$
diffPath += toRefId + "/"; //$NON-NLS-1$
if (path == null) {
diffPath += new Path(baseLocation.getPath()).removeFirstSegments(3);
} else if (isRoot) {
diffPath += new Path(baseLocation.getPath()).removeFirstSegments(3).append(path);
} else {
IPath p = new Path(baseLocation.getPath());
diffPath += p.removeLastSegments(p.segmentCount() - 5).removeFirstSegments(3).append(path);
}
return new URI(baseLocation.getScheme(), baseLocation.getAuthority(), diffPath, null, null);
}
private boolean handlePost(HttpServletRequest request, HttpServletResponse response, Repository db, Path path) throws ServletException, NoFilepatternException, IOException, JSONException, CoreException, URISyntaxException {
IPath filePath = path.hasTrailingSeparator() ? path.removeFirstSegments(1) : path.removeFirstSegments(1).removeLastSegments(1);
Set<Entry<IPath, File>> set = GitUtils.getGitDirs(filePath, Traverse.GO_UP).entrySet();
File gitDir = set.iterator().next().getValue();
if (gitDir == null)
return false; // TODO: or an error response code, 405?
db = new FileRepository(gitDir);
JSONObject requestObject = OrionServlet.readJSONRequest(request);
String commitToMerge = requestObject.optString(GitConstants.KEY_MERGE, null);
if (commitToMerge != null) {
return merge(request, response, db, commitToMerge);
}
// continue with creating new commit location
String newCommitToCreatelocation = requestObject.optString(GitConstants.KEY_COMMIT_NEW, null);
if (newCommitToCreatelocation != null)
return createCommitLocation(request, response, db, newCommitToCreatelocation);
ObjectId refId = db.resolve(path.segment(0));
if (refId == null || !Constants.HEAD.equals(path.segment(0))) {
String msg = NLS.bind("Commit failed. Ref must be HEAD and is {0}", path.segment(0));
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
}
String message = requestObject.optString(GitConstants.KEY_COMMIT_MESSAGE, null);
if (message == null || message.isEmpty()) {
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "Missing commit message.", null));
}
boolean amend = Boolean.parseBoolean(requestObject.optString(GitConstants.KEY_COMMIT_AMEND, null));
Git git = new Git(db);
CommitCommand commit = git.commit();
// support for committing by path: "git commit -o path"
boolean isRoot = true;
String pattern = GitUtils.getRelativePath(path.removeFirstSegments(1), set.iterator().next().getKey());
if (!pattern.isEmpty()) {
commit.setOnly(pattern);
isRoot = false;
}
try {
// "git commit [--amend] -m '{message}' [-a|{path}]"
RevCommit lastCommit = commit.setAmend(amend).setMessage(message).call();
JSONObject result = toJSON(db, lastCommit, getURI(request), null, isRoot);
OrionServlet.writeJSONResponse(request, response, result);
return true;
} catch (GitAPIException e) {
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "An error occured when commiting.", e));
} catch (JGitInternalException e) {
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An internal error occured when commiting.", e));
}
}
private boolean merge(HttpServletRequest request, HttpServletResponse response, Repository db, String commitToMerge) throws ServletException, JSONException {
try {
ObjectId objectId = db.resolve(commitToMerge);
Git git = new Git(db);
MergeResult mergeResult = git.merge().include(objectId).call();
JSONObject result = new JSONObject();
result.put(GitConstants.KEY_RESULT, mergeResult.getMergeStatus().name());
OrionServlet.writeJSONResponse(request, response, result);
return true;
} catch (IOException e) {
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occured when merging.", e));
} catch (GitAPIException e) {
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occured when merging.", e));
} catch (JGitInternalException e) {
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occured when merging.", e.getCause()));
}
}
private boolean handlePut(HttpServletRequest request, HttpServletResponse response, Repository db, Path path) throws ServletException, IOException, JSONException, CoreException, URISyntaxException, JGitInternalException, GitAPIException {
IPath filePath = path.removeFirstSegments(1);
Set<Entry<IPath, File>> set = GitUtils.getGitDirs(filePath, Traverse.GO_UP).entrySet();
File gitDir = set.iterator().next().getValue();
if (gitDir == null)
return false; // TODO: or an error response code, 405?
db = new FileRepository(gitDir);
boolean isRoot = "".equals(GitUtils.getRelativePath(path, set.iterator().next().getKey()));
JSONObject toPut = OrionServlet.readJSONRequest(request);
String tagName = toPut.getString(ProtocolConstants.KEY_NAME);
if (tagName != null) {
return tag(request, response, db, path.segment(0), tagName, isRoot);
}
return false;
}
private boolean tag(HttpServletRequest request, HttpServletResponse response, Repository db, String commitId, String tagName, boolean isRoot) throws AmbiguousObjectException, IOException, JGitInternalException, GitAPIException, JSONException, URISyntaxException {
Git git = new Git(db);
ObjectId objectId = db.resolve(commitId);
RevWalk walk = new RevWalk(db);
RevCommit revCommit = walk.lookupCommit(objectId);
walk.parseBody(revCommit);
GitTagHandlerV1.tag(git, revCommit, tagName);
JSONObject result = toJSON(db, revCommit, OrionServlet.getURI(request), null, isRoot);
OrionServlet.writeJSONResponse(request, response, result);
walk.dispose();
return true;
}
// from https://gist.github.com/839693, credits to zx
private static Map<String, Ref> getTagsForCommit(Repository repo, RevCommit commit) throws MissingObjectException, IOException {
final Map<String, Ref> revTags = new HashMap<String, Ref>();
final RevWalk walk = new RevWalk(repo);
walk.reset();
for (final Entry<String, Ref> revTag : repo.getTags().entrySet()) {
final RevObject obj = walk.parseAny(revTag.getValue().getObjectId());
final RevCommit tagCommit;
if (obj instanceof RevCommit) {
tagCommit = (RevCommit) obj;
} else if (obj instanceof RevTag) {
tagCommit = walk.parseCommit(((RevTag) obj).getObject());
} else {
continue;
}
if (commit.equals(tagCommit) || walk.isMergedInto(commit, tagCommit)) {
revTags.put(revTag.getKey(), revTag.getValue());
}
}
return revTags;
}
}
| false | true | private boolean handleGetCommitLog(HttpServletRequest request, HttpServletResponse response, Repository db, String refIdsRange, String path) throws AmbiguousObjectException, IOException, ServletException, JSONException, URISyntaxException, CoreException {
int page = request.getParameter("page") != null ? new Integer(request.getParameter("page")).intValue() : 0; //$NON-NLS-1$ //$NON-NLS-2$
int pageSize = request.getParameter("pageSize") != null ? new Integer(request.getParameter("pageSize")).intValue() : PAGE_SIZE; //$NON-NLS-1$ //$NON-NLS-2$
ObjectId toObjectId = null;
ObjectId fromObjectId = null;
Ref toRefId = null;
Ref fromRefId = null;
if (refIdsRange.contains("..")) { //$NON-NLS-1$
String[] commits = refIdsRange.split("\\.\\."); //$NON-NLS-1$
if (commits.length != 2) {
String msg = NLS.bind("Failed to generate commit log for ref {0}", refIdsRange); //$NON-NLS-1$
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
}
fromObjectId = db.resolve(commits[0]);
fromRefId = db.getRef(commits[0]);
if (fromObjectId == null) {
String msg = NLS.bind("Failed to generate commit log for ref {0}", commits[0]); //$NON-NLS-1$
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
}
toObjectId = db.resolve(commits[1]);
toRefId = db.getRef(commits[1]);
if (toObjectId == null) {
String msg = NLS.bind("Failed to generate commit log for ref {0}", commits[1]); //$NON-NLS-1$
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
}
} else {
toObjectId = db.resolve(refIdsRange);
toRefId = db.getRef(refIdsRange);
if (toObjectId == null) {
String msg = NLS.bind("Failed to generate commit log for ref {0}", refIdsRange); //$NON-NLS-1$
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
}
}
Git git = new Git(db);
LogCommand log = git.log();
// set the commit range
log.add(toObjectId);
if (fromObjectId != null)
log.not(fromObjectId);
// set the path filter
TreeFilter filter = null;
boolean isRoot = true;
if (path != null && !"".equals(path)) { //$NON-NLS-1$
filter = AndTreeFilter.create(PathFilterGroup.createFromStrings(Collections.singleton(path)), TreeFilter.ANY_DIFF);
log.addPath(path);
isRoot = false;
}
try {
Iterable<RevCommit> commits = log.call();
JSONObject result = toJSON(db, OrionServlet.getURI(request), commits, page, pageSize, filter, isRoot);
result.put(GitConstants.KEY_REPOSITORY_PATH, isRoot ? "" : path);
if (toRefId != null) {
result.put(GitConstants.KEY_REMOTE, BaseToRemoteConverter.getRemoteBranchLocation(getURI(request), Repository.shortenRefName(toRefId.getName()), db, BaseToRemoteConverter.REMOVE_FIRST_3));
String refTargetName = toRefId.getTarget().getName();
if (refTargetName.startsWith(Constants.R_HEADS)) {
// this is a branch
result.put(GitConstants.KEY_LOG_TO_REF, BranchToJSONConverter.toJSON(toRefId.getTarget(), db, getURI(request), 3));
}
}
if (fromRefId != null) {
String refTargetName = fromRefId.getTarget().getName();
if (refTargetName.startsWith(Constants.R_HEADS)) {
// this is a branch
result.put(GitConstants.KEY_LOG_FROM_REF, BranchToJSONConverter.toJSON(fromRefId.getTarget(), db, getURI(request), 3));
}
}
OrionServlet.writeJSONResponse(request, response, result);
return true;
} catch (NoHeadException e) {
String msg = NLS.bind("No HEAD reference found when generating log for ref {0}", refIdsRange); //$NON-NLS-1$
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e));
} catch (JGitInternalException e) {
String msg = NLS.bind("An internal error occured when generating log for ref {0}", refIdsRange); //$NON-NLS-1$
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e));
}
}
| private boolean handleGetCommitLog(HttpServletRequest request, HttpServletResponse response, Repository db, String refIdsRange, String path) throws AmbiguousObjectException, IOException, ServletException, JSONException, URISyntaxException, CoreException {
int page = request.getParameter("page") != null ? new Integer(request.getParameter("page")).intValue() : 0; //$NON-NLS-1$ //$NON-NLS-2$
int pageSize = request.getParameter("pageSize") != null ? new Integer(request.getParameter("pageSize")).intValue() : PAGE_SIZE; //$NON-NLS-1$ //$NON-NLS-2$
ObjectId toObjectId = null;
ObjectId fromObjectId = null;
Ref toRefId = null;
Ref fromRefId = null;
if (refIdsRange.contains("..")) { //$NON-NLS-1$
String[] commits = refIdsRange.split("\\.\\."); //$NON-NLS-1$
if (commits.length != 2) {
String msg = NLS.bind("Failed to generate commit log for ref {0}", refIdsRange); //$NON-NLS-1$
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
}
fromObjectId = db.resolve(commits[0]);
fromRefId = db.getRef(commits[0]);
if (fromObjectId == null) {
String msg = NLS.bind("Failed to generate commit log for ref {0}", commits[0]); //$NON-NLS-1$
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
}
toObjectId = db.resolve(commits[1]);
toRefId = db.getRef(commits[1]);
if (toObjectId == null) {
String msg = NLS.bind("Failed to generate commit log for ref {0}", commits[1]); //$NON-NLS-1$
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, "No ref or commit found: " + commits[1], null));
}
} else {
toObjectId = db.resolve(refIdsRange);
toRefId = db.getRef(refIdsRange);
if (toObjectId == null) {
String msg = NLS.bind("Failed to generate commit log for ref {0}", refIdsRange); //$NON-NLS-1$
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, "No ref or commit found: " + refIdsRange, null));
}
}
Git git = new Git(db);
LogCommand log = git.log();
// set the commit range
log.add(toObjectId);
if (fromObjectId != null)
log.not(fromObjectId);
// set the path filter
TreeFilter filter = null;
boolean isRoot = true;
if (path != null && !"".equals(path)) { //$NON-NLS-1$
filter = AndTreeFilter.create(PathFilterGroup.createFromStrings(Collections.singleton(path)), TreeFilter.ANY_DIFF);
log.addPath(path);
isRoot = false;
}
try {
Iterable<RevCommit> commits = log.call();
JSONObject result = toJSON(db, OrionServlet.getURI(request), commits, page, pageSize, filter, isRoot);
result.put(GitConstants.KEY_REPOSITORY_PATH, isRoot ? "" : path);
if (toRefId != null) {
result.put(GitConstants.KEY_REMOTE, BaseToRemoteConverter.getRemoteBranchLocation(getURI(request), Repository.shortenRefName(toRefId.getName()), db, BaseToRemoteConverter.REMOVE_FIRST_3));
String refTargetName = toRefId.getTarget().getName();
if (refTargetName.startsWith(Constants.R_HEADS)) {
// this is a branch
result.put(GitConstants.KEY_LOG_TO_REF, BranchToJSONConverter.toJSON(toRefId.getTarget(), db, getURI(request), 3));
}
}
if (fromRefId != null) {
String refTargetName = fromRefId.getTarget().getName();
if (refTargetName.startsWith(Constants.R_HEADS)) {
// this is a branch
result.put(GitConstants.KEY_LOG_FROM_REF, BranchToJSONConverter.toJSON(fromRefId.getTarget(), db, getURI(request), 3));
}
}
OrionServlet.writeJSONResponse(request, response, result);
return true;
} catch (NoHeadException e) {
String msg = NLS.bind("No HEAD reference found when generating log for ref {0}", refIdsRange); //$NON-NLS-1$
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e));
} catch (JGitInternalException e) {
String msg = NLS.bind("An internal error occured when generating log for ref {0}", refIdsRange); //$NON-NLS-1$
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e));
}
}
|
diff --git a/svn/org.cfeclipse.cfml/trunk/src/org/cfeclipse/cfml/preferences/BrowserPreferencePage.java b/svn/org.cfeclipse.cfml/trunk/src/org/cfeclipse/cfml/preferences/BrowserPreferencePage.java
index 07ab1044..155bdf7a 100644
--- a/svn/org.cfeclipse.cfml/trunk/src/org/cfeclipse/cfml/preferences/BrowserPreferencePage.java
+++ b/svn/org.cfeclipse.cfml/trunk/src/org/cfeclipse/cfml/preferences/BrowserPreferencePage.java
@@ -1,51 +1,50 @@
package org.cfeclipse.cfml.preferences;
import java.util.Map;
import java.util.Properties;
import org.cfeclipse.cfml.CFMLPlugin;
import org.eclipse.jface.preference.DirectoryFieldEditor;
import org.eclipse.jface.preference.FieldEditorPreferencePage;
import org.eclipse.jface.preference.FileFieldEditor;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.jface.preference.StringFieldEditor;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
public class BrowserPreferencePage extends FieldEditorPreferencePage implements
IWorkbenchPreferencePage {
public BrowserPreferencePage() {
super(GRID);
setPreferenceStore(CFMLPlugin.getDefault().getPreferenceStore());
}
public void createFieldEditors() {
if(System.getProperty("os.name").equals("Mac OS X")){
addField(new DirectoryFieldEditor(BrowserPreferenceConstants.P_PRIMARY_BROWSER_PATH, "Primary Browser", getFieldEditorParent()));
addField(new DirectoryFieldEditor(BrowserPreferenceConstants.P_SECONDARY_BROWSER_PATH, "Secondary Browser", getFieldEditorParent()));
- addField(new StringFieldEditor(BrowserPreferenceConstants.P_TESTCASE_QUERYSTRING, "Querystring for TestCases",getFieldEditorParent()));
}
else {
addField(new FileFieldEditor(BrowserPreferenceConstants.P_PRIMARY_BROWSER_PATH, "Primary Browser",getFieldEditorParent()));
addField(new FileFieldEditor(BrowserPreferenceConstants.P_SECONDARY_BROWSER_PATH, "Secondary Browser",getFieldEditorParent()));
}
addField(new StringFieldEditor(BrowserPreferenceConstants.P_TESTCASE_QUERYSTRING, "Querystring for TestCases",getFieldEditorParent()));
}
public void init(IWorkbench workbench) {
// TODO Auto-generated method stub
}
}
| true | true | public void createFieldEditors() {
if(System.getProperty("os.name").equals("Mac OS X")){
addField(new DirectoryFieldEditor(BrowserPreferenceConstants.P_PRIMARY_BROWSER_PATH, "Primary Browser", getFieldEditorParent()));
addField(new DirectoryFieldEditor(BrowserPreferenceConstants.P_SECONDARY_BROWSER_PATH, "Secondary Browser", getFieldEditorParent()));
addField(new StringFieldEditor(BrowserPreferenceConstants.P_TESTCASE_QUERYSTRING, "Querystring for TestCases",getFieldEditorParent()));
}
else {
addField(new FileFieldEditor(BrowserPreferenceConstants.P_PRIMARY_BROWSER_PATH, "Primary Browser",getFieldEditorParent()));
addField(new FileFieldEditor(BrowserPreferenceConstants.P_SECONDARY_BROWSER_PATH, "Secondary Browser",getFieldEditorParent()));
}
addField(new StringFieldEditor(BrowserPreferenceConstants.P_TESTCASE_QUERYSTRING, "Querystring for TestCases",getFieldEditorParent()));
}
| public void createFieldEditors() {
if(System.getProperty("os.name").equals("Mac OS X")){
addField(new DirectoryFieldEditor(BrowserPreferenceConstants.P_PRIMARY_BROWSER_PATH, "Primary Browser", getFieldEditorParent()));
addField(new DirectoryFieldEditor(BrowserPreferenceConstants.P_SECONDARY_BROWSER_PATH, "Secondary Browser", getFieldEditorParent()));
}
else {
addField(new FileFieldEditor(BrowserPreferenceConstants.P_PRIMARY_BROWSER_PATH, "Primary Browser",getFieldEditorParent()));
addField(new FileFieldEditor(BrowserPreferenceConstants.P_SECONDARY_BROWSER_PATH, "Secondary Browser",getFieldEditorParent()));
}
addField(new StringFieldEditor(BrowserPreferenceConstants.P_TESTCASE_QUERYSTRING, "Querystring for TestCases",getFieldEditorParent()));
}
|
diff --git a/ExperienceMod/src/main/java/com/comphenix/xp/listeners/ExperienceMobListener.java b/ExperienceMod/src/main/java/com/comphenix/xp/listeners/ExperienceMobListener.java
index 651727a..d1ce7fc 100644
--- a/ExperienceMod/src/main/java/com/comphenix/xp/listeners/ExperienceMobListener.java
+++ b/ExperienceMod/src/main/java/com/comphenix/xp/listeners/ExperienceMobListener.java
@@ -1,486 +1,486 @@
/*
* ExperienceMod - Bukkit server plugin for modifying the experience system in Minecraft.
* Copyright (C) 2012 Kristian S. Stangeland
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program;
* if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA
*/
package com.comphenix.xp.listeners;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.apache.commons.lang.StringUtils;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason;
import com.comphenix.xp.Action;
import com.comphenix.xp.Configuration;
import com.comphenix.xp.Debugger;
import com.comphenix.xp.Presets;
import com.comphenix.xp.SampleRange;
import com.comphenix.xp.expressions.NamedParameter;
import com.comphenix.xp.extra.Permissions;
import com.comphenix.xp.lookup.LevelingRate;
import com.comphenix.xp.lookup.MobQuery;
import com.comphenix.xp.lookup.PlayerQuery;
import com.comphenix.xp.messages.ChannelProvider;
import com.comphenix.xp.rewards.ResourceHolder;
import com.comphenix.xp.rewards.RewardProvider;
import com.comphenix.xp.rewards.items.RandomSampling;
import com.comphenix.xp.rewards.xp.CurrencyHolder;
import com.comphenix.xp.rewards.xp.ExperienceHolder;
import com.comphenix.xp.rewards.xp.ExperienceManager;
import com.comphenix.xp.rewards.xp.RewardEconomy;
import com.comphenix.xp.rewards.xp.RewardVirtual;
public class ExperienceMobListener extends AbstractExperienceListener {
/**
* Used to schedule a future reward.
* @author Kristian
*/
private class FutureReward {
public List<ResourceHolder> generated;
public Action action;
public Configuration config;
}
private Debugger debugger;
// To determine which groups are player is part of
private PlayerGroupMembership playerGroups;
// To determine spawn reason
private Map<Integer, SpawnReason> spawnReasonLookup = new HashMap<Integer, SpawnReason>();
// The resources to award
private Map<Integer, FutureReward> scheduledRewards = new HashMap<Integer, FutureReward>();
// Random source
private Random random = new Random();
// Error report creator
private ErrorReporting report = ErrorReporting.DEFAULT;
// Economy for currency subtraction
private RewardEconomy economy;
public ExperienceMobListener(Debugger debugger, PlayerGroupMembership playerGroups, Presets presets) {
this.debugger = debugger;
this.playerGroups = playerGroups;
setPresets(presets);
}
public void setEconomy(RewardEconomy economy) {
this.economy = economy;
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onCreatureSpawnEvent(CreatureSpawnEvent event) {
try {
if (event.getSpawnReason() != null) {
spawnReasonLookup.put(event.getEntity().getEntityId(),
event.getSpawnReason());
}
// Every entry method must have a generic catcher
} catch (Exception e) {
report.reportError(debugger, this, e, event);
}
}
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onEntityDamageByEntityEvent(EntityDamageByEntityEvent event) {
try {
Entity attacker = event.getDamager();
LivingEntity killer = null;
// See if we have a player or an arrow
if (attacker instanceof Player)
killer = (Player) attacker;
else if (attacker instanceof Projectile)
killer = ((Projectile) attacker).getShooter();
// Only cancel living entity damage events from players
if (event.getEntity() instanceof LivingEntity &&
killer instanceof Player) {
LivingEntity entity = (LivingEntity) event.getEntity();
Player playerKiller = (Player) killer;
int damage = event.getDamage();
// Predict the amount of damage actually inflicted
if ((float) entity.getNoDamageTicks() > (float) entity.getMaximumNoDamageTicks() / 2.0F) {
if (damage > entity.getLastDamage()) {
damage -= entity.getLastDamage();
} else {
return;
}
}
// Will this most likely cause the entity to die?
// Note that this doesn't take into account potions and armor.
if (entity.getHealth() <= damage) {
// Prevent this damage
if (!onFutureKillEvent(entity, playerKiller)) {
// Events will not be directly cancelled for untouchables
if (!Permissions.hasUntouchable(playerKiller))
event.setCancelled(true);
if (hasDebugger())
debugger.printDebug(this, "Entity %d kill cancelled: Player %s hasn't got enough resources.",
entity.getEntityId(), playerKiller.getName());
}
}
}
// Every entry method must have a generic catcher
} catch (Exception e) {
report.reportError(debugger, this, e, event);
}
}
private boolean onFutureKillEvent(LivingEntity entity, Player killer) {
Configuration config = getConfiguration(entity, killer);
Collection<NamedParameter> params = null;
// Warn, but allow
if (config == null) {
return true;
}
// Quickly retrieve the correct action
RewardProvider rewards = config.getRewardProvider();
Action action = getAction(config, entity, killer);
// Allow event
if (action == null) {
return true;
}
// Get player-specific parameters
if (entity instanceof Player) {
params = config.getParameterProviders().getParameters(action, (Player) entity);
} else {
params = config.getParameterProviders().getParameters(action, entity);
}
// Generate some rewards
List<ResourceHolder> generated = action.generateRewards(params, rewards, random);
FutureReward future = new FutureReward();
future.action = action;
future.generated = generated;
future.config = config;
scheduledRewards.put(entity.getEntityId(), future);
// Could we reward the player if this mob was killed?
if (killer != null && !action.canRewardPlayer(rewards, killer, generated)) {
future.generated = null;
return false;
}
// Allow this event
return true;
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onEntityDeathEvent(EntityDeathEvent event) {
LivingEntity entity = event.getEntity();
Collection<ResourceHolder> result = null;
try {
// Only drop experience from mobs
if (entity != null) {
Player killer = entity.getKiller();
result = handleEntityDeath(event, entity, killer);
}
if (event instanceof PlayerDeathEvent) {
handlePlayerDeath((PlayerDeathEvent) event, (Player) entity, result);
}
// Every entry method must have a generic catcher
} catch (Exception e) {
report.reportError(debugger, this, e, event);
}
}
private void handlePlayerDeath(PlayerDeathEvent event, Player player, Collection<ResourceHolder> dropped) {
// Permission check
if(Permissions.hasKeepExp(player)) {
event.setDroppedExp(0);
event.setKeepLevel(true);
if (hasDebugger())
debugger.printDebug(this, "Prevented experience loss for %s.", player.getName());
} else if (dropped != null && dropped.size() > 0) {
int total = 0;
// Manual dropped amount
event.setDroppedExp(0);
// Subtract the dropped experience
for (ResourceHolder holder : dropped) {
if (holder instanceof ExperienceHolder) {
ExperienceHolder exp = (ExperienceHolder) holder;
total += exp.getAmount();
}
}
// Set the correct level and experience
if (total > 0) {
subtractExperience(event, player, revertLevelingRate(player, total));
}
if (hasDebugger())
debugger.printDebug(this, "%s took %d experience loss.", player.getName(), total);
} else {
// Display the loss, at least
if (hasDebugger())
debugger.printDebug(this, "%s took %d standard experience loss.",
player.getName(), event.getDroppedExp());
}
// Subtract money
if (economy != null && /*config.subtract economy &&*/ dropped != null && dropped.size() > 0) {
int total = 0;
for (ResourceHolder holder : dropped) {
if (holder instanceof CurrencyHolder) {
CurrencyHolder currency = (CurrencyHolder) holder;
total += currency.getAmount();
}
}
if (total > 0) {
economy.economyReward(player, -total, debugger);
if (hasDebugger())
debugger.printDebug(this, "%s took %d currency loss.",
player.getName(), total);
}
}
}
// Revert the leveling rate we applied
private int revertLevelingRate(Player player, int experience) {
Configuration config = getConfiguration(player);
ExperienceManager manager = new ExperienceManager(player);
LevelingRate rate = config != null ? config.getLevelingRate() : null;
double rateFactor = rate != null ? RewardVirtual.getLevelingFactor(rate, player, manager) : 1;
SampleRange sampling = new SampleRange(experience / rateFactor);
return sampling.sampleInt(RandomSampling.getThreadRandom());
}
// Manually subtract experience
private void subtractExperience(PlayerDeathEvent event, Player player, int experience) {
ExperienceManager manager = new ExperienceManager(player);
int current = manager.getCurrentExp();
int after = Math.max(current - experience, 0);
int level = manager.getLevelForExp(after);
// Calculate the correct amount of experience left
event.setKeepLevel(false);
event.setNewLevel(level);
event.setNewExp(after - manager.getXpForLevel(level));
event.setNewTotalExp(Math.max(player.getTotalExperience() - experience, 0));
}
private Configuration getConfiguration(LivingEntity entity, Player killer) {
boolean hasKiller = (killer != null);
// Get the correct configuration
if (hasKiller)
return getConfiguration(killer);
else if (entity instanceof Player)
return getConfiguration((Player) entity);
else
return getConfiguration(entity.getWorld());
}
private Action getAction(Configuration config, LivingEntity entity, Player killer) {
if (entity instanceof Player) {
Player entityPlayer = (Player) entity;
PlayerQuery query = PlayerQuery.fromExact(
entityPlayer,
playerGroups.getPlayerGroups(entityPlayer),
killer != null);
if (config != null) {
return config.getPlayerDeathDrop().get(query);
} else {
// Report this problem
if (hasDebugger())
debugger.printDebug(this, "No config found for player %d, query: %s", entityPlayer.getName(), query);
return null;
}
} else {
Integer id = entity.getEntityId();
MobQuery query = MobQuery.fromExact(entity, spawnReasonLookup.get(id), killer != null);
if (hasDebugger())
debugger.printDebug(this, "Mob query: %s", query.toString());
if (config != null) {
return config.getExperienceDrop().get(query);
} else {
// Report this problem
if (hasDebugger())
debugger.printDebug(this, "No config found for mob %d, query: %s", id, query);
return null;
}
}
}
private Collection<ResourceHolder> handleEntityDeath(EntityDeathEvent event, LivingEntity entity, Player killer) {
boolean hasKiller = (killer != null);
Integer id = entity.getEntityId();
// Values that are either precomputed, or computed on the spot
Configuration config = null;
Action action = null;
FutureReward future = null;
// Resources generated and given
List<ResourceHolder> generated = null;
Collection<ResourceHolder> result = null;
// Simplify by adding the reward to the lookup regardless
if (!scheduledRewards.containsKey(id)) {
// We'll just generate the reward then
onFutureKillEvent(entity, killer);
}
// Retrieve reward from lookup
future = scheduledRewards.get(id);
if (future != null) {
action = future.action;
generated = future.generated;
config = future.config;
} else {
config = getConfiguration(entity, killer);
}
// And we're done with this mob
scheduledRewards.remove(id);
if (hasDebugger()) {
debugger.printDebug(this, "Generated: %s", StringUtils.join(generated, ", "));
}
// Make sure the reward has been changed
if (generated != null && generated.size() > 0) {
ChannelProvider channels = config.getChannelProvider();
RewardProvider rewards = config.getRewardProvider();
// Spawn the experience ourself
event.setDroppedExp(0);
// Reward the killer directly, or just drop it naturally
if (killer != null)
- result = action.rewardPlayer(rewards, killer, generated);
+ result = action.rewardPlayer(rewards, killer, generated, entity.getLocation());
else
result = action.rewardAnyone(rewards, entity.getWorld(), generated, entity.getLocation());
// Print message
config.getMessageQueue().enqueue(killer, action, channels.getFormatter(killer, result, generated));
if (hasDebugger())
debugger.printDebug(this, "Entity %d: Changed experience drop to %s.",
id, StringUtils.join(result, ", "));
} else if (action != null && action.getInheritMultiplier() != 1) {
// Inherit experience action
handleMultiplier(event, id, config.getMultiplier() * action.getInheritMultiplier());
} else if (config.isDefaultRewardsDisabled() && hasKiller) {
// Disable all mob XP
event.setDroppedExp(0);
if (hasDebugger())
debugger.printDebug(this, "Entity %d: Default mob experience disabled.", id);
} else if (!config.isDefaultRewardsDisabled() && hasKiller) {
handleMultiplier(event, id, config.getMultiplier());
}
// Remove it from the lookup
if (!(entity instanceof Player)) {
spawnReasonLookup.remove(id);
}
return result;
}
private void handleMultiplier(EntityDeathEvent event, int entityID, double multiplier) {
int expDropped = event.getDroppedExp();
// Alter the default experience drop too
if (multiplier != 1) {
SampleRange increase = new SampleRange(expDropped * multiplier);
int expChanged = increase.sampleInt(random);
event.setDroppedExp(expChanged);
if (hasDebugger())
debugger.printDebug(this, "Entity %d: Changed experience drop to %d exp.",
entityID, expChanged);
}
}
// Determine if a debugger is attached and is listening
private boolean hasDebugger() {
return debugger != null && debugger.isDebugEnabled();
}
}
| true | true | private Collection<ResourceHolder> handleEntityDeath(EntityDeathEvent event, LivingEntity entity, Player killer) {
boolean hasKiller = (killer != null);
Integer id = entity.getEntityId();
// Values that are either precomputed, or computed on the spot
Configuration config = null;
Action action = null;
FutureReward future = null;
// Resources generated and given
List<ResourceHolder> generated = null;
Collection<ResourceHolder> result = null;
// Simplify by adding the reward to the lookup regardless
if (!scheduledRewards.containsKey(id)) {
// We'll just generate the reward then
onFutureKillEvent(entity, killer);
}
// Retrieve reward from lookup
future = scheduledRewards.get(id);
if (future != null) {
action = future.action;
generated = future.generated;
config = future.config;
} else {
config = getConfiguration(entity, killer);
}
// And we're done with this mob
scheduledRewards.remove(id);
if (hasDebugger()) {
debugger.printDebug(this, "Generated: %s", StringUtils.join(generated, ", "));
}
// Make sure the reward has been changed
if (generated != null && generated.size() > 0) {
ChannelProvider channels = config.getChannelProvider();
RewardProvider rewards = config.getRewardProvider();
// Spawn the experience ourself
event.setDroppedExp(0);
// Reward the killer directly, or just drop it naturally
if (killer != null)
result = action.rewardPlayer(rewards, killer, generated);
else
result = action.rewardAnyone(rewards, entity.getWorld(), generated, entity.getLocation());
// Print message
config.getMessageQueue().enqueue(killer, action, channels.getFormatter(killer, result, generated));
if (hasDebugger())
debugger.printDebug(this, "Entity %d: Changed experience drop to %s.",
id, StringUtils.join(result, ", "));
} else if (action != null && action.getInheritMultiplier() != 1) {
// Inherit experience action
handleMultiplier(event, id, config.getMultiplier() * action.getInheritMultiplier());
} else if (config.isDefaultRewardsDisabled() && hasKiller) {
// Disable all mob XP
event.setDroppedExp(0);
if (hasDebugger())
debugger.printDebug(this, "Entity %d: Default mob experience disabled.", id);
} else if (!config.isDefaultRewardsDisabled() && hasKiller) {
handleMultiplier(event, id, config.getMultiplier());
}
// Remove it from the lookup
if (!(entity instanceof Player)) {
spawnReasonLookup.remove(id);
}
return result;
}
| private Collection<ResourceHolder> handleEntityDeath(EntityDeathEvent event, LivingEntity entity, Player killer) {
boolean hasKiller = (killer != null);
Integer id = entity.getEntityId();
// Values that are either precomputed, or computed on the spot
Configuration config = null;
Action action = null;
FutureReward future = null;
// Resources generated and given
List<ResourceHolder> generated = null;
Collection<ResourceHolder> result = null;
// Simplify by adding the reward to the lookup regardless
if (!scheduledRewards.containsKey(id)) {
// We'll just generate the reward then
onFutureKillEvent(entity, killer);
}
// Retrieve reward from lookup
future = scheduledRewards.get(id);
if (future != null) {
action = future.action;
generated = future.generated;
config = future.config;
} else {
config = getConfiguration(entity, killer);
}
// And we're done with this mob
scheduledRewards.remove(id);
if (hasDebugger()) {
debugger.printDebug(this, "Generated: %s", StringUtils.join(generated, ", "));
}
// Make sure the reward has been changed
if (generated != null && generated.size() > 0) {
ChannelProvider channels = config.getChannelProvider();
RewardProvider rewards = config.getRewardProvider();
// Spawn the experience ourself
event.setDroppedExp(0);
// Reward the killer directly, or just drop it naturally
if (killer != null)
result = action.rewardPlayer(rewards, killer, generated, entity.getLocation());
else
result = action.rewardAnyone(rewards, entity.getWorld(), generated, entity.getLocation());
// Print message
config.getMessageQueue().enqueue(killer, action, channels.getFormatter(killer, result, generated));
if (hasDebugger())
debugger.printDebug(this, "Entity %d: Changed experience drop to %s.",
id, StringUtils.join(result, ", "));
} else if (action != null && action.getInheritMultiplier() != 1) {
// Inherit experience action
handleMultiplier(event, id, config.getMultiplier() * action.getInheritMultiplier());
} else if (config.isDefaultRewardsDisabled() && hasKiller) {
// Disable all mob XP
event.setDroppedExp(0);
if (hasDebugger())
debugger.printDebug(this, "Entity %d: Default mob experience disabled.", id);
} else if (!config.isDefaultRewardsDisabled() && hasKiller) {
handleMultiplier(event, id, config.getMultiplier());
}
// Remove it from the lookup
if (!(entity instanceof Player)) {
spawnReasonLookup.remove(id);
}
return result;
}
|
diff --git a/src/main/java/net/pterodactylus/sone/web/ajax/GetStatusAjaxPage.java b/src/main/java/net/pterodactylus/sone/web/ajax/GetStatusAjaxPage.java
index 09b6f407..07fdfa87 100644
--- a/src/main/java/net/pterodactylus/sone/web/ajax/GetStatusAjaxPage.java
+++ b/src/main/java/net/pterodactylus/sone/web/ajax/GetStatusAjaxPage.java
@@ -1,203 +1,203 @@
/*
* Sone - GetStatusAjaxPage.java - Copyright © 2010 David Roden
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.pterodactylus.sone.web.ajax;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import net.pterodactylus.sone.data.Post;
import net.pterodactylus.sone.data.Reply;
import net.pterodactylus.sone.data.Sone;
import net.pterodactylus.sone.notify.ListNotificationFilters;
import net.pterodactylus.sone.template.SoneAccessor;
import net.pterodactylus.sone.web.WebInterface;
import net.pterodactylus.util.filter.Filter;
import net.pterodactylus.util.filter.Filters;
import net.pterodactylus.util.json.JsonArray;
import net.pterodactylus.util.json.JsonObject;
import net.pterodactylus.util.notify.Notification;
/**
* The “get status” AJAX handler returns all information that is necessary to
* update the web interface in real-time.
*
* @author <a href="mailto:[email protected]">David ‘Bombe’ Roden</a>
*/
public class GetStatusAjaxPage extends JsonPage {
/** Date formatter. */
private static final DateFormat dateFormat = new SimpleDateFormat("MMM d, yyyy, HH:mm:ss");
/**
* Creates a new “get status” AJAX handler.
*
* @param webInterface
* The Sone web interface
*/
public GetStatusAjaxPage(WebInterface webInterface) {
super("getStatus.ajax", webInterface);
}
/**
* {@inheritDoc}
*/
@Override
protected JsonObject createJsonObject(Request request) {
final Sone currentSone = getCurrentSone(request.getToadletContext(), false);
/* load Sones. */
boolean loadAllSones = Boolean.parseBoolean(request.getHttpRequest().getParam("loadAllSones", "false"));
Set<Sone> sones = new HashSet<Sone>(Collections.singleton(getCurrentSone(request.getToadletContext(), false)));
if (loadAllSones) {
sones.addAll(webInterface.getCore().getSones());
} else {
String loadSoneIds = request.getHttpRequest().getParam("soneIds");
if (loadSoneIds.length() > 0) {
String[] soneIds = loadSoneIds.split(",");
for (String soneId : soneIds) {
/* just add it, we skip null further down. */
sones.add(webInterface.getCore().getSone(soneId, false));
}
}
}
JsonArray jsonSones = new JsonArray();
for (Sone sone : sones) {
if (sone == null) {
continue;
}
JsonObject jsonSone = createJsonSone(sone);
jsonSones.add(jsonSone);
}
/* load notifications. */
List<Notification> notifications = ListNotificationFilters.filterNotifications(webInterface.getNotifications().getNotifications(), currentSone);
Collections.sort(notifications, Notification.LAST_UPDATED_TIME_SORTER);
JsonArray jsonNotificationInformations = new JsonArray();
for (Notification notification : notifications) {
jsonNotificationInformations.add(createJsonNotificationInformation(notification));
}
/* load new posts. */
Set<Post> newPosts = webInterface.getNewPosts();
if (currentSone != null) {
newPosts = Filters.filteredSet(newPosts, new Filter<Post>() {
@Override
public boolean filterObject(Post post) {
return ListNotificationFilters.isPostVisible(currentSone, post);
}
});
}
JsonArray jsonPosts = new JsonArray();
for (Post post : newPosts) {
JsonObject jsonPost = new JsonObject();
jsonPost.put("id", post.getId());
jsonPost.put("sone", post.getSone().getId());
jsonPost.put("recipient", (post.getRecipient() != null) ? post.getRecipient().getId() : null);
jsonPost.put("time", post.getTime());
jsonPosts.add(jsonPost);
}
/* load new replies. */
Set<Reply> newReplies = webInterface.getNewReplies();
if (currentSone != null) {
newReplies = Filters.filteredSet(newReplies, new Filter<Reply>() {
@Override
public boolean filterObject(Reply reply) {
return ListNotificationFilters.isReplyVisible(currentSone, reply);
}
});
}
JsonArray jsonReplies = new JsonArray();
for (Reply reply : newReplies) {
JsonObject jsonReply = new JsonObject();
jsonReply.put("id", reply.getId());
jsonReply.put("sone", reply.getSone().getId());
jsonReply.put("post", reply.getPost().getId());
jsonReply.put("postSone", reply.getPost().getSone().getId());
jsonReplies.add(jsonReply);
}
- return createSuccessJsonObject().put("sones", jsonSones).put("notifications", jsonNotificationInformations).put("newPosts", jsonPosts).put("newReplies", jsonReplies);
+ return createSuccessJsonObject().put("loggedIn", currentSone != null).put("sones", jsonSones).put("notifications", jsonNotificationInformations).put("newPosts", jsonPosts).put("newReplies", jsonReplies);
}
/**
* {@inheritDoc}
*/
@Override
protected boolean needsFormPassword() {
return false;
}
/**
* {@inheritDoc}
*/
@Override
protected boolean requiresLogin() {
return false;
}
//
// PRIVATE METHODS
//
/**
* Creates a JSON object from the given Sone.
*
* @param sone
* The Sone to convert to a JSON object
* @return The JSON representation of the given Sone
*/
private JsonObject createJsonSone(Sone sone) {
JsonObject jsonSone = new JsonObject();
jsonSone.put("id", sone.getId());
jsonSone.put("name", SoneAccessor.getNiceName(sone));
jsonSone.put("local", sone.getInsertUri() != null);
jsonSone.put("status", webInterface.getCore().getSoneStatus(sone).name());
jsonSone.put("modified", webInterface.getCore().isModifiedSone(sone));
jsonSone.put("locked", webInterface.getCore().isLocked(sone));
jsonSone.put("lastUpdatedUnknown", sone.getTime() == 0);
synchronized (dateFormat) {
jsonSone.put("lastUpdated", dateFormat.format(new Date(sone.getTime())));
}
jsonSone.put("lastUpdatedText", GetTimesAjaxPage.getTime(webInterface, System.currentTimeMillis() - sone.getTime()).getText());
return jsonSone;
}
/**
* Creates a JSON object that only contains the ID and the last-updated time
* of the given notification.
*
* @see Notification#getId()
* @see Notification#getLastUpdatedTime()
* @param notification
* The notification
* @return A JSON object containing the notification ID and last-updated
* time
*/
private JsonObject createJsonNotificationInformation(Notification notification) {
JsonObject jsonNotification = new JsonObject();
jsonNotification.put("id", notification.getId());
jsonNotification.put("lastUpdatedTime", notification.getLastUpdatedTime());
return jsonNotification;
}
}
| true | true | protected JsonObject createJsonObject(Request request) {
final Sone currentSone = getCurrentSone(request.getToadletContext(), false);
/* load Sones. */
boolean loadAllSones = Boolean.parseBoolean(request.getHttpRequest().getParam("loadAllSones", "false"));
Set<Sone> sones = new HashSet<Sone>(Collections.singleton(getCurrentSone(request.getToadletContext(), false)));
if (loadAllSones) {
sones.addAll(webInterface.getCore().getSones());
} else {
String loadSoneIds = request.getHttpRequest().getParam("soneIds");
if (loadSoneIds.length() > 0) {
String[] soneIds = loadSoneIds.split(",");
for (String soneId : soneIds) {
/* just add it, we skip null further down. */
sones.add(webInterface.getCore().getSone(soneId, false));
}
}
}
JsonArray jsonSones = new JsonArray();
for (Sone sone : sones) {
if (sone == null) {
continue;
}
JsonObject jsonSone = createJsonSone(sone);
jsonSones.add(jsonSone);
}
/* load notifications. */
List<Notification> notifications = ListNotificationFilters.filterNotifications(webInterface.getNotifications().getNotifications(), currentSone);
Collections.sort(notifications, Notification.LAST_UPDATED_TIME_SORTER);
JsonArray jsonNotificationInformations = new JsonArray();
for (Notification notification : notifications) {
jsonNotificationInformations.add(createJsonNotificationInformation(notification));
}
/* load new posts. */
Set<Post> newPosts = webInterface.getNewPosts();
if (currentSone != null) {
newPosts = Filters.filteredSet(newPosts, new Filter<Post>() {
@Override
public boolean filterObject(Post post) {
return ListNotificationFilters.isPostVisible(currentSone, post);
}
});
}
JsonArray jsonPosts = new JsonArray();
for (Post post : newPosts) {
JsonObject jsonPost = new JsonObject();
jsonPost.put("id", post.getId());
jsonPost.put("sone", post.getSone().getId());
jsonPost.put("recipient", (post.getRecipient() != null) ? post.getRecipient().getId() : null);
jsonPost.put("time", post.getTime());
jsonPosts.add(jsonPost);
}
/* load new replies. */
Set<Reply> newReplies = webInterface.getNewReplies();
if (currentSone != null) {
newReplies = Filters.filteredSet(newReplies, new Filter<Reply>() {
@Override
public boolean filterObject(Reply reply) {
return ListNotificationFilters.isReplyVisible(currentSone, reply);
}
});
}
JsonArray jsonReplies = new JsonArray();
for (Reply reply : newReplies) {
JsonObject jsonReply = new JsonObject();
jsonReply.put("id", reply.getId());
jsonReply.put("sone", reply.getSone().getId());
jsonReply.put("post", reply.getPost().getId());
jsonReply.put("postSone", reply.getPost().getSone().getId());
jsonReplies.add(jsonReply);
}
return createSuccessJsonObject().put("sones", jsonSones).put("notifications", jsonNotificationInformations).put("newPosts", jsonPosts).put("newReplies", jsonReplies);
}
| protected JsonObject createJsonObject(Request request) {
final Sone currentSone = getCurrentSone(request.getToadletContext(), false);
/* load Sones. */
boolean loadAllSones = Boolean.parseBoolean(request.getHttpRequest().getParam("loadAllSones", "false"));
Set<Sone> sones = new HashSet<Sone>(Collections.singleton(getCurrentSone(request.getToadletContext(), false)));
if (loadAllSones) {
sones.addAll(webInterface.getCore().getSones());
} else {
String loadSoneIds = request.getHttpRequest().getParam("soneIds");
if (loadSoneIds.length() > 0) {
String[] soneIds = loadSoneIds.split(",");
for (String soneId : soneIds) {
/* just add it, we skip null further down. */
sones.add(webInterface.getCore().getSone(soneId, false));
}
}
}
JsonArray jsonSones = new JsonArray();
for (Sone sone : sones) {
if (sone == null) {
continue;
}
JsonObject jsonSone = createJsonSone(sone);
jsonSones.add(jsonSone);
}
/* load notifications. */
List<Notification> notifications = ListNotificationFilters.filterNotifications(webInterface.getNotifications().getNotifications(), currentSone);
Collections.sort(notifications, Notification.LAST_UPDATED_TIME_SORTER);
JsonArray jsonNotificationInformations = new JsonArray();
for (Notification notification : notifications) {
jsonNotificationInformations.add(createJsonNotificationInformation(notification));
}
/* load new posts. */
Set<Post> newPosts = webInterface.getNewPosts();
if (currentSone != null) {
newPosts = Filters.filteredSet(newPosts, new Filter<Post>() {
@Override
public boolean filterObject(Post post) {
return ListNotificationFilters.isPostVisible(currentSone, post);
}
});
}
JsonArray jsonPosts = new JsonArray();
for (Post post : newPosts) {
JsonObject jsonPost = new JsonObject();
jsonPost.put("id", post.getId());
jsonPost.put("sone", post.getSone().getId());
jsonPost.put("recipient", (post.getRecipient() != null) ? post.getRecipient().getId() : null);
jsonPost.put("time", post.getTime());
jsonPosts.add(jsonPost);
}
/* load new replies. */
Set<Reply> newReplies = webInterface.getNewReplies();
if (currentSone != null) {
newReplies = Filters.filteredSet(newReplies, new Filter<Reply>() {
@Override
public boolean filterObject(Reply reply) {
return ListNotificationFilters.isReplyVisible(currentSone, reply);
}
});
}
JsonArray jsonReplies = new JsonArray();
for (Reply reply : newReplies) {
JsonObject jsonReply = new JsonObject();
jsonReply.put("id", reply.getId());
jsonReply.put("sone", reply.getSone().getId());
jsonReply.put("post", reply.getPost().getId());
jsonReply.put("postSone", reply.getPost().getSone().getId());
jsonReplies.add(jsonReply);
}
return createSuccessJsonObject().put("loggedIn", currentSone != null).put("sones", jsonSones).put("notifications", jsonNotificationInformations).put("newPosts", jsonPosts).put("newReplies", jsonReplies);
}
|
diff --git a/org.kompiro.jamcircle.kanban.ui/src/org/kompiro/jamcircle/kanban/ui/util/WorkbenchUtil.java b/org.kompiro.jamcircle.kanban.ui/src/org/kompiro/jamcircle/kanban/ui/util/WorkbenchUtil.java
index 46134499..8ba481d6 100644
--- a/org.kompiro.jamcircle.kanban.ui/src/org/kompiro/jamcircle/kanban/ui/util/WorkbenchUtil.java
+++ b/org.kompiro.jamcircle.kanban.ui/src/org/kompiro/jamcircle/kanban/ui/util/WorkbenchUtil.java
@@ -1,59 +1,60 @@
package org.kompiro.jamcircle.kanban.ui.util;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.kompiro.jamcircle.kanban.model.Board;
import org.kompiro.jamcircle.kanban.ui.KanbanView;
import org.kompiro.jamcircle.kanban.ui.model.BoardModel;
public class WorkbenchUtil {
public static KanbanView findKanbanView() {
final Object[] results = new Object[1];
getDisplay().syncExec(new Runnable() {
public void run() {
IWorkbench workbench = PlatformUI.getWorkbench();
if(workbench == null){
results[0] = null;
return;
}
IWorkbenchWindow activeWorkbenchWindow = workbench.getActiveWorkbenchWindow();
if(activeWorkbenchWindow == null){
if(workbench.getWorkbenchWindowCount() == 0){
results[0] = null;
return;
}
activeWorkbenchWindow = workbench.getWorkbenchWindows()[0];
}
IWorkbenchPage activePage = activeWorkbenchWindow.getActivePage();
if(activePage == null){
results[0] = null;
return;
}
IViewPart foundView = activePage.findView(KanbanView.ID);
if (foundView instanceof KanbanView) {
KanbanView view = (KanbanView) foundView;
results[0] = view;
+ return;
}
results[0] = null;
}
});
return (KanbanView)results[0];
}
public static BoardModel getCurrentKanbanBoard(){
return (BoardModel)findKanbanView().getAdapter(Board.class);
}
public static Display getDisplay(){
IWorkbench workbench = PlatformUI.getWorkbench();
if(workbench == null) return null;
return workbench.getDisplay();
}
}
| true | true | public static KanbanView findKanbanView() {
final Object[] results = new Object[1];
getDisplay().syncExec(new Runnable() {
public void run() {
IWorkbench workbench = PlatformUI.getWorkbench();
if(workbench == null){
results[0] = null;
return;
}
IWorkbenchWindow activeWorkbenchWindow = workbench.getActiveWorkbenchWindow();
if(activeWorkbenchWindow == null){
if(workbench.getWorkbenchWindowCount() == 0){
results[0] = null;
return;
}
activeWorkbenchWindow = workbench.getWorkbenchWindows()[0];
}
IWorkbenchPage activePage = activeWorkbenchWindow.getActivePage();
if(activePage == null){
results[0] = null;
return;
}
IViewPart foundView = activePage.findView(KanbanView.ID);
if (foundView instanceof KanbanView) {
KanbanView view = (KanbanView) foundView;
results[0] = view;
}
results[0] = null;
}
});
return (KanbanView)results[0];
}
| public static KanbanView findKanbanView() {
final Object[] results = new Object[1];
getDisplay().syncExec(new Runnable() {
public void run() {
IWorkbench workbench = PlatformUI.getWorkbench();
if(workbench == null){
results[0] = null;
return;
}
IWorkbenchWindow activeWorkbenchWindow = workbench.getActiveWorkbenchWindow();
if(activeWorkbenchWindow == null){
if(workbench.getWorkbenchWindowCount() == 0){
results[0] = null;
return;
}
activeWorkbenchWindow = workbench.getWorkbenchWindows()[0];
}
IWorkbenchPage activePage = activeWorkbenchWindow.getActivePage();
if(activePage == null){
results[0] = null;
return;
}
IViewPart foundView = activePage.findView(KanbanView.ID);
if (foundView instanceof KanbanView) {
KanbanView view = (KanbanView) foundView;
results[0] = view;
return;
}
results[0] = null;
}
});
return (KanbanView)results[0];
}
|
diff --git a/src/lichen/controller/FloodFiller.java b/src/lichen/controller/FloodFiller.java
index 65edf0c..decb209 100644
--- a/src/lichen/controller/FloodFiller.java
+++ b/src/lichen/controller/FloodFiller.java
@@ -1,472 +1,472 @@
package lichen.controller;
import ij.*;
import ij.process.ColorProcessor;
import ij.process.FloatProcessor;
import ij.process.ImageProcessor;
import java.awt.Rectangle;
import java.util.ArrayList;
import javax.naming.NameNotFoundException;
import de.thm.bi.recognition.data.Point;
import lichen.model.Genus;
import lichen.model.Measurement;
import lichen.model.MeasurementsFactory;
import lichen.view.MainGUI;
/** This class, which does flood filling, is used by the floodFill() macro function and
by the particle analyzer
The Wikipedia at "http://en.wikipedia.org/wiki/Flood_fill" has a good
description of the algorithm used here as well as examples in C and Java.
*/
public class FloodFiller {
int maxStackSize = 500; // will be increased as needed
int[] xstack = new int[maxStackSize];
int[] ystack = new int[maxStackSize];
int stackSize;
ImageProcessor ip;
int max;
boolean isFloat;
protected long pixelcount = 0;
private int ThallusCount = 0;
protected double linewidth = 0.76;
protected double pixelrate;
private UndoStack undoStack;
private ArrayList<int[]> undoPos = new ArrayList<int[]>();
private ArrayList<String[]> thalliList = new ArrayList<String[]>();
public FloodFiller(ImageProcessor ip) {
this.ip = ip;
this.undoStack = new UndoStack(ip);
MainGUI.getInstance().setUndoStack(this.undoStack);
isFloat = ip instanceof FloatProcessor;
}
/** Does a 4-connected flood fill using the current fill/draw
value, which is defined by ImageProcessor.setValue(). */
@SuppressWarnings("unchecked")
public boolean fill(int x, int y) {
double oldPixelcount = pixelcount;
String[] tmp = new String[2];
tmp[0] = x + ":" + y;
undoPos.clear();
// undoPos.clear();
int width = ip.getWidth();
int height = ip.getHeight();
int color = ip.getPixel(x, y);
fillLine(ip, x, x, y);
int newColor = ip.getPixel(x, y);
ip.putPixel(x, y, color);
if (color==newColor) return false;
stackSize = 0;
push(x, y);
while(true) {
//boolean pushed = false;
// System.out.println("SS: "+ stackSize);
x = popx();
if (x ==-1) break;
y = popy();
if (ip.getPixel(x,y)!=color) continue;
int x1 = x; int x2 = x;
while (ip.getPixel(x1,y)==color && x1>=0) x1--; // find start of scan-line
// x1++;
while (ip.getPixel(x2,y)==color && x2<width) x2++; // find end of scan-line
// x2--;
fillLine(ip, x1, x2,y);
boolean inScanLine = false;
for (int i=x1; i<=x2; i++) { // find scan-lines above this one
if (!inScanLine && y>0 && ip.getPixel(i,y-1)==color) {
push(i, y-1);
inScanLine = true;
}
else if (inScanLine && y>0 && ip.getPixel(i,y-1)!=color){
inScanLine = false;
}
}
inScanLine = false;
for (int i=x1; i<=x2; i++) { // find scan-lines below this one
if (!inScanLine && y<height-1 && ip.getPixel(i,y+1)==color){
push(i, y+1);
inScanLine = true;
}
else if (inScanLine && y<height-1 && ip.getPixel(i,y+1)!=color)
inScanLine = false;
}
}
fillEdge((int) Math.round((linewidth*pixelrate)));
undoStack.add((ArrayList<int[]>) undoPos.clone());
ThallusCount++;
- tmp[1] = pixelcount+"";
+ tmp[1] = (int)(pixelcount-oldPixelcount)+"";
this.thalliList.add(tmp);
return true;
}
/**
* finds the edge of the filled area and adds an edge to it
* TODO
*/
private void fillEdge(int n) {
//decrease edge size:
n = (int) Math.round(n-n*0.333);
int[] imageArray = new int[ip.getWidth()* ip.getHeight()];
ImageProcessor org = MainGUI.getInstance().getImp().getProcessor();
// imageArray = (int[]) MainGUI.getInstance().getImp().getProcessor().getPixels();
for(int i = 0; i < imageArray.length; i++){
imageArray[i]= -1;
}
// for(Point p: undoPos){
// imageArray[p.y*ip.getWidth()+p.x] = 0;
// }
for(int[] p: undoPos){
imageArray[p[1]*ip.getWidth()+p[0]] = 0;
}
ImagePlus imp = new ImagePlus("", new ColorProcessor(ip.getWidth(), ip.getHeight(), imageArray));
// imp.getProcessor().findEdges();
ImageProcessor impp = imp.getProcessor();
ArrayList<int[]> edge = new ArrayList<int[]>();
for(int i =0; i < impp.getWidth(); i++){
for(int j = 0; j< impp.getHeight(); j++){
int pixel = impp.getPixel(i, j);
if(pixel == 0){
for(int b = 1; b <= n; b++){
if(impp.getPixel(i, j-n) == -1)
edge.add(new int[] {i, j-n});
if(impp.getPixel(i, j+n) == -1)
edge.add(new int[] {i, j+n});
if(impp.getPixel(i-n, j) == -1)
edge.add(new int[] {i-n, j});
if(impp.getPixel(i+n, j) == -1)
edge.add(new int[] {i+n, j});
}
}
}
}
for(int[] p: edge){
if(impp.getPixel(p[0], p[1]) != 0){
// undoArray[p[0]][p[1]] = ip.getPixel(p[0], p[1]);
undoPos.add(new int[] {p[0],p[1]});
// undoPos.add(new Point(p[0], p[1]));
this.pixelcount++;
impp.setPixel(p[0] , p[1], 0);
org.drawPixel(p[0], p[1]);
}
}
// imp.setProcessor(impp);
// MainGUI.getInstance().setImp(imp);
}
/** Does a 8-connected flood fill using the current fill/draw
value, which is defined by ImageProcessor.setValue(). */
public boolean fill8(int x, int y) {
int width = ip.getWidth();
int height = ip.getHeight();
int color = ip.getPixel(x, y);
int wm1=width-1;
int hm1=height-1;
fillLine(ip, x, x, y);
int newColor = ip.getPixel(x, y);
ip.putPixel(x, y, color);
if (color==newColor) return false;
stackSize = 0;
push(x, y);
while(true) {
x = popx();
if (x==-1) return true;
y = popy();
int x1 = x; int x2 = x;
if(ip.getPixel(x1,y)==color){
while (ip.getPixel(x1,y)==color && x1>=0) x1--; // find start of scan-line
x1++;
while (ip.getPixel(x2,y)==color && x2<width) x2++; // find end of scan-line
x2--;
fillLine(ip, x1,x2,y); // fill scan-line
}
if(y>0){
if (x1>0){
if (ip.getPixel(x1-1,y-1)==color){
push(x1-1,y-1);
}
}
if (x2<wm1){
if (ip.getPixel(x2+1,y-1)==color){
push(x2+1,y-1);
}
}
}
if(y<hm1){
if (x1>0){
if (ip.getPixel(x1-1,y+1)==color){
push(x1-1,y+1);
}
}
if (x2<wm1){
if (ip.getPixel(x2+1,y+1)==color){
push(x2+1,y+1);
}
}
}
boolean inScanLine = false;
for (int i=x1; i<=x2; i++) { // find scan-lines above this one
if (!inScanLine && y>0 && ip.getPixel(i,y-1)==color)
{push(i, y-1); inScanLine = true;}
else if (inScanLine && y>0 && ip.getPixel(i,y-1)!=color)
inScanLine = false;
}
inScanLine = false;
for (int i=x1; i<=x2; i++) {// find scan-lines below this one
if (!inScanLine && y<hm1 && ip.getPixel(i,y+1)==color)
{push(i, y+1); inScanLine = true;}
else if (inScanLine && y<hm1 && ip.getPixel(i,y+1)!=color)
inScanLine = false;
}
}
}
/** This method is used by the particle analyzer to remove interior holes from particle masks. */
public void particleAnalyzerFill(int x, int y, double level1, double level2, ImageProcessor mask, Rectangle bounds) {
//if (count>100) return;
int width = ip.getWidth();
int height = ip.getHeight();
mask.setColor(0);
mask.fill();
mask.setColor(255);
stackSize = 0;
push(x, y);
while(true) {
x = popx();
if (x ==-1) break;
y = popy();
if (!inParticle(x,y,level1,level2)) continue;
int x1 = x; int x2 = x;
while (inParticle(x1,y,level1,level2) && x1>=0) x1--; // find start of scan-line
x1++;
while (inParticle(x2,y,level1,level2) && x2<width) x2++; // find end of scan-line
x2--;
fillLine(mask, x1-bounds.x, x2-bounds.x, y-bounds.y); // fill scan-line i mask
fillLine(ip,x1,x2,y); // fill scan-line in image
boolean inScanLine = false;
if (x1>0) x1--; if (x2<width-1) x2++;
for (int i=x1; i<=x2; i++) { // find scan-lines above this one
if (!inScanLine && y>0 && inParticle(i,y-1,level1,level2))
{push(i, y-1); inScanLine = true;}
else if (inScanLine && y>0 && !inParticle(i,y-1,level1,level2))
inScanLine = false;
}
inScanLine = false;
for (int i=x1; i<=x2; i++) { // find scan-lines below this one
if (!inScanLine && y<height-1 && inParticle(i,y+1,level1,level2))
{push(i, y+1); inScanLine = true;}
else if (inScanLine && y<height-1 && !inParticle(i,y+1,level1,level2))
inScanLine = false;
}
}
}
final boolean inParticle(int x, int y, double level1, double level2) {
if (isFloat)
return ip.getPixelValue(x,y)>=level1 && ip.getPixelValue(x,y)<=level2;
else {
int v = ip.getPixel(x,y);
return v>=level1 && v<=level2;
}
}
final void push(int x, int y) {
stackSize++;
if (stackSize==maxStackSize) {
int[] newXStack = new int[maxStackSize*2];
int[] newYStack = new int[maxStackSize*2];
System.arraycopy(xstack, 0, newXStack, 0, maxStackSize);
System.arraycopy(ystack, 0, newYStack, 0, maxStackSize);
xstack = newXStack;
ystack = newYStack;
maxStackSize *= 2;
}
xstack[stackSize-1] = x;
ystack[stackSize-1] = y;
}
final int popx() {
if (stackSize==0)
return -1;
else
return xstack[stackSize-1];
}
final int popy() {
int value = ystack[stackSize-1];
stackSize--;
return value;
}
private void fillLine(ImageProcessor ip, int x1, int x2, int y) {
// System.out.println("fillline" + x1 + ":" + x2 + "linec: " + y);
if (x1>x2) {
int t = x1;
x1=x2;
x2=t;
}
if(x1 < 0)
x1 =0;
if( x1 > ip.getWidth()-1)
x1 = ip.getWidth()-1;
if(x2 < 0)
x2 =0;
if(x2 > ip.getWidth()-1)
x2 = ip.getWidth()-1;
if(y < 0)
y =0;
if( y > ip.getHeight()-1)
y = ip.getHeight()-1;
for (int x=x1; x<=x2; x++){
undoPos.add(new int[]{x,y});
// undoPos.add(new Point(x, y));
ip.drawPixel(x, y);
pixelcount++;
}
}
public long getPixelCount() {
return this.pixelcount;
}
public void setPixelCount(int i) {
this.pixelcount = 0;
}
/**
* Restores the previous filled pixels from undoPos
* @pre an area should have been filled
*/
public void unfill() {
int sub = undoStack.undo();
//TODO: remove from thallus list
//if pixelcount < 0 substract undo area from old measurment
if(pixelcount-sub < 0){
ArrayList<Measurement> mList = MeasurementsFactory.getInstance().returnAll();
Measurement m =mList.get(mList.size()-1);
m.addArea(-sub);
m.setCount(m.getCount()-1);
if(m.getArea() == 0){
try {
Genus.getInstance().getSpeciesFromID(m.getSpecies()).setResults(null);;
} catch (NameNotFoundException e) {
//Nothing to be done here, cannot happen
}
mList.remove(mList.size()-1);
}
}else{
this.pixelcount -= sub;
this.ThallusCount--;
}
}
public void setPixelrate(double pixelrate) {
this.pixelrate = pixelrate;
}
/**
* @return the linewidth
*/
public double getLinewidth() {
return linewidth;
}
/**
* @param linewidth the linewidth to set
*/
public void setLinewidth(double linewidth) {
this.linewidth = linewidth;
}
/**
* @return the thallusCount
*/
public int getThallusCount() {
return ThallusCount;
}
/**
* @param thallusCount the thallusCount to set
*/
public void setThallusCount(int thallusCount) {
ThallusCount = thallusCount;
}
/**
* @return the thalliList
*/
public ArrayList<String[]> getThalliList() {
return thalliList;
}
/**
* @param thalliList the thalliList to set
*/
public void setThalliList(ArrayList<String[]> thalliList) {
this.thalliList = thalliList;
}
}
| true | true | public boolean fill(int x, int y) {
double oldPixelcount = pixelcount;
String[] tmp = new String[2];
tmp[0] = x + ":" + y;
undoPos.clear();
// undoPos.clear();
int width = ip.getWidth();
int height = ip.getHeight();
int color = ip.getPixel(x, y);
fillLine(ip, x, x, y);
int newColor = ip.getPixel(x, y);
ip.putPixel(x, y, color);
if (color==newColor) return false;
stackSize = 0;
push(x, y);
while(true) {
//boolean pushed = false;
// System.out.println("SS: "+ stackSize);
x = popx();
if (x ==-1) break;
y = popy();
if (ip.getPixel(x,y)!=color) continue;
int x1 = x; int x2 = x;
while (ip.getPixel(x1,y)==color && x1>=0) x1--; // find start of scan-line
// x1++;
while (ip.getPixel(x2,y)==color && x2<width) x2++; // find end of scan-line
// x2--;
fillLine(ip, x1, x2,y);
boolean inScanLine = false;
for (int i=x1; i<=x2; i++) { // find scan-lines above this one
if (!inScanLine && y>0 && ip.getPixel(i,y-1)==color) {
push(i, y-1);
inScanLine = true;
}
else if (inScanLine && y>0 && ip.getPixel(i,y-1)!=color){
inScanLine = false;
}
}
inScanLine = false;
for (int i=x1; i<=x2; i++) { // find scan-lines below this one
if (!inScanLine && y<height-1 && ip.getPixel(i,y+1)==color){
push(i, y+1);
inScanLine = true;
}
else if (inScanLine && y<height-1 && ip.getPixel(i,y+1)!=color)
inScanLine = false;
}
}
fillEdge((int) Math.round((linewidth*pixelrate)));
undoStack.add((ArrayList<int[]>) undoPos.clone());
ThallusCount++;
tmp[1] = pixelcount+"";
this.thalliList.add(tmp);
return true;
}
| public boolean fill(int x, int y) {
double oldPixelcount = pixelcount;
String[] tmp = new String[2];
tmp[0] = x + ":" + y;
undoPos.clear();
// undoPos.clear();
int width = ip.getWidth();
int height = ip.getHeight();
int color = ip.getPixel(x, y);
fillLine(ip, x, x, y);
int newColor = ip.getPixel(x, y);
ip.putPixel(x, y, color);
if (color==newColor) return false;
stackSize = 0;
push(x, y);
while(true) {
//boolean pushed = false;
// System.out.println("SS: "+ stackSize);
x = popx();
if (x ==-1) break;
y = popy();
if (ip.getPixel(x,y)!=color) continue;
int x1 = x; int x2 = x;
while (ip.getPixel(x1,y)==color && x1>=0) x1--; // find start of scan-line
// x1++;
while (ip.getPixel(x2,y)==color && x2<width) x2++; // find end of scan-line
// x2--;
fillLine(ip, x1, x2,y);
boolean inScanLine = false;
for (int i=x1; i<=x2; i++) { // find scan-lines above this one
if (!inScanLine && y>0 && ip.getPixel(i,y-1)==color) {
push(i, y-1);
inScanLine = true;
}
else if (inScanLine && y>0 && ip.getPixel(i,y-1)!=color){
inScanLine = false;
}
}
inScanLine = false;
for (int i=x1; i<=x2; i++) { // find scan-lines below this one
if (!inScanLine && y<height-1 && ip.getPixel(i,y+1)==color){
push(i, y+1);
inScanLine = true;
}
else if (inScanLine && y<height-1 && ip.getPixel(i,y+1)!=color)
inScanLine = false;
}
}
fillEdge((int) Math.round((linewidth*pixelrate)));
undoStack.add((ArrayList<int[]>) undoPos.clone());
ThallusCount++;
tmp[1] = (int)(pixelcount-oldPixelcount)+"";
this.thalliList.add(tmp);
return true;
}
|
diff --git a/org/xbill/DNS/LOCRecord.java b/org/xbill/DNS/LOCRecord.java
index 05d5de5..f0db11a 100644
--- a/org/xbill/DNS/LOCRecord.java
+++ b/org/xbill/DNS/LOCRecord.java
@@ -1,323 +1,323 @@
// Copyright (c) 1999 Brian Wellington ([email protected])
// Portions Copyright (c) 1999 Network Associates, Inc.
package org.xbill.DNS;
import java.io.*;
import java.util.*;
import java.text.*;
import org.xbill.DNS.utils.*;
/**
* Location - describes the physical location of hosts, networks, subnets.
*
* @author Brian Wellington
*/
public class LOCRecord extends Record {
private long size, hPrecision, vPrecision;
private int latitude, longitude, altitude;
private
LOCRecord() {}
/**
* Creates an LOC Record from the given data
* @param latitude The latitude of the center of the sphere
* @param longitude The longitude of the center of the sphere
* @param altitude The altitude of the center of the sphere, in m
* @param size The diameter of a sphere enclosing the described entity, in m.
* @param hPrecision The horizontal precision of the data, in m.
* @param vPrecision The vertical precision of the data, in m.
*/
public
LOCRecord(Name _name, short _dclass, int _ttl, double _latitude,
double _longitude, double _altitude, double _size,
double _hPrecision, double _vPrecision)
throws IOException
{
super(_name, Type.LOC, _dclass, _ttl);
latitude = (int)(_latitude * 3600 * 1000 + (1 << 31));
longitude = (int)(_longitude * 3600 * 1000 + (1 << 31));
altitude = (int)((_altitude + 100000) * 100);
size = (long)(_size * 100);
hPrecision = (long)(_hPrecision * 100);
vPrecision = (long)(_vPrecision * 100);
}
LOCRecord(Name _name, short _dclass, int _ttl, int length,
DataByteInputStream in, Compression c) throws IOException
{
super(_name, Type.LOC, _dclass, _ttl);
if (in == null)
return;
int version, temp;
version = in.readByte();
if (version != 0)
throw new WireParseException("Invalid LOC version");
size = parseLOCformat(in.readUnsignedByte());
hPrecision = parseLOCformat(in.readUnsignedByte());
vPrecision = parseLOCformat(in.readUnsignedByte());
latitude = in.readInt();
longitude = in.readInt();
altitude = in.readInt();
}
LOCRecord(Name _name, short _dclass, int _ttl, MyStringTokenizer st,
Name origin)
throws IOException
{
super(_name, Type.LOC, _dclass, _ttl);
String s = null;
int deg, min;
double sec;
/* Latitude */
deg = min = 0;
sec = 0.0;
try {
s = st.nextToken();
deg = Integer.parseInt(s);
s = st.nextToken();
min = Integer.parseInt(s);
s = st.nextToken();
- sec = Double.parseDouble(s);
+ sec = new Double(s).doubleValue();
s = st.nextToken();
}
catch (NumberFormatException e) {
}
if (!s.equalsIgnoreCase("S") && !s.equalsIgnoreCase("N"))
throw new WireParseException("Invalid LOC latitude");
latitude = (int) (1000 * (sec + 60 * (min + 60 * deg)));
if (s.equalsIgnoreCase("S"))
latitude = -latitude;
latitude += (1 << 31);
/* Longitude */
deg = min = 0;
sec = 0.0;
try {
s = st.nextToken();
deg = Integer.parseInt(s);
s = st.nextToken();
min = Integer.parseInt(s);
s = st.nextToken();
- sec = Double.parseDouble(s);
+ sec = new Double(s).doubleValue();
s = st.nextToken();
}
catch (NumberFormatException e) {
}
if (!s.equalsIgnoreCase("W") && !s.equalsIgnoreCase("E"))
throw new WireParseException("Invalid LOC longitude");
longitude = (int) (1000 * (sec + 60 * (min + 60 * deg)));
if (s.equalsIgnoreCase("W"))
longitude = -longitude;
longitude += (1 << 31);
/* Altitude */
if (!st.hasMoreTokens())
return;
s = st.nextToken();
if (s.length() > 1 && s.charAt(s.length() - 1) == 'm')
s = s.substring(0, s.length() - 1);
try {
altitude = (int)((new Double(s).doubleValue() + 100000) * 100);
}
catch (NumberFormatException e) {
throw new WireParseException("Invalid LOC altitude");
}
/* Size */
if (!st.hasMoreTokens())
return;
s = st.nextToken();
if (s.length() > 1 && s.charAt(s.length() - 1) == 'm')
s = s.substring(0, s.length() - 1);
try {
size = (int) (100 * new Double(s).doubleValue());
}
catch (NumberFormatException e) {
throw new WireParseException("Invalid LOC size");
}
/* Horizontal precision */
if (!st.hasMoreTokens())
return;
s = st.nextToken();
if (s.length() > 1 && s.charAt(s.length() - 1) == 'm')
s = s.substring(0, s.length() - 1);
try {
hPrecision = (int) (100 * new Double(s).doubleValue());
}
catch (NumberFormatException e) {
throw new WireParseException("Invalid LOC horizontal precision");
}
/* Vertical precision */
if (!st.hasMoreTokens())
return;
s = st.nextToken();
if (s.length() > 1 && s.charAt(s.length() - 1) == 'm')
s = s.substring(0, s.length() - 1);
try {
vPrecision = (int) (100 * new Double(s).doubleValue());
}
catch (NumberFormatException e) {
throw new WireParseException("Invalid LOC vertical precision");
}
}
/** Convert to a String */
public String
toString() {
StringBuffer sb = toStringNoData();
if (latitude != 0 || longitude != 0 || altitude != 0) {
long temp;
char direction;
NumberFormat nf = new DecimalFormat();
nf.setMaximumFractionDigits(3);
nf.setGroupingUsed(false);
/* Latitude */
temp = (latitude & 0xFFFFFFFF) - (1 << 31);
if (temp < 0) {
temp = -temp;
direction = 'S';
}
else
direction = 'N';
sb.append(temp / (3600 * 1000)); /* degrees */
temp = temp % (3600 * 1000);
sb.append(" ");
sb.append(temp / (60 * 1000)); /* minutes */
temp = temp % (60 * 1000);
sb.append(" ");
sb.append(nf.format((double)temp / 1000)); /* seconds */
sb.append(" ");
sb.append(direction);
sb.append(" ");
/* Latitude */
temp = (longitude & 0xFFFFFFFF) - (1 << 31);
if (temp < 0) {
temp = -temp;
direction = 'W';
}
else
direction = 'E';
sb.append(temp / (3600 * 1000)); /* degrees */
temp = temp % (3600 * 1000);
sb.append(" ");
sb.append(temp / (60 * 1000)); /* minutes */
temp = temp % (60 * 1000);
sb.append(" ");
sb.append(nf.format((double)temp / 1000)); /* seconds */
sb.append(" ");
sb.append(direction);
sb.append(" ");
nf.setMaximumFractionDigits(2);
/* Altitude */
sb.append(nf.format((double)(altitude - 10000000)/100));
sb.append("m ");
/* Size */
sb.append(nf.format((double)size/100));
sb.append("m ");
/* Horizontal precision */
sb.append(nf.format((double)hPrecision/100));
sb.append("m ");
/* Vertical precision */
sb.append(nf.format((double)vPrecision/100));
sb.append("m");
}
return sb.toString();
}
/** Returns the latitude */
public double
getLatitude() {
return (double)(latitude - (1<<31)) / (3600 * 1000);
}
/** Returns the longitude */
public double
getLongitude() {
return (double)(longitude - (1<<31)) / (3600 * 1000);
}
/** Returns the altitude */
public double
getAltitude() {
return (double)(altitude - 10000000)/100;
}
/** Returns the diameter of the enclosing sphere */
public double
getSize() {
return (double)size / 100;
}
/** Returns the horizontal precision */
public double
getHPrecision() {
return (double)hPrecision / 100;
}
/** Returns the horizontal precision */
public double
getVPrecision() {
return (double)vPrecision / 100;
}
void
rrToWire(DataByteOutputStream out, Compression c) throws IOException {
if (latitude == 0 && longitude == 0 && altitude == 0)
return;
out.writeByte(0); /* version */
out.writeByte(toLOCformat(size));
out.writeByte(toLOCformat(hPrecision));
out.writeByte(toLOCformat(vPrecision));
out.writeInt(latitude);
out.writeInt(longitude);
out.writeInt(altitude);
}
private long
parseLOCformat(int b) throws WireParseException {
long out = b >> 4;
int exp = b & 0xF;
if (out > 9 || exp > 9)
throw new WireParseException("Invalid LOC Encoding");
while (exp-- > 0)
out *= 10;
return (out);
}
private byte
toLOCformat(long l) {
byte exp = 0;
while (l > 9) {
exp++;
l = (l + 5) / 10;
}
return (byte)((l << 4) + exp);
}
}
| false | true | LOCRecord(Name _name, short _dclass, int _ttl, MyStringTokenizer st,
Name origin)
throws IOException
{
super(_name, Type.LOC, _dclass, _ttl);
String s = null;
int deg, min;
double sec;
/* Latitude */
deg = min = 0;
sec = 0.0;
try {
s = st.nextToken();
deg = Integer.parseInt(s);
s = st.nextToken();
min = Integer.parseInt(s);
s = st.nextToken();
sec = Double.parseDouble(s);
s = st.nextToken();
}
catch (NumberFormatException e) {
}
if (!s.equalsIgnoreCase("S") && !s.equalsIgnoreCase("N"))
throw new WireParseException("Invalid LOC latitude");
latitude = (int) (1000 * (sec + 60 * (min + 60 * deg)));
if (s.equalsIgnoreCase("S"))
latitude = -latitude;
latitude += (1 << 31);
/* Longitude */
deg = min = 0;
sec = 0.0;
try {
s = st.nextToken();
deg = Integer.parseInt(s);
s = st.nextToken();
min = Integer.parseInt(s);
s = st.nextToken();
sec = Double.parseDouble(s);
s = st.nextToken();
}
catch (NumberFormatException e) {
}
if (!s.equalsIgnoreCase("W") && !s.equalsIgnoreCase("E"))
throw new WireParseException("Invalid LOC longitude");
longitude = (int) (1000 * (sec + 60 * (min + 60 * deg)));
if (s.equalsIgnoreCase("W"))
longitude = -longitude;
longitude += (1 << 31);
/* Altitude */
if (!st.hasMoreTokens())
return;
s = st.nextToken();
if (s.length() > 1 && s.charAt(s.length() - 1) == 'm')
s = s.substring(0, s.length() - 1);
try {
altitude = (int)((new Double(s).doubleValue() + 100000) * 100);
}
catch (NumberFormatException e) {
throw new WireParseException("Invalid LOC altitude");
}
/* Size */
if (!st.hasMoreTokens())
return;
s = st.nextToken();
if (s.length() > 1 && s.charAt(s.length() - 1) == 'm')
s = s.substring(0, s.length() - 1);
try {
size = (int) (100 * new Double(s).doubleValue());
}
catch (NumberFormatException e) {
throw new WireParseException("Invalid LOC size");
}
/* Horizontal precision */
if (!st.hasMoreTokens())
return;
s = st.nextToken();
if (s.length() > 1 && s.charAt(s.length() - 1) == 'm')
s = s.substring(0, s.length() - 1);
try {
hPrecision = (int) (100 * new Double(s).doubleValue());
}
catch (NumberFormatException e) {
throw new WireParseException("Invalid LOC horizontal precision");
}
/* Vertical precision */
if (!st.hasMoreTokens())
return;
s = st.nextToken();
if (s.length() > 1 && s.charAt(s.length() - 1) == 'm')
s = s.substring(0, s.length() - 1);
try {
vPrecision = (int) (100 * new Double(s).doubleValue());
}
catch (NumberFormatException e) {
throw new WireParseException("Invalid LOC vertical precision");
}
}
| LOCRecord(Name _name, short _dclass, int _ttl, MyStringTokenizer st,
Name origin)
throws IOException
{
super(_name, Type.LOC, _dclass, _ttl);
String s = null;
int deg, min;
double sec;
/* Latitude */
deg = min = 0;
sec = 0.0;
try {
s = st.nextToken();
deg = Integer.parseInt(s);
s = st.nextToken();
min = Integer.parseInt(s);
s = st.nextToken();
sec = new Double(s).doubleValue();
s = st.nextToken();
}
catch (NumberFormatException e) {
}
if (!s.equalsIgnoreCase("S") && !s.equalsIgnoreCase("N"))
throw new WireParseException("Invalid LOC latitude");
latitude = (int) (1000 * (sec + 60 * (min + 60 * deg)));
if (s.equalsIgnoreCase("S"))
latitude = -latitude;
latitude += (1 << 31);
/* Longitude */
deg = min = 0;
sec = 0.0;
try {
s = st.nextToken();
deg = Integer.parseInt(s);
s = st.nextToken();
min = Integer.parseInt(s);
s = st.nextToken();
sec = new Double(s).doubleValue();
s = st.nextToken();
}
catch (NumberFormatException e) {
}
if (!s.equalsIgnoreCase("W") && !s.equalsIgnoreCase("E"))
throw new WireParseException("Invalid LOC longitude");
longitude = (int) (1000 * (sec + 60 * (min + 60 * deg)));
if (s.equalsIgnoreCase("W"))
longitude = -longitude;
longitude += (1 << 31);
/* Altitude */
if (!st.hasMoreTokens())
return;
s = st.nextToken();
if (s.length() > 1 && s.charAt(s.length() - 1) == 'm')
s = s.substring(0, s.length() - 1);
try {
altitude = (int)((new Double(s).doubleValue() + 100000) * 100);
}
catch (NumberFormatException e) {
throw new WireParseException("Invalid LOC altitude");
}
/* Size */
if (!st.hasMoreTokens())
return;
s = st.nextToken();
if (s.length() > 1 && s.charAt(s.length() - 1) == 'm')
s = s.substring(0, s.length() - 1);
try {
size = (int) (100 * new Double(s).doubleValue());
}
catch (NumberFormatException e) {
throw new WireParseException("Invalid LOC size");
}
/* Horizontal precision */
if (!st.hasMoreTokens())
return;
s = st.nextToken();
if (s.length() > 1 && s.charAt(s.length() - 1) == 'm')
s = s.substring(0, s.length() - 1);
try {
hPrecision = (int) (100 * new Double(s).doubleValue());
}
catch (NumberFormatException e) {
throw new WireParseException("Invalid LOC horizontal precision");
}
/* Vertical precision */
if (!st.hasMoreTokens())
return;
s = st.nextToken();
if (s.length() > 1 && s.charAt(s.length() - 1) == 'm')
s = s.substring(0, s.length() - 1);
try {
vPrecision = (int) (100 * new Double(s).doubleValue());
}
catch (NumberFormatException e) {
throw new WireParseException("Invalid LOC vertical precision");
}
}
|
diff --git a/resolvers/resolvers-ning-async/src/main/java/org/httpcache4j/resolver/ning/NingResponseResolver.java b/resolvers/resolvers-ning-async/src/main/java/org/httpcache4j/resolver/ning/NingResponseResolver.java
index bba5972..39c4556 100644
--- a/resolvers/resolvers-ning-async/src/main/java/org/httpcache4j/resolver/ning/NingResponseResolver.java
+++ b/resolvers/resolvers-ning-async/src/main/java/org/httpcache4j/resolver/ning/NingResponseResolver.java
@@ -1,112 +1,112 @@
package org.httpcache4j.resolver.ning;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.FluentCaseInsensitiveStringsMap;
import com.ning.http.client.Response;
import org.codehaus.httpcache4j.*;
import org.codehaus.httpcache4j.auth.*;
import org.codehaus.httpcache4j.mutable.MutableHeaders;
import org.codehaus.httpcache4j.payload.InputStreamPayload;
import org.codehaus.httpcache4j.resolver.AbstractResponseResolver;
import org.codehaus.httpcache4j.util.ResponseWriter;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import static org.codehaus.httpcache4j.HTTPMethod.*;
/**
* @author <a href="mailto:[email protected]">Erlend Hamnaberg</a>
* @version $Revision: $
*/
public class NingResponseResolver extends AbstractResponseResolver {
private final AsyncHttpClient client;
public NingResponseResolver(ProxyAuthenticator proxyAuthenticator, Authenticator authenticator) {
super(proxyAuthenticator, authenticator);
client = new AsyncHttpClient();
}
@Override
protected HTTPResponse resolveImpl(HTTPRequest request) throws IOException {
Future<Response> responseFuture = execute(request);
return translate(responseFuture);
}
public void shutdown() {
client.close();
}
private HTTPResponse translate(Future<Response> responseFuture) throws IOException {
try {
System.out.println("NingResponseResolver.execute");
Response response = responseFuture.get();
System.out.println("NingResponseResolver.execute");
StatusLine line = new StatusLine(Status.valueOf(response.getStatusCode()), response.getStatusText());
FluentCaseInsensitiveStringsMap headers = response.getHeaders();
MutableHeaders convertedHeaders = new MutableHeaders();
for (Map.Entry<String, List<String>> entry : headers) {
final String key = entry.getKey();
List<String> values = entry.getValue();
- convertedHeaders.add(key, Lists.transform(values, stringToHeader(key)));
+ convertedHeaders.add(Lists.transform(values, stringToHeader(key)));
}
InputStream stream = response.getResponseBodyAsStream();
return new HTTPResponse(new InputStreamPayload(stream, MIMEType.valueOf(response.getContentType())), line, convertedHeaders.toHeaders());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (ExecutionException e) {
throw new HTTPException(e.getCause());
}
throw new HTTPException("Not possible to get response");
}
private Future<Response> execute(HTTPRequest request) throws IOException {
AsyncHttpClient.BoundRequestBuilder builder = builder(request.getRequestURI(), request.getMethod());
if (request.getMethod().canHavePayload()) {
builder = builder.setBody(request.getPayload().getInputStream());
}
for (Header header : request.getAllHeaders()) {
builder = builder.addHeader(header.getName(), header.getValue());
}
return builder.execute();
}
private AsyncHttpClient.BoundRequestBuilder builder(URI uri, HTTPMethod method) {
if (DELETE.equals(method)) {
return client.prepareDelete(uri.toString());
}
else if (GET.equals(method)) {
return client.prepareGet(uri.toString());
}
else if (HEAD.equals(method)) {
return client.prepareHead(uri.toString());
}
else if (OPTIONS.equals(method)) {
return client.prepareOptions(uri.toString());
}
else if (POST.equals(method)) {
return client.preparePost(uri.toString());
}
else if (PUT.equals(method)) {
return client.preparePut(uri.toString());
}
return null;
}
private Function<String, Header> stringToHeader(final String key) {
return new Function<String, Header>() {
public Header apply(String from) {
return new Header(key, from);
}
};
}
}
| true | true | private HTTPResponse translate(Future<Response> responseFuture) throws IOException {
try {
System.out.println("NingResponseResolver.execute");
Response response = responseFuture.get();
System.out.println("NingResponseResolver.execute");
StatusLine line = new StatusLine(Status.valueOf(response.getStatusCode()), response.getStatusText());
FluentCaseInsensitiveStringsMap headers = response.getHeaders();
MutableHeaders convertedHeaders = new MutableHeaders();
for (Map.Entry<String, List<String>> entry : headers) {
final String key = entry.getKey();
List<String> values = entry.getValue();
convertedHeaders.add(key, Lists.transform(values, stringToHeader(key)));
}
InputStream stream = response.getResponseBodyAsStream();
return new HTTPResponse(new InputStreamPayload(stream, MIMEType.valueOf(response.getContentType())), line, convertedHeaders.toHeaders());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (ExecutionException e) {
throw new HTTPException(e.getCause());
}
throw new HTTPException("Not possible to get response");
}
| private HTTPResponse translate(Future<Response> responseFuture) throws IOException {
try {
System.out.println("NingResponseResolver.execute");
Response response = responseFuture.get();
System.out.println("NingResponseResolver.execute");
StatusLine line = new StatusLine(Status.valueOf(response.getStatusCode()), response.getStatusText());
FluentCaseInsensitiveStringsMap headers = response.getHeaders();
MutableHeaders convertedHeaders = new MutableHeaders();
for (Map.Entry<String, List<String>> entry : headers) {
final String key = entry.getKey();
List<String> values = entry.getValue();
convertedHeaders.add(Lists.transform(values, stringToHeader(key)));
}
InputStream stream = response.getResponseBodyAsStream();
return new HTTPResponse(new InputStreamPayload(stream, MIMEType.valueOf(response.getContentType())), line, convertedHeaders.toHeaders());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (ExecutionException e) {
throw new HTTPException(e.getCause());
}
throw new HTTPException("Not possible to get response");
}
|
diff --git a/de.xwic.etlgine/src/de/xwic/etlgine/finalizer/MoveFileFinalizer.java b/de.xwic.etlgine/src/de/xwic/etlgine/finalizer/MoveFileFinalizer.java
index b60d091..9ee7282 100644
--- a/de.xwic.etlgine/src/de/xwic/etlgine/finalizer/MoveFileFinalizer.java
+++ b/de.xwic.etlgine/src/de/xwic/etlgine/finalizer/MoveFileFinalizer.java
@@ -1,154 +1,154 @@
/**
*
*/
package de.xwic.etlgine.finalizer;
import java.io.File;
import de.xwic.etlgine.IETLProcess;
import de.xwic.etlgine.IMonitor;
import de.xwic.etlgine.IProcess;
import de.xwic.etlgine.IProcessContext;
import de.xwic.etlgine.IProcessFinalizer;
import de.xwic.etlgine.ISource;
import de.xwic.etlgine.Result;
import de.xwic.etlgine.sources.FileSource;
/**
* @author lippisch
*
*/
public class MoveFileFinalizer implements IProcessFinalizer {
private File sourceFile = null;
private File targetPath;
private boolean deleteTargetIfExists = true;
private IMonitor monitor;
/**
* @param targetPath
*/
public MoveFileFinalizer(File targetPath) {
super();
this.targetPath = targetPath;
}
/**
* @param targetPath
*/
public MoveFileFinalizer(String targetPath) {
super();
this.targetPath = new File(targetPath);
}
/**
* @param targetPath
*/
public MoveFileFinalizer(File targetPath, File sourceFile) {
super();
this.targetPath = targetPath;
this.sourceFile = sourceFile;
}
/**
* @param targetPath
*/
public MoveFileFinalizer(String targetPath, String sourceFileName) {
super();
this.targetPath = new File(targetPath);
this.sourceFile = new File(sourceFileName);
}
/* (non-Javadoc)
* @see de.xwic.etlgine.IProcessFinalizer#onFinish(de.xwic.etlgine.IProcessContext)
*/
public void onFinish(IProcessContext context) {
monitor = context.getMonitor();
if (!targetPath.exists()) {
if (!targetPath.mkdirs()) {
monitor.logError("Error creating target directory: " + targetPath.getAbsolutePath());
return;
}
}
if (!targetPath.isDirectory()) {
monitor.logError("The target path is no directory!");
return;
}
if (sourceFile != null) {
if (!moveFile(sourceFile)) {
context.setResult(Result.FINISHED_WITH_ERRORS);
}
} else {
IProcess process = context.getProcess();
if (process instanceof IETLProcess) {
IETLProcess etlp = (IETLProcess)process;
for (ISource source : etlp.getSources()) {
if (source instanceof FileSource) {
FileSource fs = (FileSource)source;
File file = fs.getFile();
- if (file != null) {
+ if (file != null && file.exists()) {
if (!moveFile(file)) {
context.setResult(Result.FINISHED_WITH_ERRORS);
}
}
} else {
monitor.logWarn("Cannot move source " + source.getName() + " as it is no FileSource.");
}
}
}
}
}
/**
* @param file
* @return
*/
private boolean moveFile(File file) {
if (!file.exists()) {
monitor.logWarn("Can not move file " + file.getName() + " because it does not exist.");
return false;
}
File destFile = new File(targetPath, file.getName());
if (destFile.exists() && !deleteTargetIfExists) {
monitor.logWarn("Cannot move file " + file.getName() + " as it already exists in the target location.");
return false;
} else {
if (destFile.exists()) {
if (!destFile.delete()) {
monitor.logError("Error deleting target file - file cannot be moved!");
return false;
}
}
if (!file.renameTo(destFile)) {
monitor.logWarn("File was not moved to " + destFile.getAbsolutePath());
return false;
} else {
monitor.logInfo("File " + file.getName() + " moved to " + targetPath.getAbsolutePath());
return true;
}
}
}
/**
* @return the deleteTargetIfExists
*/
public boolean isDeleteTargetIfExists() {
return deleteTargetIfExists;
}
/**
* @param deleteTargetIfExists the deleteTargetIfExists to set
*/
public void setDeleteTargetIfExists(boolean deleteTargetIfExists) {
this.deleteTargetIfExists = deleteTargetIfExists;
}
}
| true | true | public void onFinish(IProcessContext context) {
monitor = context.getMonitor();
if (!targetPath.exists()) {
if (!targetPath.mkdirs()) {
monitor.logError("Error creating target directory: " + targetPath.getAbsolutePath());
return;
}
}
if (!targetPath.isDirectory()) {
monitor.logError("The target path is no directory!");
return;
}
if (sourceFile != null) {
if (!moveFile(sourceFile)) {
context.setResult(Result.FINISHED_WITH_ERRORS);
}
} else {
IProcess process = context.getProcess();
if (process instanceof IETLProcess) {
IETLProcess etlp = (IETLProcess)process;
for (ISource source : etlp.getSources()) {
if (source instanceof FileSource) {
FileSource fs = (FileSource)source;
File file = fs.getFile();
if (file != null) {
if (!moveFile(file)) {
context.setResult(Result.FINISHED_WITH_ERRORS);
}
}
} else {
monitor.logWarn("Cannot move source " + source.getName() + " as it is no FileSource.");
}
}
}
}
}
| public void onFinish(IProcessContext context) {
monitor = context.getMonitor();
if (!targetPath.exists()) {
if (!targetPath.mkdirs()) {
monitor.logError("Error creating target directory: " + targetPath.getAbsolutePath());
return;
}
}
if (!targetPath.isDirectory()) {
monitor.logError("The target path is no directory!");
return;
}
if (sourceFile != null) {
if (!moveFile(sourceFile)) {
context.setResult(Result.FINISHED_WITH_ERRORS);
}
} else {
IProcess process = context.getProcess();
if (process instanceof IETLProcess) {
IETLProcess etlp = (IETLProcess)process;
for (ISource source : etlp.getSources()) {
if (source instanceof FileSource) {
FileSource fs = (FileSource)source;
File file = fs.getFile();
if (file != null && file.exists()) {
if (!moveFile(file)) {
context.setResult(Result.FINISHED_WITH_ERRORS);
}
}
} else {
monitor.logWarn("Cannot move source " + source.getName() + " as it is no FileSource.");
}
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.